Files
halo/ui/console-src/composables/use-slugify.ts
Ryan Wang ac88ee70cb Rename @halo-dev/console-shared to @halo-dev/ui-shared (#7926)
#### What type of PR is this?

/area ui
/kind api-change
/milestone 2.22.x

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

See #7925 

#### Which issue(s) this PR fixes:

Fixes #7925 

#### Special notes for your reviewer:

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

```release-note
将 `@halo-dev/console-shared` 重命名为 `@halo-dev/ui-shared`
```
2025-11-10 16:20:41 +00:00

68 lines
1.5 KiB
TypeScript

import { FormType, stores, utils } from "@halo-dev/ui-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: () => utils.id.uuid(),
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,
};
}