1 | /* eslint-env browser */
|
2 |
|
3 | /**
|
4 | * Isomorphic variable storage.
|
5 | *
|
6 | * Uses LocalStorage in the browser and falls back to in-memory storage.
|
7 | *
|
8 | * @module storage
|
9 | */
|
10 |
|
11 | /* c8 ignore start */
|
12 | class VarStoragePolyfill {
|
13 | constructor () {
|
14 | this.map = new Map()
|
15 | }
|
16 |
|
17 | /**
|
18 | * @param {string} key
|
19 | * @param {any} newValue
|
20 | */
|
21 | setItem (key, newValue) {
|
22 | this.map.set(key, newValue)
|
23 | }
|
24 |
|
25 | /**
|
26 | * @param {string} key
|
27 | */
|
28 | getItem (key) {
|
29 | return this.map.get(key)
|
30 | }
|
31 | }
|
32 | /* c8 ignore stop */
|
33 |
|
34 | /**
|
35 | * @type {any}
|
36 | */
|
37 | let _localStorage = new VarStoragePolyfill()
|
38 | let usePolyfill = true
|
39 |
|
40 | /* c8 ignore start */
|
41 | try {
|
42 | // if the same-origin rule is violated, accessing localStorage might thrown an error
|
43 | if (typeof localStorage !== 'undefined' && localStorage) {
|
44 | _localStorage = localStorage
|
45 | usePolyfill = false
|
46 | }
|
47 | } catch (e) { }
|
48 | /* c8 ignore stop */
|
49 |
|
50 | /**
|
51 | * This is basically localStorage in browser, or a polyfill in nodejs
|
52 | */
|
53 | /* c8 ignore next */
|
54 | export const varStorage = _localStorage
|
55 |
|
56 | /**
|
57 | * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.
|
58 | *
|
59 | * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler
|
60 | * @function
|
61 | */
|
62 | /* c8 ignore next */
|
63 | export const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))
|
64 |
|
65 | /**
|
66 | * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.
|
67 | *
|
68 | * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler
|
69 | * @function
|
70 | */
|
71 | /* c8 ignore next */
|
72 | export const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))
|