aboutsummaryrefslogtreecommitdiffstats
path: root/src/shared/modify-dom.ts
blob: b268ae265d77b0e1b9cb9f0dd118b39ef045d1fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { observeDOM } from "@/shared/observe-dom";

type DOMReplacements = {
	innerHTML?: string;
	[key: string]: string | undefined | null;
};
type DOMModificaitonRule = readonly [string, DOMReplacements];
type DOMModificationRules = (DOMModificaitonRule | null)[];

let domModificationRules: DOMModificationRules = [];
let domModificationFinishedCount = 0;

/**
 * Runs whenever the DOM mutates.  Iterates over pending modification
 * rules; when the selector matches, the element's innerHTML and
 * attributes are updated and the rule is marked as complete.
 */
observeDOM(() => {
	for (let i = 0; i < domModificationRules.length; i++) {
		if (domModificationRules[i]) {
			const element = document.querySelector(domModificationRules[i]![0]) as HTMLElement | null;

			if (element) {
				const attributes = domModificationRules[i]![1];

				if (attributes.innerHTML) {
					element.innerHTML = attributes.innerHTML as string;
				}

				delete attributes.innerHTML;

				for (const attribute in attributes) {
					if (attributes[attribute] === null) {
						element.removeAttribute(attribute);
					} else {
						element.setAttribute(attribute, attributes[attribute] as string);
					}
				}

				domModificationRules[i] = null;
				domModificationFinishedCount++;

				if (domModificationFinishedCount >= domModificationRules.length) {
					return true;
				}
			}
		}
	}

	return false;
});

/**
 * Registers one or more DOM modification rules.  Each rule is a tuple of
 * `[selector, attributeMap]`.  When an element matching the selector is
 * found, its `innerHTML` is replaced (if `attributeMap.innerHTML` is set)
 * and all other entries in the map are applied as `setAttribute` calls
 * (or `removeAttribute` when the value is `null`).
 *
 * @param modificationRules - Array of `[selector, attributes]` rules.
 */
export function modifyDOM(modificationRules: DOMModificationRules) {
	domModificationRules = domModificationRules.concat(modificationRules);
};