-
-
Notifications
You must be signed in to change notification settings - Fork 648
/
Copy pathatomWithStorage.ts
193 lines (175 loc) · 5.43 KB
/
atomWithStorage.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import { atom } from '../../vanilla.ts'
import type { WritableAtom } from '../../vanilla.ts'
import { RESET } from './constants.ts'
const isPromiseLike = (x: unknown): x is PromiseLike<unknown> =>
typeof (x as any)?.then === 'function'
type Unsubscribe = () => void
type SetStateActionWithReset<Value> =
| Value
| typeof RESET
| ((prev: Value) => Value | typeof RESET)
export interface AsyncStorage<Value> {
getItem: (key: string, initialValue: Value) => PromiseLike<Value>
setItem: (key: string, newValue: Value) => PromiseLike<void>
removeItem: (key: string) => PromiseLike<void>
subscribe?: (
key: string,
callback: (value: Value) => void,
initialValue: Value
) => Unsubscribe
}
export interface SyncStorage<Value> {
getItem: (key: string, initialValue: Value) => Value
setItem: (key: string, newValue: Value) => void
removeItem: (key: string) => void
subscribe?: (
key: string,
callback: (value: Value) => void,
initialValue: Value
) => Unsubscribe
}
export interface AsyncStringStorage {
getItem: (key: string) => PromiseLike<string | null>
setItem: (key: string, newValue: string) => PromiseLike<void>
removeItem: (key: string) => PromiseLike<void>
}
export interface SyncStringStorage {
getItem: (key: string) => string | null
setItem: (key: string, newValue: string) => void
removeItem: (key: string) => void
}
export function createJSONStorage<Value>(
getStringStorage: () => AsyncStringStorage
): AsyncStorage<Value>
export function createJSONStorage<Value>(
getStringStorage: () => SyncStringStorage
): SyncStorage<Value>
export function createJSONStorage<Value>(
getStringStorage: () => AsyncStringStorage | SyncStringStorage | undefined
): AsyncStorage<Value> | SyncStorage<Value> {
let lastStr: string | undefined
let lastValue: any
const storage: AsyncStorage<Value> | SyncStorage<Value> = {
getItem: (key, initialValue) => {
const parse = (str: string | null) => {
str = str || ''
if (lastStr !== str) {
try {
lastValue = JSON.parse(str)
} catch {
return initialValue
}
lastStr = str
}
return lastValue
}
const str = getStringStorage()?.getItem(key) ?? null
if (isPromiseLike(str)) {
return str.then(parse)
}
return parse(str)
},
setItem: (key, newValue) =>
getStringStorage()?.setItem(key, JSON.stringify(newValue)),
removeItem: (key) => getStringStorage()?.removeItem(key),
}
if (
typeof window !== 'undefined' &&
typeof window.addEventListener === 'function'
) {
storage.subscribe = (key, callback, initialValue) => {
if (!(getStringStorage() instanceof window.Storage)) {
return () => {}
}
const storageEventCallback = (e: StorageEvent) => {
if (e.storageArea === getStringStorage() && e.key === key) {
let newValue: Value
try {
newValue = JSON.parse(e.newValue || '')
} catch {
newValue = initialValue
}
callback(newValue)
}
}
window.addEventListener('storage', storageEventCallback)
return () => {
window.removeEventListener('storage', storageEventCallback)
}
}
}
return storage
}
const defaultStorage = createJSONStorage(() =>
typeof window !== 'undefined'
? window.localStorage
: (undefined as unknown as Storage)
)
export function atomWithStorage<Value>(
key: string,
initialValue: Value,
storage: AsyncStorage<Value>,
unstable_options?: { unstable_getOnInit?: boolean }
): WritableAtom<
PromiseLike<Value> | Value,
[SetStateActionWithReset<PromiseLike<Value> | Value>],
PromiseLike<void>
>
export function atomWithStorage<Value>(
key: string,
initialValue: Value,
storage?: SyncStorage<Value>,
unstable_options?: { unstable_getOnInit?: boolean }
): WritableAtom<Value, [SetStateActionWithReset<Value>], void>
export function atomWithStorage<Value>(
key: string,
initialValue: Value,
storage:
| SyncStorage<Value>
| AsyncStorage<Value> = defaultStorage as SyncStorage<Value>,
unstable_options?: { unstable_getOnInit?: boolean }
): any {
const getOnInit = unstable_options?.unstable_getOnInit
const baseAtom = atom(
getOnInit ? storage.getItem(key, initialValue) : initialValue
)
if (import.meta.env?.MODE !== 'production') {
baseAtom.debugPrivate = true
}
baseAtom.onMount = (setAtom) => {
if (!getOnInit) {
setAtom(storage.getItem(key, initialValue))
}
let unsub: Unsubscribe | undefined
if (storage.subscribe) {
unsub = storage.subscribe(key, setAtom, initialValue)
}
return unsub
}
const anAtom = atom(
(get) => get(baseAtom),
(get, set, update: SetStateActionWithReset<PromiseLike<Value> | Value>) => {
const nextValue =
typeof update === 'function'
? (
update as (
prev: PromiseLike<Value> | Value
) => PromiseLike<Value> | Value | typeof RESET
)(get(baseAtom))
: update
if (nextValue === RESET) {
set(baseAtom, initialValue)
return storage.removeItem(key)
}
if (isPromiseLike(nextValue)) {
return nextValue.then((resolvedValue) => {
set(baseAtom, resolvedValue)
return storage.setItem(key, resolvedValue)
})
}
set(baseAtom, nextValue)
return storage.setItem(key, nextValue)
}
)
return anAtom
}