Files
zettelclean/src/slug.ts

51 lines
2.8 KiB
TypeScript
Raw Normal View History

// *************************************************************************
// * (C)opyright 2026 by Ruben Carlo Benante *
// * *
// * This program is free software; you can redistribute it and/or modify *
// * it under the terms of the GNU General Public License as published by *
// * the Free Software Foundation, either version 3 of the License, or *
// * (at your option) any later version. *
// * *
// * This program is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
// * GNU General Public License for more details. *
// * *
// * You should have received a copy of the GNU General Public License *
// * along with this program. If not, see http://www.gnu.org/licenses/. *
// * *
// * Contact author at: *
// * Ruben Carlo Benante *
// * rcb@beco.cc *
// *************************************************************************
2026-07-28 16:52:46 -03:00
// Pure string logic for zettelclean. No Obsidian imports, so it is unit-testable
// in isolation. The transform is always one-way (H1 -> filename), which lets us
// freely drop characters without worrying about a reverse mapping.
// A TIMEID is the leading run of 12 to 18 digits, ending at any non-digit or
// end-of-name (so "202607290947 test" and "202607290947-slug" both qualify).
2026-07-28 16:52:46 -03:00
// 12-18 because collision-avoidance may append extra digits to a 14-digit stamp.
const TIMEID_RE = /^(\d{12,18})(?=\D|$)/;
2026-07-28 16:52:46 -03:00
// Return the immutable id prefix, or null if this file is not a zettel.
export function extractTimeId(basename: string): string | null {
const m = basename.match(TIMEID_RE);
return m?.[1] ?? null;
}
// text (an H1 or a folder name) -> ASCII, case-preserving, dash-separated slug.
// Shared by the file-rename sync and the folder-slug menu.
export function generateSlug(text: string): string {
return text
2026-07-28 16:52:46 -03:00
.normalize('NFKD') // split accented letters into base + combining mark
.replace(/[̀-ͯ]/g, '') // strip the combining marks (c-cedilla -> c)
.replace(/[^a-zA-Z0-9]+/g, '-') // non-alphanumerics -> one dash (case kept)
2026-07-28 16:52:46 -03:00
.replace(/^-+|-+$/g, ''); // trim leading/trailing dashes
}
// Reassemble; an empty slug collapses to the bare id.
export function buildFilename(id: string, slug: string): string {
return slug ? `${id}-${slug}` : id;
}