@isograph/pico 0.0.0-main-5f205c00

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.
@@ -0,0 +1,150 @@
1
+ import { scheduleCleanupIfNotFlushing } from '../batch/batch';
2
+ import { addToCleanupQueue } from '../disposal/cleanup';
3
+ import { DEPENDENTS_NOT_NECESSARILY_ALL_DIRTY } from '../state';
4
+ import type {
5
+ CallingNode,
6
+ DerivedNode,
7
+ MutableDerivedNode,
8
+ MutableSourceNode,
9
+ SourceNode,
10
+ } from './nodes';
11
+ import {
12
+ type Edge,
13
+ addEdgeToDerivedDependents,
14
+ addEdgeToSourceDependents,
15
+ createSourceEdge,
16
+ moveEdgeBeforeKnownMarkedDependents,
17
+ removeEdgeFromDerivedDependents,
18
+ removeEdgeFromSourceDependents,
19
+ } from './edges';
20
+ import { getCurrentDerivedValue } from './refresh';
21
+
22
+ /**
23
+ * Returns the value of `source` and records it as a dependency of
24
+ * `callingNode`.
25
+ *
26
+ * Contract: called only while the computation of `callingNode` runs.
27
+ */
28
+ export function readSource<TValue>(
29
+ callingNode: CallingNode,
30
+ source: SourceNode<TValue>,
31
+ ): TValue {
32
+ const mutableCallingNode = callingNode as MutableDerivedNode<unknown>;
33
+ const mutableSource = source as MutableSourceNode<unknown>;
34
+ // A write records that every node in the source's dependents list is
35
+ // `DIRTY`, so the next write skips marking. The calling node is `CLEAN` in
36
+ // that list once this computation finishes, so the read clears the record.
37
+ mutableSource.dependentsStatus = DEPENDENTS_NOT_NECESSARILY_ALL_DIRTY;
38
+ // On a rerun, reuse the old source edges in read order. If the source at
39
+ // this position changed, move the edge to the new source's list of readers.
40
+ const lastReadEdge = mutableCallingNode.lastSourceDependency;
41
+ const reusableEdge =
42
+ lastReadEdge === undefined
43
+ ? mutableCallingNode.firstSourceDependency
44
+ : lastReadEdge.nextDependencyEdge;
45
+ if (reusableEdge !== undefined) {
46
+ if (reusableEdge.dependency !== mutableSource) {
47
+ removeEdgeFromSourceDependents(reusableEdge);
48
+ reusableEdge.dependency = mutableSource;
49
+ addEdgeToSourceDependents(reusableEdge);
50
+ }
51
+ mutableCallingNode.lastSourceDependency = reusableEdge;
52
+ } else if (
53
+ lastReadEdge === undefined ||
54
+ lastReadEdge.dependency !== mutableSource
55
+ ) {
56
+ const edge = createSourceEdge(mutableSource, mutableCallingNode);
57
+ addEdgeToSourceDependents(edge);
58
+ if (lastReadEdge === undefined) {
59
+ mutableCallingNode.firstSourceDependency = edge;
60
+ } else {
61
+ lastReadEdge.nextDependencyEdge = edge;
62
+ }
63
+ mutableCallingNode.lastSourceDependency = edge;
64
+ }
65
+ return source.value;
66
+ }
67
+
68
+ /**
69
+ * Brings `node` up to date, returns its value, and records it as a dependency
70
+ * of `callingNode`.
71
+ *
72
+ * Contract: called only while the computation of `callingNode` runs.
73
+ */
74
+ export function readDerived<TValue>(
75
+ callingNode: CallingNode,
76
+ node: DerivedNode<TValue>,
77
+ ): TValue {
78
+ const mutableCallingNode = callingNode as MutableDerivedNode<unknown>;
79
+ const mutableNode = node as MutableDerivedNode<TValue>;
80
+ const value = getCurrentDerivedValue(mutableNode);
81
+ // Reuse the next edge in the calling node's derived dependency list. Moving
82
+ // it to another input can leave the old derived input eligible for disposal.
83
+ const lastReadEdge = mutableCallingNode.lastDerivedDependency;
84
+ const reusableEdge =
85
+ lastReadEdge === undefined
86
+ ? mutableCallingNode.firstDerivedDependency
87
+ : lastReadEdge.nextDependencyEdge;
88
+ if (reusableEdge !== undefined) {
89
+ if (reusableEdge.dependency !== mutableNode) {
90
+ const previousDependency = reusableEdge.dependency;
91
+ removeEdgeFromDerivedDependents(reusableEdge);
92
+ reusableEdge.dependency = mutableNode;
93
+ addEdgeToDerivedDependents(reusableEdge);
94
+ if (
95
+ previousDependency.firstDependent === undefined &&
96
+ previousDependency.firstRetain === undefined
97
+ ) {
98
+ addToCleanupQueue(previousDependency);
99
+ }
100
+ } else if (mutableNode.firstKnownMarkedDependentEdge !== undefined) {
101
+ // The calling node becomes `CLEAN` when its computation returns, so its
102
+ // reused edge must lie strictly before `firstKnownMarkedDependentEdge`.
103
+ moveEdgeBeforeKnownMarkedDependents(reusableEdge);
104
+ }
105
+ mutableCallingNode.lastDerivedDependency = reusableEdge;
106
+ } else if (
107
+ lastReadEdge === undefined ||
108
+ lastReadEdge.dependency !== mutableNode
109
+ ) {
110
+ const edge: Edge<MutableDerivedNode<unknown>> = {
111
+ dependency: mutableNode,
112
+ dependent: mutableCallingNode,
113
+ nextDependencyEdge: undefined,
114
+ previousDependentEdge: undefined,
115
+ nextDependentEdge: undefined,
116
+ };
117
+ addEdgeToDerivedDependents(edge);
118
+ if (lastReadEdge === undefined) {
119
+ mutableCallingNode.firstDerivedDependency = edge;
120
+ } else {
121
+ lastReadEdge.nextDependencyEdge = edge;
122
+ }
123
+ mutableCallingNode.lastDerivedDependency = edge;
124
+ }
125
+ return value;
126
+ }
127
+
128
+ /**
129
+ * Top-level read of `node`: brings `node` up to date and returns its value. A
130
+ * recompute links edges as in a tracked read. A node left unneeded goes on the
131
+ * cleanup queue, so the scheduler can dispose it and each dependency that its
132
+ * disposal leaves unneeded.
133
+ *
134
+ * Contract: called outside computations and write batch bodies. Inside an
135
+ * `onChange`, it is allowed.
136
+ */
137
+ export function readDerivedOutsideComputation<TValue>(
138
+ node: DerivedNode<TValue>,
139
+ ): TValue {
140
+ const mutableNode = node as MutableDerivedNode<TValue>;
141
+ const value = getCurrentDerivedValue(mutableNode);
142
+ if (
143
+ mutableNode.firstRetain === undefined &&
144
+ mutableNode.firstDependent === undefined
145
+ ) {
146
+ addToCleanupQueue(mutableNode);
147
+ }
148
+ scheduleCleanupIfNotFlushing();
149
+ return value;
150
+ }
@@ -0,0 +1,127 @@
1
+ import { addToCleanupQueue } from '../disposal/cleanup';
2
+ import { CHANGED, CLEAN, UNCHANGED } from '../state';
3
+ import {
4
+ type Edge,
5
+ removeEdgeFromDerivedDependents,
6
+ unlinkRemainingSourceDependencies,
7
+ } from './edges';
8
+ import {
9
+ markDependentsOfChangedDerivedNode,
10
+ markMaybeDirtyDependentsDirty,
11
+ } from './marking';
12
+ import type { MutableDerivedNode } from './nodes';
13
+
14
+ /**
15
+ * The first run starts with empty dependency lists. Every edge it creates
16
+ * belongs to this run, so there are no old edges to unlink.
17
+ */
18
+ export function computeInitialDerivedValue<TValue>(
19
+ node: MutableDerivedNode<TValue>,
20
+ ): TValue {
21
+ const value = node.computation(node, undefined);
22
+ node.status = CLEAN;
23
+ node.value = value;
24
+ return value;
25
+ }
26
+
27
+ export function recomputeValueAndMarkDependents<TValue>(
28
+ node: MutableDerivedNode<TValue>,
29
+ ): TValue {
30
+ const previous = node.value;
31
+ const value = rerunComputationAndUpdateDependencies(node, previous);
32
+ if (value === previous) {
33
+ return previous;
34
+ }
35
+ node.value = value;
36
+ // A reader marked `MAYBE_DIRTY` now has a confirmed change to a direct
37
+ // input. Its next refresh can skip verification and rerun immediately.
38
+ markMaybeDirtyDependentsDirty(node.firstDependent);
39
+ return value;
40
+ }
41
+
42
+ function rerunComputationAndUpdateDependencies<TValue>(
43
+ node: MutableDerivedNode<TValue>,
44
+ previous: TValue,
45
+ ): TValue {
46
+ // Reuse the source and derived dependency lists in read order. Each
47
+ // last*Dependency marks the end of the part used by this computation.
48
+ // Reset both cursors to start before the first edge. As reads arrive, reuse
49
+ // the next edge (retargeting it if the input changed) or append a new edge
50
+ // when needed. The cursor then points to the edge for that read.
51
+ node.lastSourceDependency = undefined;
52
+ node.lastDerivedDependency = undefined;
53
+ const value = node.computation(node, previous);
54
+ // If the previous run read sources A then B, its list has two edges.
55
+ // If this run reads only A, lastSourceDependency points to the edge for A.
56
+ // Only the edge for B needs to be unlinked.
57
+ unlinkUnreadDependencies(node);
58
+ node.status = CLEAN;
59
+ return value;
60
+ }
61
+
62
+ /**
63
+ * Unlink the edges after the last read in each dependency list. If the
64
+ * computation read no inputs of that kind, unlink the whole list.
65
+ */
66
+ function unlinkUnreadDependencies(node: MutableDerivedNode<unknown>): void {
67
+ const lastSource = node.lastSourceDependency;
68
+ if (lastSource === undefined) {
69
+ const first = node.firstSourceDependency;
70
+ if (first !== undefined) {
71
+ unlinkRemainingSourceDependencies(first);
72
+ node.firstSourceDependency = undefined;
73
+ }
74
+ } else if (lastSource.nextDependencyEdge !== undefined) {
75
+ unlinkRemainingSourceDependencies(lastSource.nextDependencyEdge);
76
+ lastSource.nextDependencyEdge = undefined;
77
+ }
78
+ const lastDerived = node.lastDerivedDependency;
79
+ if (lastDerived === undefined) {
80
+ const first = node.firstDerivedDependency;
81
+ if (first !== undefined) {
82
+ unlinkRemainingDerivedDependencies(first);
83
+ node.firstDerivedDependency = undefined;
84
+ }
85
+ } else if (lastDerived.nextDependencyEdge !== undefined) {
86
+ unlinkRemainingDerivedDependencies(lastDerived.nextDependencyEdge);
87
+ lastDerived.nextDependencyEdge = undefined;
88
+ }
89
+ }
90
+
91
+ function unlinkRemainingDerivedDependencies(
92
+ first: Edge<MutableDerivedNode<unknown>>,
93
+ ): void {
94
+ let edge: Edge<MutableDerivedNode<unknown>> | undefined = first;
95
+ do {
96
+ removeEdgeFromDerivedDependents(edge);
97
+ const dependency = edge.dependency;
98
+ if (
99
+ dependency.firstDependent === undefined &&
100
+ dependency.firstRetain === undefined
101
+ ) {
102
+ addToCleanupQueue(dependency);
103
+ }
104
+ edge = edge.nextDependencyEdge;
105
+ } while (edge !== undefined);
106
+ }
107
+
108
+ /**
109
+ * A downstream node with a callback can be waiting for this result. If it
110
+ * changes, `markDependentsOfChangedDerivedNode` queues those readers for refresh. Returning
111
+ * `CHANGED` tells `refreshNodeAndRecordChange` to record this node for notification.
112
+ */
113
+ export function recomputeAndQueueAffectedDependents(
114
+ flushQueue: Array<MutableDerivedNode<unknown>>,
115
+ node: MutableDerivedNode<unknown>,
116
+ ): typeof CHANGED | typeof UNCHANGED {
117
+ const previous = node.value;
118
+ const value = rerunComputationAndUpdateDependencies(node, previous);
119
+ if (value === previous) {
120
+ return UNCHANGED;
121
+ }
122
+ node.value = value;
123
+ if (node.firstDependent !== undefined) {
124
+ markDependentsOfChangedDerivedNode(flushQueue, node);
125
+ }
126
+ return CHANGED;
127
+ }
@@ -0,0 +1,232 @@
1
+ import {
2
+ UNCOMPUTED,
3
+ DIRTY,
4
+ MAYBE_DIRTY,
5
+ CLEAN,
6
+ HAS_CALLBACK,
7
+ CHANGED,
8
+ UNCHANGED,
9
+ } from '../state';
10
+ import { recordChangedNode } from '../batch/notifications';
11
+ import type { MutableDerivedNode } from './nodes';
12
+ import { type Edge, moveEdgeBeforeKnownMarkedDependents } from './edges';
13
+ import {
14
+ computeInitialDerivedValue,
15
+ recomputeValueAndMarkDependents,
16
+ recomputeAndQueueAffectedDependents,
17
+ } from './recompute';
18
+
19
+ /**
20
+ * Returns the current value of a derived node. During a flush, reading a node
21
+ * with a callback can refresh it ahead of its turn in the queue. The flush
22
+ * records any change so it can notify the callback after all refreshes finish.
23
+ */
24
+ export function getCurrentDerivedValue<TValue>(
25
+ node: MutableDerivedNode<TValue>,
26
+ ): TValue {
27
+ switch (node.status) {
28
+ case CLEAN:
29
+ return node.value;
30
+ case DIRTY:
31
+ return node.callbackState === HAS_CALLBACK
32
+ ? getCurrentValueForNodeWithCallback(node)
33
+ : recomputeValueAndMarkDependents(node);
34
+ case MAYBE_DIRTY:
35
+ return node.callbackState === HAS_CALLBACK
36
+ ? getCurrentValueForNodeWithCallback(node)
37
+ : getValueAfterVerifyingDependencies(node);
38
+ case UNCOMPUTED:
39
+ return computeInitialDerivedValue(node);
40
+ }
41
+ }
42
+
43
+ function getValueAfterVerifyingDependencies<TValue>(
44
+ node: MutableDerivedNode<TValue>,
45
+ ): TValue {
46
+ return verifyDerivedDependencies(node) === DIRTY
47
+ ? recomputeValueAndMarkDependents(node)
48
+ : node.value;
49
+ }
50
+
51
+ /**
52
+ * During a flush, use the active queue so this read can record a change
53
+ * and queue downstream nodes that need refreshing. Outside a flush,
54
+ * a node can still be `MAYBE_DIRTY` after an input kept its value. A read
55
+ * verifies that input before deciding whether to rerun the node.
56
+ */
57
+ function getCurrentValueForNodeWithCallback<TValue>(
58
+ node: MutableDerivedNode<TValue>,
59
+ ): TValue {
60
+ const queue = refreshQueue;
61
+ if (queue !== undefined) {
62
+ refreshNodeAndRecordChange(queue, node);
63
+ return node.value;
64
+ }
65
+ return node.status === DIRTY
66
+ ? recomputeValueAndMarkDependents(node)
67
+ : getValueAfterVerifyingDependencies(node);
68
+ }
69
+
70
+ /**
71
+ * Can requestedNode reuse its cached value? A write to a direct source
72
+ * already marks its reader DIRTY. Here the reader is MAYBE_DIRTY, so only
73
+ * its derived inputs need checking.
74
+ *
75
+ * Suppose A read B1, then B2. The outer loop checks A → B1 first. If B1
76
+ * is lazy and MAYBE_DIRTY, the loop starts checking B1's inputs. Once B1
77
+ * is up to date, the inner loop recovers A → B1 to get back to A.
78
+ * A must rerun if either B1 or B2 changed. If A is still MAYBE_DIRTY
79
+ * after checking B1, check B2. If either input marks A DIRTY, stop
80
+ * checking. A's rerun will read the inputs it needs. If both inputs kept
81
+ * their values, A becomes CLEAN and keeps its cached value.
82
+ */
83
+ function verifyDerivedDependencies(
84
+ requestedNode: MutableDerivedNode<unknown>,
85
+ ): typeof DIRTY | typeof CLEAN {
86
+ let savedReaderEdges: Array<Edge<MutableDerivedNode<unknown>>> | undefined;
87
+ let nodeBeingVerified = requestedNode;
88
+ let nextInputEdge = requestedNode.firstDerivedDependency;
89
+ while (true) {
90
+ if (nextInputEdge !== undefined) {
91
+ const derivedInput = nextInputEdge.dependency;
92
+ // This reader may become CLEAN. Keep its edge out of the part of
93
+ // the input's reader list that future writes can skip.
94
+ if (derivedInput.firstKnownMarkedDependentEdge !== undefined) {
95
+ moveEdgeBeforeKnownMarkedDependents(nextInputEdge);
96
+ }
97
+ if (
98
+ derivedInput.status === MAYBE_DIRTY &&
99
+ derivedInput.callbackState !== HAS_CALLBACK
100
+ ) {
101
+ // To get back to A, we need this exact edge and its nextDependencyEdge.
102
+ // Both links below belong to B1's list of reader edges. If both are
103
+ // undefined, A → B1 is the only edge and B1.firstDependent gives it
104
+ // back. If either exists, save A → B1 before descending. This lets
105
+ // a single-reader chain skip every push and pop.
106
+ if (
107
+ nextInputEdge.previousDependentEdge !== undefined ||
108
+ nextInputEdge.nextDependentEdge !== undefined
109
+ ) {
110
+ (savedReaderEdges ??= []).push(nextInputEdge);
111
+ }
112
+ nodeBeingVerified = derivedInput;
113
+ nextInputEdge = derivedInput.firstDerivedDependency;
114
+ continue; // Check B1's own inputs before deciding whether A must run.
115
+ }
116
+ if (derivedInput.status !== CLEAN) {
117
+ // A changed input marks this reader DIRTY. Verification only needs
118
+ // that status, so it discards the value returned by the read.
119
+ getCurrentDerivedValue(derivedInput);
120
+ }
121
+ if (nodeBeingVerified.status !== DIRTY) {
122
+ // No input marked A dirty during the refresh. Check B2.
123
+ nextInputEdge = nextInputEdge.nextDependencyEdge;
124
+ continue;
125
+ }
126
+ if (nodeBeingVerified === requestedNode) {
127
+ // An input changed. The caller recomputes requestedNode and marks
128
+ // its readers DIRTY only if requestedNode's own value changes.
129
+ return DIRTY;
130
+ }
131
+ // Rerun an intermediate reader here so its own readers see any change.
132
+ recomputeValueAndMarkDependents(nodeBeingVerified);
133
+ } else {
134
+ // Every input kept its value, so this node can reuse its cached result.
135
+ nodeBeingVerified.status = CLEAN;
136
+ }
137
+
138
+ while (true) {
139
+ if (nodeBeingVerified === requestedNode) {
140
+ return CLEAN;
141
+ }
142
+ // We're at B1. Did the descent from A push A → B1? Any edges saved
143
+ // deeper in the traversal have already been popped, so if we pushed
144
+ // this edge it must be on top, with B1 as its dependency.
145
+ let edgeBackToReader: Edge<MutableDerivedNode<unknown>>;
146
+ if (
147
+ savedReaderEdges !== undefined &&
148
+ savedReaderEdges.length > 0 &&
149
+ savedReaderEdges[savedReaderEdges.length - 1]!.dependency ===
150
+ nodeBeingVerified
151
+ ) {
152
+ // We pushed A → B1 because B1 had multiple reader edges.
153
+ edgeBackToReader = savedReaderEdges.pop()!;
154
+ } else {
155
+ // B1 had one reader edge, so B1.firstDependent gives us A → B1.
156
+ // If the stack has a top entry, it belongs to a reader farther up
157
+ // the chain. Popping it here would skip A.
158
+ edgeBackToReader = nodeBeingVerified.firstDependent!;
159
+ }
160
+ nodeBeingVerified = edgeBackToReader.dependent;
161
+ if (nodeBeingVerified.status !== DIRTY) {
162
+ // A is still MAYBE_DIRTY. Step from A → B1 to A → B2 in A's inputs.
163
+ // After the last input, the outer loop sees undefined and marks A CLEAN.
164
+ nextInputEdge = edgeBackToReader.nextDependencyEdge;
165
+ break;
166
+ }
167
+ if (nodeBeingVerified === requestedNode) {
168
+ // A direct input changed. The caller will rerun A and read its inputs.
169
+ return DIRTY;
170
+ }
171
+ // For an intermediate reader, rerun it here. Its value determines
172
+ // whether the next reader up also needs to run.
173
+ recomputeValueAndMarkDependents(nodeBeingVerified);
174
+ }
175
+ }
176
+ }
177
+
178
+ function refreshNodeAndRecordChange(
179
+ flushQueue: Array<MutableDerivedNode<unknown>>,
180
+ node: MutableDerivedNode<unknown>,
181
+ ): void {
182
+ const result = refreshNodeIfItHasCallback(flushQueue, node);
183
+ if (result === CHANGED) {
184
+ recordChangedNode(node);
185
+ }
186
+ }
187
+
188
+ type RefreshResult = typeof CHANGED | typeof UNCHANGED;
189
+
190
+ function refreshNodeIfItHasCallback(
191
+ flushQueue: Array<MutableDerivedNode<unknown>>,
192
+ node: MutableDerivedNode<unknown>,
193
+ ): RefreshResult {
194
+ if (node.callbackState !== HAS_CALLBACK) {
195
+ return UNCHANGED;
196
+ }
197
+ switch (node.status) {
198
+ case DIRTY:
199
+ return recomputeAndQueueAffectedDependents(flushQueue, node);
200
+ case MAYBE_DIRTY:
201
+ return verifyDerivedDependencies(node) === DIRTY
202
+ ? recomputeAndQueueAffectedDependents(flushQueue, node)
203
+ : UNCHANGED;
204
+ // Internal invariant: a `CLEAN` node on the flush queue was recomputed after
205
+ // marking put it there, by a pull or by an earlier entry of the same node.
206
+ // A node that reaches this switch has a callback, so it is retained and never
207
+ // `UNCOMPUTED`.
208
+ case CLEAN:
209
+ case UNCOMPUTED:
210
+ return UNCHANGED;
211
+ }
212
+ }
213
+
214
+ /**
215
+ * While the flush refreshes A, A's computation can read B before B's turn
216
+ * in the queue. That read refreshes B immediately. If B changes, the pull
217
+ * uses this same queue for B's affected readers and records B for notification.
218
+ * The refresh loop clears this reference before callbacks run.
219
+ */
220
+ let refreshQueue: Array<MutableDerivedNode<unknown>> | undefined;
221
+
222
+ export function refreshNodesInFlushQueue(
223
+ flushQueue: Array<MutableDerivedNode<unknown>>,
224
+ ): void {
225
+ refreshQueue = flushQueue;
226
+ // Refresh can append downstream callbacks. Read the current length so
227
+ // every queued node has its final value before the first notification.
228
+ for (let index = 0; index < flushQueue.length; index += 1) {
229
+ refreshNodeAndRecordChange(flushQueue, flushQueue[index]!);
230
+ }
231
+ refreshQueue = undefined;
232
+ }
package/src/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ export { endWriteBatch, startWriteBatch, writeSource } from './batch/batch';
2
+ export { disposeAll, disposeNext } from './disposal/cleanup';
3
+ export { scheduler } from './disposal/schedule';
4
+ export { createDerivedNode, createSourceNode } from './graph/nodes';
5
+ export { disposeOlderThanUpdates } from './disposal/older-than-updates';
6
+ export type {
7
+ CallingNode,
8
+ DerivedNode,
9
+ Retain,
10
+ SourceNode,
11
+ } from './graph/nodes';
12
+ export {
13
+ readDerived,
14
+ readDerivedOutsideComputation,
15
+ readSource,
16
+ } from './graph/read';
17
+ export { releaseRetain, retainDerivedNode } from './retention/retain';
18
+ export { disposeIfUnneeded, takeUnneeded } from './disposal/take';
@@ -0,0 +1,133 @@
1
+ import { CLEAN, NO_CALLBACK, HAS_CALLBACK } from '../state';
2
+ import {
3
+ scheduleCleanupIfOutsideBatchAndFlush,
4
+ flushQueuedNodesOrDisposeMarkedNodes,
5
+ } from '../batch/batch';
6
+ import { markTransitiveDependentsMaybeDirty } from '../graph/marking';
7
+ import type {
8
+ DerivedNode,
9
+ MutableDerivedNode,
10
+ MutableRetain,
11
+ Retain,
12
+ } from '../graph/nodes';
13
+ import { addToCleanupQueue } from '../disposal/cleanup';
14
+ import { getCurrentDerivedValue } from '../graph/refresh';
15
+ import { scheduleCleanupIfRequested } from '../disposal/schedule';
16
+
17
+ /**
18
+ * Brings `node` up to date, adds a retain to the head of its retain list, and
19
+ * returns the retain. A retained node keeps its value and its edges to its
20
+ * dependencies until its last retain is released. A retain with an
21
+ * `onChange` gives the node a callback.
22
+ *
23
+ * Guarantee: the flush calls `onChange` with the node's value once for each
24
+ * update or batch that changed the node's value, after the flush has
25
+ * refreshed every node on the flush queue. The first recompute of a node does
26
+ * not call `onChange`.
27
+ *
28
+ * Contract: called outside computations, `onChange` callbacks, and write
29
+ * batch bodies, because retaining computes the node. `onChange` does not
30
+ * write, start or end a batch, retain, release, or dispose. It may call
31
+ * `readDerivedOutsideComputation`.
32
+ */
33
+ export function retainDerivedNode<TValue>(
34
+ node: DerivedNode<TValue>,
35
+ onChange?: (value: TValue) => void,
36
+ ): Retain<TValue> {
37
+ const mutableNode = node as MutableDerivedNode<TValue>;
38
+ // Populate the cache before attaching onChange. The retain needs the
39
+ // node to be CLEAN and its dependencies linked, so it discards the value.
40
+ getCurrentDerivedValue(mutableNode);
41
+ const head = mutableNode.firstRetain;
42
+ const retainFields: Omit<MutableRetain<TValue>, keyof Retain<TValue>> = {
43
+ node: mutableNode,
44
+ onChange,
45
+ previousRetain: undefined,
46
+ nextRetain: head,
47
+ };
48
+ const retain = retainFields as MutableRetain<TValue>;
49
+ if (head !== undefined) {
50
+ head.previousRetain = retain;
51
+ }
52
+ mutableNode.firstRetain = retain;
53
+ if (onChange !== undefined) {
54
+ mutableNode.callbackState = HAS_CALLBACK;
55
+ }
56
+ scheduleCleanupIfRequested();
57
+ return retain;
58
+ }
59
+
60
+ /**
61
+ * Releases `retain`. A release that leaves the node unneeded puts the node on
62
+ * the cleanup queue. The node keeps its value and its edges until a disposal,
63
+ * or the marking of a write, reaches it.
64
+ *
65
+ * Contract: called once per retain, outside computations and `onChange`
66
+ * callbacks.
67
+ */
68
+ export function releaseRetain<TValue>(retain: Retain<TValue>): void {
69
+ const mutableRetain = retain as MutableRetain<TValue>;
70
+ const mutableNode = mutableRetain.node!;
71
+ mutableRetain.node = undefined;
72
+ const previous = mutableRetain.previousRetain;
73
+ const next = mutableRetain.nextRetain;
74
+ if (previous === undefined) {
75
+ mutableNode.firstRetain = next;
76
+ } else {
77
+ previous.nextRetain = next;
78
+ mutableRetain.previousRetain = undefined;
79
+ }
80
+ if (next !== undefined) {
81
+ next.previousRetain = previous;
82
+ mutableRetain.nextRetain = undefined;
83
+ }
84
+ if (mutableRetain.onChange !== undefined) {
85
+ mutableRetain.onChange = undefined;
86
+ clearCallbackStateIfNoCallbackRetainsRemain(mutableNode);
87
+ }
88
+ // Internal invariant: a retained node is not `UNCOMPUTED`. Retaining pulled
89
+ // it, and no disposal reaches a node with a retain.
90
+ if (
91
+ mutableNode.firstRetain === undefined &&
92
+ mutableNode.firstDependent === undefined
93
+ ) {
94
+ addToCleanupQueue(mutableNode);
95
+ }
96
+ scheduleCleanupIfOutsideBatchAndFlush();
97
+ }
98
+
99
+ /**
100
+ * Internal invariant: a node that loses its last callback while `DIRTY` or
101
+ * `MAYBE_DIRTY` has no `CLEAN` dependents, and its dependents may be
102
+ * `MAYBE_DIRTY` with `MARKED_BEYOND`, waiting for its refresh to put the
103
+ * nodes with callbacks among them on the flush queue. The walk through lazy nodes
104
+ * from the node clears that bit on them, as the dependents of a lazy node that
105
+ * is `DIRTY` or `MAYBE_DIRTY` require, and puts those nodes with callbacks on the
106
+ * flush queue. A node that gets a callback was brought
107
+ * up to date first, so it is `CLEAN`.
108
+ */
109
+ function clearCallbackStateIfNoCallbackRetainsRemain(
110
+ node: MutableDerivedNode<unknown>,
111
+ ): void {
112
+ if (hasOnChangeRetain(node)) {
113
+ return;
114
+ }
115
+ node.callbackState = NO_CALLBACK;
116
+ // The retain kept this node computed until this release.
117
+ if (node.status !== CLEAN) {
118
+ flushQueuedNodesOrDisposeMarkedNodes(
119
+ markTransitiveDependentsMaybeDirty(undefined, node, undefined, undefined),
120
+ );
121
+ }
122
+ }
123
+
124
+ function hasOnChangeRetain(node: MutableDerivedNode<unknown>): boolean {
125
+ let retain = node.firstRetain;
126
+ while (retain !== undefined) {
127
+ if (retain.onChange !== undefined) {
128
+ return true;
129
+ }
130
+ retain = retain.nextRetain;
131
+ }
132
+ return false;
133
+ }