@tldraw/state 5.4.0-next.09eca5dee30d → 5.4.0-next.0a83c4ec44f1

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 (68) hide show
  1. package/DOCS.md +64 -63
  2. package/README.md +35 -36
  3. package/dist-cjs/index.d.ts +26 -27
  4. package/dist-cjs/index.js +1 -1
  5. package/dist-cjs/lib/ArraySet.js +47 -144
  6. package/dist-cjs/lib/ArraySet.js.map +2 -2
  7. package/dist-cjs/lib/Atom.js +10 -25
  8. package/dist-cjs/lib/Atom.js.map +2 -2
  9. package/dist-cjs/lib/Computed.js +36 -61
  10. package/dist-cjs/lib/Computed.js.map +2 -2
  11. package/dist-cjs/lib/EffectScheduler.js +4 -2
  12. package/dist-cjs/lib/EffectScheduler.js.map +2 -2
  13. package/dist-cjs/lib/HistoryBuffer.js +8 -8
  14. package/dist-cjs/lib/HistoryBuffer.js.map +2 -2
  15. package/dist-cjs/lib/capture.js.map +2 -2
  16. package/dist-cjs/lib/constants.js.map +2 -2
  17. package/dist-cjs/lib/helpers.js +3 -11
  18. package/dist-cjs/lib/helpers.js.map +2 -2
  19. package/dist-cjs/lib/localStorageAtom.js +7 -2
  20. package/dist-cjs/lib/localStorageAtom.js.map +2 -2
  21. package/dist-cjs/lib/transactions.js +37 -49
  22. package/dist-cjs/lib/transactions.js.map +2 -2
  23. package/dist-cjs/lib/types.js.map +1 -1
  24. package/dist-esm/index.d.mts +26 -27
  25. package/dist-esm/index.mjs +1 -1
  26. package/dist-esm/lib/ArraySet.mjs +47 -144
  27. package/dist-esm/lib/ArraySet.mjs.map +2 -2
  28. package/dist-esm/lib/Atom.mjs +10 -25
  29. package/dist-esm/lib/Atom.mjs.map +2 -2
  30. package/dist-esm/lib/Computed.mjs +37 -62
  31. package/dist-esm/lib/Computed.mjs.map +2 -2
  32. package/dist-esm/lib/EffectScheduler.mjs +4 -2
  33. package/dist-esm/lib/EffectScheduler.mjs.map +2 -2
  34. package/dist-esm/lib/HistoryBuffer.mjs +8 -8
  35. package/dist-esm/lib/HistoryBuffer.mjs.map +2 -2
  36. package/dist-esm/lib/capture.mjs.map +2 -2
  37. package/dist-esm/lib/constants.mjs.map +2 -2
  38. package/dist-esm/lib/helpers.mjs +3 -11
  39. package/dist-esm/lib/helpers.mjs.map +2 -2
  40. package/dist-esm/lib/localStorageAtom.mjs +7 -2
  41. package/dist-esm/lib/localStorageAtom.mjs.map +2 -2
  42. package/dist-esm/lib/transactions.mjs +37 -49
  43. package/dist-esm/lib/transactions.mjs.map +2 -2
  44. package/dist-esm/lib/types.mjs.map +1 -1
  45. package/package.json +8 -2
  46. package/src/lib/ArraySet.ts +68 -176
  47. package/src/lib/Atom.ts +22 -27
  48. package/src/lib/Computed.ts +68 -95
  49. package/src/lib/EffectScheduler.ts +13 -9
  50. package/src/lib/HistoryBuffer.ts +12 -10
  51. package/src/lib/__tests__/ArraySet.test.ts +39 -13
  52. package/src/lib/__tests__/EffectScheduler.test.ts +69 -0
  53. package/src/lib/__tests__/HistoryBuffer.test.ts +6 -3
  54. package/src/lib/__tests__/computed.test.ts +75 -0
  55. package/src/lib/__tests__/deferAsyncEffects.test.ts +23 -0
  56. package/src/lib/__tests__/errors.test.ts +24 -0
  57. package/src/lib/__tests__/fuzz.tlstate.test.ts +97 -8
  58. package/src/lib/__tests__/helpers.test.ts +7 -11
  59. package/src/lib/__tests__/history.test.ts +32 -2
  60. package/src/lib/__tests__/localStorageAtom.test.ts +15 -0
  61. package/src/lib/__tests__/propagation.test.ts +104 -1
  62. package/src/lib/__tests__/transactions.test.ts +23 -0
  63. package/src/lib/capture.ts +12 -12
  64. package/src/lib/constants.ts +3 -22
  65. package/src/lib/helpers.ts +19 -139
  66. package/src/lib/localStorageAtom.ts +9 -2
  67. package/src/lib/transactions.ts +68 -98
  68. package/src/lib/types.ts +7 -7
