-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugins.ts
57 lines (52 loc) · 1.66 KB
/
plugins.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
import { IGenericModule, IPlugin, IState } from './interfaces'
export interface ILocalStoragePluginState<S extends IState> {
state: S
__version: number
}
const migrateState = <S extends IState>(oldState: IState, newState: S): S => {
const migratedState = {} as S
for (const key in newState) {
const [oldValue, newValue] = [oldState[key], newState[key]]
if (key in oldState && typeof oldValue === typeof newValue) {
migratedState[key as keyof S] = oldValue
} else {
migratedState[key as keyof S] = newValue
}
}
return migratedState
}
export const LocalStoragePlugin = <S extends IState>(
module: IGenericModule<S>,
): IPlugin<S> => {
const onDataChange = (value: S): S => {
const payload: ILocalStoragePluginState<S> = {
state: value,
__version: module.options.version,
}
localStorage.setItem(module.options.name, JSON.stringify(payload))
return value
}
return {
onStateInit: (state: S) => {
const { name, version } = module.options
const stateString = localStorage.getItem(name)
let initializedState: S
if (!stateString) {
initializedState = state
} else {
const payload = (JSON.parse(stateString) || {}) as ILocalStoragePluginState<S>
if (payload.__version !== version) {
console.warn(
`Upgrade module '${name}' from ${payload.__version ?? 0} to ${version}.\n` +
'States has been migrated',
)
initializedState = migrateState(payload.state ?? {}, state)
} else {
initializedState = payload.state
}
}
return onDataChange(initializedState)
},
onDataChange,
}
}