/** * Get a callback for when the page changes * * @param callback The callback to call when the page changes */ export function pageChangeCallback(callback: (path: string) => void) { let previousUrl = ""; const observer = new MutationObserver(() => { const currentUrl = location.pathname; // Get the current URL without parameters if (currentUrl == previousUrl) { return; } previousUrl = currentUrl; callback(currentUrl); }); const config = { subtree: true, childList: true }; observer.observe(document, config); } /** * Gets the Svelte class of an element * * @param baseClass The base class of the element */ export function getSvelteClass(baseClass: string): string | null { const element = document.querySelector(baseClass); if (!element) { return null; } // Get the Svelte class for (let string of element.className.split(" ")) { if (string.startsWith("svelte-")) { return string; } } return null; } /** * Gets an element from the page and waits * for it to load or be available * * @param selector the selector of the element * @param checkInterval the interval to check for the element */ export function getElement(selector: string, checkInterval: number = 250): Promise { return new Promise((resolve, reject) => { const element = document.querySelector(selector); if (element) { resolve(element as HTMLElement); return; } let checkCount = 0; const checkElement = () => { const element = document.querySelector(selector); if (element) { clearInterval(interval); resolve(element as HTMLElement); return; } checkCount++; if (checkCount * checkInterval >= 2500) { // Give up after 2.5 seconds clearInterval(interval); reject(new Error("Element not found within timeout")); return; } }; const interval = setInterval(checkElement, checkInterval); }); }