@@ -36,6 +36,30 @@ describe('computed signals that throw (CE)', () => {
36
36
  expect(b.get()).toBe(3)
37
37
  })
38
38
 
39
+ it('[CE1] cache a throw from the very first computation too', () => {
40
+ let numComputations = 0
41
+ const a = atom('', 1)
42
+ const b = computed('', () => {
43
+ numComputations++
44
+ if (a.get() === 1) throw new Error('test')
45
+ return a.get()
46
+ })
47
+
48
+ expect(() => b.get()).toThrowErrorMatchingInlineSnapshot(`[Error: test]`)
49
+ expect(() => b.get()).toThrowErrorMatchingInlineSnapshot(`[Error: test]`)
50
+ expect(() => b.get()).toThrowErrorMatchingInlineSnapshot(`[Error: test]`)
51
+ expect(numComputations).toBe(1)
52
+
53
+ // an unrelated change doesn't re-run it either
54
+ atom('', 0).set(1)
55
+ expect(() => b.get()).toThrowErrorMatchingInlineSnapshot(`[Error: test]`)
56
+ expect(numComputations).toBe(1)
57
+
58
+ a.set(2)
59
+ expect(b.get()).toBe(2)
60
+ expect(numComputations).toBe(2)
61
+ })
62
+
39
63
  it('[CE2] entering the error state notifies effects, but consecutive errors do not', () => {
40
64
  const a = atom('', 1)
41
65
  let numComputations = 0
@@ -79,7 +79,19 @@ interface FuzzSystemState {
79
79
  derivations: Record<string, { derivation: Computed<Letter>; sneakyGet: () => Letter }>
80
80
  derivationsInDerivations: Record<string, Computed<Computed<Letter>>>
81
81
  atomsInDerivations: Record<string, Computed<Atom<Letter>>>
82
- reactors: Record<string, { reactor: Reactor; result: string | null; dependencies: Signal<any>[] }>
82
+ reactors: Record<
83
+ string,
84
+ {
85
+ reactor: Reactor
86
+ result: string | null
87
+ dependencies: Signal<any>[]
88
+ // runs its body inside a transaction that first writes a fixed letter to an atom, so
89
+ // that reads inside transactions inside the reaction phase get exercised
90
+ transacting: boolean
91
+ // schedules through a queue drained by the `flush_deferred` op (like state-react does)
92
+ deferred: boolean
93
+ }
94
+ >
83
95
  }
84
96
 
85
97
  type Op =
@@ -91,6 +103,8 @@ type Op =
91
103
  | { type: 'run_several_ops_in_transaction'; ops: Op[] }
92
104
  | { type: 'start_reactor'; id: string }
93
105
  | { type: 'stop_reactor'; id: string }
106
+ | { type: 'deref_derivation_in_transaction'; id: string; atomId: string; value: Letter }
107
+ | { type: 'flush_deferred' }
94
108
 
95
109
  const MAX_ATOMS = 10
96
110
  const MAX_ATOMS_IN_ATOMS = 10
@@ -103,6 +117,7 @@ const MAX_OPS_IN_TRANSACTION = 10
103
117
 
104
118
  class Test {
105
119
  source: RandomSource
120
+ deferredExecutes: Array<() => void> = []
106
121
  systemState: FuzzSystemState = {
107
122
  atoms: {},
108
123
  atomsInAtoms: {},
@@ -132,10 +147,13 @@ class Test {
132
147
  expected: {},
133
148
  actual: {},
134
149
  }
135
- for (const [reactorId, { reactor, result: actualResult, dependencies }] of Object.entries(
136
- this.systemState.reactors
137
- )) {
150
+ for (const [
151
+ reactorId,
152
+ { reactor, result: actualResult, dependencies, deferred },
153
+ ] of Object.entries(this.systemState.reactors)) {
138
154
  if (!reactor.scheduler.isActivelyListening) continue
155
+ // a deferred reactor's result lags until its queued execute runs
156
+ if (deferred && this.deferredExecutes.length > 0) continue
139
157
  result.expected[reactorId] = dependencies.map(this.unpack_sneaky).join(':')
140
158
  result.actual[reactorId] = actualResult
141
159
  }
@@ -202,6 +220,10 @@ class Test {
202
220
  )
203
221
  })
204
222
 
223
+ // atoms not yet claimed by a transacting reactor; two reactors writing different letters to
224
+ // the same atom would keep re-triggering each other
225
+ const writableAtoms = Object.values(this.systemState.atoms)
226
+
205
227
  times(this.source.nextIntInRange(1, MAX_REACTORS), () => {
206
228
  const reactorId = this.source.nextId()
207
229
  const dependencies: Signal<any>[] = []
@@ -235,12 +257,39 @@ class Test {
235
257
  dependencies.push(this.source.selectOne(Object.values(this.systemState.atoms)))
236
258
  })
237
259
 
260
+ const transacting = writableAtoms.length > 0 && this.source.choice(0.3)
261
+ const deferred = !transacting && this.source.choice(0.3)
262
+ // A transacting reactor writes one fixed letter to its own atom before reading its
263
+ // dependencies, inside a transaction. Writing the same letter every run means it cannot
264
+ // keep re-triggering itself, and the oracle (which reads the atoms' current values)
265
+ // stays valid once the reaction phase has settled.
266
+ const writeAtom = transacting
267
+ ? writableAtoms.splice(this.source.nextInt(writableAtoms.length), 1)[0]
268
+ : null
269
+ const writeLetter = this.source.selectOne(LETTERS)
270
+ const body = () => {
271
+ this.systemState.reactors[reactorId].result = dependencies.map(unpack).join(':')
272
+ }
273
+ const fn = writeAtom
274
+ ? () => {
275
+ transact(() => {
276
+ writeAtom.set(writeLetter)
277
+ body()
278
+ })
279
+ }
280
+ : body
238
281
  this.systemState.reactors[reactorId] = {
239
- reactor: reactor(reactorId, () => {
240
- this.systemState.reactors[reactorId].result = dependencies.map(unpack).join(':')
241
- }),
282
+ reactor: reactor(
283
+ reactorId,
284
+ fn,
285
+ deferred
286
+ ? { scheduleEffect: (execute) => this.deferredExecutes.push(execute) }
287
+ : undefined
288
+ ),
242
289
  result: '',
243
290
  dependencies,
291
+ transacting,
292
+ deferred,
244
293
  }
245
294
  })
246
295
  }
@@ -299,6 +348,17 @@ class Test {
299
348
  id: this.source.selectOne(Object.keys(this.systemState.reactors)),
300
349
  }
301
350
  },
