@esportsplus/reactivity 0.41.0 → 0.43.0

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.
Files changed (49) hide show
  1. package/README.md +7 -5
  2. package/bench/compiler.bench.ts +24 -16
  3. package/bench/lib/reactive-adapter.ts +1 -1
  4. package/bench/ownership.bench.ts +9 -5
  5. package/bench/reactive/array.bench.ts +6 -2
  6. package/bench/system.bench.ts +9 -5
  7. package/build/compiler/array.d.ts +1 -1
  8. package/build/compiler/array.js +2 -2
  9. package/build/compiler/bindings.d.ts +9 -9
  10. package/build/compiler/bindings.js +59 -62
  11. package/build/compiler/index.d.ts +2 -2
  12. package/build/compiler/index.js +19 -13
  13. package/build/compiler/object.d.ts +1 -1
  14. package/build/compiler/object.js +19 -10
  15. package/build/compiler/plugins/vite.d.ts +18 -4
  16. package/build/compiler/primitives.d.ts +1 -1
  17. package/build/compiler/primitives.js +38 -20
  18. package/build/constants.d.ts +3 -1
  19. package/build/constants.js +3 -1
  20. package/build/reactive/array.js +89 -17
  21. package/build/system.d.ts +4 -3
  22. package/build/system.js +48 -16
  23. package/package.json +2 -2
  24. package/src/compiler/array.ts +2 -2
  25. package/src/compiler/bindings.ts +82 -86
  26. package/src/compiler/index.ts +25 -14
  27. package/src/compiler/object.ts +31 -17
  28. package/src/compiler/primitives.ts +61 -25
  29. package/src/constants.ts +6 -1
  30. package/src/reactive/array.ts +130 -23
  31. package/src/system.ts +66 -23
  32. package/test/async-hardening.test.ts +2 -2
  33. package/test/async-iterable.test.ts +3 -3
  34. package/test/compiler/compiler.test.ts +169 -156
  35. package/test/compiler/composition.test.ts +31 -27
  36. package/test/compiler/coverage.test.ts +12 -12
  37. package/test/compiler/origins.test.ts +18 -18
  38. package/test/compiler/output.test.ts +4 -4
  39. package/test/deep-graphs.test.ts +6 -6
  40. package/test/effects.test.ts +5 -5
  41. package/test/errors.test.ts +4 -4
  42. package/test/invalidate.test.ts +2 -2
  43. package/test/ownership.test.ts +30 -30
  44. package/test/pause.test.ts +267 -0
  45. package/test/reactive/array.test.ts +5 -5
  46. package/test/reactive/reactive.test.ts +3 -3
  47. package/test/signal-selector.test.ts +4 -4
  48. package/test/system.test.ts +10 -9
  49. package/test/untrack.test.ts +9 -9
@@ -1,8 +1,8 @@
1
1
  import { isArray } from '@esportsplus/utilities';
2
2
  import { PACKAGE_NAME, REACTIVE_ARRAY } from '../constants';
3
- import { effect, read, root, signal, write } from '../system';
3
+ import { dispose as disposeNode, effect, read, root, signal, write } from '../system';
4
4
  import { isReactiveObject } from './object';
5
- import type { Signal } from '../types';
5
+ import type { Computed, Signal } from '../types';
6
6
 
7
7
 
8
8
  // One mutation as the batch event reports it: the matching event's payload, named by 'op'
@@ -69,15 +69,90 @@ function dispose(value: unknown) {
69
69
  }
70
70
  }
71
71
 
