@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/helpers.ts
CHANGED
|
@@ -1,42 +1,23 @@
|
|
|
1
1
|
import { Child, Signal } from './types'
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
* Get whether the given value is a child.
|
|
5
|
-
*
|
|
6
|
-
* @param x The value to check.
|
|
7
|
-
* @returns True if the value is a child, false otherwise.
|
|
8
|
-
* @internal
|
|
9
|
-
*/
|
|
10
3
|
function isChild(x: any): x is Child {
|
|
11
4
|
return x && typeof x === 'object' && 'parents' in x
|
|
12
5
|
}
|
|
13
6
|
|
|
14
7
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* This function is used internally to determine if a computed signal or effect needs to
|
|
19
|
-
* be re-evaluated because one of its dependencies has changed.
|
|
8
|
+
* Whether any of the child's parents changed since the child last recorded their epochs. O(parents);
|
|
9
|
+
* returns at the first changed parent, so parents after it are not brought up to date.
|
|
20
10
|
*
|
|
21
|
-
* @param child - The child (computed signal or effect) to check for parent changes
|
|
22
|
-
* @returns `true` if any parent signal has changed since the child last observed it, `false` otherwise
|
|
23
|
-
* @example
|
|
24
|
-
* ```ts
|
|
25
|
-
* const childSignal = computed('child', () => parentAtom.get())
|
|
26
|
-
* // Check if the child needs to recompute
|
|
27
|
-
* if (haveParentsChanged(childSignal)) {
|
|
28
|
-
* // Recompute the child's value
|
|
29
|
-
* }
|
|
30
|
-
* ```
|
|
31
11
|
* @internal
|
|
32
12
|
*/
|
|
33
13
|
export function haveParentsChanged(child: Child): boolean {
|
|
34
14
|
for (let i = 0, n = child.parents.length; i < n; i++) {
|
|
35
|
-
|
|
36
|
-
|
|
15
|
+
const parent = child.parents[i]
|
|
16
|
+
// Bring the parent up to date first: a computed parent's `lastChangedEpoch` only moves when
|
|
17
|
+
// it is re-derived.
|
|
18
|
+
parent.__unsafe__getWithoutCapture(true)
|
|
37
19
|
|
|
38
|
-
|
|
39
|
-
if (child.parents[i].lastChangedEpoch !== child.parentEpochs[i]) {
|
|
20
|
+
if (parent.lastChangedEpoch !== child.parentEpochs[i]) {
|
|
40
21
|
return true
|
|
41
22
|
}
|
|
42
23
|
}
|
|
@@ -45,32 +26,17 @@ export function haveParentsChanged(child: Child): boolean {
|
|
|
45
26
|
}
|
|
46
27
|
|
|
47
28
|
/**
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* This function is used internally to clean up the dependency graph when signals are no
|
|
53
|
-
* longer needed or when dependencies change.
|
|
29
|
+
* Removes `child` from `parent.children`. A computed parent that loses its last child stops
|
|
30
|
+
* listening itself, recursively, so a signal's `children` set is empty whenever nothing downstream
|
|
31
|
+
* is actively listening.
|
|
54
32
|
*
|
|
55
|
-
* @param parent - The parent signal to detach from
|
|
56
|
-
* @param child - The child signal to detach
|
|
57
|
-
* @example
|
|
58
|
-
* ```ts
|
|
59
|
-
* // When a computed signal's dependencies change
|
|
60
|
-
* const oldParent = atom('old', 1)
|
|
61
|
-
* const child = computed('child', () => oldParent.get())
|
|
62
|
-
* // Later, detach the child from the old parent
|
|
63
|
-
* detach(oldParent, child)
|
|
64
|
-
* ```
|
|
65
33
|
* @internal
|
|
66
34
|
*/
|
|
67
35
|
export function detach(parent: Signal<any>, child: Child) {
|
|
68
|
-
// If the child is not attached to the parent, do nothing.
|
|
69
36
|
if (!parent.children.remove(child)) {
|
|
70
37
|
return
|
|
71
38
|
}
|
|
72
39
|
|
|
73
|
-
// If the parent has no more children, then detach the parent from its parents.
|
|
74
40
|
if (parent.children.isEmpty && isChild(parent)) {
|
|
75
41
|
for (let i = 0, n = parent.parents.length; i < n; i++) {
|
|
76
42
|
detach(parent.parents[i], parent)
|
|
@@ -79,32 +45,21 @@ export function detach(parent: Signal<any>, child: Child) {
|
|
|
79
45
|
}
|
|
80
46
|
|
|
81
47
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
* attach to its own parents to maintain the dependency chain.
|
|
48
|
+
* Adds `child` to `parent.children`. A computed parent that gains its first child starts
|
|
49
|
+
* listening itself, recursively, so that changes to any ancestor are traversed down to the child.
|
|
85
50
|
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
51
|
+
* `parent` must be up to date when it is attached: `Computed` assumes an actively-listening
|
|
52
|
+
* computed has been traversed for every ancestor change since it was last checked, which only
|
|
53
|
+
* holds from the moment it started listening. Capture attaches a parent right after reading it;
|
|
54
|
+
* `EffectScheduler.attach` refreshes its parents first.
|
|
88
55
|
*
|
|
89
|
-
* @param parent - The parent signal to attach to
|
|
90
|
-
* @param child - The child signal to attach
|
|
91
|
-
* @example
|
|
92
|
-
* ```ts
|
|
93
|
-
* // When a computed signal captures a new dependency
|
|
94
|
-
* const parentAtom = atom('parent', 1)
|
|
95
|
-
* const child = computed('child', () => parentAtom.get())
|
|
96
|
-
* // Internally, attach is called to establish the dependency
|
|
97
|
-
* attach(parentAtom, child)
|
|
98
|
-
* ```
|
|
99
56
|
* @internal
|
|
100
57
|
*/
|
|
101
58
|
export function attach(parent: Signal<any>, child: Child) {
|
|
102
|
-
// If the child is already attached to the parent, do nothing.
|
|
103
59
|
if (!parent.children.add(child)) {
|
|
104
60
|
return
|
|
105
61
|
}
|
|
106
62
|
|
|
107
|
-
// If the parent itself is a child, add the parent to the parent's parents.
|
|
108
63
|
if (isChild(parent)) {
|
|
109
64
|
for (let i = 0, n = parent.parents.length; i < n; i++) {
|
|
110
65
|
attach(parent.parents[i], parent)
|
|
@@ -113,25 +68,10 @@ export function attach(parent: Signal<any>, child: Child) {
|
|
|
113
68
|
}
|
|
114
69
|
|
|
115
70
|
/**
|
|
116
|
-
*
|
|
71
|
+
* The default equality used for change detection: `===`, then `Object.is` (so `NaN` equals
|
|
72
|
+
* `NaN`; `0` and `-0` are already equal by `===`), then the old value's own `.equals(b)` method
|
|
73
|
+
* if it has one. Only the old value's `equals` is consulted.
|
|
117
74
|
*
|
|
118
|
-
* This function performs equality checks in the following order:
|
|
119
|
-
* 1. Reference equality (`===`)
|
|
120
|
-
* 2. `Object.is()` equality (handles NaN and -0/+0 cases)
|
|
121
|
-
* 3. Custom `.equals()` method when the left-hand value provides one
|
|
122
|
-
*
|
|
123
|
-
* This is used internally to determine if a signal's value has actually changed
|
|
124
|
-
* when setting new values, preventing unnecessary updates and re-computations.
|
|
125
|
-
*
|
|
126
|
-
* @param a - The first value to compare
|
|
127
|
-
* @param b - The second value to compare
|
|
128
|
-
* @returns `true` if the values are considered equal, `false` otherwise
|
|
129
|
-
* @example
|
|
130
|
-
* ```ts
|
|
131
|
-
* equals(1, 1) // true
|
|
132
|
-
* equals(NaN, NaN) // true (unlike === which returns false)
|
|
133
|
-
* equals({ equals: (other: any) => other.id === 1 }, { id: 1 }) // Uses custom equals method
|
|
134
|
-
* ```
|
|
135
75
|
* @internal
|
|
136
76
|
*/
|
|
137
77
|
export function equals(a: any, b: any): boolean {
|
|
@@ -140,32 +80,6 @@ export function equals(a: any, b: any): boolean {
|
|
|
140
80
|
return shallowEquals
|
|
141
81
|
}
|
|
142
82
|
|
|
143
|
-
/**
|
|
144
|
-
* A TypeScript utility function for exhaustiveness checking in switch statements and
|
|
145
|
-
* conditional branches. This function should never be called at runtime—it exists
|
|
146
|
-
* purely for compile-time type checking and is `undefined` in emitted JavaScript.
|
|
147
|
-
*
|
|
148
|
-
* @param x - A value that should be of type `never`
|
|
149
|
-
* @throws Always at runtime because the identifier is undefined
|
|
150
|
-
* @example
|
|
151
|
-
* ```ts
|
|
152
|
-
* type Color = 'red' | 'blue'
|
|
153
|
-
*
|
|
154
|
-
* function handleColor(color: Color) {
|
|
155
|
-
* switch (color) {
|
|
156
|
-
* case 'red':
|
|
157
|
-
* return 'Stop'
|
|
158
|
-
* case 'blue':
|
|
159
|
-
* return 'Go'
|
|
160
|
-
* default:
|
|
161
|
-
* return assertNever(color) // TypeScript error if not all cases handled
|
|
162
|
-
* }
|
|
163
|
-
* }
|
|
164
|
-
* ```
|
|
165
|
-
* @public
|
|
166
|
-
*/
|
|
167
|
-
export declare function assertNever(x: never): never
|
|
168
|
-
|
|
169
83
|
/**
|
|
170
84
|
* Creates or retrieves a singleton instance using a global symbol registry.
|
|
171
85
|
* This ensures that the same instance is shared across all code that uses
|
|
@@ -199,37 +113,3 @@ export function singleton<T>(key: string, init: () => T): T {
|
|
|
199
113
|
* @public
|
|
200
114
|
*/
|
|
201
115
|
export const EMPTY_ARRAY: [] = singleton('empty_array', () => Object.freeze([]) as any)
|
|
202
|
-
|
|
203
|
-
/**
|
|
204
|
-
* Checks if a signal has any active reactors (effects or computed signals) that are
|
|
205
|
-
* currently listening to it. This determines whether changes to the signal will
|
|
206
|
-
* cause any side effects or recomputations to occur.
|
|
207
|
-
*
|
|
208
|
-
* A signal is considered to have active reactors if any of its child dependencies
|
|
209
|
-
* are actively listening for changes.
|
|
210
|
-
*
|
|
211
|
-
* @param signal - The signal to check for active reactors
|
|
212
|
-
* @returns `true` if the signal has active reactors, `false` otherwise
|
|
213
|
-
* @example
|
|
214
|
-
* ```ts
|
|
215
|
-
* const count = atom('count', 0)
|
|
216
|
-
*
|
|
217
|
-
* console.log(hasReactors(count)) // false - no effects listening
|
|
218
|
-
*
|
|
219
|
-
* const stop = react('logger', () => console.log(count.get()))
|
|
220
|
-
* console.log(hasReactors(count)) // true - effect is listening
|
|
221
|
-
*
|
|
222
|
-
* stop()
|
|
223
|
-
* console.log(hasReactors(count)) // false - effect stopped
|
|
224
|
-
* ```
|
|
225
|
-
* @public
|
|
226
|
-
*/
|
|
227
|
-
export function hasReactors(signal: Signal<any>) {
|
|
228
|
-
for (const child of signal.children) {
|
|
229
|
-
if (child.isActivelyListening) {
|
|
230
|
-
return true
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
return false
|
|
235
|
-
}
|
|
@@ -75,12 +75,19 @@ export function localStorageAtom<Value, Diff = unknown>(
|
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
|
|
78
|
+
// The storage helpers above tolerate environments without localStorage (Node, SSR); do the
|
|
79
|
+
// same here rather than throwing on `window`.
|
|
80
|
+
const canListen = typeof window !== 'undefined'
|
|
81
|
+
if (canListen) {
|
|
82
|
+
window.addEventListener('storage', handleStorageEvent)
|
|
83
|
+
}
|
|
79
84
|
|
|
80
85
|
// Combined cleanup function
|
|
81
86
|
const cleanup = () => {
|
|
82
87
|
reactCleanup()
|
|
83
|
-
|
|
88
|
+
if (canListen) {
|
|
89
|
+
window.removeEventListener('storage', handleStorageEvent)
|
|
90
|
+
}
|
|
84
91
|
}
|
|
85
92
|
|
|
86
93
|
return [outAtom, cleanup]
|
package/src/lib/transactions.ts
CHANGED
|
@@ -17,56 +17,51 @@ class Transaction {
|
|
|
17
17
|
|
|
18
18
|
initialAtomValues = new Map<_Atom, any>()
|
|
19
19
|
|
|
20
|
-
/**
|
|
21
|
-
* Get whether this transaction is a root (no parents).
|
|
22
|
-
*
|
|
23
|
-
* @public
|
|
24
|
-
*/
|
|
25
20
|
// eslint-disable-next-line tldraw/no-setter-getter
|
|
26
21
|
get isRoot() {
|
|
27
22
|
return this.parent === null
|
|
28
23
|
}
|
|
29
24
|
|
|
30
|
-
/**
|
|
31
|
-
* Commit the transaction's changes.
|
|
32
|
-
*
|
|
33
|
-
* @public
|
|
34
|
-
*/
|
|
35
25
|
commit() {
|
|
36
|
-
if (
|
|
37
|
-
// if we're committing during a reaction we actually need to
|
|
38
|
-
// use the 'cleanup' reactors set to ensure we re-run effects if necessary
|
|
39
|
-
for (const atom of this.initialAtomValues.keys()) {
|
|
40
|
-
traverseAtomForCleanup(atom)
|
|
41
|
-
}
|
|
42
|
-
} else if (this.isRoot) {
|
|
26
|
+
if (this.isRoot) {
|
|
43
27
|
// For root transactions, flush changed atoms
|
|
44
28
|
flushChanges(this.initialAtomValues.keys())
|
|
45
|
-
|
|
46
|
-
// For transactions with parents, add the transaction's initial values to the parent's.
|
|
47
|
-
this.initialAtomValues.forEach((value, atom) => {
|
|
48
|
-
if (!this.parent!.initialAtomValues.has(atom)) {
|
|
49
|
-
this.parent!.initialAtomValues.set(atom, value)
|
|
50
|
-
}
|
|
51
|
-
})
|
|
29
|
+
return
|
|
52
30
|
}
|
|
31
|
+
// For transactions with parents, add the transaction's initial values to the parent's, so
|
|
32
|
+
// an outer rollback can still undo them (T7). This must come before any "are we reacting?" special case: a nested
|
|
33
|
+
// transaction committed by an effect during the reaction phase used to skip this fold and
|
|
34
|
+
// its changes survived the outer rollback.
|
|
35
|
+
// A parent that has recorded nothing yet adopts the map outright: this transaction is
|
|
36
|
+
// finished with it, and the common nested case is a single inner transaction doing all
|
|
37
|
+
// the writes.
|
|
38
|
+
const parentValues = this.parent!.initialAtomValues
|
|
39
|
+
if (parentValues.size === 0) {
|
|
40
|
+
this.parent!.initialAtomValues = this.initialAtomValues
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
this.initialAtomValues.forEach((value, atom) => {
|
|
44
|
+
if (!parentValues.has(atom)) {
|
|
45
|
+
parentValues.set(atom, value)
|
|
46
|
+
}
|
|
47
|
+
})
|
|
53
48
|
}
|
|
54
49
|
|
|
55
50
|
/**
|
|
56
|
-
* Abort the transaction.
|
|
51
|
+
* Abort the transaction. Restores every atom changed in this transaction to its initial
|
|
52
|
+
* value, then commits. Must be called while this is still `inst.currentTransaction`, so that
|
|
53
|
+
* the restoring sets are recorded against it instead of each flushing effects on their own.
|
|
57
54
|
*
|
|
58
55
|
* @public
|
|
59
56
|
*/
|
|
60
57
|
abort() {
|
|
61
58
|
inst.globalEpoch++
|
|
62
59
|
|
|
63
|
-
// Reset each of the transaction's atoms to its initial value.
|
|
64
60
|
this.initialAtomValues.forEach((value, atom) => {
|
|
65
61
|
atom.set(value)
|
|
66
62
|
atom.historyBuffer?.clear()
|
|
67
63
|
})
|
|
68
64
|
|
|
69
|
-
// Commit the changes.
|
|
70
65
|
this.commit()
|
|
71
66
|
}
|
|
72
67
|
}
|
|
@@ -79,20 +74,8 @@ const inst = singleton('transactions', () => ({
|
|
|
79
74
|
currentTransaction: null as Transaction | null,
|
|
80
75
|
|
|
81
76
|
cleanupReactors: null as null | Set<Reactor>,
|
|
82
|
-
reactionEpoch: GLOBAL_START_EPOCH + 1,
|
|
83
77
|
}))
|
|
84
78
|
|
|
85
|
-
/**
|
|
86
|
-
* Gets the current reaction epoch, which is used to track when reactions are running.
|
|
87
|
-
* The reaction epoch is updated at the start of each reaction cycle.
|
|
88
|
-
*
|
|
89
|
-
* @returns The current reaction epoch number
|
|
90
|
-
* @public
|
|
91
|
-
*/
|
|
92
|
-
export function getReactionEpoch() {
|
|
93
|
-
return inst.reactionEpoch
|
|
94
|
-
}
|
|
95
|
-
|
|
96
79
|
/**
|
|
97
80
|
* Gets the current global epoch, which is incremented every time any atom changes.
|
|
98
81
|
* This is used to track changes across the entire reactive system.
|
|
@@ -105,17 +88,18 @@ export function getGlobalEpoch() {
|
|
|
105
88
|
}
|
|
106
89
|
|
|
107
90
|
/**
|
|
108
|
-
*
|
|
109
|
-
*
|
|
91
|
+
* Whether a transaction (sync or async) is currently open. While one is, atom changes are
|
|
92
|
+
* recorded but their children are not traversed until it commits.
|
|
110
93
|
*
|
|
111
|
-
* @
|
|
112
|
-
* @public
|
|
94
|
+
* @internal
|
|
113
95
|
*/
|
|
114
|
-
export function
|
|
115
|
-
return inst.
|
|
96
|
+
export function getIsInTransaction() {
|
|
97
|
+
return inst.currentTransaction !== null
|
|
116
98
|
}
|
|
117
99
|
|
|
118
|
-
//
|
|
100
|
+
// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a
|
|
101
|
+
// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user
|
|
102
|
+
// code, so nothing can re-enter and swap it mid-walk.
|
|
119
103
|
let traverseReactors: Set<Reactor>
|
|
120
104
|
|
|
121
105
|
function traverseChild(child: Child) {
|
|
@@ -132,33 +116,32 @@ function traverseChild(child: Child) {
|
|
|
132
116
|
}
|
|
133
117
|
}
|
|
134
118
|
|
|
135
|
-
function traverse(reactors: Set<Reactor>, child: Child) {
|
|
136
|
-
traverseReactors = reactors
|
|
137
|
-
traverseChild(child)
|
|
138
|
-
}
|
|
139
|
-
|
|
140
119
|
/**
|
|
141
|
-
* Collect all of the reactors that need to run for an atom and run them.
|
|
120
|
+
* Collect all of the reactors that need to run for an atom and run them. During the reaction
|
|
121
|
+
* phase the affected effects are instead queued for the cleanup pass, so a change made by an
|
|
122
|
+
* effect never interrupts the pass that is running (P4).
|
|
142
123
|
*
|
|
143
124
|
* @param atoms - The atoms to flush changes for.
|
|
144
125
|
*/
|
|
145
126
|
function flushChanges(atoms: Iterable<_Atom>) {
|
|
146
127
|
if (inst.globalIsReacting) {
|
|
147
|
-
|
|
128
|
+
for (const atom of atoms) {
|
|
129
|
+
traverseAtomForCleanup(atom)
|
|
130
|
+
}
|
|
131
|
+
return
|
|
148
132
|
}
|
|
149
133
|
|
|
150
134
|
const outerTxn = inst.currentTransaction
|
|
151
135
|
try {
|
|
152
|
-
// clear the transaction stack
|
|
136
|
+
// clear the transaction stack. Transactions started by effects must be roots: the committing
|
|
137
|
+
// transaction (if any) has already handed its changes to this flush.
|
|
153
138
|
inst.currentTransaction = null
|
|
154
139
|
inst.globalIsReacting = true
|
|
155
|
-
inst.reactionEpoch = inst.globalEpoch
|
|
156
140
|
|
|
157
|
-
// Collect all of the visited reactors.
|
|
158
141
|
const reactors = new Set<Reactor>()
|
|
159
|
-
|
|
142
|
+
traverseReactors = reactors
|
|
160
143
|
for (const atom of atoms) {
|
|
161
|
-
atom.children.visit(
|
|
144
|
+
atom.children.visit(traverseChild)
|
|
162
145
|
}
|
|
163
146
|
|
|
164
147
|
// Run each reactor.
|
|
@@ -185,28 +168,17 @@ function flushChanges(atoms: Iterable<_Atom>) {
|
|
|
185
168
|
}
|
|
186
169
|
}
|
|
187
170
|
|
|
188
|
-
/**
|
|
189
|
-
* Handle a change to an atom.
|
|
190
|
-
*
|
|
191
|
-
* @param atom The atom that changed.
|
|
192
|
-
* @param previousValue The atom's previous value.
|
|
193
|
-
*
|
|
194
|
-
* @internal
|
|
195
|
-
*/
|
|
171
|
+
/** @internal */
|
|
196
172
|
export function atomDidChange(atom: _Atom, previousValue: any) {
|
|
197
173
|
if (inst.currentTransaction) {
|
|
198
174
|
// If we are in a transaction, then all we have to do is preserve
|
|
199
175
|
// the value of the atom at the start of the transaction in case
|
|
200
|
-
// we need to roll back.
|
|
176
|
+
// we need to roll back. Children are not traversed until the
|
|
177
|
+
// transaction commits, which is why `Computed` must not trust its
|
|
178
|
+
// traversal-based cache shortcut while a transaction is open.
|
|
201
179
|
if (!inst.currentTransaction.initialAtomValues.has(atom)) {
|
|
202
180
|
inst.currentTransaction.initialAtomValues.set(atom, previousValue)
|
|
203
181
|
}
|
|
204
|
-
} else if (inst.globalIsReacting) {
|
|
205
|
-
// If the atom changed during the reaction phase of flushChanges
|
|
206
|
-
// (and there are no transactions started inside the reaction phase)
|
|
207
|
-
// then we are past the point where a transaction can be aborted
|
|
208
|
-
// so we don't need to note down the previousValue.
|
|
209
|
-
traverseAtomForCleanup(atom)
|
|
210
182
|
} else {
|
|
211
183
|
// If there is no transaction, flush the changes immediately.
|
|
212
184
|
flushChanges([atom])
|
|
@@ -214,16 +186,11 @@ export function atomDidChange(atom: _Atom, previousValue: any) {
|
|
|
214
186
|
}
|
|
215
187
|
|
|
216
188
|
function traverseAtomForCleanup(atom: _Atom) {
|
|
217
|
-
|
|
218
|
-
atom.children.visit(
|
|
189
|
+
traverseReactors = inst.cleanupReactors ??= new Set()
|
|
190
|
+
atom.children.visit(traverseChild)
|
|
219
191
|
}
|
|
220
192
|
|
|
221
|
-
/**
|
|
222
|
-
* Advances the global epoch counter by one.
|
|
223
|
-
* This is used internally to track when changes occur across the reactive system.
|
|
224
|
-
*
|
|
225
|
-
* @internal
|
|
226
|
-
*/
|
|
193
|
+
/** @internal */
|
|
227
194
|
export function advanceGlobalEpoch() {
|
|
228
195
|
inst.globalEpoch++
|
|
229
196
|
}
|
|
@@ -251,7 +218,7 @@ export function advanceGlobalEpoch() {
|
|
|
251
218
|
* // Logs "Hello, Jane Smith!"
|
|
252
219
|
* ```
|
|
253
220
|
*
|
|
254
|
-
* If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began.
|
|
221
|
+
* If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.
|
|
255
222
|
*
|
|
256
223
|
* @example
|
|
257
224
|
* ```ts
|
|
@@ -269,8 +236,9 @@ export function advanceGlobalEpoch() {
|
|
|
269
236
|
* throw new Error('oops')
|
|
270
237
|
* })
|
|
271
238
|
*
|
|
272
|
-
* // Does not log
|
|
273
239
|
* // firstName.get() === 'John'
|
|
240
|
+
* // Logs "Hello, John Doe!" again: effects whose parents were changed and restored still run,
|
|
241
|
+
* // and observe the restored values.
|
|
274
242
|
* ```
|
|
275
243
|
*
|
|
276
244
|
* A `rollback` callback is passed into the function.
|
|
@@ -293,9 +261,9 @@ export function advanceGlobalEpoch() {
|
|
|
293
261
|
* rollback()
|
|
294
262
|
* })
|
|
295
263
|
*
|
|
296
|
-
* // Does not log
|
|
297
264
|
* // firstName.get() === 'John'
|
|
298
265
|
* // lastName.get() === 'Doe'
|
|
266
|
+
* // Logs "Hello, John Doe!" again, as above.
|
|
299
267
|
* ```
|
|
300
268
|
*
|
|
301
269
|
* @param fn - The function to run in a transaction, called with a function to roll back the change.
|
|
@@ -305,7 +273,6 @@ export function advanceGlobalEpoch() {
|
|
|
305
273
|
export function transaction<T>(fn: (rollback: () => void) => T) {
|
|
306
274
|
const txn = new Transaction(inst.currentTransaction, true)
|
|
307
275
|
|
|
308
|
-
// Set the current transaction to the transaction
|
|
309
276
|
inst.currentTransaction = txn
|
|
310
277
|
|
|
311
278
|
try {
|
|
@@ -313,10 +280,8 @@ export function transaction<T>(fn: (rollback: () => void) => T) {
|
|
|
313
280
|
let rollback = false
|
|
314
281
|
|
|
315
282
|
try {
|
|
316
|
-
// Run the function.
|
|
317
283
|
result = fn(() => (rollback = true))
|
|
318
284
|
} catch (e) {
|
|
319
|
-
// Abort the transaction if the function throws.
|
|
320
285
|
txn.abort()
|
|
321
286
|
throw e
|
|
322
287
|
}
|
|
@@ -326,7 +291,6 @@ export function transaction<T>(fn: (rollback: () => void) => T) {
|
|
|
326
291
|
}
|
|
327
292
|
|
|
328
293
|
if (rollback) {
|
|
329
|
-
// If the rollback was triggered, abort the transaction.
|
|
330
294
|
txn.abort()
|
|
331
295
|
} else {
|
|
332
296
|
txn.commit()
|
|
@@ -334,7 +298,6 @@ export function transaction<T>(fn: (rollback: () => void) => T) {
|
|
|
334
298
|
|
|
335
299
|
return result
|
|
336
300
|
} finally {
|
|
337
|
-
// Set the current transaction to the transaction's parent.
|
|
338
301
|
inst.currentTransaction = txn.parent
|
|
339
302
|
}
|
|
340
303
|
}
|
|
@@ -420,6 +383,7 @@ export async function deferAsyncEffects<T>(fn: () => Promise<T>) {
|
|
|
420
383
|
|
|
421
384
|
let result = undefined as T | undefined
|
|
422
385
|
|
|
386
|
+
// `undefined` means "did not throw"; a thrown `undefined` is stored as `null` so it still counts.
|
|
423
387
|
let error = undefined as any
|
|
424
388
|
try {
|
|
425
389
|
// Run the function.
|
|
@@ -430,6 +394,7 @@ export async function deferAsyncEffects<T>(fn: () => Promise<T>) {
|
|
|
430
394
|
}
|
|
431
395
|
|
|
432
396
|
if (--txn.asyncProcessCount > 0) {
|
|
397
|
+
// Other processes still share this transaction; it settles when the last one finishes.
|
|
433
398
|
if (typeof error !== 'undefined') {
|
|
434
399
|
// If the rollback was triggered, abort the transaction.
|
|
435
400
|
throw error
|
|
@@ -438,14 +403,19 @@ export async function deferAsyncEffects<T>(fn: () => Promise<T>) {
|
|
|
438
403
|
}
|
|
439
404
|
}
|
|
440
405
|
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
406
|
+
// Settle while this is still the current transaction (see `Transaction.abort`): clearing it
|
|
407
|
+
// first made every restoring set inside `abort()` flush effects on its own, so effects
|
|
408
|
+
// observed half-restored state.
|
|
409
|
+
try {
|
|
410
|
+
if (typeof error !== 'undefined') {
|
|
411
|
+
// If the rollback was triggered, abort the transaction.
|
|
412
|
+
txn.abort()
|
|
413
|
+
throw error
|
|
414
|
+
} else {
|
|
415
|
+
txn.commit()
|
|
416
|
+
return result
|
|
417
|
+
}
|
|
418
|
+
} finally {
|
|
419
|
+
inst.currentTransaction = null
|
|
450
420
|
}
|
|
451
421
|
}
|
package/src/lib/types.ts
CHANGED
|
@@ -9,12 +9,12 @@ import { ArraySet } from './ArraySet'
|
|
|
9
9
|
*
|
|
10
10
|
* @example
|
|
11
11
|
* ```ts
|
|
12
|
-
* import { atom,
|
|
12
|
+
* import { atom, RESET_VALUE } from '@tldraw/state'
|
|
13
13
|
*
|
|
14
|
-
* const count = atom('count', 0, { historyLength: 3 })
|
|
15
|
-
* const oldEpoch =
|
|
14
|
+
* const count = atom('count', 0, { historyLength: 3, computeDiff: (prev, next) => next - prev })
|
|
15
|
+
* const oldEpoch = count.lastChangedEpoch
|
|
16
16
|
*
|
|
17
|
-
* // Make
|
|
17
|
+
* // Make more changes than the history length can hold
|
|
18
18
|
* count.set(1)
|
|
19
19
|
* count.set(2)
|
|
20
20
|
* count.set(3)
|
|
@@ -183,8 +183,8 @@ export interface Child {
|
|
|
183
183
|
* A function type that computes the difference between two values of a signal.
|
|
184
184
|
*
|
|
185
185
|
* This function is used to generate incremental diffs that can be applied to
|
|
186
|
-
* reconstruct state changes over time
|
|
187
|
-
*
|
|
186
|
+
* reconstruct state changes over time, so that downstream computeds and effects can
|
|
187
|
+
* update incrementally instead of recomputing from scratch.
|
|
188
188
|
*
|
|
189
189
|
* The function should analyze the previous and current values and return a
|
|
190
190
|
* diff object that represents the change. If the diff cannot be computed
|
|
@@ -193,7 +193,7 @@ export interface Child {
|
|
|
193
193
|
*
|
|
194
194
|
* @param previousValue - The previous value of the signal
|
|
195
195
|
* @param currentValue - The current value of the signal
|
|
196
|
-
* @param lastComputedEpoch -
|
|
196
|
+
* @param lastComputedEpoch - For an atom, the epoch when the previous value was set. For a computed, the epoch at which it was last checked (the same value its compute function receives), so that `other.getDiffSince(lastComputedEpoch)` yields exactly the changes not yet accounted for.
|
|
197
197
|
* @param currentEpoch - The epoch when the current value was set
|
|
198
198
|
* @returns A diff object representing the change, or the unique symbol RESET_VALUE if no diff can be computed
|
|
199
199
|
*
|