351
+ 'deref derivation in transaction': () => {
352
+ return {
353
+ type: 'deref_derivation_in_transaction',
354
+ id: this.source.selectOne(Object.keys(this.systemState.derivations)),
355
+ atomId: this.source.selectOne(Object.keys(this.systemState.atoms)),
356
+ value: this.source.selectOne(LETTERS),
357
+ }
358
+ },
359
+ flush_deferred: () => {
360
+ return { type: 'flush_deferred' }
361
+ },
302
362
  })
303
363
  }
304
364
 
@@ -313,7 +373,14 @@ class Test {
313
373
  break
314
374
  }
315
375
  case 'deref_derivation': {
316
- this.systemState.derivations[op.id].derivation.get()
376
+ const { derivation, sneakyGet } = this.systemState.derivations[op.id]
377
+ const actual = derivation.get()
378
+ const expected = sneakyGet()
379
+ if (actual !== expected) {
380
+ throw new Error(
381
+ `derivation ${op.id} returned ${String(actual)}, expected ${String(expected)}`
382
+ )
383
+ }
317
384
  break
318
385
  }
319
386
  case 'deref_derivation_in_derivation': {
@@ -338,6 +405,28 @@ class Test {
338
405
  this.systemState.reactors[op.id].reactor.stop()
339
406
  break
340
407
  }
408
+ case 'deref_derivation_in_transaction': {
409
+ // T2: a read inside a transaction must see the in-transaction value, whether or not
410
+ // the derivation is actively listening
411
+ const { derivation, sneakyGet } = this.systemState.derivations[op.id]
412
+ transact(() => {
413
+ this.systemState.atoms[op.atomId].set(op.value)
414
+ const actual = derivation.get()
415
+ const expected = sneakyGet()
416
+ if (actual !== expected) {
417
+ throw new Error(
418
+ `derivation ${op.id} read inside a transaction returned ${String(actual)}, expected ${String(expected)}`
419
+ )
420
+ }
421
+ })
422
+ break
423
+ }
424
+ case 'flush_deferred': {
425
+ const executes = this.deferredExecutes
426
+ this.deferredExecutes = []
427
+ for (const execute of executes) execute()
428
+ break
429
+ }
341
430
  default: {
342
431
  throw new Error(`Unknown op type: ${op}`)
343
432
  }
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
2
2
  import { ArraySet } from '../ArraySet'
3
3
  import { atom } from '../Atom'
4
4
  import { reactor } from '../EffectScheduler'
5
- import { attach, detach, equals, hasReactors, haveParentsChanged, singleton } from '../helpers'
5
+ import { attach, detach, equals, haveParentsChanged, singleton } from '../helpers'
6
6
  import { Child } from '../types'
7
7
 
8
8
  // Unit tests for the internal helpers behind SPEC.md rules EQ1/EQ2 (equals),
@@ -132,25 +132,21 @@ describe('helpers', () => {
132
132
  })
133
133
  })
