about summary refs log tree commit diff stats
path: root/src/pages/options_src/url.js
blob: 010e5b21fee2a8f4876832f3aedb73e606aced67 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// https://svelte.dev/repl/5abaac000b164aa1aacc6051d5c4f584?version=3.59.2

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 = () => {
    originalPushState.apply(this, arguments)
    updateHref()
  }

  history.replaceState = () => {
    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()