waybetter/packages/runtime/src/textNet.ts

129 lines
5.2 KiB
TypeScript

// A DOM safety net for strings a catalog hook cannot reach (published as
// `waybetter/runtime/textNet`): labels the server sends already worded, or text that is painted
// before the hook can act. It replaces exact texts in text nodes and in `aria-label`,
// `placeholder` and `title`, keeps the site's own value per node, and puts everything back when it
// is disposed. It is secondary to a catalog hook: it cannot see parameters or plural forms, and a
// rendered text only maps back to one key in a language without homonyms.
//
// Text is written through `nodeValue` / `setAttribute` (never `textContent` or HTML), so the site's
// framework keeps owning its nodes; when the site rewrites a node, the net looks at it again.
export type TextNetOptions = {
/** Exact original text -> replacement. A text that is not a key is left alone. */
map: ReadonlyMap<string, string>;
/** Attributes to cover (default `aria-label`, `placeholder`, `title`). */
attributes?: readonly string[];
/** Elements whose content is never touched (default: scripts, styles, editable text). */
skip?: string;
};
export type TextNetHandle = {
/** Text nodes and attributes currently replaced. */
count(): number;
/** Restores every node and attribute to the site's own value and stops observing. */
dispose(): void;
};
const DEFAULT_ATTRIBUTES = ['aria-label', 'placeholder', 'title'];
const DEFAULT_SKIP = 'script, style, noscript, textarea, [contenteditable=""], [contenteditable="true"]';
const TEXT_NODE = 3;
const ELEMENT_NODE = 1;
const SHOW_TEXT = 4;
export function installTextNet(win: Window, options: TextNetOptions): TextNetHandle {
const doc = win.document;
const attributes = options.attributes ?? DEFAULT_ATTRIBUTES;
const skip = options.skip ?? DEFAULT_SKIP;
const map = options.map;
/** The site's own value and ours, per text node. */
const texts = new WeakMap<Node, { original: string; applied: string }>();
/** The same per element and attribute. */
const attrs = new WeakMap<Element, Map<string, { original: string; applied: string }>>();
let count = 0;
let active = true;
const skipped = (element: Element | null) => !!element && !!skip && !!element.closest(skip);
const text = (node: Node) => {
const value = node.nodeValue ?? '';
const kept = texts.get(node);
if (kept) {
if (value === kept.applied) return;
// The site wrote the node again: what it wrote is the new original.
texts.delete(node);
count -= 1;
}
const next = map.get(value);
if (next === undefined || next === value || skipped(node.parentElement)) return;
texts.set(node, { original: value, applied: next });
count += 1;
node.nodeValue = next;
};
const attribute = (element: Element, name: string) => {
const value = element.getAttribute(name);
const kept = attrs.get(element)?.get(name);
if (kept) {
if (value === kept.applied) return;
attrs.get(element)!.delete(name);
count -= 1;
}
if (value === null) return;
const next = map.get(value);
if (next === undefined || next === value || skipped(element)) return;
let own = attrs.get(element);
if (!own) attrs.set(element, own = new Map());
own.set(name, { original: value, applied: next });
count += 1;
element.setAttribute(name, next);
};
const sweep = (root: Node) => {
if (root.nodeType === TEXT_NODE) { text(root); return; }
if (root.nodeType !== ELEMENT_NODE) return;
const element = root as Element;
const walker = doc.createTreeWalker(element, SHOW_TEXT);
while (walker.nextNode()) text(walker.currentNode);
for (const name of attributes) {
if (element.hasAttribute(name)) attribute(element, name);
for (const child of element.querySelectorAll(`[${name}]`)) attribute(child, name);
}
};
const observer = new (win as unknown as { MutationObserver: typeof MutationObserver }).MutationObserver(records => {
if (!active) return;
for (const record of records) {
if (record.type === 'characterData') text(record.target);
else if (record.type === 'attributes') { if (record.attributeName) attribute(record.target as Element, record.attributeName); }
else for (const node of record.addedNodes) sweep(node);
}
});
if (map.size) {
if (doc.documentElement) sweep(doc.documentElement);
observer.observe(doc, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: [...attributes] });
}
return {
count: () => count,
dispose() {
if (!active) return;
active = false;
observer.disconnect();
if (!doc.documentElement) return;
const walker = doc.createTreeWalker(doc.documentElement, SHOW_TEXT);
while (walker.nextNode()) {
const node = walker.currentNode;
const kept = texts.get(node);
if (kept && node.nodeValue === kept.applied) node.nodeValue = kept.original;
texts.delete(node);
}
for (const name of attributes) {
for (const element of doc.querySelectorAll(`[${name}]`)) {
const kept = attrs.get(element)?.get(name);
if (kept && element.getAttribute(name) === kept.applied) element.setAttribute(name, kept.original);
}
}
count = 0;
},
};
}