134
134
 
135
- describe('hasReactors', () => {
136
- it('returns false when signal has no actively listening children', () => {
137
- const signal = atom('test', 1)
138
- expect(hasReactors(signal)).toBe(false)
139
- })
140
-
141
- it('integrates correctly with real reactive signals', () => {
135
+ // CAP7: a signal's children set is non-empty exactly while something downstream is listening
136
+ describe('children', () => {
137
+ it('is empty unless something is actively listening', () => {
142
138
  const baseAtom = atom('base', 1)
143
- expect(hasReactors(baseAtom)).toBe(false)
139
+ expect(baseAtom.children.isEmpty).toBe(true)
144
140
 
145
141
  const reactorInstance = reactor('test-reactor', () => {
146
142
  baseAtom.get()
147
143
  })
148
144
 
149
145
  reactorInstance.start()
150
- expect(hasReactors(baseAtom)).toBe(true)
146
+ expect(baseAtom.children.isEmpty).toBe(false)
151
147
 
152
148
  reactorInstance.stop()
153
- expect(hasReactors(baseAtom)).toBe(false)
149
+ expect(baseAtom.children.isEmpty).toBe(true)
154
150
  })
155
151
  })
156
152
  })
@@ -1,8 +1,9 @@
1
+ import { exhaustiveSwitchError } from '@tldraw/utils'
1
2
  import { vi } from 'vitest'
2
3
  import { atom } from '../Atom'
3
4
  import { Computed, UNINITIALIZED, computed, isUninitialized, withDiff } from '../Computed'
4
5
  import { react } from '../EffectScheduler'
5
- import { EMPTY_ARRAY, assertNever } from '../helpers'
6
+ import { EMPTY_ARRAY } from '../helpers'
6
7
  import { getGlobalEpoch, transact, transaction } from '../transactions'
7
8
  import { RESET_VALUE, Signal } from '../types'
8
9
 
@@ -78,6 +79,35 @@ describe('atom history (H)', () => {
78
79
  expect(calls).toEqual([[1, 5, epochBeforeSet, getGlobalEpoch()]])
79
80
  })
80
81
 
82
+ it('[H2][C2] a computed read inside computeDiff still sees the change afterwards', () => {
83
+ // computeDiff runs before the epoch ticks, so a dependent computed it reads is not stamped as
84
+ // checked at the epoch of the write that is still in progress.
85
+ const a = atom('', 1, {
86
+ historyLength: 10,
87
+ computeDiff: (prev, next) => {
88
+ c.get()
89
+ return next - prev
90
+ },
91
+ })
92
+ const c: Computed<number> = computed('', () => a.get() * 2)
93
+ const seen: number[] = []
94
+ react('', () => seen.push(c.get()))
95
+
96
+ a.set(2)
97
+
98
+ expect(c.get()).toBe(4)
99
+ expect(seen).toEqual([2, 4])
100
+ expect(a.getDiffSince(a.lastChangedEpoch - 1)).toEqual([1])
101
+ })
102
+
103
+ it('[H2] records an explicit null diff rather than treating it as missing', () => {
104
+ const a = atom<number, null | number>('', 1, { historyLength: 3 })
105
+ const startEpoch = a.lastChangedEpoch
106
+ a.set(2, 1)
107
+ a.set(3, null)
108
+ expect(a.getDiffSince(startEpoch)).toEqual([1, null])
109
+ })
110
+
81
111
  it('[H4] clears the history buffer if no diff can be determined', () => {
82
112
  const a = atom('', 1, { historyLength: 3 })
83
113
  const startEpoch = getGlobalEpoch()
@@ -383,7 +413,7 @@ function getIncrementalRecordMapper<In, Out>(
383
413
  }
384
414
  break
385
415
  default:
386
- assertNever(change)
416
+ exhaustiveSwitchError(change)
387
417
  }
388
418
  }
389
419
 
@@ -260,4 +260,19 @@ describe('localStorageAtom', () => {
260
260
  cleanup2()
261
261
  })
262
262
  })
