Files
halo/ui/console-src/composables/use-slugify.ts
Ryan Wang e53bfd4edb Refactor user and global info stores to shared package (#7858)
#### What type of PR is this?

/area ui
/kind feature
/milestone 2.22.x

#### What this PR does / why we need it:

This PR moves the `currentUser` and `globalInfo` stores to the `@halo-dev/console-shared` package, making them easily accessible for plugins.

In addition, it’s now possible for plugins to define their own global stores using Pinia.

#### Does this PR introduce a user-facing change?

```release-note
- 在 `@halo-dev/console-shared` 包中提供 `stores` 对象,包含 currentUser 和 globalInfo。
- 支持在插件的 UI 中使用 Pinia 定义全局 Store
```
2025-10-23 10:32:14 +00:00

69 lines
1.6 KiB
TypeScript

import { randomUUID } from "@/utils/id";
import { FormType, stores } from "@halo-dev/console-shared";
import ShortUniqueId from "short-unique-id";
import { slugify } from "transliteration";
import { computed, watch, type Ref } from "vue";
const uid = new ShortUniqueId();
type SlugStrategy = (value?: string) => string;
const strategies: Record<string, SlugStrategy> = {
generateByTitle: (value?: string) => slugify(value || "", { trim: true }),
shortUUID: () => uid.randomUUID(8),
UUID: () => randomUUID(),
timestamp: () => new Date().getTime().toString(),
};
const onceStrategies = new Set(["shortUUID", "UUID", "timestamp"]);
export default function useSlugify(
source: Ref<string>,
target: Ref<string>,
auto: Ref<boolean>,
formType: FormType
) {
const globalInfoStore = stores.globalInfo();
const currentStrategy = computed(
() =>
globalInfoStore.globalInfo?.postSlugGenerationStrategy ||
"generateByTitle"
);
const generateSlug = (value: string): string => {
const strategy =
formType === FormType.POST
? strategies[currentStrategy.value]
: strategies.generateByTitle;
return strategy(value);
};
const handleGenerateSlug = (forceUpdate = false) => {
if (
!forceUpdate &&
onceStrategies.has(currentStrategy.value) &&
target.value
) {
return;
}
target.value = generateSlug(source.value);
};
watch(
source,
() => {
if (auto.value) {
handleGenerateSlug(true);
}
},
{ immediate: true }
);
return {
handleGenerateSlug,
};
}