-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathindex.ts
145 lines (118 loc) · 4.48 KB
/
index.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import { writable as internal, type Writable } from 'svelte/store'
declare type Updater<T> = (value: T) => T;
declare type StoreDict<T> = { [key: string]: Persisted<T> }
export interface Persisted<T> extends Writable<T> {
reset: () => void
}
/* eslint-disable @typescript-eslint/no-explicit-any */
interface Stores {
local: StoreDict<any>,
session: StoreDict<any>,
}
const stores: Stores = {
local: {},
session: {}
}
export interface Serializer<T> {
parse(text: string): T
stringify(object: T): string
}
export type StorageType = 'local' | 'session'
export interface Options<StoreType, SerializerType> {
serializer?: Serializer<SerializerType>
storage?: StorageType,
syncTabs?: boolean,
onError?: (e: unknown) => void
onWriteError?: (e: unknown) => void
onParseError?: (newValue: string | null, e: unknown) => void
beforeRead?: (val: SerializerType) => StoreType
beforeWrite?: (val: StoreType) => SerializerType
}
function getStorage(type: StorageType) {
return type === 'local' ? localStorage : sessionStorage
}
/** @deprecated `writable()` has been renamed to `persisted()` */
export function writable<StoreType, SerializerType = StoreType>(key: string, initialValue: StoreType, options?: Options<StoreType, SerializerType>): Persisted<StoreType> {
console.warn("writable() has been deprecated. Please use persisted() instead.\n\nchange:\n\nimport { writable } from 'svelte-persisted-store'\n\nto:\n\nimport { persisted } from 'svelte-persisted-store'")
return persisted<StoreType, SerializerType>(key, initialValue, options)
}
export function persisted<StoreType, SerializerType = StoreType>(key: string, initialValue: StoreType, options?: Options<StoreType, SerializerType>): Persisted<StoreType> {
if (options?.onError) console.warn("onError has been deprecated. Please use onWriteError instead")
const storageType = options?.storage ?? 'local'
const browser = typeof (window) !== 'undefined' && typeof (document) !== 'undefined'
if (browser && stores[storageType][key]) {
return stores[storageType][key]
}
const serializer = options?.serializer ?? JSON
const syncTabs = options?.syncTabs ?? true
const onWriteError = options?.onWriteError ?? options?.onError ?? ((e) => console.error(`Error when writing value from persisted store "${key}" to ${storageType}`, e))
const onParseError = options?.onParseError ?? ((newVal, e) => console.error(`Error when parsing ${newVal ? '"' + newVal + '"' : "value"} from persisted store "${key}"`, e))
const beforeRead = options?.beforeRead ?? ((val) => val as unknown as StoreType)
const beforeWrite = options?.beforeWrite ?? ((val) => val as unknown as SerializerType)
const storage = browser ? getStorage(storageType) : null
function updateStorage(key: string, value: StoreType) {
const newVal = beforeWrite(value)
try {
storage?.setItem(key, serializer.stringify(newVal))
} catch (e) {
onWriteError(e)
}
}
function maybeLoadInitial(): StoreType {
function serialize(json: any) {
try {
return <SerializerType>serializer.parse(json)
} catch (e) {
onParseError(json, e)
}
}
const json = storage?.getItem(key)
if (json == null) return initialValue
const serialized = serialize(json)
if (serialized == null) return initialValue
const newVal = beforeRead(serialized)
return newVal
}
const initial = maybeLoadInitial()
const store = internal(initial, (set) => {
if (browser && storageType == 'local' && syncTabs) {
const handleStorage = (event: StorageEvent) => {
if (event.key === key && event.newValue) {
let newVal: any
try {
newVal = serializer.parse(event.newValue)
} catch (e) {
onParseError(event.newValue, e)
return
}
const processedVal = beforeRead(newVal)
set(processedVal)
}
}
window.addEventListener("storage", handleStorage)
return () => window.removeEventListener("storage", handleStorage)
}
})
const { subscribe, set } = store
const persistedStore = {
set(value: StoreType) {
set(value)
updateStorage(key, value)
},
update(callback: Updater<StoreType>) {
return store.update((last) => {
const value = callback(last)
updateStorage(key, value)
return value
})
},
reset() {
this.set(initialValue)
},
subscribe
}
if (browser) {
stores[storageType][key] = persistedStore
}
return persistedStore
}