55 lines
2.0 KiB
JavaScript
55 lines
2.0 KiB
JavaScript
import slugify from 'slugify';
|
|
/**
|
|
* Normalizes a string into a URL slug. slugify handles diacritics out of the
|
|
* box (Polish included: "Strona główna" → "strona-glowna").
|
|
*/ export function toSlug(input) {
|
|
return slugify(input, {
|
|
lower: true,
|
|
strict: true,
|
|
trim: true
|
|
});
|
|
}
|
|
/**
|
|
* Builds a slug field that auto-generates from a source field (default 'title')
|
|
* only when left empty — an editor's manual slug is never overwritten (mode 4a).
|
|
*
|
|
* Localized-safe: on a localized field Payload runs the hook per locale, so
|
|
* `value` is the slug for the active locale and `siblingData[from]` is the
|
|
* source in that same locale. Editing the doc in 'pl' fills slug.pl from
|
|
* title.pl; editing in 'en' fills slug.en from title.en — giving genuinely
|
|
* per-locale slugs (strona-glowna / homepage) that the language switcher needs.
|
|
*/ export function buildSlugField(options = {}) {
|
|
const { name = 'slug', from = 'title', localized = true, overrides = {}, required = true } = options;
|
|
const autoGenerate = ({ originalDoc, siblingData, value })=>{
|
|
// Respect a manually entered slug — only generate when empty (mode 4a).
|
|
if (typeof value === 'string' && value.trim()) {
|
|
return toSlug(value) // still normalize what the editor typed
|
|
;
|
|
}
|
|
// Derive from the source field in the current locale.
|
|
const source = siblingData?.[from] ?? originalDoc?.[from];
|
|
if (typeof source === 'string' && source.trim()) {
|
|
return toSlug(source);
|
|
}
|
|
return value;
|
|
};
|
|
return {
|
|
name,
|
|
type: 'text',
|
|
admin: {
|
|
description: 'Auto-generated from the title when left empty. You can override it.',
|
|
...overrides.admin
|
|
},
|
|
hooks: {
|
|
beforeValidate: [
|
|
autoGenerate
|
|
]
|
|
},
|
|
index: true,
|
|
localized,
|
|
required,
|
|
...overrides
|
|
};
|
|
}
|
|
|
|
//# sourceMappingURL=buildSlugField.js.map
|