@tldraw/state 5.4.0-next.ef99ab47e5ce → 5.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DOCS.md +64 -63
- package/README.md +35 -36
- package/dist-cjs/index.d.ts +26 -27
- package/dist-cjs/index.js +1 -1
- package/dist-cjs/lib/ArraySet.js +47 -144
- package/dist-cjs/lib/ArraySet.js.map +2 -2
- package/dist-cjs/lib/Atom.js +10 -25
- package/dist-cjs/lib/Atom.js.map +2 -2
- package/dist-cjs/lib/Computed.js +36 -61
- package/dist-cjs/lib/Computed.js.map +2 -2
- package/dist-cjs/lib/EffectScheduler.js +4 -2
- package/dist-cjs/lib/EffectScheduler.js.map +2 -2
- package/dist-cjs/lib/HistoryBuffer.js +8 -8
- package/dist-cjs/lib/HistoryBuffer.js.map +2 -2
- package/dist-cjs/lib/capture.js.map +2 -2
- package/dist-cjs/lib/constants.js.map +2 -2
- package/dist-cjs/lib/helpers.js +3 -11
- package/dist-cjs/lib/helpers.js.map +2 -2
- package/dist-cjs/lib/localStorageAtom.js +7 -2
- package/dist-cjs/lib/localStorageAtom.js.map +2 -2
- package/dist-cjs/lib/transactions.js +37 -49
- package/dist-cjs/lib/transactions.js.map +2 -2
- package/dist-cjs/lib/types.js.map +1 -1
- package/dist-esm/index.d.mts +26 -27
- package/dist-esm/index.mjs +1 -1
- package/dist-esm/lib/ArraySet.mjs +47 -144
- package/dist-esm/lib/ArraySet.mjs.map +2 -2
- package/dist-esm/lib/Atom.mjs +10 -25
- package/dist-esm/lib/Atom.mjs.map +2 -2
- package/dist-esm/lib/Computed.mjs +37 -62
- package/dist-esm/lib/Computed.mjs.map +2 -2
- package/dist-esm/lib/EffectScheduler.mjs +4 -2
- package/dist-esm/lib/EffectScheduler.mjs.map +2 -2
- package/dist-esm/lib/HistoryBuffer.mjs +8 -8
- package/dist-esm/lib/HistoryBuffer.mjs.map +2 -2
- package/dist-esm/lib/capture.mjs.map +2 -2
- package/dist-esm/lib/constants.mjs.map +2 -2
- package/dist-esm/lib/helpers.mjs +3 -11
- package/dist-esm/lib/helpers.mjs.map +2 -2
- package/dist-esm/lib/localStorageAtom.mjs +7 -2
- package/dist-esm/lib/localStorageAtom.mjs.map +2 -2
- package/dist-esm/lib/transactions.mjs +37 -49
- package/dist-esm/lib/transactions.mjs.map +2 -2
- package/dist-esm/lib/types.mjs.map +1 -1
- package/package.json +8 -2
- package/src/lib/ArraySet.ts +68 -176
- package/src/lib/Atom.ts +22 -27
- package/src/lib/Computed.ts +68 -95
- package/src/lib/EffectScheduler.ts +13 -9
- package/src/lib/HistoryBuffer.ts +12 -10
- package/src/lib/__tests__/ArraySet.test.ts +39 -13
- package/src/lib/__tests__/EffectScheduler.test.ts +69 -0
- package/src/lib/__tests__/HistoryBuffer.test.ts +6 -3
- package/src/lib/__tests__/computed.test.ts +75 -0
- package/src/lib/__tests__/deferAsyncEffects.test.ts +23 -0
- package/src/lib/__tests__/errors.test.ts +24 -0
- package/src/lib/__tests__/fuzz.tlstate.test.ts +97 -8
- package/src/lib/__tests__/helpers.test.ts +7 -11
- package/src/lib/__tests__/history.test.ts +32 -2
- package/src/lib/__tests__/localStorageAtom.test.ts +15 -0
- package/src/lib/__tests__/propagation.test.ts +104 -1
- package/src/lib/__tests__/transactions.test.ts +23 -0
- package/src/lib/capture.ts +12 -12
- package/src/lib/constants.ts +3 -22
- package/src/lib/helpers.ts +19 -139
- package/src/lib/localStorageAtom.ts +9 -2
- package/src/lib/transactions.ts +68 -98
- package/src/lib/types.ts +7 -7
package/src/lib/Computed.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { maybeCaptureParent, startCapturingParents, stopCapturingParents } from
|
|
|
5
5
|
import { GLOBAL_START_EPOCH } from './constants'
|
|
6
6
|
import { EMPTY_ARRAY, equals, haveParentsChanged, singleton } from './helpers'
|
|
7
7
|
import { HistoryBuffer } from './HistoryBuffer'
|
|
8
|
-
import { getGlobalEpoch,
|
|
8
|
+
import { getGlobalEpoch, getIsInTransaction } from './transactions'
|
|
9
9
|
import { Child, ComputeDiff, RESET_VALUE, Signal } from './types'
|
|
10
10
|
import { logComputedGetterWarning } from './warnings'
|
|
11
11
|
|
|
@@ -150,7 +150,7 @@ export interface ComputedOptions<Value, Diff> {
|
|
|
150
150
|
/**
|
|
151
151
|
* The maximum number of diffs to keep in the history buffer.
|
|
152
152
|
*
|
|
153
|
-
* If you don't need
|
|
153
|
+
* If you don't need diffs, leave this as `undefined` and no history buffer will be created. Diffs supplied via {@link withDiff} or {@link ComputedOptions.computeDiff} are only recorded when this is set.
|
|
154
154
|
*
|
|
155
155
|
* If you expect the value to be part of an active effect subscription all the time, and to not change multiple times inside of a single transaction, you can set this to a relatively low number (e.g. 10).
|
|
156
156
|
*
|
|
@@ -217,7 +217,8 @@ class __UNSAFE__Computed<Value, Diff = unknown> implements Computed<Value, Diff>
|
|
|
217
217
|
__debug_ancestor_epochs__: Map<Signal<any, any>, number> | null = null
|
|
218
218
|
|
|
219
219
|
/**
|
|
220
|
-
* The epoch when the reactor was last checked.
|
|
220
|
+
* The epoch when the reactor was last checked. Advances on every check, including ones that
|
|
221
|
+
* find no change, unlike `lastChangedEpoch`.
|
|
221
222
|
*/
|
|
222
223
|
private lastCheckedEpoch = GLOBAL_START_EPOCH
|
|
223
224
|
|
|
@@ -272,9 +273,13 @@ class __UNSAFE__Computed<Value, Diff = unknown> implements Computed<Value, Diff>
|
|
|
272
273
|
if (
|
|
273
274
|
!isNew &&
|
|
274
275
|
(this.lastCheckedEpoch === globalEpoch ||
|
|
276
|
+
// Every ancestor change to an actively-listening computed traverses it (`flushChanges`),
|
|
277
|
+
// so if it hasn't been traversed since it was last checked the O(parents) scan can be
|
|
278
|
+
// skipped. Not valid while a transaction is open (changes traverse at commit), and only
|
|
279
|
+
// if it was up to date when attached (see `attach` in helpers.ts).
|
|
275
280
|
(this.isActivelyListening &&
|
|
276
|
-
|
|
277
|
-
this.lastTraversedEpoch
|
|
281
|
+
!getIsInTransaction() &&
|
|
282
|
+
this.lastTraversedEpoch <= this.lastCheckedEpoch) ||
|
|
278
283
|
!haveParentsChanged(this))
|
|
279
284
|
) {
|
|
280
285
|
this.lastCheckedEpoch = globalEpoch
|
|
@@ -299,13 +304,16 @@ class __UNSAFE__Computed<Value, Diff = unknown> implements Computed<Value, Diff>
|
|
|
299
304
|
const epoch = getGlobalEpoch()
|
|
300
305
|
if (isUninitialized || !this.isEqual(this.state, newState)) {
|
|
301
306
|
if (this.historyBuffer && !isUninitialized) {
|
|
307
|
+
// Only `undefined` means "no diff supplied"; `null` can be a legitimate diff.
|
|
302
308
|
const diff = result instanceof WithDiff ? result.diff : undefined
|
|
303
309
|
this.historyBuffer.pushEntry(
|
|
304
310
|
this.lastChangedEpoch,
|
|
305
311
|
epoch,
|
|
306
|
-
diff
|
|
307
|
-
|
|
308
|
-
|
|
312
|
+
diff !== undefined
|
|
313
|
+
? diff
|
|
314
|
+
: this.computeDiff
|
|
315
|
+
? this.computeDiff(this.state, newState, this.lastCheckedEpoch, epoch)
|
|
316
|
+
: RESET_VALUE
|
|
309
317
|
)
|
|
310
318
|
}
|
|
311
319
|
this.lastChangedEpoch = epoch
|
|
@@ -318,7 +326,12 @@ class __UNSAFE__Computed<Value, Diff = unknown> implements Computed<Value, Diff>
|
|
|
318
326
|
} catch (e) {
|
|
319
327
|
// if a derived value throws an error, we reset the state to UNINITIALIZED
|
|
320
328
|
const epoch = getGlobalEpoch()
|
|
321
|
-
|
|
329
|
+
// Entering the error state (from a value, or from never having computed) is a change;
|
|
330
|
+
// throwing again while already in it is not. Checking `error` rather than `state` matters
|
|
331
|
+
// for a first run that throws: `state` is already UNINITIALIZED then, and leaving
|
|
332
|
+
// `lastChangedEpoch` at GLOBAL_START_EPOCH would keep `isNew` true and re-run `derive` on
|
|
333
|
+
// every read instead of rethrowing the cached error.
|
|
334
|
+
if (this.error === null) {
|
|
322
335
|
this.state = UNINITIALIZED as unknown as Value
|
|
323
336
|
this.lastChangedEpoch = epoch
|
|
324
337
|
}
|
|
@@ -374,74 +387,23 @@ export const _Computed = singleton('Computed', () => __UNSAFE__Computed)
|
|
|
374
387
|
*/
|
|
375
388
|
export type _Computed = InstanceType<typeof __UNSAFE__Computed>
|
|
376
389
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
_target: any,
|
|
380
|
-
key: string,
|
|
381
|
-
descriptor: PropertyDescriptor
|
|
382
|
-
) {
|
|
383
|
-
const originalMethod = descriptor.value
|
|
384
|
-
const derivationKey = Symbol.for('__@tldraw/state__computed__' + key)
|
|
385
|
-
|
|
386
|
-
descriptor.value = function (this: any) {
|
|
387
|
-
let d = this[derivationKey] as Computed<any> | undefined
|
|
388
|
-
|
|
389
|
-
if (!d) {
|
|
390
|
-
d = new _Computed(key, originalMethod!.bind(this) as any, options)
|
|
391
|
-
Object.defineProperty(this, derivationKey, {
|
|
392
|
-
enumerable: false,
|
|
393
|
-
configurable: false,
|
|
394
|
-
writable: false,
|
|
395
|
-
value: d,
|
|
396
|
-
})
|
|
397
|
-
}
|
|
398
|
-
return d.get()
|
|
399
|
-
}
|
|
400
|
-
descriptor.value[isComputedMethodKey] = true
|
|
401
|
-
|
|
402
|
-
return descriptor
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
function computedGetterLegacyDecorator(
|
|
406
|
-
options: ComputedOptions<any, any> = {},
|
|
407
|
-
_target: any,
|
|
408
|
-
key: string,
|
|
409
|
-
descriptor: PropertyDescriptor
|
|
410
|
-
) {
|
|
411
|
-
const originalMethod = descriptor.get
|
|
412
|
-
const derivationKey = Symbol.for('__@tldraw/state__computed__' + key)
|
|
390
|
+
// Set on every decorated wrapper: the symbol its per-instance computed is stored under.
|
|
391
|
+
const derivationKeyKey = '@@__computedDerivationKey__@@'
|
|
413
392
|
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
writable: false,
|
|
423
|
-
value: d,
|
|
424
|
-
})
|
|
425
|
-
}
|
|
426
|
-
return d.get()
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
return descriptor
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
function computedMethodTc39Decorator<This extends object, Value>(
|
|
433
|
-
options: ComputedOptions<Value, any>,
|
|
434
|
-
compute: () => Value,
|
|
435
|
-
context: ClassMethodDecoratorContext<This, () => Value>
|
|
436
|
-
) {
|
|
437
|
-
assert(context.kind === 'method', '@computed can only be used on methods')
|
|
438
|
-
const derivationKey = Symbol.for('__@tldraw/state__computed__' + String(context.name))
|
|
393
|
+
/**
|
|
394
|
+
* Builds the method (or getter) body that `@computed` installs: a per-instance, lazily-created
|
|
395
|
+
* computed over the original method. The storage symbol is unique per decoration rather than
|
|
396
|
+
* `Symbol.for(name)` so that a subclass which overrides a `@computed` method and calls
|
|
397
|
+
* `super.method()` reaches the superclass's computed instead of re-entering its own.
|
|
398
|
+
*/
|
|
399
|
+
function makeComputedWrapper(name: string, compute: () => any, options: ComputedOptions<any, any>) {
|
|
400
|
+
const derivationKey = Symbol('__@tldraw/state__computed__' + name)
|
|
439
401
|
|
|
440
|
-
const
|
|
402
|
+
const wrapper = function (this: any) {
|
|
441
403
|
let d = this[derivationKey] as Computed<any> | undefined
|
|
442
404
|
|
|
443
405
|
if (!d) {
|
|
444
|
-
d = new _Computed(
|
|
406
|
+
d = new _Computed(name, compute.bind(this) as any, options)
|
|
445
407
|
Object.defineProperty(this, derivationKey, {
|
|
446
408
|
enumerable: false,
|
|
447
409
|
configurable: false,
|
|
@@ -450,9 +412,9 @@ function computedMethodTc39Decorator<This extends object, Value>(
|
|
|
450
412
|
})
|
|
451
413
|
}
|
|
452
414
|
return d.get()
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
return
|
|
415
|
+
} as any
|
|
416
|
+
wrapper[derivationKeyKey] = derivationKey
|
|
417
|
+
return wrapper
|
|
456
418
|
}
|
|
457
419
|
|
|
458
420
|
function computedDecorator(
|
|
@@ -463,20 +425,20 @@ function computedDecorator(
|
|
|
463
425
|
) {
|
|
464
426
|
if (args.length === 2) {
|
|
465
427
|
const [originalMethod, context] = args
|
|
466
|
-
|
|
428
|
+
assert(context.kind === 'method', '@computed can only be used on methods')
|
|
429
|
+
return makeComputedWrapper(String(context.name), originalMethod, options)
|
|
467
430
|
} else {
|
|
468
431
|
const [_target, key, descriptor] = args
|
|
469
432
|
if (descriptor.get) {
|
|
470
433
|
logComputedGetterWarning()
|
|
471
|
-
|
|
434
|
+
descriptor.get = makeComputedWrapper(key, descriptor.get, options)
|
|
472
435
|
} else {
|
|
473
|
-
|
|
436
|
+
descriptor.value = makeComputedWrapper(key, descriptor.value, options)
|
|
474
437
|
}
|
|
438
|
+
return descriptor
|
|
475
439
|
}
|
|
476
440
|
}
|
|
477
441
|
|
|
478
|
-
const isComputedMethodKey = '@@__isComputedMethod__@@'
|
|
479
|
-
|
|
480
442
|
/**
|
|
481
443
|
* Retrieves the underlying computed instance for a given property created with the `computed`
|
|
482
444
|
* decorator.
|
|
@@ -485,7 +447,7 @@ const isComputedMethodKey = '@@__isComputedMethod__@@'
|
|
|
485
447
|
* ```ts
|
|
486
448
|
* class Counter {
|
|
487
449
|
* max = 100
|
|
488
|
-
* count = atom(0)
|
|
450
|
+
* count = atom('count', 0)
|
|
489
451
|
*
|
|
490
452
|
* @computed getRemaining() {
|
|
491
453
|
* return this.max - this.count.get()
|
|
@@ -506,19 +468,29 @@ const isComputedMethodKey = '@@__isComputedMethod__@@'
|
|
|
506
468
|
export function getComputedInstance<Obj extends object, Prop extends keyof Obj>(
|
|
507
469
|
obj: Obj,
|
|
508
470
|
propertyName: Prop
|
|
509
|
-
): Computed<Obj[Prop]> {
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
const
|
|
515
|
-
|
|
516
|
-
|
|
471
|
+
): Computed<Obj[Prop] extends () => infer Value ? Value : Obj[Prop]> {
|
|
472
|
+
// The nearest decorated wrapper (a method, or a legacy getter) on the prototype chain knows
|
|
473
|
+
// which symbol the instance's computed is stored under.
|
|
474
|
+
for (let proto: any = obj; proto; proto = Object.getPrototypeOf(proto)) {
|
|
475
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, propertyName)
|
|
476
|
+
const wrapper = descriptor?.get ?? descriptor?.value
|
|
477
|
+
const key = wrapper?.[derivationKeyKey]
|
|
478
|
+
if (!key) continue
|
|
479
|
+
|
|
480
|
+
let inst = (obj as any)[key]
|
|
481
|
+
if (!inst) {
|
|
482
|
+
// calling the wrapper creates the computed (before it first derives, so a throwing derive
|
|
483
|
+
// still leaves the instance behind)
|
|
484
|
+
try {
|
|
485
|
+
wrapper.call(obj)
|
|
486
|
+
} catch {
|
|
487
|
+
// the caller asked for the instance, not its value
|
|
488
|
+
}
|
|
489
|
+
inst = (obj as any)[key]
|
|
517
490
|
}
|
|
518
|
-
|
|
519
|
-
inst = obj[key as keyof typeof obj] as Computed<Obj[Prop]> | undefined
|
|
491
|
+
return inst
|
|
520
492
|
}
|
|
521
|
-
return
|
|
493
|
+
return undefined as any
|
|
522
494
|
}
|
|
523
495
|
|
|
524
496
|
/**
|
|
@@ -539,7 +511,7 @@ export function getComputedInstance<Obj extends object, Prop extends keyof Obj>(
|
|
|
539
511
|
* ```ts
|
|
540
512
|
* class Counter {
|
|
541
513
|
* max = 100
|
|
542
|
-
* count = atom
|
|
514
|
+
* count = atom('count', 0)
|
|
543
515
|
*
|
|
544
516
|
* @computed getRemaining() {
|
|
545
517
|
* return this.max - this.count.get()
|
|
@@ -553,7 +525,7 @@ export function getComputedInstance<Obj extends object, Prop extends keyof Obj>(
|
|
|
553
525
|
* ```ts
|
|
554
526
|
* class Counter {
|
|
555
527
|
* max = 100
|
|
556
|
-
* count = atom
|
|
528
|
+
* count = atom('count', 0)
|
|
557
529
|
*
|
|
558
530
|
* @computed({isEqual: (a, b) => a === b})
|
|
559
531
|
* getRemaining() {
|
|
@@ -665,7 +637,8 @@ export function computed<Value, Diff = unknown>(
|
|
|
665
637
|
* @public
|
|
666
638
|
*/
|
|
667
639
|
export function computed() {
|
|
668
|
-
if (arguments.length
|
|
640
|
+
if (arguments.length <= 1) {
|
|
641
|
+
// decorator factory: `@computed(options)` or `@computed()`
|
|
669
642
|
const options = arguments[0]
|
|
670
643
|
return (...args: any) => computedDecorator(options, args)
|
|
671
644
|
} else if (typeof arguments[0] === 'string') {
|
|
@@ -29,12 +29,9 @@ export interface EffectSchedulerOptions {
|
|
|
29
29
|
* }
|
|
30
30
|
* }
|
|
31
31
|
* const stop = react('set page title', () => {
|
|
32
|
-
* document.title = doc.title
|
|
33
|
-
* }, scheduleEffect)
|
|
32
|
+
* document.title = doc.title
|
|
33
|
+
* }, { scheduleEffect })
|
|
34
34
|
* ```
|
|
35
|
-
*
|
|
36
|
-
* @param execute - A function that will execute the effect.
|
|
37
|
-
* @returns void
|
|
38
35
|
*/
|
|
39
36
|
// eslint-disable-next-line tldraw/method-signature-style
|
|
40
37
|
scheduleEffect?: (execute: () => void) => void
|
|
@@ -95,12 +92,16 @@ class __EffectScheduler__<Result> implements EffectScheduler<Result> {
|
|
|
95
92
|
// bail out if no atoms have changed since the last time we ran this effect
|
|
96
93
|
if (this.lastReactedEpoch === getGlobalEpoch()) return
|
|
97
94
|
|
|
98
|
-
//
|
|
99
|
-
if
|
|
95
|
+
// An effect that has run before (or captured parents before throwing) only needs to run
|
|
96
|
+
// again if one of those parents changed; that includes an effect that captured no parents at
|
|
97
|
+
// all. An effect that has never run always runs.
|
|
98
|
+
if (
|
|
99
|
+
(this.lastReactedEpoch !== GLOBAL_START_EPOCH || this.parents.length > 0) &&
|
|
100
|
+
!haveParentsChanged(this)
|
|
101
|
+
) {
|
|
100
102
|
this.lastReactedEpoch = getGlobalEpoch()
|
|
101
103
|
return
|
|
102
104
|
}
|
|
103
|
-
// if we don't have parents it's probably the first time this is running.
|
|
104
105
|
this.scheduleEffect()
|
|
105
106
|
}
|
|
106
107
|
|
|
@@ -133,7 +134,10 @@ class __EffectScheduler__<Result> implements EffectScheduler<Result> {
|
|
|
133
134
|
attach() {
|
|
134
135
|
this._isActivelyListening = true
|
|
135
136
|
for (let i = 0, n = this.parents.length; i < n; i++) {
|
|
136
|
-
|
|
137
|
+
const parent = this.parents[i]
|
|
138
|
+
// a computed parent may have gone stale while nothing listened; see `attach` in helpers.ts
|
|
139
|
+
parent.__unsafe__getWithoutCapture(true)
|
|
140
|
+
attach(parent, this)
|
|
137
141
|
}
|
|
138
142
|
}
|
|
139
143
|
|
package/src/lib/HistoryBuffer.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { EMPTY_ARRAY } from './helpers'
|
|
1
2
|
import { RESET_VALUE } from './types'
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -15,6 +16,9 @@ type RangeTuple<Diff> = [fromEpoch: number, toEpoch: number, diff: Diff]
|
|
|
15
16
|
* The buffer uses a wrap-around strategy to maintain a fixed-size history of the most recent
|
|
16
17
|
* changes, automatically overwriting older entries when the capacity is exceeded.
|
|
17
18
|
*
|
|
19
|
+
* Entries must be contiguous (`entry[k].toEpoch === entry[k+1].fromEpoch`); `getChangesSince`
|
|
20
|
+
* relies on that to find the entry covering an epoch.
|
|
21
|
+
*
|
|
18
22
|
* @example
|
|
19
23
|
* ```ts
|
|
20
24
|
* const buffer = new HistoryBuffer<string>(5)
|
|
@@ -54,12 +58,14 @@ export class HistoryBuffer<Diff> {
|
|
|
54
58
|
/**
|
|
55
59
|
* Adds a diff entry to the history buffer, representing a change between two epochs.
|
|
56
60
|
*
|
|
57
|
-
* If the diff is
|
|
58
|
-
*
|
|
61
|
+
* If the diff is RESET_VALUE, or undefined (meaning no diff is available), the entire buffer is
|
|
62
|
+
* cleared to indicate that historical tracking should restart. Silently skipping an entry would
|
|
63
|
+
* leave a gap, and a later `getChangesSince` from before the gap would return an incomplete
|
|
64
|
+
* diff list rather than RESET_VALUE.
|
|
59
65
|
*
|
|
60
66
|
* @param lastComputedEpoch - The epoch when the previous value was computed
|
|
61
67
|
* @param currentEpoch - The epoch when the current value was computed
|
|
62
|
-
* @param diff - The diff representing the change, or RESET_VALUE to clear history
|
|
68
|
+
* @param diff - The diff representing the change, or RESET_VALUE / undefined to clear history
|
|
63
69
|
* @example
|
|
64
70
|
* ```ts
|
|
65
71
|
* const buffer = new HistoryBuffer<string>(5)
|
|
@@ -67,12 +73,8 @@ export class HistoryBuffer<Diff> {
|
|
|
67
73
|
* buffer.pushEntry(1, 2, RESET_VALUE) // Clears the buffer
|
|
68
74
|
* ```
|
|
69
75
|
*/
|
|
70
|
-
pushEntry(lastComputedEpoch: number, currentEpoch: number, diff: Diff | RESET_VALUE) {
|
|
71
|
-
if (diff === undefined) {
|
|
72
|
-
return
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
if (diff === RESET_VALUE) {
|
|
76
|
+
pushEntry(lastComputedEpoch: number, currentEpoch: number, diff: Diff | RESET_VALUE | undefined) {
|
|
77
|
+
if (diff === RESET_VALUE || diff === undefined) {
|
|
76
78
|
this.clear()
|
|
77
79
|
return
|
|
78
80
|
}
|
|
@@ -139,7 +141,7 @@ export class HistoryBuffer<Diff> {
|
|
|
139
141
|
|
|
140
142
|
// If the first element is already too early, bail
|
|
141
143
|
if (i === 0 && sinceEpoch >= toEpoch) {
|
|
142
|
-
return
|
|
144
|
+
return EMPTY_ARRAY
|
|
143
145
|
}
|
|
144
146
|
|
|
145
147
|
// If the element is since the given epoch, return an array with all diffs from this element and all following elements
|
|
@@ -91,6 +91,24 @@ describe(ArraySet, () => {
|
|
|
91
91
|
expect(as.add(1)).toBe(true)
|
|
92
92
|
})
|
|
93
93
|
|
|
94
|
+
it('[AS4] a fresh ArraySet answers every query as empty and survives remove and clear', () => {
|
|
95
|
+
const as = new ArraySet<number>()
|
|
96
|
+
|
|
97
|
+
expect(as.has(1)).toBe(false)
|
|
98
|
+
expect(as.size()).toBe(0)
|
|
99
|
+
expect(as.isEmpty).toBe(true)
|
|
100
|
+
expect([...as]).toEqual([])
|
|
101
|
+
expect(get(as)).toEqual(new Set())
|
|
102
|
+
|
|
103
|
+
expect(as.remove(1)).toBe(false)
|
|
104
|
+
as.clear()
|
|
105
|
+
|
|
106
|
+
expect(as.isEmpty).toBe(true)
|
|
107
|
+
expect(as.add(1)).toBe(true)
|
|
108
|
+
expect(as.has(1)).toBe(true)
|
|
109
|
+
expect(as.size()).toBe(1)
|
|
110
|
+
})
|
|
111
|
+
|
|
94
112
|
it('works with small numbers of things', () => {
|
|
95
113
|
const as = new ArraySet<number>()
|
|
96
114
|
|
|
@@ -172,25 +190,33 @@ function runTest(seed: number) {
|
|
|
172
190
|
const s = new Set<number>()
|
|
173
191
|
const r = rng(seed)
|
|
174
192
|
|
|
175
|
-
|
|
193
|
+
// Enough candidates, and enough bias toward adds, that the set fills past the promotion
|
|
194
|
+
// threshold rather than hovering below it in array mode forever.
|
|
195
|
+
const nums = new Array(ARRAY_SIZE_THRESHOLD * 4).fill(0).map(() => Math.floor(r() * 100))
|
|
176
196
|
|
|
177
197
|
for (let i = 0; i < 1000; i++) {
|
|
178
198
|
const num = nums[Math.floor(r() * nums.length)]
|
|
179
199
|
|
|
180
200
|
const choice = r()
|
|
181
|
-
if (choice < 0.45) {
|
|
182
|
-
as.add(num)
|
|
183
|
-
s.add(num)
|
|
184
|
-
} else if (choice < 0.9) {
|
|
185
|
-
as.remove(num)
|
|
186
|
-
s.delete(num)
|
|
187
|
-
} else {
|
|
188
|
-
as.clear()
|
|
189
|
-
s.clear()
|
|
190
|
-
}
|
|
191
|
-
|
|
192
201
|
try {
|
|
202
|
+
if (choice < 0.55) {
|
|
203
|
+
expect(as.add(num)).toBe(!s.has(num))
|
|
204
|
+
s.add(num)
|
|
205
|
+
} else if (choice < 0.95) {
|
|
206
|
+
expect(as.remove(num)).toBe(s.has(num))
|
|
207
|
+
s.delete(num)
|
|
208
|
+
} else {
|
|
209
|
+
as.clear()
|
|
210
|
+
s.clear()
|
|
211
|
+
}
|
|
212
|
+
|
|
193
213
|
expect(get(as)).toEqual(s)
|
|
214
|
+
expect(new Set([...as])).toEqual(s)
|
|
215
|
+
expect(as.size()).toBe(s.size)
|
|
216
|
+
expect(as.isEmpty).toBe(s.size === 0)
|
|
217
|
+
for (const n of nums) {
|
|
218
|
+
expect(as.has(n)).toBe(s.has(n))
|
|
219
|
+
}
|
|
194
220
|
} catch (e) {
|
|
195
221
|
console.error('Failed on iteration', i, 'with seed', seed)
|
|
196
222
|
throw e
|
|
@@ -198,7 +224,7 @@ function runTest(seed: number) {
|
|
|
198
224
|
}
|
|
199
225
|
}
|
|
200
226
|
|
|
201
|
-
describe('fuzzing
|
|
227
|
+
describe('fuzzing against a reference Set', () => {
|
|
202
228
|
new Array(10).fill(0).forEach(() => {
|
|
203
229
|
const seed = Math.floor(Math.random() * 1000000)
|
|
204
230
|
it(`fuzz with seed ${seed}`, () => {
|
|
@@ -233,6 +233,50 @@ describe('reactor (E)', () => {
|
|
|
233
233
|
r.scheduler.maybeScheduleEffect()
|
|
234
234
|
expect(rfn).toHaveBeenCalledTimes(1)
|
|
235
235
|
})
|
|
236
|
+
|
|
237
|
+
it('[E2] start() inside a reaction phase runs the effect if a parent changed while stopped', () => {
|
|
238
|
+
// Regression: re-attaching during a reaction used to make a stale computed parent "actively
|
|
239
|
+
// listening" without refreshing it, and Computed's cache then served the stale value, so the
|
|
240
|
+
// restarted reactor never ran and the computed stayed wrong until its ancestor changed again.
|
|
241
|
+
const a = atom('a', 1)
|
|
242
|
+
const c = computed('c', () => a.get() * 2)
|
|
243
|
+
const seen: number[] = []
|
|
244
|
+
const r = reactor('r', () => {
|
|
245
|
+
seen.push(c.get())
|
|
246
|
+
})
|
|
247
|
+
r.start()
|
|
248
|
+
expect(seen).toEqual([2])
|
|
249
|
+
r.stop()
|
|
250
|
+
|
|
251
|
+
a.set(5) // nothing is listening to c now, so it goes stale
|
|
252
|
+
|
|
253
|
+
const trigger = atom('trigger', 0)
|
|
254
|
+
react('outer', () => {
|
|
255
|
+
if (trigger.get() === 1) r.start()
|
|
256
|
+
})
|
|
257
|
+
trigger.set(1) // r.start() runs inside this reaction phase
|
|
258
|
+
|
|
259
|
+
expect(seen).toEqual([2, 10])
|
|
260
|
+
expect(c.get()).toBe(10)
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
it('[E2][E9] an effect that captured no parents does not re-run on start() after unrelated changes', () => {
|
|
264
|
+
const unrelated = atom('', 0)
|
|
265
|
+
const rfn = vi.fn()
|
|
266
|
+
const r = reactor('', rfn)
|
|
267
|
+
|
|
268
|
+
r.start()
|
|
269
|
+
expect(rfn).toHaveBeenCalledTimes(1)
|
|
270
|
+
|
|
271
|
+
r.stop()
|
|
272
|
+
unrelated.set(1)
|
|
273
|
+
r.start()
|
|
274
|
+
// no parent changed (there are none), so there is nothing to react to
|
|
275
|
+
expect(rfn).toHaveBeenCalledTimes(1)
|
|
276
|
+
|
|
277
|
+
r.start({ force: true })
|
|
278
|
+
expect(rfn).toHaveBeenCalledTimes(2)
|
|
279
|
+
})
|
|
236
280
|
})
|
|
237
281
|
|
|
238
282
|
describe('custom scheduling (E6, E7)', () => {
|
|
@@ -400,4 +444,29 @@ describe('EffectScheduler attach/detach (E8)', () => {
|
|
|
400
444
|
a.set(4)
|
|
401
445
|
expect(numReactions).toBe(4)
|
|
402
446
|
})
|
|
447
|
+
|
|
448
|
+
it('[E8] attach() brings stale computed parents up to date before listening to them', () => {
|
|
449
|
+
const a = atom('a', 1)
|
|
450
|
+
const c = computed('c', () => a.get() * 2)
|
|
451
|
+
const seen: number[] = []
|
|
452
|
+
const scheduler = new EffectScheduler('test', () => {
|
|
453
|
+
seen.push(c.get())
|
|
454
|
+
})
|
|
455
|
+
scheduler.attach()
|
|
456
|
+
scheduler.execute()
|
|
457
|
+
scheduler.detach()
|
|
458
|
+
a.set(5) // c is stale now
|
|
459
|
+
|
|
460
|
+
// the useStateTracking pattern: re-attach, then ask whether a run is needed, inside a reaction
|
|
461
|
+
const trigger = atom('trigger', 0)
|
|
462
|
+
react('outer', () => {
|
|
463
|
+
if (trigger.get() === 1) {
|
|
464
|
+
scheduler.attach()
|
|
465
|
+
scheduler.maybeScheduleEffect()
|
|
466
|
+
}
|
|
467
|
+
})
|
|
468
|
+
trigger.set(1)
|
|
469
|
+
|
|
470
|
+
expect(seen).toEqual([2, 10])
|
|
471
|
+
})
|
|
403
472
|
})
|
|
@@ -47,13 +47,16 @@ describe('HistoryBuffer', () => {
|
|
|
47
47
|
expect(buf.getChangesSince(0)).toEqual(RESET_VALUE)
|
|
48
48
|
})
|
|
49
49
|
|
|
50
|
-
it('[HB1]
|
|
50
|
+
it('[HB1] treats an undefined diff like RESET_VALUE: it clears rather than leaving a gap', () => {
|
|
51
51
|
const buf = new HistoryBuffer<string>(3)
|
|
52
52
|
buf.pushEntry(0, 1, 'a')
|
|
53
53
|
buf.pushEntry(1, 2, undefined as any)
|
|
54
|
+
buf.pushEntry(2, 3, 'c')
|
|
54
55
|
|
|
55
|
-
|
|
56
|
-
expect(buf.getChangesSince(
|
|
56
|
+
// if the undefined entry had been skipped, this would be ['a', 'c'] with the 1 -> 2 change missing
|
|
57
|
+
expect(buf.getChangesSince(0)).toEqual(RESET_VALUE)
|
|
58
|
+
expect(buf.getChangesSince(1)).toEqual(RESET_VALUE)
|
|
59
|
+
expect(buf.getChangesSince(2)).toEqual(['c'])
|
|
57
60
|
})
|
|
58
61
|
|
|
59
62
|
it('[HB1] will clear if you push RESET_VALUE', () => {
|
|
@@ -333,4 +333,79 @@ describe('the computed decorator (C8, C9, C10)', () => {
|
|
|
333
333
|
|
|
334
334
|
warn.mockRestore()
|
|
335
335
|
})
|
|
336
|
+
|
|
337
|
+
it('[C8] can be applied as a factory with no options', () => {
|
|
338
|
+
// the options argument is optional, so `@computed()` must work like `@computed`
|
|
339
|
+
class Foo {
|
|
340
|
+
a = atom('a', 1)
|
|
341
|
+
@computed()
|
|
342
|
+
getB() {
|
|
343
|
+
return this.a.get() * 2
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const foo = new Foo()
|
|
348
|
+
expect(foo.getB()).toBe(2)
|
|
349
|
+
foo.a.set(2)
|
|
350
|
+
expect(foo.getB()).toBe(4)
|
|
351
|
+
})
|
|
352
|
+
|
|
353
|
+
it('[C8] a subclass override can call the superclass computed via super', () => {
|
|
354
|
+
// each decoration stores its computed under its own key; keying by method name made the
|
|
355
|
+
// super call re-enter the subclass's own computed and overflow the stack
|
|
356
|
+
class Base {
|
|
357
|
+
a = atom('a', 1)
|
|
358
|
+
@computed
|
|
359
|
+
getB() {
|
|
360
|
+
return this.a.get() * 2
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
class Sub extends Base {
|
|
364
|
+
@computed
|
|
365
|
+
override getB() {
|
|
366
|
+
return super.getB() + 1
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const sub = new Sub()
|
|
371
|
+
expect(sub.getB()).toBe(3)
|
|
372
|
+
sub.a.set(2)
|
|
373
|
+
expect(sub.getB()).toBe(5)
|
|
374
|
+
expect(new Base().getB()).toBe(2)
|
|
375
|
+
})
|
|
376
|
+
|
|
377
|
+
it('[C9] getComputedInstance resolves the nearest decorated method on the prototype chain', () => {
|
|
378
|
+
class Base {
|
|
379
|
+
a = atom('a', 1)
|
|
380
|
+
@computed
|
|
381
|
+
getB() {
|
|
382
|
+
return this.a.get() * 2
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
class Sub extends Base {
|
|
386
|
+
@computed
|
|
387
|
+
override getB() {
|
|
388
|
+
return super.getB() + 1
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
class PlainSub extends Base {
|
|
392
|
+
override getB() {
|
|
393
|
+
return super.getB() + 100
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const sub = new Sub()
|
|
398
|
+
const subInst = getComputedInstance(sub, 'getB')
|
|
399
|
+
expect(subInst.get()).toBe(3)
|
|
400
|
+
sub.a.set(2)
|
|
401
|
+
expect(subInst.get()).toBe(5)
|
|
402
|
+
|
|
403
|
+
// a plain (undecorated) override still exposes the superclass's computed
|
|
404
|
+
const plain = new PlainSub()
|
|
405
|
+
expect(getComputedInstance(plain, 'getB').get()).toBe(2)
|
|
406
|
+
|
|
407
|
+
// the returned type unwraps the method's return type
|
|
408
|
+
const n: number = getComputedInstance(new Base(), 'getB').get()
|
|
409
|
+
expect(n).toBe(2)
|
|
410
|
+
})
|
|
336
411
|
})
|
|
@@ -112,6 +112,29 @@ describe('deferAsyncEffects (AT)', () => {
|
|
|
112
112
|
expect(b.get()).toBe(0)
|
|
113
113
|
})
|
|
114
114
|
|
|
115
|
+
it('[AT3][T6] effects never observe partially restored values when an async transaction aborts', async () => {
|
|
116
|
+
// Regression: the rollback used to run after the async transaction had been cleared, so each
|
|
117
|
+
// restoring set flushed effects on its own and they saw one atom restored but not the other.
|
|
118
|
+
const a = atom('', 1)
|
|
119
|
+
const b = atom('', 1)
|
|
120
|
+
const seen: string[] = []
|
|
121
|
+
react('', () => {
|
|
122
|
+
seen.push(`${a.get()},${b.get()}`)
|
|
123
|
+
})
|
|
124
|
+
seen.length = 0
|
|
125
|
+
|
|
126
|
+
await expect(
|
|
127
|
+
deferAsyncEffects(async () => {
|
|
128
|
+
a.set(2)
|
|
129
|
+
b.set(2)
|
|
130
|
+
await sleep(1)
|
|
131
|
+
throw new Error('boom')
|
|
132
|
+
})
|
|
133
|
+
).rejects.toThrow('boom')
|
|
134
|
+
|
|
135
|
+
expect(seen).toEqual(['1,1'])
|
|
136
|
+
})
|
|
137
|
+
|
|
115
138
|
it('[AT3][AT4] rolls back everything when a nested async transaction throws', async () => {
|
|
116
139
|
const a = atom('', 0)
|
|
117
140
|
const b = atom('', 0)
|