263
+
264
+ describe('outside the browser', () => {
265
+ it('[LS6] does not throw without a window and returns a working atom', () => {
266
+ vi.stubGlobal('window', undefined)
267
+ try {
268
+ const [atom, cleanup] = localStorageAtom('test-key', 'initial-value')
269
+ expect(atom.get()).toBe('initial-value')
270
+ atom.set('next')
271
+ expect(atom.get()).toBe('next')
272
+ expect(() => cleanup()).not.toThrow()
273
+ } finally {
274
+ vi.unstubAllGlobals()
275
+ }
276
+ })
277
+ })
263
278
  })
@@ -1,7 +1,7 @@
1
1
  import { vi } from 'vitest'
2
2
  import { atom } from '../Atom'
3
3
  import { computed } from '../Computed'
4
- import { react, reactor } from '../EffectScheduler'
4
+ import { EffectScheduler, react, reactor } from '../EffectScheduler'
5
5
  import { transact, transaction } from '../transactions'
6
6
 
7
7
  // Tests for SPEC.md §10 (change propagation and the reaction phase).
@@ -276,4 +276,107 @@ describe('transactions during the reaction phase (P6)', () => {
276
276
  expect(a.__unsafe__getWithoutCapture()).toBe(3)
277
277
  expect(cChanged).toHaveBeenCalledTimes(2)
278
278
  })
