-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmemo-context.js
151 lines (113 loc) · 2.63 KB
/
memo-context.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import {
createContext,
useContext,
useMemo,
useEffect,
useState,
createElement,
useLayoutEffect,
} from "react";
const actualDeps = Symbol();
function Store() {
const listeners = new Set();
let proxy = {};
let newKeys = false;
let changed = false;
const instance = {
s: subscribe,
e: emit,
u: update,
p: proxy,
v: undefined,
};
function update(nextValue) {
if (nextValue === instance.v) return;
changed = true;
for (const key in nextValue) {
if (!(key in proxy)) {
Object.defineProperty(proxy, key, {
get: function () {
this[actualDeps].add(key);
return this[actualValue][key];
},
});
newKeys = true;
}
}
instance.v = nextValue;
}
function subscribe(callback) {
listeners.add(callback);
return () => listeners.delete(callback);
}
function emit() {
if (!changed) return;
listeners.forEach((callback) => {
callback(newKeys);
});
newKeys = false;
changed = false;
}
return instance;
}
const actualValue = Symbol();
function Tracker() {
const deps = new Set();
let prevValue;
const instance = {
v: prevValue,
t: track,
};
function track(value, proxy) {
if (value === prevValue) return false;
let changed = false;
deps.forEach((key) => {
if (!changed) changed = value[key] !== prevValue[key];
});
//Creates a new reference to make equality checks work
instance.v = Object.create(proxy);
instance.v[actualValue] = value;
instance.v[actualDeps] = deps;
prevValue = value;
return changed;
}
return instance;
}
export function createMemoContext(defaultValue) {
const c = createContext(defaultValue);
const instance = {
c,
Provider,
Consumer,
d: defaultValue,
};
function Provider({ value, children }) {
const store = useMemo(Store, []);
store.u(value);
useLayoutEffect(store.e);
return createElement(c.Provider, { value: store }, children);
}
function Consumer({ children }) {
return children(useMemoContext(instance));
}
return instance;
}
export function useMemoContext(context) {
const store = useContext(context.c);
const tracker = useMemo(() => (store !== context.d ? Tracker() : undefined), [
store,
]);
const requestUpdate = useState()[1];
tracker && tracker.t(store.v, store.p);
useEffect(
() =>
tracker &&
store.s((forceRender) => {
if (tracker.t(store.v, store.p) || forceRender) {
requestUpdate(tracker.v);
}
}),
[tracker]
);
return tracker ? tracker.v : store;
}