72
+ // One element move of Array.prototype's algorithms: a hole moves as a hole
73
+ function move<T>(array: T[], from: number, to: number) {
74
+ if (from in array) {
75
+ array[to] = array[from];
76
+ }
77
+ else {
78
+ // oxlint-disable-next-line typescript/no-array-delete -- a hole must move as a hole, as the builtin does
79
+ delete array[to];
80
+ }
81
+ }
82
+
83
+ // Array.prototype.splice's element steps after the removal: `count` slots at `start` become `items`. Slots
84
+ // past the end are filled in ascending order, so a packed array stays packed.
85
+ function place<T>(array: T[], start: number, count: number, items: T[]) {
86
+ let length = array.length,
87
+ n = items.length,
88
+ total = length - count + n;
89
+
90
+ if (n < count) {
91
+ for (let i = start + count; i < length; i++) {
92
+ move(array, i, i - count + n);
93
+ }
94
+ }
95
+ else if (n > count) {
96
+ let shift = n - count;
97
+
98
+ for (let i = length; i < total; i++) {
99
+ if (i < start + n) {
100
+ array[i] = items[i - start];
101
+ }
102
+ else {
103
+ move(array, i - shift, i);
104
+ }
105
+ }
106
+
107
+ for (let i = length - 1; i >= start + n; i--) {
108
+ move(array, i - shift, i);
109
+ }
110
+ }
111
+
112
+ for (let i = 0; i < n; i++) {
113
+ array[start + i] = items[i];
114
+ }
115
+
116
+ // Trims what moved down, or restores a length a hole moved past the old end could not set
117
+ if (array.length !== total) {
118
+ array.length = total;
119
+ }
120
+ }
121
+
122
+ // Array.prototype.sort's steps: present values sorted apart (a plain array sorts on the fast path), written
123
+ // back in order, holes left at the end
124
+ function rank<T>(array: T[], fn?: (a: T, b: T) => number) {
125
+ let n = array.length,
126
+ values: T[] = [];
127
+
128
+ for (let i = 0; i < n; i++) {
129
+ if (i in array) {
130
+ values.push(array[i]);
131
+ }
132
+ }
133
+
134
+ values.sort(fn);
135
+
136
+ for (let i = 0, m = values.length; i < m; i++) {
137
+ array[i] = values[i];
138
+ }
139
+
140
+ for (let i = values.length; i < n; i++) {
141
+ // oxlint-disable-next-line typescript/no-array-delete -- holes sort to the end, as the builtin leaves them
142
+ delete array[i];
143
+ }
144
+ }
72
145
 
73
146
  // Derived arrays (splice removals, map/filter/slice) must be plain Arrays: species-creating a
74
147
  // ReactiveArray runs the reactive constructor per call and seeds _length from the length argument.