279
+
280
+ it('[P6][T2][P7] an actively-listening computed read inside a transaction during a reaction sees in-transaction values', () => {
281
+ // Regression: Computed's cache shortcut for actively-listening computeds ("not traversed this
282
+ // reaction, so unchanged") ignored that in-transaction changes are only traversed at commit,
283
+ // and served the pre-transaction value.
284
+ const a = atom('', 0)
285
+ const c = computed('', () => a.get() * 2)
286
+ react('listener', () => {
287
+ c.get()
288
+ })
289
+
290
+ const trigger = atom('', 0)
291
+ const seen: number[] = []
292
+ react('', () => {
293
+ if (trigger.get() === 0) return
294
+ transact(() => {
295
+ a.set(5)
296
+ seen.push(c.get())
297
+ })
298
+ })
299
+ trigger.set(1)
300
+
301
+ expect(seen).toEqual([10])
302
+ expect(c.get()).toBe(10)
303
+ })
304
+
305
+ it('[P6][T2] an incremental computed read inside a transaction during a reaction is not corrupted', () => {
306
+ // The stale read above also stamped the computed as checked at the current epoch, so an
307
+ // incremental computed would later ask for diffs since an epoch that skipped the change.
308
+ const log = atom<number[], number[]>('log', [], {
309
+ historyLength: 10,
310
+ computeDiff: (prev, next) => next.slice(prev.length),
311
+ })
312
+ const sum = computed<number>('sum', (prev, lastComputedEpoch) => {
313
+ if (typeof prev !== 'number') return log.get().reduce((a, b) => a + b, 0)
314
+ const diffs = log.getDiffSince(lastComputedEpoch)
315
+ if (typeof diffs === 'symbol') return log.get().reduce((a, b) => a + b, 0)
316
+ let s = prev
317
+ for (const diff of diffs) for (const n of diff) s += n
318
+ return s
319
+ })
320
+ react('listener', () => {
321
+ sum.get()
322
+ })
323
+
324
+ const trigger = atom('', 0)
325
+ const seen: number[] = []
326
+ let done = false
327
+ react('', () => {
328
+ if (trigger.get() === 0 || done) return
329
+ done = true
330
+ transact(() => {
331
+ log.update((l) => [...l, 10])
332
+ seen.push(sum.get())
333
+ })
334
+ })
335
+ trigger.set(1)
336
+ expect(seen).toEqual([10])
337
+
338
+ log.update((l) => [...l, 5])
339
+ expect(sum.get()).toBe(15)
340
+ })
341
+ })
342
+
343
+ describe('actively-listening computeds stay fresh (C2)', () => {
344
+ it('[C2][E6] a computed traversed for a deferred effect but not re-checked is not served stale', () => {
345
+ // Regression: with deferred scheduling (as in state-react), haveParentsChanged returns at the
346
+ // first changed parent, so a later computed parent is traversed but never re-checked; a read
347
+ // during a subsequent reaction then took the "not traversed this reaction" shortcut.
348
+ const a = atom('', 0)
349
+ const b = atom('', 0)
350
+ const c = computed('', () => a.get())
351
+ const deferred: (() => void)[] = []
352
+ const scheduler = new EffectScheduler(
353
+ '',
354
+ () => {
355
+ b.get()
356
+ c.get()
357
+ },
358
+ { scheduleEffect: (execute) => deferred.push(execute) }
359
+ )
360
+ scheduler.attach()
361
+ scheduler.execute()
362
+
363
+ // b is checked first, changed, so c is traversed but not re-checked; the run is deferred
364
+ transact(() => {
365
+ b.set(1)
366
+ a.set(1)
367
+ })
368
+
369
+ const z = atom('', 0)
370
+ const seen: number[] = []
371
+ react('', () => {
372
+ if (z.get() > 0) seen.push(c.get())
373
+ })
374
+ z.set(1)
375
+
376
+ expect(seen).toEqual([1])
377
+ expect(c.get()).toBe(1)
378
+
379
+ deferred.forEach((execute) => execute())
380
+ expect(c.get()).toBe(1)
381
+ })
279
382
  })
@@ -183,6 +183,29 @@ describe('transactions (T)', () => {
183
183
  expect(a.get()).toBe('a')
184
184
  })
185
185
 
