From 0298432501d883c10b9d4bbaea0e0d414d04f86f Mon Sep 17 00:00:00 2001 From: Austen Adler Date: Sun, 30 Apr 2023 15:28:20 -0400 Subject: [PATCH] Add page permalink --- web-frontend/src/lib/url.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 web-frontend/src/lib/url.js diff --git a/web-frontend/src/lib/url.js b/web-frontend/src/lib/url.js new file mode 100644 index 0000000..096e34c --- /dev/null +++ b/web-frontend/src/lib/url.js @@ -0,0 +1,37 @@ +// From: https://svelte.dev/repl/5abaac000b164aa1aacc6051d5c4f584?version=3.49.0 +import { derived, writable } from 'svelte/store'; + +export function createUrlStore(ssrUrl) { + // Ideally a bundler constant so that it's tree-shakable + if (typeof window === 'undefined') { + const { subscribe } = writable(ssrUrl); + return { subscribe }; + } + + const href = writable(window.location.href); + + const originalPushState = history.pushState; + const originalReplaceState = history.replaceState; + + const updateHref = () => href.set(window.location.href); + + history.pushState = function () { + originalPushState.apply(this, arguments); + updateHref(); + }; + + history.replaceState = function () { + originalReplaceState.apply(this, arguments); + updateHref(); + }; + + window.addEventListener('popstate', updateHref); + window.addEventListener('hashchange', updateHref); + + return { + subscribe: derived(href, ($href) => new URL($href)).subscribe + }; +} + +// If you're using in a pure SPA, you can return a store directly and share it everywhere +export default createUrlStore();