aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/modify-dom.ts
blob: 4e36008e451c714ac4b2cb7bdbf8ac052d9628b2 (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
import { observeDOM } from "@/utils/observe-dom";

type Replacements = {
	innerHTML?: string;
	styles?: {
		[key: string]: string
	};
} | {
	[key: string]: string | null
};

export class DOMModifier {
	selector: string;
	replaced: Replacements;
	constructor(selector: string, replaced: Replacements) {
		this.selector = selector;
		this.replaced = replaced;
	}
}

export const modifyDOM = (elements: (DOMModifier | null)[]) => {
	let count = 0;

	observeDOM(() => {
		for (let i = 0; i < elements.length; i++) {
			if (elements[i]) {
				const element = document.querySelector(elements[i]!.selector) as HTMLElement | null;
				if (element) {
					const attributes = elements[i]!.replaced as any;
					if (attributes.innerHTML) {
						element.innerHTML = attributes.innerHTML;
					}
					if (attributes.styles) {
						for (const styleType in attributes.styles) {
							element.style[styleType as any] = attributes.styles[styleType];
						}
					}
					delete attributes.innerHTML;
					delete attributes.styles;
					for (const attribute in attributes) {
						if (attributes[attribute] === null) {
							element.removeAttribute(attribute);
						} else {
							element.setAttribute(attribute, attributes[attribute]);
						}
					}
					elements[i] = null;
					count++;
					if (count >= elements.length) {
						return true;
					}
				}
			}
		}

		return false;
	});
};