186
+ it('[T7] an outer rollback undoes an inner transaction committed during the reaction phase', () => {
187
+ // Regression: committing a nested transaction inside an effect used to skip folding its
188
+ // initial values into the parent, so the outer rollback could not restore them.
189
+ const trigger = atom('', 0)
190
+ const a = atom('', 'a')
191
+ const b = atom('', 'b')
192
+
193
+ react('', () => {
194
+ if (trigger.get() === 0) return
195
+ transaction((rollback) => {
196
+ b.set('B')
197
+ transaction(() => {
198
+ a.set('A')
199
+ })
200
+ rollback()
201
+ })
202
+ })
203
+ trigger.set(1)
204
+
205
+ expect(a.get()).toBe('a')
206
+ expect(b.get()).toBe('b')
207
+ })
208
+
186
209
  it('[T4] rollback restores computed signals too', () => {
187
210
  const firstName = atom('', 'John')
188
211
  const lastName = atom('', 'Doe')
@@ -24,10 +24,10 @@ const inst = singleton('capture', () => ({ stack: null as null | CaptureStackFra
24
24
  * @example
25
25
  * ```ts
26
26
  * const name = atom('name', 'Sam')
27
- * const time = atom('time', () => new Date().getTime())
27
+ * const time = atom('time', Date.now())
28
28
  *
29
29
  * setInterval(() => {
30
- * time.set(new Date().getTime())
30
+ * time.set(Date.now())
31
31
  * })
32
32
  *
33
33
  * react('log name changes', () => {
@@ -149,13 +149,9 @@ export function stopCapturingParents() {
149
149
  */
150
150
  export function maybeCaptureParent(p: Signal<any, any>) {
151
151
  if (inst.stack) {
152
- // if the child didn't deref this parent last time it executed, then idx will be -1
153
- // if the child did deref this parent last time but in a different order relative to other parents, then idx will be greater than stack.offset
154
- // if the child did deref this parent last time in the same order, then idx will be the same as stack.offset
155
- // if the child did deref this parent already during this capture session then 0 <= idx < stack.offset
156
-
157
- // `add` returns false when the parent was already captured. In array mode both `has` and
158
- // `add` scan with indexOf, so going straight to `add` halves the scans per captured parent.
152
+ // `add` returns false when the parent was already captured this run. In array mode both
153
+ // `has` and `add` scan with indexOf, so going straight to `add` halves the scans per
154
+ // captured parent.
159
155
  if (!inst.stack.child.parentSet.add(p)) {
160
156
  return
161
157
  }
@@ -164,6 +160,9 @@ export function maybeCaptureParent(p: Signal<any, any>) {
164
160
  attach(p, inst.stack.child)
165
161
  }
166
162
 
163
+ // Parents are recorded in deref order. If the slot at this offset held a different parent
164
+ // last run, that parent may have moved later in the order or been dropped; only
165
+ // stopCapturingParents can tell, so remember it for then.
167
166
  if (inst.stack.offset < inst.stack.child.parents.length) {
168
167
  const maybeRemovedParent = inst.stack.child.parents[inst.stack.offset]
169
168
  if (maybeRemovedParent !== p) {
@@ -183,7 +182,8 @@ export function maybeCaptureParent(p: Signal<any, any>) {
183
182
 
184
183
  /**
185
184
  * A debugging tool that tells you why a computed signal or effect is running.
186
- * Call in the body of a computed signal or effect function.
185
+ * Call in the body of a computed signal or effect function. Nothing is logged for the run that
186
+ * calls it; from the next run on, each run logs the ancestors that changed.
187
187
  *
188
188
  * @example
189
189
  * ```ts
@@ -195,8 +195,8 @@ export function maybeCaptureParent(p: Signal<any, any>) {
195
195
  *
196
196
  * name.set('Alice')
197
197
  *
198
- * // 'greeting' is running because:
199
- * // 'name' changed => 'Alice'
198
+ * // Effect(greeting) is executing because:
199
+ * // ↳ Atom(name) changed
200
200
  * ```
201
201
  *
202
202
  * @public
@@ -1,26 +1,7 @@
1
1
  /**
2
- * The initial epoch value used to mark derivations (computed signals and effects) as dirty before their first computation.
2
+ * Sentinel below any real epoch. Derived signals and effects start with their epochs set to this
3
+ * so they are dirty until their first run; real epochs start at `GLOBAL_START_EPOCH + 1`.
3
4
  *
4
- * This constant ensures that all computed signals and effects start in a "dirty" state, guaranteeing they will
5
- * be computed/executed at least once when first accessed or started. The value -1 is used because:
6
- * - Global epoch starts at 0 (GLOBAL_START_EPOCH + 1)
7
- * - Any derived signal initialized with GLOBAL_START_EPOCH (-1) will be considered dirty when compared to any positive epoch
8
- * - This forces initial computation/execution without requiring special initialization logic
9
- *
10
- * Used by:
11
- * - Computed signals to track when they were last changed
12
- * - Effect schedulers to track when they were last executed
13
- * - Transaction system for initial global and reaction epoch values
14
- *
15
- * @example
16
- * ```ts
17
- * // In Computed class constructor
18
- * lastChangedEpoch = GLOBAL_START_EPOCH // -1, marking as dirty
19
- *
20
- * // When global epoch is 5, this computed will be dirty since -1 < 5
21
- * const needsComputation = this.lastChangedEpoch < globalEpoch
22
- * ```
23
- *
24
- * @public
5
+ * @internal
25
6
  */
26
7
  export const GLOBAL_START_EPOCH = -1