-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcomponent-api.ts
422 lines (333 loc) · 10.6 KB
/
component-api.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
import watch, {
set,
unset,
mute,
watchHandlers,
MultipleWatchHandler,
Watcher,
WatchHandlerParams
} from 'core/object/watch';
import { getPropertyInfo } from 'core/component/reflect';
import {
dynamicHandlers,
immediateDynamicHandlers,
cacheStatus,
tiedWatchers,
watcherInitializer,
toComponentObject
} from 'core/component/watch/const';
import { createWatchFn } from 'core/component/watch/create';
import { attachDynamicWatcher } from 'core/component/watch/helpers';
import type { ComponentInterface, RawWatchHandler } from 'core/component/interface';
/**
* Implements watch API to the passed component instance
* @param component
*/
export function implementComponentWatchAPI(component: ComponentInterface): void {
const {
unsafe,
unsafe: {$destructors, meta: {computedFields, watchDependencies, watchPropDependencies, params}},
$renderEngine: {proxyGetters}
} = component;
const
isFunctional = SSR || params.functional === true,
usedHandlers = new Set<Function>();
let timerId: CanUndef<ReturnType<typeof setImmediate>>;
const
fieldsInfo = proxyGetters.field(component),
systemFieldsInfo = proxyGetters.system(component);
const watchOpts = {
deep: true,
withProto: true,
collapse: true,
postfixes: ['Store'],
dependencies: watchDependencies
};
// We need to manage situations when we have accessors with dependencies from external components,
// that's why we iterate over the all dependencies list,
// find external dependencies and attach watchers that directly update state
if (watchDependencies.size > 0) {
const
invalidateComputedCache = createComputedCacheInvalidator(),
broadcastAccessorMutations = createAccessorMutationEmitter();
broadcastAccessorMutations[tiedWatchers] = [];
invalidateComputedCache[tiedWatchers] = broadcastAccessorMutations[tiedWatchers];
const watchOpts = {
deep: true,
withProto: true
};
for (const [path, deps] of watchDependencies) {
const newDeps: typeof deps = [];
let needForkDeps = false;
for (let i = 0; i < deps.length; i++) {
const dep = deps[i];
newDeps[i] = dep;
const
depPath = Object.isString(dep) ? dep : dep.join('.'),
watchInfo = getPropertyInfo(depPath, component);
if (watchInfo.ctx === component && !watchDependencies.has(dep)) {
needForkDeps = true;
newDeps[i] = watchInfo.path;
continue;
}
const invalidateCache = (value, oldValue, info) => {
info = Object.assign(Object.create(info), {
path: Array.concat([], path),
parent: {value, oldValue, info}
});
invalidateComputedCache(value, oldValue, info);
};
attachDynamicWatcher(
component,
watchInfo,
{
...watchOpts,
immediate: true
},
invalidateCache,
immediateDynamicHandlers
);
const broadcastMutations = (mutations, ...args) => {
if (args.length > 0) {
mutations = [Object.cast([mutations, ...args])];
}
const modifiedMutations: Array<[unknown, unknown, WatchHandlerParams]> = [];
for (let i = 0; i < mutations.length; i++) {
const [value, oldValue, info] = mutations[i];
modifiedMutations.push([
value,
oldValue,
Object.assign(Object.create(info), {
path: Array.concat([], path),
originalPath: watchInfo.type === 'mounted' ?
[watchInfo.name, ...info.originalPath] :
info.originalPath,
parent: {value, oldValue, info}
})
]);
}
broadcastAccessorMutations(modifiedMutations);
};
attachDynamicWatcher(component, watchInfo, watchOpts, broadcastMutations, dynamicHandlers);
}
if (needForkDeps) {
watchDependencies.set(path, newDeps);
}
}
}
// Watcher of fields
let fieldsWatcher;
if (isFunctional) {
// Don't force watching of fields until it becomes necessary
fieldsInfo.value[watcherInitializer] = () => {
delete fieldsInfo.value[watcherInitializer];
initFieldsWatcher();
};
} else {
initFieldsWatcher();
}
// Don't force watching of system fields until it becomes necessary
systemFieldsInfo.value[watcherInitializer] = () => {
delete systemFieldsInfo.value[watcherInitializer];
const immediateSystemWatchOpts = {
...watchOpts,
immediate: true
};
const systemFieldsWatcher = watch(
systemFieldsInfo.value,
immediateSystemWatchOpts,
createComputedCacheInvalidator()
);
const accessorsWatcher = watch(
systemFieldsWatcher.proxy,
watchOpts,
createAccessorMutationEmitter()
);
$destructors.push(() => {
systemFieldsWatcher.unwatch();
accessorsWatcher.unwatch();
});
initWatcher(systemFieldsInfo.key, systemFieldsWatcher);
};
// Register the base watch API methods
Object.defineProperty(component, '$watch', {
enumerable: true,
configurable: true,
writable: true,
value: createWatchFn(component)
});
Object.defineProperty(component, '$set', {
enumerable: true,
configurable: true,
writable: true,
value: (obj, path, val) => {
set(obj, path, val, obj[watchHandlers] ?? fieldsWatcher?.proxy[watchHandlers]);
return val;
}
});
Object.defineProperty(component, '$delete', {
enumerable: true,
configurable: true,
writable: true,
value: (obj, path) => {
unset(obj, path, obj[watchHandlers] ?? fieldsWatcher?.proxy[watchHandlers]);
}
});
// Watching of component props.
// The root component and functional components can't watch their props.
if (!isFunctional && !params.root) {
const
props = proxyGetters.prop(component),
propsStore = props.value;
// We need to attach a watcher for a prop object
// and watchers for each non-primitive value of that object, like arrays or maps
if (Object.isTruly(propsStore)) {
const propWatchOpts = {
...watchOpts,
postfixes: ['Prop']
};
// If a component engine does not have the own mechanism of watching,
// we need to wrap a prop object by myself
if (!('watch' in props)) {
const propsWatcher = watch(propsStore, propWatchOpts);
$destructors.push(() => propsWatcher.unwatch());
initWatcher(props.key, propsWatcher);
}
// We need to attach default watchers for all props that can affect component computed fields
if (watchPropDependencies.size > 0) {
for (const [path, props] of watchPropDependencies.entries()) {
const
invalidateComputedCache = createComputedCacheInvalidator(),
broadcastAccessorMutations = createAccessorMutationEmitter();
const
tiedLinks = Object.isArray(path) ? [path] : [[path]];
// Provide a list of connections to the handlers
invalidateComputedCache[tiedWatchers] = tiedLinks;
broadcastAccessorMutations[tiedWatchers] = tiedLinks;
for (const prop of props) {
unsafe.$watch(prop, {...propWatchOpts, flush: 'sync'}, invalidateComputedCache);
unsafe.$watch(prop, propWatchOpts, broadcastAccessorMutations);
}
}
}
}
}
function initWatcher(name: Nullable<string>, watcher: Watcher) {
if (name == null) {
return;
}
mute(watcher.proxy);
watcher.proxy[toComponentObject] = component;
Object.defineProperty(component, name, {
enumerable: true,
configurable: true,
value: watcher.proxy
});
if (isFunctional) {
// We need to track all modified fields of the functional instance
// to restore state if a parent has re-created the component
const w = watch(watcher.proxy, {deep: true, collapse: true, immediate: true}, (_v, _o, i) => {
unsafe.$modifiedFields[String(i.path[0])] = true;
});
$destructors.push(() => w.unwatch());
}
}
function initFieldsWatcher() {
const immediateFieldWatchOpts = {
...watchOpts,
immediate: true
};
fieldsWatcher = watch(
fieldsInfo.value,
immediateFieldWatchOpts,
createComputedCacheInvalidator()
);
const accessorsWatcher = watch(
fieldsWatcher.proxy,
watchOpts,
createAccessorMutationEmitter()
);
$destructors.push(() => {
fieldsWatcher.unwatch();
accessorsWatcher.unwatch();
});
initWatcher(fieldsInfo.key, fieldsWatcher);
}
function createComputedCacheInvalidator(): RawWatchHandler {
// eslint-disable-next-line @typescript-eslint/typedef
return function invalidateComputedCache(val, ...args) {
const
oldVal = args[0],
info = args[1];
if (info == null) {
return;
}
const rootKey = String(info.path[0]);
// If there has been changed properties that can affect memoized computed fields,
// then we need to invalidate these caches
if (computedFields[rootKey]?.get != null) {
delete Object.getOwnPropertyDescriptor(component, rootKey)?.get?.[cacheStatus];
}
// We need to provide this mutation to other listeners.
// This behavior fixes a bug when we have some accessor that depends on a property from another component.
const
ctx = invalidateComputedCache[tiedWatchers] != null ? component : info.root[toComponentObject] ?? component,
currentDynamicHandlers = immediateDynamicHandlers.get(ctx)?.[rootKey];
if (currentDynamicHandlers != null) {
for (const handler of currentDynamicHandlers) {
handler(val, oldVal, info);
}
}
};
}
function createAccessorMutationEmitter(): MultipleWatchHandler {
// eslint-disable-next-line @typescript-eslint/typedef
return function emitAccessorEvents(mutations, ...args) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (args.length > 0) {
mutations = [Object.cast([mutations, ...args])];
}
for (let i = 0; i < mutations.length; i++) {
const [val, oldVal, info] = mutations[i];
const {path} = info;
if (path[path.length - 1] === '__proto__') {
continue;
}
if (info.parent != null) {
const {path: parentPath} = info.parent.info;
if (parentPath[parentPath.length - 1] === '__proto__') {
continue;
}
}
const
rootKey = String(path[0]),
ctx = emitAccessorEvents[tiedWatchers] != null ? component : info.root[toComponentObject] ?? component,
currentDynamicHandlers = dynamicHandlers.get(ctx)?.[rootKey];
if (currentDynamicHandlers != null) {
for (const handler of currentDynamicHandlers) {
// Because we register several watchers (props, fields, etc.) at the same time,
// we need to control that every dynamic handler must be invoked no more than one time per tick
if (usedHandlers.has(handler)) {
continue;
}
handler(val, oldVal, info);
usedHandlers.add(handler);
if (timerId == null) {
timerId = setImmediate(() => {
timerId = undefined;
usedHandlers.clear();
});
}
}
}
}
};
}
}