mirror of
https://notabug.org/SuperSaltyGamer/ame
synced 2026-01-15 16:22:56 -03:00
54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
export function fromHTML<T extends HTMLElement>(value: string): T {
|
|
const el = document.createElement("template");
|
|
el.innerHTML = value;
|
|
return el.content.firstElementChild as T;
|
|
}
|
|
|
|
interface WaitForOptions {
|
|
waitSelector?: string;
|
|
timeout?: number;
|
|
}
|
|
|
|
export function observeSelector<T extends HTMLElement>(selector: string, options?: WaitForOptions): Promise<T | null> {
|
|
return new Promise((resolve) => {
|
|
const waitSelector = options?.waitSelector;
|
|
const timeout = options?.timeout ?? 3000;
|
|
|
|
if (timeout !== 0) {
|
|
const el = document.querySelector<T>(selector);
|
|
if (el) {
|
|
resolve(el);
|
|
return;
|
|
}
|
|
}
|
|
|
|
const disposeTimeout = setTimeout(() => {
|
|
if (timeout === 0) return;
|
|
observer.disconnect();
|
|
resolve(null);
|
|
}, timeout);
|
|
|
|
const observer = new MutationObserver(mutations => {
|
|
for (const mutation of mutations) {
|
|
for (const node of Array.from(mutation.addedNodes)) {
|
|
if (!(node instanceof Element)) continue;
|
|
if (!node.matches(waitSelector ?? selector)) continue;
|
|
|
|
if (timeout !== 0) {
|
|
observer.disconnect();
|
|
clearTimeout(disposeTimeout);
|
|
}
|
|
|
|
resolve(waitSelector ? document.querySelector<T>(selector) : node as T);
|
|
return;
|
|
}
|
|
}
|
|
});
|
|
|
|
observer.observe(document.body, {
|
|
childList: true,
|
|
subtree: true
|
|
});
|
|
});
|
|
}
|