-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
76 lines (65 loc) · 1.83 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
import {diff, cloneObject, parseJson} from './utils/index'
import {Operation, OperationType} from './utils/types'
export function createArkPlugin(namespace: string){
const StoreKey = `Store_${namespace}`
let cacheData = {}
function initState(store: any, StoreKey: string){
let newData = globalThis[StoreKey]
if(newData){
// TODO: 深拷贝
cacheData = parseJson(JSON.stringify(newData));
store.replaceState(newData);
}
}
return (store) => {
if (!globalThis[`${StoreKey}_LIST`]) {
globalThis[`${StoreKey}_LIST`] = []
}
globalThis[`${StoreKey}_LIST`].push(store)
initState(store, StoreKey)
store.subscribe((mutation, state) => {
globalThis[StoreKey] = state
let ops = diff(cacheData, state);
if(!ops || ops.length === 0){
return
}
globalThis[`${StoreKey}_LIST`].forEach(iStore => {
if (iStore && iStore !== store) {
resetStore(iStore, ops);
}
});
globalThis[StoreKey] = cloneObject(state);
})
}
}
function setObjectValue(ob:any, keys:Array<string>, value: any){
let temp = ob;
let lastKey = keys.pop();
keys.forEach((key,index) => {
temp = temp[key]
})
temp && lastKey && (temp[lastKey] = value)
}
function resetStore(store: any, operations:Array<Operation>){
operations.forEach(operation=> {
updateStore(store, operation)
})
}
function updateStore(store:any, operation:Operation){
let {type, key, value} = operation;
store._withCommit(() => {
switch(type){
case OperationType.ADD:
setObjectValue(store.state, key, value)
break;
case OperationType.DELETE:
setObjectValue(store.state, key, undefined)
break;
case OperationType.UPDATE:
setObjectValue(store.state, key, value)
break;
default:
break;
}
})
}