Simplify ElementOnce observer

This commit is contained in:
2026-03-31 17:42:35 +02:00
parent efdf71d69e
commit 6ac065462a

View File

@@ -61,7 +61,25 @@ const startObserver = (observer: MutationObserver) => {
}); });
}; };
// Refresh *-once components when changes happens // Refresh all ElementOnce components on the document based on their tag name
// They should all be be extended from the `elementOnce` factory
const refreshElement = (componentName: string, tagName: string) => {
for (const element of document.getElementsByTagName(componentName)) {
// Creating a base class would be really complicated, we can use any ElementOnce
// element instead to cast, it doesn't matter
const node = element as LinkOnce;
// We can't guess if an element is compatible before we get one
// We exit the function completely if it's not compatible
if (node.inheritedTagName.toUpperCase() !== tagName.toUpperCase()) {
return;
}
node.refresh();
}
};
// Refresh ElementOnce components when changes happens
const observer = new MutationObserver((mutations: MutationRecord[]) => { const observer = new MutationObserver((mutations: MutationRecord[]) => {
observer.disconnect(); observer.disconnect();
for (const mutation of mutations) { for (const mutation of mutations) {
@@ -69,19 +87,6 @@ const observer = new MutationObserver((mutations: MutationRecord[]) => {
if (node.nodeType !== node.ELEMENT_NODE) { if (node.nodeType !== node.ELEMENT_NODE) {
continue; continue;
} }
const refreshElement = (componentName: string, tagName: string) => {
for (const element of document.getElementsByTagName(componentName)) {
// We can't guess if an element is compatible before we get one
// We exit the function completely if it's not compatible
if (
(element as any).inheritedTagName.toUpperCase() !== tagName.toUpperCase()
) {
return;
}
(element as any).refresh();
}
};
for (const registered of registeredComponents) { for (const registered of registeredComponents) {
refreshElement(registered, (node as HTMLElement).tagName); refreshElement(registered, (node as HTMLElement).tagName);
} }