@ibodr/state 0.2.5 → 0.2.7

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/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { registerDrawLibraryVersion, getFromLocalStorage, deleteFromLocalStorage, setInLocalStorage, assert } from '@ibodr/utils';
1
+ import { registerDrawLibraryVersion, getFromLocalStorage, deleteFromLocalStorage, setInLocalStorage, assert, warnOnce } from '@ibodr/utils';
2
2
 
3
3
  // src/index.ts
4
4
 
@@ -8,8 +8,9 @@ function isChild(x) {
8
8
  }
9
9
  function haveParentsChanged(child) {
10
10
  for (let i = 0, n = child.parents.length; i < n; i++) {
11
- child.parents[i].__unsafe__getWithoutCapture(true);
12
- if (child.parents[i].lastChangedEpoch !== child.parentEpochs[i]) {
11
+ const parent = child.parents[i];
12
+ parent.__unsafe__getWithoutCapture(true);
13
+ if (parent.lastChangedEpoch !== child.parentEpochs[i]) {
13
14
  return true;
14
15
  }
15
16
  }
@@ -36,8 +37,7 @@ function attach(parent, child) {
36
37
  }
37
38
  }
38
39
  function equals(a, b) {
39
- const shallowEquals = a === b || Object.is(a, b) || Boolean(a && b && typeof a.equals === "function" && a.equals(b));
40
- return shallowEquals;
40
+ return a === b || Object.is(a, b) || Boolean(a && b && typeof a.equals === "function" && a.equals(b));
41
41
  }
42
42
  function singleton(key, init) {
43
43
  const symbol = /* @__PURE__ */ Symbol.for(`com.draw.state/${key}`);
@@ -50,54 +50,27 @@ var EMPTY_ARRAY = singleton("empty_array", () => Object.freeze([]));
50
50
  // src/lib/ArraySet.ts
51
51
  var ARRAY_SIZE_THRESHOLD = 8;
52
52
  var ArraySet = class {
53
- arraySize = 0;
54
- array = Array(ARRAY_SIZE_THRESHOLD);
55
53
  set = null;
54
+ // Slots [0, arraySize) hold the items; slots beyond are undefined. `add`/`has` scan the whole
55
+ // array with indexOf, which is why `clear` and `remove` must blank vacated slots.
56
+ array = null;
57
+ arraySize = 0;
56
58
  /**
57
59
  * Get whether this ArraySet has any elements.
58
- *
59
- * @returns True if this ArraySet has any elements, false otherwise.
60
60
  */
61
61
  // eslint-disable-next-line tldraw/no-setter-getter
62
62
  get isEmpty() {
63
- if (this.array) {
64
- return this.arraySize === 0;
65
- }
66
63
  if (this.set) {
67
64
  return this.set.size === 0;
68
65
  }
69
- throw new Error("no set or array");
66
+ return this.arraySize === 0;
70
67
  }
71
68
  /**
72
69
  * Add an element to the ArraySet if it is not already present.
73
70
  *
74
- * @param elem - The element to add to the set
75
71
  * @returns `true` if the element was added, `false` if it was already present
76
- * @example
77
- * ```ts
78
- * const arraySet = new ArraySet<string>()
79
- *
80
- * console.log(arraySet.add('hello')) // true
81
- * console.log(arraySet.add('hello')) // false (already exists)
82
- * ```
83
72
  */
84
73
  add(elem) {
85
- if (this.array) {
86
- const idx = this.array.indexOf(elem);
87
- if (idx !== -1) {
88
- return false;
89
- }
90
- if (this.arraySize < ARRAY_SIZE_THRESHOLD) {
91
- this.array[this.arraySize] = elem;
92
- this.arraySize++;
93
- return true;
94
- } else {
95
- this.set = new Set(this.array);
96
- this.array = null;
97
- this.set.add(elem);
98
- return true;
99
- }
100
- }
101
74
  if (this.set) {
102
75
  if (this.set.has(elem)) {
103
76
  return false;
@@ -105,168 +78,98 @@ var ArraySet = class {
105
78
  this.set.add(elem);
106
79
  return true;
107
80
  }
108
- throw new Error("no set or array");
81
+ if (!this.array) {
82
+ this.array = Array(ARRAY_SIZE_THRESHOLD);
83
+ } else if (this.array.indexOf(elem) !== -1) {
84
+ return false;
85
+ }
86
+ if (this.arraySize < ARRAY_SIZE_THRESHOLD) {
87
+ this.array[this.arraySize] = elem;
88
+ this.arraySize++;
89
+ return true;
90
+ }
91
+ this.set = new Set(this.array);
92
+ this.set.add(elem);
93
+ this.array = null;
94
+ this.arraySize = 0;
95
+ return true;
109
96
  }
110
97
  /**
111
98
  * Remove an element from the ArraySet if it is present.
112
99
  *
113
- * @param elem - The element to remove from the set
114
100
  * @returns `true` if the element was removed, `false` if it was not present
115
- * @example
116
- * ```ts
117
- * const arraySet = new ArraySet<string>()
118
- * arraySet.add('hello')
119
- *
120
- * console.log(arraySet.remove('hello')) // true
121
- * console.log(arraySet.remove('hello')) // false (not present)
122
- * ```
123
101
  */
124
102
  remove(elem) {
125
- if (this.array) {
126
- const idx = this.array.indexOf(elem);
127
- if (idx === -1) {
128
- return false;
129
- }
130
- this.array[idx] = void 0;
131
- this.arraySize--;
132
- if (idx !== this.arraySize) {
133
- this.array[idx] = this.array[this.arraySize];
134
- this.array[this.arraySize] = void 0;
135
- }
136
- return true;
137
- }
138
103
  if (this.set) {
139
- if (!this.set.has(elem)) {
140
- return false;
141
- }
142
- this.set.delete(elem);
143
- return true;
104
+ return this.set.delete(elem);
105
+ }
106
+ if (!this.array) {
107
+ return false;
144
108
  }
145
- throw new Error("no set or array");
109
+ const idx = this.array.indexOf(elem);
110
+ if (idx === -1) {
111
+ return false;
112
+ }
113
+ this.arraySize--;
114
+ this.array[idx] = this.array[this.arraySize];
115
+ this.array[this.arraySize] = void 0;
116
+ return true;
146
117
  }
147
118
  /**
148
119
  * Execute a callback function for each element in the ArraySet.
149
- *
150
- * @param visitor - A function to call for each element in the set
151
- * @example
152
- * ```ts
153
- * const arraySet = new ArraySet<string>()
154
- * arraySet.add('hello')
155
- * arraySet.add('world')
156
- *
157
- * arraySet.visit((item) => {
158
- * console.log(item) // 'hello', 'world'
159
- * })
160
- * ```
161
120
  */
162
121
  visit(visitor) {
163
- if (this.array) {
164
- for (let i = 0; i < this.arraySize; i++) {
165
- const elem = this.array[i];
166
- if (typeof elem !== "undefined") {
167
- visitor(elem);
168
- }
169
- }
170
- return;
171
- }
172
122
  if (this.set) {
173
123
  this.set.forEach(visitor);
174
124
  return;
175
125
  }
176
- throw new Error("no set or array");
126
+ if (!this.array) {
127
+ return;
128
+ }
129
+ for (let i = 0; i < this.arraySize; i++) {
130
+ visitor(this.array[i]);
131
+ }
177
132
  }
178
133
  /**
179
134
  * Make the ArraySet iterable, allowing it to be used in for...of loops and with spread syntax.
180
- *
181
- * @returns An iterator that yields each element in the set
182
- * @example
183
- * ```ts
184
- * const arraySet = new ArraySet<number>()
185
- * arraySet.add(1)
186
- * arraySet.add(2)
187
- *
188
- * for (const item of arraySet) {
189
- * console.log(item) // 1, 2
190
- * }
191
- *
192
- * const items = [...arraySet] // [1, 2]
193
- * ```
194
135
  */
195
136
  *[Symbol.iterator]() {
196
- if (this.array) {
137
+ if (this.set) {
138
+ yield* this.set;
139
+ } else if (this.array) {
197
140
  for (let i = 0; i < this.arraySize; i++) {
198
- const elem = this.array[i];
199
- if (typeof elem !== "undefined") {
200
- yield elem;
201
- }
141
+ yield this.array[i];
202
142
  }
203
- } else if (this.set) {
204
- yield* this.set;
205
- } else {
206
- throw new Error("no set or array");
207
143
  }
208
144
  }
209
145
  /**
210
146
  * Check whether an element is present in the ArraySet.
211
- *
212
- * @param elem - The element to check for
213
- * @returns `true` if the element is present, `false` otherwise
214
- * @example
215
- * ```ts
216
- * const arraySet = new ArraySet<string>()
217
- * arraySet.add('hello')
218
- *
219
- * console.log(arraySet.has('hello')) // true
220
- * console.log(arraySet.has('world')) // false
221
- * ```
222
147
  */
223
148
  has(elem) {
224
- if (this.array) {
225
- return this.array.indexOf(elem) !== -1;
226
- } else {
149
+ if (this.set) {
227
150
  return this.set.has(elem);
228
151
  }
152
+ return this.array ? this.array.indexOf(elem) !== -1 : false;
229
153
  }
230
154
  /**
231
155
  * Remove all elements from the ArraySet.
232
- *
233
- * @example
234
- * ```ts
235
- * const arraySet = new ArraySet<string>()
236
- * arraySet.add('hello')
237
- * arraySet.add('world')
238
- *
239
- * arraySet.clear()
240
- * console.log(arraySet.size()) // 0
241
- * ```
242
156
  */
243
157
  clear() {
244
158
  if (this.set) {
245
159
  this.set.clear();
246
- } else {
160
+ } else if (this.array) {
161
+ this.array.fill(void 0, 0, this.arraySize);
247
162
  this.arraySize = 0;
248
- this.array = [];
249
163
  }
250
164
  }
251
165
  /**
252
166
  * Get the number of elements in the ArraySet.
253
- *
254
- * @returns The number of elements in the set
255
- * @example
256
- * ```ts
257
- * const arraySet = new ArraySet<string>()
258
- * console.log(arraySet.size()) // 0
259
- *
260
- * arraySet.add('hello')
261
- * console.log(arraySet.size()) // 1
262
- * ```
263
167
  */
264
168
  size() {
265
169
  if (this.set) {
266
170
  return this.set.size;
267
- } else {
268
- return this.arraySize;
269
171
  }
172
+ return this.arraySize;
270
173
  }
271
174
  };
272
175
 
@@ -311,52 +214,52 @@ function startCapturingParents(child) {
311
214
  function stopCapturingParents() {
312
215
  const frame = inst.stack;
313
216
  inst.stack = frame.below;
314
- if (frame.offset < frame.child.parents.length) {
315
- for (let i = frame.offset; i < frame.child.parents.length; i++) {
316
- const maybeRemovedParent = frame.child.parents[i];
317
- if (!frame.child.parentSet.has(maybeRemovedParent)) {
318
- detach(maybeRemovedParent, frame.child);
217
+ const { child, offset, maybeRemoved } = frame;
218
+ if (offset < child.parents.length) {
219
+ for (let i = offset; i < child.parents.length; i++) {
220
+ const maybeRemovedParent = child.parents[i];
221
+ if (!child.parentSet.has(maybeRemovedParent)) {
222
+ detach(maybeRemovedParent, child);
319
223
  }
320
224
  }
321
- frame.child.parents.length = frame.offset;
322
- frame.child.parentEpochs.length = frame.offset;
323
- }
324
- if (frame.maybeRemoved) {
325
- for (let i = 0; i < frame.maybeRemoved.length; i++) {
326
- const maybeRemovedParent = frame.maybeRemoved[i];
327
- if (!frame.child.parentSet.has(maybeRemovedParent)) {
328
- detach(maybeRemovedParent, frame.child);
225
+ child.parents.length = offset;
226
+ child.parentEpochs.length = offset;
227
+ }
228
+ if (maybeRemoved) {
229
+ for (let i = 0; i < maybeRemoved.length; i++) {
230
+ const maybeRemovedParent = maybeRemoved[i];
231
+ if (!child.parentSet.has(maybeRemovedParent)) {
232
+ detach(maybeRemovedParent, child);
329
233
  }
330
234
  }
331
235
  }
332
- if (frame.child.__debug_ancestor_epochs__) {
333
- captureAncestorEpochs(frame.child, frame.child.__debug_ancestor_epochs__);
236
+ if (child.__debug_ancestor_epochs__) {
237
+ captureAncestorEpochs(child, child.__debug_ancestor_epochs__);
334
238
  }
335
239
  }
336
240
  function maybeCaptureParent(p) {
337
- if (inst.stack) {
338
- const wasCapturedAlready = inst.stack.child.parentSet.has(p);
339
- if (wasCapturedAlready) {
340
- return;
341
- }
342
- inst.stack.child.parentSet.add(p);
343
- if (inst.stack.child.isActivelyListening) {
344
- attach(p, inst.stack.child);
345
- }
346
- if (inst.stack.offset < inst.stack.child.parents.length) {
347
- const maybeRemovedParent = inst.stack.child.parents[inst.stack.offset];
348
- if (maybeRemovedParent !== p) {
349
- if (!inst.stack.maybeRemoved) {
350
- inst.stack.maybeRemoved = [maybeRemovedParent];
351
- } else {
352
- inst.stack.maybeRemoved.push(maybeRemovedParent);
353
- }
241
+ const stack = inst.stack;
242
+ if (!stack) return;
243
+ const { child } = stack;
244
+ if (!child.parentSet.add(p)) {
245
+ return;
246
+ }
247
+ if (child.isActivelyListening) {
248
+ attach(p, child);
249
+ }
250
+ if (stack.offset < child.parents.length) {
251
+ const maybeRemovedParent = child.parents[stack.offset];
252
+ if (maybeRemovedParent !== p) {
253
+ if (!stack.maybeRemoved) {
254
+ stack.maybeRemoved = [maybeRemovedParent];
255
+ } else {
256
+ stack.maybeRemoved.push(maybeRemovedParent);
354
257
  }
355
258
  }
356
- inst.stack.child.parents[inst.stack.offset] = p;
357
- inst.stack.child.parentEpochs[inst.stack.offset] = p.lastChangedEpoch;
358
- inst.stack.offset++;
359
259
  }
260
+ child.parents[stack.offset] = p;
261
+ child.parentEpochs[stack.offset] = p.lastChangedEpoch;
262
+ stack.offset++;
360
263
  }
361
264
  function whyAmIRunning() {
362
265
  const child = inst.stack?.child;
@@ -368,13 +271,11 @@ function whyAmIRunning() {
368
271
  function captureAncestorEpochs(child, ancestorEpochs) {
369
272
  for (let i = 0; i < child.parents.length; i++) {
370
273
  const parent = child.parents[i];
371
- const epoch = child.parentEpochs[i];
372
- ancestorEpochs.set(parent, epoch);
274
+ ancestorEpochs.set(parent, child.parentEpochs[i]);
373
275
  if (isComputed(parent)) {
374
276
  captureAncestorEpochs(parent, ancestorEpochs);
375
277
  }
376
278
  }
377
- return ancestorEpochs;
378
279
  }
379
280
  function collectChangedAncestors(child, ancestorEpochs) {
380
281
  const changeTree = {};
@@ -383,9 +284,7 @@ function collectChangedAncestors(child, ancestorEpochs) {
383
284
  if (!ancestorEpochs.has(parent)) {
384
285
  continue;
385
286
  }
386
- const prevEpoch = ancestorEpochs.get(parent);
387
- const currentEpoch = parent.lastChangedEpoch;
388
- if (currentEpoch !== prevEpoch) {
287
+ if (parent.lastChangedEpoch !== ancestorEpochs.get(parent)) {
389
288
  if (isComputed(parent)) {
390
289
  changeTree[parent.name] = collectChangedAncestors(parent, ancestorEpochs);
391
290
  } else {
@@ -449,12 +348,14 @@ var HistoryBuffer = class {
449
348
  /**
450
349
  * Adds a diff entry to the history buffer, representing a change between two epochs.
451
350
  *
452
- * If the diff is undefined, the operation is ignored. If the diff is RESET_VALUE,
453
- * the entire buffer is cleared to indicate that historical tracking should restart.
351
+ * If the diff is RESET_VALUE, or undefined (meaning no diff is available), the entire buffer is
352
+ * cleared to indicate that historical tracking should restart. Silently skipping an entry would
353
+ * leave a gap, and a later `getChangesSince` from before the gap would return an incomplete
354
+ * diff list rather than RESET_VALUE.
454
355
  *
455
356
  * @param lastComputedEpoch - The epoch when the previous value was computed
456
357
  * @param currentEpoch - The epoch when the current value was computed
457
- * @param diff - The diff representing the change, or RESET_VALUE to clear history
358
+ * @param diff - The diff representing the change, or RESET_VALUE / undefined to clear history
458
359
  * @example
459
360
  * ```ts
460
361
  * const buffer = new HistoryBuffer<string>(5)
@@ -463,10 +364,7 @@ var HistoryBuffer = class {
463
364
  * ```
464
365
  */
465
366
  pushEntry(lastComputedEpoch, currentEpoch, diff) {
466
- if (diff === void 0) {
467
- return;
468
- }
469
- if (diff === RESET_VALUE) {
367
+ if (diff === RESET_VALUE || diff === void 0) {
470
368
  this.clear();
471
369
  return;
472
370
  }
@@ -519,7 +417,7 @@ var HistoryBuffer = class {
519
417
  }
520
418
  const [fromEpoch, toEpoch] = elem;
521
419
  if (i === 0 && sinceEpoch >= toEpoch) {
522
- return [];
420
+ return EMPTY_ARRAY;
523
421
  }
524
422
  if (fromEpoch <= sinceEpoch && sinceEpoch < toEpoch) {
525
423
  const len = i + 1;
@@ -547,37 +445,26 @@ var Transaction = class {
547
445
  isSync;
548
446
  asyncProcessCount = 0;
549
447
  initialAtomValues = /* @__PURE__ */ new Map();
550
- /**
551
- * Get whether this transaction is a root (no parents).
552
- *
553
- * @public
554
- */
555
- // eslint-disable-next-line tldraw/no-setter-getter
556
- get isRoot() {
557
- return this.parent === null;
558
- }
559
- /**
560
- * Commit the transaction's changes.
561
- *
562
- * @public
563
- */
564
448
  commit() {
565
- if (inst2.globalIsReacting) {
566
- for (const atom2 of this.initialAtomValues.keys()) {
567
- traverseAtomForCleanup(atom2);
568
- }
569
- } else if (this.isRoot) {
449
+ if (this.parent === null) {
570
450
  flushChanges(this.initialAtomValues.keys());
571
- } else {
572
- this.initialAtomValues.forEach((value, atom2) => {
573
- if (!this.parent.initialAtomValues.has(atom2)) {
574
- this.parent.initialAtomValues.set(atom2, value);
575
- }
576
- });
451
+ return;
452
+ }
453
+ const parentValues = this.parent.initialAtomValues;
454
+ if (parentValues.size === 0) {
455
+ this.parent.initialAtomValues = this.initialAtomValues;
456
+ return;
577
457
  }
458
+ this.initialAtomValues.forEach((value, atom2) => {
459
+ if (!parentValues.has(atom2)) {
460
+ parentValues.set(atom2, value);
461
+ }
462
+ });
578
463
  }
579
464
  /**
580
- * Abort the transaction.
465
+ * Abort the transaction. Restores every atom changed in this transaction to its initial
466
+ * value, then commits. Must be called while this is still `inst.currentTransaction`, so that
467
+ * the restoring sets are recorded against it instead of each flushing effects on their own.
581
468
  *
582
469
  * @public
583
470
  */
@@ -596,17 +483,13 @@ var inst2 = singleton("transactions", () => ({
596
483
  // Whether any transaction is reacting.
597
484
  globalIsReacting: false,
598
485
  currentTransaction: null,
599
- cleanupReactors: null,
600
- reactionEpoch: GLOBAL_START_EPOCH + 1
486
+ cleanupReactors: null
601
487
  }));
602
- function getReactionEpoch() {
603
- return inst2.reactionEpoch;
604
- }
605
488
  function getGlobalEpoch() {
606
489
  return inst2.globalEpoch;
607
490
  }
608
- function getIsReacting() {
609
- return inst2.globalIsReacting;
491
+ function getIsInTransaction() {
492
+ return inst2.currentTransaction !== null;
610
493
  }
611
494
  var traverseReactors;
612
495
  function traverseChild(child) {
@@ -620,22 +503,21 @@ function traverseChild(child) {
620
503
  child.children.visit(traverseChild);
621
504
  }
622
505
  }
623
- function traverse(reactors, child) {
624
- traverseReactors = reactors;
625
- traverseChild(child);
626
- }
627
506
  function flushChanges(atoms) {
628
507
  if (inst2.globalIsReacting) {
629
- throw new Error("flushChanges cannot be called during a reaction");
508
+ for (const atom2 of atoms) {
509
+ traverseAtomForCleanup(atom2);
510
+ }
511
+ return;
630
512
  }
631
513
  const outerTxn = inst2.currentTransaction;
632
514
  try {
633
515
  inst2.currentTransaction = null;
634
516
  inst2.globalIsReacting = true;
635
- inst2.reactionEpoch = inst2.globalEpoch;
636
517
  const reactors = /* @__PURE__ */ new Set();
518
+ traverseReactors = reactors;
637
519
  for (const atom2 of atoms) {
638
- atom2.children.visit((child) => traverse(reactors, child));
520
+ atom2.children.visit(traverseChild);
639
521
  }
640
522
  for (const r of reactors) {
641
523
  r.maybeScheduleEffect();
@@ -663,15 +545,13 @@ function atomDidChange(atom2, previousValue) {
663
545
  if (!inst2.currentTransaction.initialAtomValues.has(atom2)) {
664
546
  inst2.currentTransaction.initialAtomValues.set(atom2, previousValue);
665
547
  }
666
- } else if (inst2.globalIsReacting) {
667
- traverseAtomForCleanup(atom2);
668
548
  } else {
669
549
  flushChanges([atom2]);
670
550
  }
671
551
  }
672
552
  function traverseAtomForCleanup(atom2) {
673
- const rs = inst2.cleanupReactors ??= /* @__PURE__ */ new Set();
674
- atom2.children.visit((child) => traverse(rs, child));
553
+ traverseReactors = inst2.cleanupReactors ??= /* @__PURE__ */ new Set();
554
+ atom2.children.visit(traverseChild);
675
555
  }
676
556
  function advanceGlobalEpoch() {
677
557
  inst2.globalEpoch++;
@@ -732,13 +612,16 @@ async function deferAsyncEffects(fn) {
732
612
  return result;
733
613
  }
734
614
  }
735
- inst2.currentTransaction = null;
736
- if (typeof error !== "undefined") {
737
- txn.abort();
738
- throw error;
739
- } else {
740
- txn.commit();
741
- return result;
615
+ try {
616
+ if (typeof error !== "undefined") {
617
+ txn.abort();
618
+ throw error;
619
+ } else {
620
+ txn.commit();
621
+ return result;
622
+ }
623
+ } finally {
624
+ inst2.currentTransaction = null;
742
625
  }
743
626
  }
744
627
 
@@ -747,39 +630,23 @@ var __Atom__ = class {
747
630
  constructor(name, current, options) {
748
631
  this.name = name;
749
632
  this.current = current;
750
- this.isEqual = options?.isEqual ?? null;
751
- if (!options) return;
752
- if (options.historyLength) {
633
+ this.isEqual = options?.isEqual ?? equals;
634
+ if (options?.historyLength) {
753
635
  this.historyBuffer = new HistoryBuffer(options.historyLength);
754
636
  }
755
- this.computeDiff = options.computeDiff;
637
+ this.computeDiff = options?.computeDiff;
756
638
  }
757
639
  name;
758
640
  current;
759
- /**
760
- * Custom equality function for comparing values, or null to use default equality.
761
- * @internal
762
- */
641
+ /** @internal */
763
642
  isEqual;
764
- /**
765
- * Optional function to compute diffs between old and new values.
766
- * @internal
767
- */
643
+ /** @internal */
768
644
  computeDiff;
769
- /**
770
- * The global epoch when this atom was last changed.
771
- * @internal
772
- */
645
+ /** @internal */
773
646
  lastChangedEpoch = getGlobalEpoch();
774
- /**
775
- * Set of child signals that depend on this atom.
776
- * @internal
777
- */
647
+ /** @internal */
778
648
  children = new ArraySet();
779
- /**
780
- * Optional history buffer for tracking changes over time.
781
- * @internal
782
- */
649
+ /** @internal */
783
650
  historyBuffer;
784
651
  /**
785
652
  * Gets the current value without capturing it as a dependency in the current reactive context.
@@ -820,18 +687,19 @@ var __Atom__ = class {
820
687
  * ```
821
688
  */
822
689
  set(value, diff) {
823
- if (this.isEqual?.(this.current, value) ?? equals(this.current, value)) {
690
+ if (this.isEqual(this.current, value)) {
824
691
  return this.current;
825
692
  }
693
+ let historyDiff;
694
+ if (this.historyBuffer) {
695
+ historyDiff = diff !== void 0 ? diff : this.computeDiff ? this.computeDiff(this.current, value, this.lastChangedEpoch, getGlobalEpoch() + 1) : RESET_VALUE;
696
+ }
826
697
  advanceGlobalEpoch();
698
+ const epoch = getGlobalEpoch();
827
699
  if (this.historyBuffer) {
828
- this.historyBuffer.pushEntry(
829
- this.lastChangedEpoch,
830
- getGlobalEpoch(),
831
- diff ?? this.computeDiff?.(this.current, value, this.lastChangedEpoch, getGlobalEpoch()) ?? RESET_VALUE
832
- );
700
+ this.historyBuffer.pushEntry(this.lastChangedEpoch, epoch, historyDiff);
833
701
  }
834
- this.lastChangedEpoch = getGlobalEpoch();
702
+ this.lastChangedEpoch = epoch;
835
703
  const oldValue = this.current;
836
704
  this.current = value;
837
705
  atomDidChange(this, oldValue);
@@ -874,13 +742,8 @@ function atom(name, initialValue, options) {
874
742
  function isAtom(value) {
875
743
  return value instanceof _Atom;
876
744
  }
877
-
878
- // src/lib/warnings.ts
879
- var didWarnComputedGetter = false;
880
745
  function logComputedGetterWarning() {
881
- if (didWarnComputedGetter) return;
882
- didWarnComputedGetter = true;
883
- console.warn(
746
+ warnOnce(
884
747
  `Using \`@computed\` as a decorator for getters is deprecated and will be removed in the near future. Please refactor to use \`@computed\` as a decorator for methods.
885
748
 
886
749
  // Before
@@ -934,7 +797,8 @@ var __UNSAFE__Computed = class {
934
797
  lastTraversedEpoch = GLOBAL_START_EPOCH;
935
798
  __debug_ancestor_epochs__ = null;
936
799
  /**
937
- * The epoch when the reactor was last checked.
800
+ * The epoch when the reactor was last checked. Advances on every check, including ones that
801
+ * find no change, unlike `lastChangedEpoch`.
938
802
  */
939
803
  lastCheckedEpoch = GLOBAL_START_EPOCH;
940
804
  parentSet = new ArraySet();
@@ -955,7 +819,11 @@ var __UNSAFE__Computed = class {
955
819
  __unsafe__getWithoutCapture(ignoreErrors) {
956
820
  const isNew = this.lastChangedEpoch === GLOBAL_START_EPOCH;
957
821
  const globalEpoch = getGlobalEpoch();
958
- if (!isNew && (this.lastCheckedEpoch === globalEpoch || this.isActivelyListening && getIsReacting() && this.lastTraversedEpoch < getReactionEpoch() || !haveParentsChanged(this))) {
822
+ if (!isNew && (this.lastCheckedEpoch === globalEpoch || // Every ancestor change to an actively-listening computed traverses it (`flushChanges`),
823
+ // so if it hasn't been traversed since it was last checked the O(parents) scan can be
824
+ // skipped. Not valid while a transaction is open (changes traverse at commit), and only
825
+ // if it was up to date when attached (see `attach` in helpers.ts).
826
+ this.isActivelyListening && !getIsInTransaction() && this.lastTraversedEpoch <= this.lastCheckedEpoch || !haveParentsChanged(this))) {
959
827
  this.lastCheckedEpoch = globalEpoch;
960
828
  if (this.error) {
961
829
  if (!ignoreErrors) {
@@ -972,27 +840,29 @@ var __UNSAFE__Computed = class {
972
840
  const result = this.derive(this.state, this.lastCheckedEpoch);
973
841
  const newState = result instanceof WithDiff ? result.value : result;
974
842
  const isUninitialized2 = this.state === UNINITIALIZED;
975
- if (isUninitialized2 || !this.isEqual(newState, this.state)) {
843
+ const epoch = getGlobalEpoch();
844
+ if (isUninitialized2 || !this.isEqual(this.state, newState)) {
976
845
  if (this.historyBuffer && !isUninitialized2) {
977
846
  const diff = result instanceof WithDiff ? result.diff : void 0;
978
847
  this.historyBuffer.pushEntry(
979
848
  this.lastChangedEpoch,
980
- getGlobalEpoch(),
981
- diff ?? this.computeDiff?.(this.state, newState, this.lastCheckedEpoch, getGlobalEpoch()) ?? RESET_VALUE
849
+ epoch,
850
+ diff !== void 0 ? diff : this.computeDiff ? this.computeDiff(this.state, newState, this.lastCheckedEpoch, epoch) : RESET_VALUE
982
851
  );
983
852
  }
984
- this.lastChangedEpoch = getGlobalEpoch();
853
+ this.lastChangedEpoch = epoch;
985
854
  this.state = newState;
986
855
  }
987
856
  this.error = null;
988
- this.lastCheckedEpoch = getGlobalEpoch();
857
+ this.lastCheckedEpoch = epoch;
989
858
  return this.state;
990
859
  } catch (e) {
991
- if (this.state !== UNINITIALIZED) {
860
+ const epoch = getGlobalEpoch();
861
+ if (this.error === null) {
992
862
  this.state = UNINITIALIZED;
993
- this.lastChangedEpoch = getGlobalEpoch();
863
+ this.lastChangedEpoch = epoch;
994
864
  }
995
- this.lastCheckedEpoch = getGlobalEpoch();
865
+ this.lastCheckedEpoch = epoch;
996
866
  if (this.historyBuffer) {
997
867
  this.historyBuffer.clear();
998
868
  }
@@ -1020,50 +890,13 @@ var __UNSAFE__Computed = class {
1020
890
  }
1021
891
  };
1022
892
  var _Computed = singleton("Computed", () => __UNSAFE__Computed);
1023
- function computedMethodLegacyDecorator(options = {}, _target, key, descriptor) {
1024
- const originalMethod = descriptor.value;
1025
- const derivationKey = /* @__PURE__ */ Symbol.for("__@ibodr/state__computed__" + key);
1026
- descriptor.value = function() {
1027
- let d = this[derivationKey];
1028
- if (!d) {
1029
- d = new _Computed(key, originalMethod.bind(this), options);
1030
- Object.defineProperty(this, derivationKey, {
1031
- enumerable: false,
1032
- configurable: false,
1033
- writable: false,
1034
- value: d
1035
- });
1036
- }
1037
- return d.get();
1038
- };
1039
- descriptor.value[isComputedMethodKey] = true;
1040
- return descriptor;
1041
- }
1042
- function computedGetterLegacyDecorator(options = {}, _target, key, descriptor) {
1043
- const originalMethod = descriptor.get;
1044
- const derivationKey = /* @__PURE__ */ Symbol.for("__@ibodr/state__computed__" + key);
1045
- descriptor.get = function() {
1046
- let d = this[derivationKey];
1047
- if (!d) {
1048
- d = new _Computed(key, originalMethod.bind(this), options);
1049
- Object.defineProperty(this, derivationKey, {
1050
- enumerable: false,
1051
- configurable: false,
1052
- writable: false,
1053
- value: d
1054
- });
1055
- }
1056
- return d.get();
1057
- };
1058
- return descriptor;
1059
- }
1060
- function computedMethodTc39Decorator(options, compute, context) {
1061
- assert(context.kind === "method", "@computed can only be used on methods");
1062
- const derivationKey = /* @__PURE__ */ Symbol.for("__@ibodr/state__computed__" + String(context.name));
1063
- const fn = function() {
893
+ var derivationKeyKey = "@@__computedDerivationKey__@@";
894
+ function makeComputedWrapper(name, compute, options) {
895
+ const derivationKey = /* @__PURE__ */ Symbol("__@ibodr/state__computed__" + name);
896
+ const wrapper = function() {
1064
897
  let d = this[derivationKey];
1065
898
  if (!d) {
1066
- d = new _Computed(String(context.name), compute.bind(this), options);
899
+ d = new _Computed(name, compute.bind(this), options);
1067
900
  Object.defineProperty(this, derivationKey, {
1068
901
  enumerable: false,
1069
902
  configurable: false,
@@ -1073,38 +906,45 @@ function computedMethodTc39Decorator(options, compute, context) {
1073
906
  }
1074
907
  return d.get();
1075
908
  };
1076
- fn[isComputedMethodKey] = true;
1077
- return fn;
909
+ wrapper[derivationKeyKey] = derivationKey;
910
+ return wrapper;
1078
911
  }
1079
912
  function computedDecorator(options = {}, args) {
1080
913
  if (args.length === 2) {
1081
914
  const [originalMethod, context] = args;
1082
- return computedMethodTc39Decorator(options, originalMethod, context);
915
+ assert(context.kind === "method", "@computed can only be used on methods");
916
+ return makeComputedWrapper(String(context.name), originalMethod, options);
1083
917
  } else {
1084
918
  const [_target, key, descriptor] = args;
1085
919
  if (descriptor.get) {
1086
920
  logComputedGetterWarning();
1087
- return computedGetterLegacyDecorator(options, _target, key, descriptor);
921
+ descriptor.get = makeComputedWrapper(key, descriptor.get, options);
1088
922
  } else {
1089
- return computedMethodLegacyDecorator(options, _target, key, descriptor);
923
+ descriptor.value = makeComputedWrapper(key, descriptor.value, options);
1090
924
  }
925
+ return descriptor;
1091
926
  }
1092
927
  }
1093
- var isComputedMethodKey = "@@__isComputedMethod__@@";
1094
928
  function getComputedInstance(obj, propertyName) {
1095
- const key = /* @__PURE__ */ Symbol.for("__@ibodr/state__computed__" + propertyName.toString());
1096
- let inst3 = obj[key];
1097
- if (!inst3) {
1098
- const val = obj[propertyName];
1099
- if (typeof val === "function" && val[isComputedMethodKey]) {
1100
- val.call(obj);
929
+ for (let proto = obj; proto; proto = Object.getPrototypeOf(proto)) {
930
+ const descriptor = Object.getOwnPropertyDescriptor(proto, propertyName);
931
+ const wrapper = descriptor?.get ?? descriptor?.value;
932
+ const key = wrapper?.[derivationKeyKey];
933
+ if (!key) continue;
934
+ let inst3 = obj[key];
935
+ if (!inst3) {
936
+ try {
937
+ wrapper.call(obj);
938
+ } catch {
939
+ }
940
+ inst3 = obj[key];
1101
941
  }
1102
- inst3 = obj[key];
942
+ return inst3;
1103
943
  }
1104
- return inst3;
944
+ return void 0;
1105
945
  }
1106
946
  function computed() {
1107
- if (arguments.length === 1) {
947
+ if (arguments.length <= 1) {
1108
948
  const options = arguments[0];
1109
949
  return (...args) => computedDecorator(options, args);
1110
950
  } else if (typeof arguments[0] === "string") {
@@ -1141,6 +981,10 @@ var __EffectScheduler__ = class {
1141
981
  /** @internal */
1142
982
  _scheduleCount = 0;
1143
983
  /** @internal */
984
+ _executeDepth = 0;
985
+ /** @internal */
986
+ _wasScheduledWhileExecuting = false;
987
+ /** @internal */
1144
988
  __debug_ancestor_epochs__ = null;
1145
989
  /**
1146
990
  * The number of times this effect has been scheduled.
@@ -1162,7 +1006,7 @@ var __EffectScheduler__ = class {
1162
1006
  maybeScheduleEffect() {
1163
1007
  if (!this._isActivelyListening) return;
1164
1008
  if (this.lastReactedEpoch === getGlobalEpoch()) return;
1165
- if (this.parents.length && !haveParentsChanged(this)) {
1009
+ if ((this.lastReactedEpoch !== GLOBAL_START_EPOCH || this.parents.length > 0) && !haveParentsChanged(this)) {
1166
1010
  this.lastReactedEpoch = getGlobalEpoch();
1167
1011
  return;
1168
1012
  }
@@ -1174,13 +1018,17 @@ var __EffectScheduler__ = class {
1174
1018
  if (this._scheduleEffect) {
1175
1019
  this._scheduleEffect(this.maybeExecute);
1176
1020
  } else {
1177
- this.execute();
1021
+ this.maybeExecute();
1178
1022
  }
1179
1023
  }
1180
1024
  /** @internal */
1181
1025
  // eslint-disable-next-line tldraw/prefer-class-methods
1182
1026
  maybeExecute = () => {
1183
1027
  if (!this._isActivelyListening) return;
1028
+ if (this._executeDepth > 0) {
1029
+ this._wasScheduledWhileExecuting = true;
1030
+ return;
1031
+ }
1184
1032
  this.execute();
1185
1033
  };
1186
1034
  /**
@@ -1192,7 +1040,9 @@ var __EffectScheduler__ = class {
1192
1040
  attach() {
1193
1041
  this._isActivelyListening = true;
1194
1042
  for (let i = 0, n = this.parents.length; i < n; i++) {
1195
- attach(this.parents[i], this);
1043
+ const parent = this.parents[i];
1044
+ parent.__unsafe__getWithoutCapture(true);
1045
+ attach(parent, this);
1196
1046
  }
1197
1047
  }
1198
1048
  /**
@@ -1212,6 +1062,25 @@ var __EffectScheduler__ = class {
1212
1062
  * @public
1213
1063
  */
1214
1064
  execute() {
1065
+ if (this._executeDepth > 0) return this.executeOnce();
1066
+ this._wasScheduledWhileExecuting = false;
1067
+ let result = this.executeOnce();
1068
+ for (let depth = 0; this._wasScheduledWhileExecuting; depth++) {
1069
+ this._wasScheduledWhileExecuting = false;
1070
+ if (depth >= 1e3) {
1071
+ throw new Error("Reaction update depth limit exceeded");
1072
+ }
1073
+ if (!this._isActivelyListening) break;
1074
+ if (!haveParentsChanged(this)) {
1075
+ this.lastReactedEpoch = getGlobalEpoch();
1076
+ break;
1077
+ }
1078
+ result = this.executeOnce();
1079
+ }
1080
+ return result;
1081
+ }
1082
+ executeOnce() {
1083
+ this._executeDepth++;
1215
1084
  try {
1216
1085
  startCapturingParents(this);
1217
1086
  const currentEpoch = getGlobalEpoch();
@@ -1220,6 +1089,7 @@ var __EffectScheduler__ = class {
1220
1089
  return result;
1221
1090
  } finally {
1222
1091
  stopCapturingParents();
1092
+ this._executeDepth--;
1223
1093
  }
1224
1094
  }
1225
1095
  };
@@ -1284,10 +1154,15 @@ function localStorageAtom(name, initialValue, options) {
1284
1154
  } catch {
1285
1155
  }
1286
1156
  };
1287
- window.addEventListener("storage", handleStorageEvent);
1157
+ const canListen = typeof window !== "undefined";
1158
+ if (canListen) {
1159
+ window.addEventListener("storage", handleStorageEvent);
1160
+ }
1288
1161
  const cleanup = () => {
1289
1162
  reactCleanup();
1290
- window.removeEventListener("storage", handleStorageEvent);
1163
+ if (canListen) {
1164
+ window.removeEventListener("storage", handleStorageEvent);
1165
+ }
1291
1166
  };
1292
1167
  return [outAtom, cleanup];
1293
1168
  }
@@ -1302,7 +1177,7 @@ if (actualApiVersion !== currentApiVersion) {
1302
1177
  }
1303
1178
  registerDrawLibraryVersion(
1304
1179
  "@ibodr/state",
1305
- "0.2.5",
1180
+ "0.2.7",
1306
1181
  "esm"
1307
1182
  );
1308
1183