148
+ // V8 runs Array.prototype mutators on its generic path for an instance whose prototype is not
149
+ // Array.prototype, so mutations are spelled out as indexed reads and stores, which stay fast.
75
150
  class ReactiveArray<T> extends Array<T> {
76
151
 
77
152
  private _length: Signal<number>;
78
153
 
79
154
  // The batch listeners' delivery: the mutations not yet delivered, and the effect that delivers them
80
- private batched: { ops: ArrayOp<T>[] | null; stop: VoidFunction; tick: Signal<number> } | null = null;
155
+ private batched: { ops: ArrayOp<T>[] | null; stop: Computed<unknown>; tick: Signal<number> } | null = null;
81
156
 
82
157
  private delivering = false;
83
158
 
@@ -210,7 +285,7 @@ class ReactiveArray<T> extends Array<T> {
210
285
 
211
286
  if (batched !== null) {
212
287
  this.batched = null;
213
- batched.stop();
288
+ disposeNode(batched.stop);
214
289
  }
215
290
  }
216
291
 
@@ -232,13 +307,15 @@ class ReactiveArray<T> extends Array<T> {
232
307
 
233
308
  if (isArray(item)) {
234
309
  for (let j = 0, o = item.length; j < o; j++) {
235
- added.push(item[j]);
236
- super.push(item[j]);
310
+ let value = item[j];
311
+
312
+ added.push(value);
313
+ this[this.length] = value;
237
314
  }
238
315
  }
239
316
  else {
240
317
  added.push(item as T);
241
- super.push(item as T);
318
+ this[this.length] = item as T;
242
319
  }
243
320
  }
244
321
 
@@ -392,7 +469,11 @@ class ReactiveArray<T> extends Array<T> {
392
469
  return this.length;
393
470
  }
394
471
 
395
- let length = super.push(...items);
472
+ let length = this.length;
473
+
474
+ for (let i = 0, n = items.length; i < n; i++) {
475
+ this[length++] = items[i];
476
+ }
396
477
 
397
478
  write(this._length, length);
398
479
 
@@ -403,7 +484,21 @@ class ReactiveArray<T> extends Array<T> {
403
484
  }
404
485
 
405
486
  reverse() {
406
- super.reverse();
487
+ for (let lower = 0, upper = this.length - 1; lower < upper; lower++, upper--) {
488
+ let value = this[lower],
489
+ within = lower in this;
490
+
491
+ move(this, upper, lower);
492
+
493
+ if (within) {
494
+ this[upper] = value;
495
+ }
496
+ else {
497
+ // oxlint-disable-next-line typescript/no-array-delete -- a hole must move as a hole, as the builtin does
498
+ delete this[upper];
499
+ }
500
+ }
501
+
407
502
  this.dispatch('reverse');
408
503
  this.record({ op: 'reverse' });
409
504
 
@@ -415,8 +510,9 @@ class ReactiveArray<T> extends Array<T> {
415
510
  return undefined;
416
511
  }
417
512
 
418
- let item = super.shift() as T;
513
+ let item = this[0];
419
514
 
515
+ place(this, 0, 1, []);
420
516
  dispose(item);
421
517
  write(this._length, this.length);
422
518
  this.dispatch('shift', { item });
@@ -427,7 +523,7 @@ class ReactiveArray<T> extends Array<T> {
427
523
 
428
524
  sort(fn?: (a: T, b: T) => number) {
429
525
  if (this.listeners.sort === undefined && this.batched === null) {
430
- super.sort(fn);
526
+ rank(this, fn);
431
527
  }
432
528
  else {
433
529
  let n = this.length,
@@ -438,7 +534,7 @@ class ReactiveArray<T> extends Array<T> {
438
534
  before[i] = this[i];
439
535
  }
440
536
 
441
- super.sort(fn);
537
+ rank(this, fn);
442
538
 
443
539
  let buckets = new Map<T, { indices: number[]; next: number }>(),
444
540
  // oxlint-disable-next-line unicorn/no-new-array -- preallocated to n, every slot is written next
@@ -470,23 +566,32 @@ class ReactiveArray<T> extends Array<T> {
470
566
  }
471
567
 
472
568
  splice(start: number, deleteCount: number = this.length, ...items: T[]) {
569
+ // Arguments resolve as Array.prototype.splice resolves them (negative, fractional and out-of-range
570
+ // values clamped); listeners receive the resolved position and count, never the raw arguments
473
571
  let length = this.length,
474
- removed = super.splice(start, deleteCount, ...items);
572
+ index = Math.trunc(start) || 0,
573
+ resolved = index < 0 ? Math.max(length + index, 0) : Math.min(index, length),
574
+ count = Math.min(Math.max(Math.trunc(deleteCount) || 0, 0), length - resolved),
575
+ removed: T[] = [];
576
+
577
+ for (let i = 0; i < count; i++) {
578
+ if (resolved + i in this) {
579
+ removed[i] = this[resolved + i];
580
+ }
581
+ }
582
+
583
+ removed.length = count;
475
584
 
476
- if (items.length > 0 || removed.length > 0) {
585
+ if (items.length > 0 || count > 0) {
586
+ place(this, resolved, count, items);
477
587
  write(this._length, this.length);
478
588
 
479
- for (let i = 0, n = removed.length; i < n; i++) {
589
+ for (let i = 0; i < count; i++) {
480
590
  dispose(removed[i]);
481
591
  }
482
592
 
483
- // Listeners receive the position and count Array.prototype.splice actually applied
484
- // (negative, fractional and out-of-range arguments resolved), never the raw arguments
485
- let index = Math.trunc(start) || 0,
486
- resolved = index < 0 ? Math.max(length + index, 0) : Math.min(index, length);
487
-
488
- this.dispatch('splice', { deleteCount: removed.length, items, start: resolved });
489
- this.record({ deleteCount: removed.length, items, op: 'splice', start: resolved });
593
+ this.dispatch('splice', { deleteCount: count, items, start: resolved });
594
+ this.record({ deleteCount: count, items, op: 'splice', start: resolved });
490
595
  }
491
596
 
492
597
  return removed;
@@ -497,7 +602,9 @@ class ReactiveArray<T> extends Array<T> {
497
602
  return this.length;
498
603
  }
499
604
 
500
- let length = super.unshift(...items);
605
+ place(this, 0, 0, items);
606
+
607
+ let length = this.length;
501
608
 
502
609
  write(this._length, length);
503
610
  this.dispatch('unshift', { items });
package/src/system.ts CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  PACKAGE_NAME,
3
3
  SIGNAL,
4
4
  STABILIZER_DEFERRED, STABILIZER_IDLE, STABILIZER_RESCHEDULE, STABILIZER_RUNNING, STABILIZER_SCHEDULED,
5
- STATE_CHECK, STATE_COMPUTED, STATE_DIRTY, STATE_DISPOSED, STATE_EFFECT, STATE_ERROR, STATE_IN_HEAP, STATE_NOTIFY_MASK, STATE_RECOMPUTING
5
+ STATE_CHECK, STATE_COMPUTED, STATE_DIRTY, STATE_DISPOSED, STATE_EFFECT, STATE_ERROR, STATE_IN_HEAP, STATE_NOTIFY_MASK, STATE_PAUSED, STATE_RECOMPUTING, STATE_STALE
6
6
  } from './constants';
7
7
  import { Computed, ComputedResult, Link, SelectorSignal, Settled, Signal } from './types';
8
8
  import { isObject, isPromise } from '@esportsplus/utilities';
@@ -424,8 +424,16 @@ function propagate<T>(computed: Computed<T>) {
424
424
  }
425
425
 
426
426
  function recompute<T>(computed: Computed<T>) {
427
- if (computed.state & STATE_IN_HEAP) {
428
- deleteFromHeap(computed);
427
+ // One test on the common path: a node neither queued nor paused goes straight to its run
428
+ if (computed.state & (STATE_IN_HEAP | STATE_PAUSED)) {
429
+ if (computed.state & STATE_IN_HEAP) {
430
+ deleteFromHeap(computed);
431
+ }
432
+
433
+ if (computed.state & STATE_PAUSED) {
434
+ computed.state |= STATE_STALE;
435
+ return;
436
+ }
429
437
  }
430
438
 
431
439
  if (computed.cleanup !== null || computed.owned !== null) {
@@ -468,7 +476,7 @@ function recompute<T>(computed: Computed<T>) {
468
476
  version++;
469
477
  observer = o;
470
478
  // fn may have re-queued this node (a tracked read drains pending writes), so heap membership survives
471
- computed.state = STATE_COMPUTED | flags | (computed.state & STATE_IN_HEAP);
479
+ computed.state = STATE_COMPUTED | flags | (computed.state & (STATE_IN_HEAP | STATE_PAUSED));
472
480
  // Entry snapshot, not current writes: a node whose fn wrote mid-run must stay gv < writes and validate normally
473
481
  computed.gv = w;
474
482
 
@@ -476,16 +484,23 @@ function recompute<T>(computed: Computed<T>) {
476
484
  remove = depsTail ? depsTail.nextDep : computed.deps;
477
485
 
478
486
  if (remove) {
479
- do {
480
- remove = unlink(remove);
481
- }
482
- while (remove);
483
-
484
- if (depsTail) {
485
- depsTail.nextDep = null;
487
+ // A run that paused its own effect read only part of what it depends on: the rest stays linked and the run
488
+ // counts as skipped, so resume() replays it
489
+ if (computed.state & STATE_PAUSED) {
490
+ computed.state |= STATE_STALE;
486
491
  }
487
492
  else {
488
- computed.deps = null;
493
+ do {
494
+ remove = unlink(remove);
495
+ }
496
+ while (remove);
497
+
498
+ if (depsTail) {
499
+ depsTail.nextDep = null;
500
+ }
501
+ else {
502
+ computed.deps = null;
503
+ }
489
504
  }
490
505
  }
491
506
 
@@ -785,7 +800,7 @@ function makeAsyncComputed<T>(factory: Computed<Promise<T> | AsyncIterable<T> |
785
800
  wrapper.pending = pending;
786
801
 
787
802
  asyncFactory.set(wrapper as Computed<unknown>, factory as Computed<unknown>);
788
- wrapper.disposal = stop;
803
+ wrapper.disposal = () => dispose(stop);
789
804
 
790
805
  return wrapper;
791
806
  }
@@ -1023,9 +1038,7 @@ const effect = <T>(fn: Computed<T>['fn'], apply?: (value: T, prev: T | undefined
1023
1038
  });
1024
1039
  }
1025
1040
 
1026
- return () => {
1027
- dispose(c);
1028
- };
1041
+ return c;
1029
1042
  };
1030
1043
 
1031
1044
  // A no-op while a pass is running: re-entering stabilize() would corrupt heap_i.
@@ -1035,10 +1048,6 @@ const flush = (): void => {
1035
1048
  }
1036
1049
  };
1037
1050
 
1038
- // Whether an onCleanup() made now would land on an owner (a running computed/effect, also inside
1039
- // untrack, or a root's scope)
1040
- const hasOwner = (): boolean => observer !== null || scope !== null;
1041
-
1042
1051
  const isComputed = (value: unknown): value is Computed<unknown> => {
1043
1052
  return isObject(value) && !!((value as unknown as Computed<unknown>).state & STATE_COMPUTED);
1044
1053
  };
@@ -1123,6 +1132,41 @@ const read = <T>(node: Signal<T> | Computed<T>): T => {
1123
1132
  // .owner chain finds every enclosing owner.
1124
1133
  const owner = (): Computed<unknown> | null => observer || scope;
1125
1134
 
1135
+ // Effects only: a computed must stay derivable on read, which a skipped run would leave stale
1136
+ const pause = <T>(node: Computed<T>): void => {
1137
+ let state = node.state;
1138
+
1139
+ if (state & STATE_DISPOSED) {
1140
+ return;
1141
+ }
1142
+
1143
+ if (!(state & STATE_EFFECT)) {
1144
+ throw new Error(`${PACKAGE_NAME}: pause() expects an effect`);
1145
+ }
1146
+
1147
+ node.state = state | STATE_PAUSED;
1148
+ };
1149
+
1150
+ // A run skipped while paused is replayed once through the heap, so it lands in a normal stabilize pass
1151
+ const resume = <T>(node: Computed<T>): void => {
1152
+ let state = node.state;
1153
+
1154
+ if (state & STATE_DISPOSED) {
1155
+ return;
1156
+ }
1157
+
1158
+ if (!(state & STATE_EFFECT)) {
1159
+ throw new Error(`${PACKAGE_NAME}: resume() expects an effect`);
1160
+ }
1161
+
1162
+ node.state = state & ~(STATE_PAUSED | STATE_STALE);
1163
+
1164
+ if (state & STATE_STALE) {
1165
+ insertIntoHeap(node);
1166
+ schedule();
1167
+ }
1168
+ };
1169
+
1126
1170
  // Owned before fn runs (nothing can register on the owner meanwhile, so ownerSlot is unchanged): a
1127
1171
  // root disposed inside its own fn then unlinks instead of being parked on the owner as a dead child.
1128
1172
  //
@@ -1282,11 +1326,10 @@ export {
1282
1326
  dispose,
1283
1327
  effect,
1284
1328
  flush,
1285
- hasOwner,
1286
1329
  isComputed, isSignal,
1287
1330
  onCleanup, owner,
1288
- peek,
1289
- read, root,
1331
+ pause, peek,
1332
+ read, resume, root,
1290
1333
  signal,
1291
1334
  untrack,
1292
1335
  write
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { computed, effect, read, root, signal, write } from '~/system';
2
+ import { computed, dispose, effect, read, root, signal, write } from '~/system';
3
3
  import { tick, waitFor } from './lib/wait-for';
4
4
  import type { Computed } from '~/system';
5
5
 
@@ -61,7 +61,7 @@ describe('asyncComputed outside root', () => {
61
61
  expect(read(node)).toBe(1);
62
62
  expect(calls).toBe(1);
63
63
 
64
- stop();
64
+ dispose(stop);
65
65
 
66
66
  write(s, 2);
67
67
  await tick();
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { computed, effect, read, root, signal, write } from '~/system';
2
+ import { computed, dispose, effect, read, root, signal, write } from '~/system';
3
3
  import { tick } from './lib/wait-for';
4
4
  import type { Computed } from '~/system';
5
5
 
@@ -128,7 +128,7 @@ describe('asyncComputed AsyncIterable support', () => {
128
128
  expect(read(node)).toBe(1);
129
129
 
130
130
  // Mid-iteration: dispose while the generator is suspended awaiting its second gate.
131
- keeper();
131
+ dispose(keeper);
132
132
  stopRoot();
133
133
 
134
134
  allGates[0][1].resolve();
@@ -248,7 +248,7 @@ describe('asyncComputed AsyncIterable support', () => {
248
248
 
249
249
  await tick();
250
250
 
251
- keeper();
251
+ dispose(keeper);
252
252
  stopRoot();
253
253
 
254
254
  await tick();