Files
outline/shared/editor/lib/headingToSlug.ts
Tom Moor c4006cef7b perf: Remove markdown serialize from editor render path (#3567)
* perf: Remove markdown serialize from editor render path

* fix: Simplify heading equality check

* perf: Add cache for slugified headings

* tsc
2022-05-21 12:50:27 -07:00

40 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { escape } from "lodash";
import { Node } from "prosemirror-model";
import slugify from "slugify";
const cache = new Map<string, string>();
// Slugify, escape, and remove periods from headings so that they are
// compatible with both url hashes AND dom ID's (querySelector does not like
// ID's that begin with a number or a period, for example).
function safeSlugify(text: string) {
if (cache.has(text)) {
return cache.get(text) as string;
}
const slug = `h-${escape(
slugify(text, {
remove: /[!"#$%&'\.()*+,\/:;<=>?@\[\]\\^_`{|}~]/g,
lower: true,
})
)}`;
cache.set(text, slug);
return slug;
}
// calculates a unique slug for this heading based on it's text and position
// in the document that is as stable as possible
export default function headingToSlug(node: Node, index = 0) {
const slugified = safeSlugify(node.textContent);
if (index === 0) {
return slugified;
}
return `${slugified}-${index}`;
}
export function headingToPersistenceKey(node: Node, id?: string) {
const slug = headingToSlug(node);
return `rme-${id || window?.location.pathname}${slug}`;
}