-
Notifications
You must be signed in to change notification settings - Fork 5
/
observe.js
507 lines (464 loc) · 12.8 KB
/
observe.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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import { attrNameFromPropName } from './dom.js';
import { buildMergePatch, hasMergePatch } from './jsonMergePatch.js';
/** @typedef {'string' | 'boolean' | 'map' | 'set' | 'float' | 'integer' | 'object' | 'function' | 'array'} ObserverPropertyType */
/**
* @template {ObserverPropertyType} T
* @typedef {(
* T extends 'boolean' ? boolean
* : T extends 'string' ? string
* : T extends 'float' | 'integer' ? number
* : T extends 'array' ? any[]
* : T extends 'object' ? any
* : T extends 'function' ? (...args:any) => any
* : unknown
* )} ParsedObserverPropertyType
*/
/**
* @template {ObserverPropertyType} T1
* @template {any} T2
* @template {Object} [C=any]
* @typedef {Object} ObserverOptions
* @prop {T1} [type]
* @prop {string} [attr]
* @prop {boolean} [readonly]
* @prop {boolean} [enumerable]
* Defaults to false if type is boolean
* @prop {boolean} [nullable]
* @prop {T2} [empty]
* @prop {T2} [value]
* @prop {WeakMap<C,T2>} [values]
* @prop {boolean|'write'|'read'} [reflect]
* Function used when null passed
* @prop {(this:C, value:null|undefined)=>T2} [nullParser]
* @prop {(this:C, value:any)=>T2} [parser]
* Function used when comparing
* @prop {(this:C, a:T2, b:T2)=> any} [diff]
* @prop {(this:C, a:T2, b:T2)=>boolean} [is]
* @prop {(this:C, data:Partial<C>, fn?: () => T2) => T2} [get]
* @prop {(this:C, value: T2, fn?:(value2: T2) => any) => any} [set]
* Simple callback
* @prop {(this:C, oldValue:T2, newValue:T2, changes:any)=>any} [changedCallback]
* Named callback
* @prop {(this:C, name:string, oldValue: T2, newValue: T2, changes:any) => any} [propChangedCallback]
* Attribute callback
* @prop {(this:C, name:string, oldValue: string, newValue: string) => any} [attributeChangedCallback]
* @prop {WeakMap<C, T2>} [computedValues]
* @prop {[keyof C, (this:C, ...args:any[]) => any][]} [watchers]
* @prop {WeakSet<C>} [needsSelfInvalidation]
* @prop {Set<keyof C>} [props]
*/
/**
* @template {ObserverPropertyType} T1
* @template {any} [T2=any]
* @template {string} [K=string]
* @template {Object} [C=any]
* @typedef {ObserverOptions<T1, T2, C> & { key: K, values?: WeakMap<C, T2>; attrValues?: WeakMap<C, string> }} ObserverConfiguration
*/
/**
* @param {ObserverPropertyType} type
* @return {any}
*/
function emptyFromType(type) {
switch (type) {
case 'boolean':
return false;
case 'integer':
case 'float':
return 0;
case 'map':
return new Map();
case 'set':
return new Set();
case 'array':
return [];
case 'object':
return null;
default:
case 'string':
return '';
}
}
/**
* @template {Object} T
* @param {T} proxyTarget
* @param {Set<string>} set
* @param {Set<string>} deepSet
* @param {string} [prefix]
* @return {T}
*/
function buildProxy(proxyTarget, set, deepSet, prefix) {
// @ts-ignore
proxyTarget ??= {};
return new Proxy(proxyTarget, {
get(target, p) {
// @ts-ignore
const value = target[p];
if (typeof p !== 'symbol') {
const arg = prefix ? `${prefix}.${p}` : p;
if (prefix) {
deepSet.add(arg);
} else {
set.add(arg);
}
if (typeof value === 'object' && value != null) {
console.debug('tried to arg poke object get', p, value);
return buildProxy(value, set, deepSet, arg);
}
}
return value;
},
has(target, p) {
const value = Reflect.has(target, p);
if (typeof p !== 'symbol') {
const arg = prefix ? `${prefix}.p` : p;
if (prefix) {
deepSet.add(arg);
} else {
set.add(arg);
}
}
return value;
},
});
}
/**
* @param {ObserverPropertyType} type
* @return {any}
*/
function defaultParserFromType(type) {
switch (type) {
case 'boolean':
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion
* @param {any} v
* @return {boolean}
*/
return (v) => !!v;
case 'integer':
// Calls ToNumber(x)
return Math.round;
case 'float':
/**
* Doesn't support `BigInt` types
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion
* @param {any} v
* @return {number}
*/
return (v) => +v;
case 'map':
return Map;
case 'set':
return Set;
case 'object':
case 'array':
/**
* Reflect self
* @template T
* @param {T} o
* @return {T}
*/
return (o) => o;
default:
case 'string':
/**
* Doesn't support `Symbol` types
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion
* @param {any} v
* @return {string}
*/
return (v) => `${v}`;
}
}
/**
* @param {(data: Partial<any>) => any} fn
* @param {...any} args
* @this {any}
* @return {{
* props: {
* this: string[],
* args: string[][],
* },
* deepPropStrings: {
* this: string[],
* args: string[][],
* },
* deepProps: {
* this: string[][],
* args: string[][][],
* },
* defaultValue: any,
* reusable: boolean,
* }}
*/
export function observeFunction(fn, ...args) {
/** @type {Set<string>} */
const thisPoked = new Set();
/** @type {Set<string>} */
const thisPokedDeep = new Set();
const argWatchers = args.map((arg) => {
const poked = new Set();
const pokedDeep = new Set();
const proxy = buildProxy(arg, poked, pokedDeep);
return { poked, pokedDeep, proxy };
});
const thisProxy = buildProxy(this ?? {}, thisPoked, thisPokedDeep);
const defaultValue = fn.apply(thisProxy, argWatchers.map((watcher) => watcher.proxy));
/* Arrow functions can reused if they don't poke `this` */
const reusable = fn.name ? true : !thisPoked.size;
return {
props: {
this: [...thisPoked],
args: argWatchers.map((watcher) => [...watcher.poked]),
},
deepPropStrings: {
this: [...thisPokedDeep],
args: argWatchers.map((watcher) => [...watcher.pokedDeep]),
},
deepProps: {
this: [...thisPokedDeep].map((deepPropString) => deepPropString.split('.')),
args: argWatchers.map((watcher) => [...watcher.pokedDeep].map((deepPropString) => deepPropString.split('.'))),
},
defaultValue,
reusable,
};
}
/**
* @template {string} K
* @template {ObserverPropertyType} [T1=any]
* @template {any} [T2=ParsedObserverPropertyType<T1>]
* @param {K} name
* @param {T1|ObserverOptions<T1,T2>} [typeOrOptions='string']
* @param {any} [object]
* @return {ObserverConfiguration<T1,T2,K> & ObserverOptions<T1,T2>}
*/
export function parseObserverOptions(name, typeOrOptions, object) {
/** @type {Partial<ObserverOptions<T1,T2>>} */
const options = (typeof typeOrOptions === 'string')
? { type: typeOrOptions }
: typeOrOptions;
let {
watchers, value, readonly,
empty, type,
enumerable, reflect, attr,
nullable, parser, nullParser,
get,
is, diff,
props,
} = options;
watchers ??= [];
readonly ??= false;
if (empty === undefined) {
empty = null;
}
value ??= empty;
if (get && !props) {
// Custom `get` uses computed values.
// Invalidate computed value when dependent `prop` changes
const observeResult = observeFunction(get.bind(object), object, () => value);
value ??= observeResult.defaultValue;
const uniqueProps = new Set([
...observeResult.props.this,
...observeResult.props.args[0],
]);
props = uniqueProps;
}
/** @type {ObserverPropertyType} */
if (!type) {
if (value == null) {
// @ts-ignore
type = 'string';
} else {
const parsed = typeof value;
// @ts-ignore
type = (parsed === 'number')
? (Number.isInteger(value) ? 'integer' : 'number')
: parsed;
}
}
enumerable ??= name[0] !== '_';
reflect ??= enumerable ? type !== 'object' : (attr ? 'write' : false);
attr ??= (reflect ? attrNameFromPropName(name) : null);
nullable ??= (type === 'boolean') ? false : (empty == null);
if (!nullable) {
empty ??= emptyFromType(type);
value ??= empty;
}
// if defined ? value
// else if boolean ? false
// else if onNullish ? false
// else if empty == null
parser ??= defaultParserFromType(type);
if (!nullParser) {
if (nullable) {
nullParser = () => null;
} else {
nullParser = (empty === null)
? () => emptyFromType(type)
: () => empty;
}
}
is ??= (type === 'object')
? (a, b) => !hasMergePatch(a, b)
: ((type === 'array') ? () => false : Object.is);
if (diff === undefined) {
// @ts-ignore
diff = ((type === 'object') ? (a, b) => buildMergePatch(a, b, 'reference') : null);
}
return {
...options,
type,
is,
diff,
attr,
reflect,
readonly,
enumerable,
value,
parser,
nullParser,
key: name,
props,
watchers,
};
}
/**
* @this {ObserverConfiguration<?,?,?>}
* @param {*} value
*/
export function parsePropertyValue(value) {
let newValue = value;
newValue = value == null
? this.nullParser.call(this, value)
: this.parser.call(this, newValue);
}
/**
* @param {ObserverConfiguration<?,?,?,?>} config
* @param {any} oldValue
* @param {any} value
* @return {boolean} changed
*/
function detectChange(config, oldValue, value) {
if (config.get) {
// TODO: Custom getter vs parser
}
// Compute real new value after parsing
const newValue = (value == null)
? config.nullParser.call(this, value)
: config.parser.call(this, value);
// Default change is the newValue
let changes = newValue;
// Null check
if (oldValue == null) {
if (newValue == null) {
// Both nullish
return false;
}
} else if (newValue != null) {
// Both non-null, compare
if (config.diff) {
// Custom change diff
changes = config.diff.call(this, oldValue, newValue);
if (changes == null) {
// No difference
return false;
}
} else if (config.is.call(this, oldValue, newValue)) {
// Non-equal
return false;
}
}
// Commit value
if (config.values) {
config.values.set(this, newValue);
} else {
config.values = new WeakMap([[this, newValue]]);
}
// Emit change
config.propChangedCallback?.call(this, config.key, oldValue, newValue, changes);
config.changedCallback?.call(this, oldValue, newValue, changes);
return true;
}
/**
* @template {ObserverPropertyType} T1
* @template {any} T2
* @template {string} K
* @template [C=any]
* @param {C} object
* @param {K} key
* @param {ObserverOptions<T1, T2, C>} options
* @return {ObserverConfiguration<T1,T2,K,C>}
*/
export function defineObservableProperty(object, key, options) {
/** @type {ObserverConfiguration<T1,T2,K,C>} */
// @ts-ignore
const config = parseObserverOptions(key, options, object);
/**
* @this {C}
* @return {T2}
*/
function internalGet() {
return config.values?.has(this) ? config.values.get(this) : config.value;
}
/**
* @this {C}
* @param {T2} value
* @return {void}
*/
function internalSet(value) {
// @ts-ignore
const oldValue = this[key];
detectChange.call(this, config, oldValue, value);
}
/** @return {void} */
function onInvalidate() {
// Current value is now invalidated. Recompute and check if changed
// eslint-disable-next-line no-multi-assign
const oldValue = config.computedValues?.get(this);
const newValue = this[key];
config.needsSelfInvalidation?.delete(this);
detectChange.call(this, config, oldValue, newValue);
}
if (config.props) {
for (const prop of config.props) {
config.watchers.push([prop, onInvalidate]);
}
}
/**
* @this {C}
* @return {T2}
*/
function cachedGet() {
const newValue = config.get.call(this, this, internalGet.bind(this));
// Store computed value internally. Used by onInvalidate to get previous value
const computedValues = (config.computedValues ??= new WeakMap());
computedValues.set(this, newValue);
return newValue;
}
/**
* @this {C}
* @param {T2} value
* @return {void}
*/
function cachedSet(value) {
if (config.needsSelfInvalidation) {
config.needsSelfInvalidation.add(this);
} else {
config.needsSelfInvalidation = new WeakSet([this]);
}
const oldValue = this[key];
config.set.call(this, value, internalSet.bind(this));
const newValue = this[key];
if (!config.needsSelfInvalidation.has(this)) return;
config.needsSelfInvalidation.delete(this);
detectChange.call(this, config, oldValue, newValue);
}
/** @type {Partial<PropertyDescriptor>} */
const descriptor = {
enumerable: config.enumerable,
configurable: true,
get: config.get ? cachedGet : internalGet,
set: config.set ? cachedSet : internalSet,
};
Object.defineProperty(object, key, descriptor);
return config;
}