blob: 41e87300bce2434f448378478d5ea0f9a1b9c273 (
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
65
66
|
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++) {
const rule = domModificationRules[i];
if (rule?.[0]) {
const element = document.querySelector(rule[0]);
if (element) {
const attributes = rule[1];
if (attributes.innerHTML) {
element.innerHTML = attributes.innerHTML;
}
delete attributes.innerHTML;
for (const attributeName in attributes) {
const attribute = attributes[attributeName];
if (attribute) {
element.setAttribute(attributeName, attribute);
} else {
element.removeAttribute(attributeName);
}
}
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): void {
domModificationRules = domModificationRules.concat(modificationRules);
};
|