-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
134 lines (118 loc) · 2.66 KB
/
index.js
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
/*!
* useKeepState for React v1.2.10
* https://github.com/mousejs/use-keep-state
*
* Copyright xiejiahe and other contributors
* Released under the MIT license
* https://github.com/mousejs/use-keep-state/LICENSE
*
*/
import { useReducer, useEffect, useMemo } from 'react';
let cache = Object.create(null);
const STORAGE_KEY = 'USE-KEEP-STATE';
const toString = Object.prototype.toString;
function isObject(v) {
return toString.call(v) === '[object Object]';
}
window.addEventListener('beforeunload', () => {
setStorage();
});
function destroyState(namespace) {
setTimeout(() => {
if (namespace) {
delete cache[namespace];
} else {
cache = Object.create(null);
window.sessionStorage.removeItem(STORAGE_KEY);
}
}, 25);
}
function useKeepState(initState, options) {
options = useMemo(() => {
return isObject(options)
? {
keepAlive: true,
sessionStorage: false,
...options
} : {
keepAlive: true,
sessionStorage: false,
namespace: options
};
}, [options]);
function reducer(prevState, nextState) {
const value = {
...prevState,
...nextState
};
if (options.namespace) {
const key = String(options.namespace);
if (!cache[key]) {
cache[key] = {};
}
cache[key] = {
storage: options.sessionStorage,
value
}
}
return value;
}
const [state, setState] = useReducer(reducer, initState, v => {
const namespace = options.namespace;
if (!namespace) {
options.keepAlive = false;
}
if (options.keepAlive) {
if (options.sessionStorage && Object.keys(cache).length <= 0) {
cache = getStorage();
}
const value = cache[namespace] && cache[namespace].value;
if (value) {
v = value;
}
}
return v
});
useEffect(() => {
return () => {
const namespace = options.namespace;
if (options.sessionStorage) {
setStorage();
}
if (!options.keepAlive) {
delete cache[namespace];
}
};
}, []);
return [
state,
setState,
destroyState
];
}
function getStorage() {
const content = window.sessionStorage.getItem(STORAGE_KEY);
const o = Object.create(null);
if (!content) return o;
try {
const json = JSON.parse(content);
return json;
} catch {
return o;
}
}
function setStorage(v) {
v = v || cache;
if (!(isObject(v))) return;
const filterNotStorage = {};
for (let k in v) {
if (v[k].storage) {
filterNotStorage[k] = v[k];
}
}
return window.sessionStorage.setItem(
STORAGE_KEY,
JSON.stringify(filterNotStorage)
);
}
export default useKeepState;