diff --git a/packages/parsers/src/hfIdAssignment.ts b/packages/parsers/src/hfIdAssignment.ts index af0d9f4ab5..72152e839d 100644 --- a/packages/parsers/src/hfIdAssignment.ts +++ b/packages/parsers/src/hfIdAssignment.ts @@ -30,6 +30,9 @@ function toHfId(hash: number): string { return `hf-${four}`; } +// Per set, each key's last dup: ids only join a set, so every slot below it is still taken. +const lastDup = new WeakMap, Map>(); + // Element's own direct text (TEXT_NODE children), not descendants'. function ownText(el: Element): string { let text = ""; @@ -78,9 +81,14 @@ function contentKey(el: Element): string { // drag-to-edit targeting. export function mintHfId(el: Element, assigned: Set): string { const key = contentKey(el); - let id = toHfId(fnv1a(key)); - let dup = 0; - while (assigned.has(id)) { + const twins = lastDup.get(assigned) ?? new Map(); + lastDup.set(assigned, twins); + let dup = twins.get(key) ?? 0; + let id = + dup > 10000 + ? `hf-${(fnv1a(key) >>> 0).toString(36)}-${dup}` + : toHfId(fnv1a(dup ? `${key}#${dup}` : key)); + while (dup <= 10000 && assigned.has(id)) { dup += 1; // Graceful fallback instead of a hard throw: rehashing only fails to find a // free 4-char slot in a pathological document (~1.6M identical elements). @@ -92,6 +100,7 @@ export function mintHfId(el: Element, assigned: Set): string { } id = toHfId(fnv1a(`${key}#${dup}`)); } + twins.set(key, dup); assigned.add(id); return id; } diff --git a/packages/parsers/src/hfIds.test.ts b/packages/parsers/src/hfIds.test.ts index 662aec881f..ae4b2bdc4d 100644 --- a/packages/parsers/src/hfIds.test.ts +++ b/packages/parsers/src/hfIds.test.ts @@ -228,6 +228,23 @@ describe("ensureHfIds", () => { expect(b).toMatch(/^hf-[a-z0-9]{4}$/); }); + it("mints a run of identical elements with a few set lookups each, not one per earlier twin", () => { + const { document } = parseHTML(`

same

`); + const el = document.querySelector("p") as Element; + let lookups = 0; + class Counted extends Set { + override has(id: string) { + lookups += 1; + return super.has(id); + } + } + const assigned = new Counted(); + const twins = 2000; + for (let i = 0; i < twins; i += 1) mintHfId(el, assigned); + expect(assigned.size).toBe(twins); + expect(lookups).toBeLessThan(3 * twins); + }); + // Post-persist stability: once data-hf-id is written back to source, edits // don't drift the id because the attribute is already present and pinned. it("pinned id survives text edit after first persist", () => {