import { unidecode } from "../deps/unidecode.ts";import { merge } from "../core/utils.ts";
import type { Helper, Page, Site } from "../core.ts";
export interface Options { extensions: string[];
lowercase: boolean;
alphanumeric: boolean;
separator: string;
replace: { [index: string]: string; };
stopWords: string[];}
export const defaults: Options = { extensions: [".html"], lowercase: true, alphanumeric: true, separator: "-", replace: { "Γ": "D", "Γ°": "d", "Δ": "D", "Δ": "d", "ΓΈ": "o", "Γ": "ss", "Γ¦": "ae", "Ε": "oe", }, stopWords: [],};
export default function (userOptions?: Partial<Options>) { const options = merge(defaults, userOptions); const slugify = createSlugifier(options);
return (site: Site) => { site.filter("slugify", slugify as Helper); site.preprocess(options.extensions, slugifyUrls); };
function slugifyUrls(page: Page) { if (typeof page.data.url === "string") { page.data.url = slugify(page.data.url); } }}
export function createSlugifier( options: Options = defaults,): (string: string) => string { const { lowercase, alphanumeric, separator, replace, stopWords } = options;
return function (string) { if (lowercase) { string = string.toLowerCase(); }
string = string.replaceAll(/[^a-z\d/.-]/giu, (char) => { if (char in replace) { return replace[char]; }
if (alphanumeric) { char = char.normalize("NFKD").replaceAll(/[\u0300-\u036F]/g, ""); char = unidecode(char).trim(); }
char = /[\p{L}\u0300-\u036F]+/u.test(char) ? char : "-";
return alphanumeric && /[^\w-]+/.test(char) ? "" : char; });
if (lowercase) { string = string.toLowerCase(); }
string = string.trim().split(/-+/).filter((word) => stopWords.indexOf(word) === -1 ).join("-");
string = string.replaceAll( /(?<=^|[/.])-+(?=[^/.-])|(?<=[^/.-])-+(?=$|[/.])/g, "", );
return string.replaceAll("-", separator); };}