UNPKG

@discoveryjs/discovery

Version:

Frontend framework for rapid data (JSON) analysis, shareable serverless reports and dashboards

34 lines (33 loc) 1 kB
export function createLocationSync(onChange, logger) { const location = globalThis.location; const ignoreHashChange = []; const listener = ({ newURL, oldURL }) => { const newUrlHash = new URL(newURL).hash || "#"; const oldUrlHash = new URL(oldURL).hash || "#"; if (newUrlHash !== ignoreHashChange.shift()) { logger?.debug("locationSync onChange:", oldUrlHash, "->", newUrlHash); ignoreHashChange.length = 0; onChange(newUrlHash, oldUrlHash); } }; addEventListener("hashchange", listener); return { set(hash, replace) { const newHash = hash || "#"; const currentHash = location.hash || "#"; if (currentHash === newHash) { return; } logger?.debug("locationSync set:", newHash, replace); ignoreHashChange.push(hash); if (replace) { location.replace(hash); } else { location.hash = hash; } }, dispose() { removeEventListener("hashchange", listener); } }; }