@wardic/core 1.1.0 → 1.1.2

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 (101) hide show
  1. package/dist/unstable/AnimationControls.d.ts +110 -0
  2. package/dist/unstable/AnimationControls.d.ts.map +1 -0
  3. package/dist/unstable/AnimationControls.js +107 -0
  4. package/dist/unstable/AnimationControls.js.map +1 -0
  5. package/dist/unstable/AppearHandoff.d.ts +53 -0
  6. package/dist/unstable/AppearHandoff.d.ts.map +1 -0
  7. package/dist/unstable/AppearHandoff.js +23 -0
  8. package/dist/unstable/AppearHandoff.js.map +1 -0
  9. package/dist/unstable/Config.d.ts +285 -0
  10. package/dist/unstable/Config.d.ts.map +1 -0
  11. package/dist/unstable/Config.js +3 -0
  12. package/dist/unstable/Config.js.map +1 -0
  13. package/dist/unstable/FlushGate.d.ts +222 -0
  14. package/dist/unstable/FlushGate.d.ts.map +1 -0
  15. package/dist/unstable/FlushGate.js +567 -0
  16. package/dist/unstable/FlushGate.js.map +1 -0
  17. package/dist/unstable/FrameTime.d.ts +21 -0
  18. package/dist/unstable/FrameTime.d.ts.map +1 -0
  19. package/dist/unstable/FrameTime.js +45 -0
  20. package/dist/unstable/FrameTime.js.map +1 -0
  21. package/dist/unstable/MeasuredPairs.d.ts +51 -0
  22. package/dist/unstable/MeasuredPairs.d.ts.map +1 -0
  23. package/dist/unstable/MeasuredPairs.js +20 -0
  24. package/dist/unstable/MeasuredPairs.js.map +1 -0
  25. package/dist/unstable/OwnValues.d.ts +29 -0
  26. package/dist/unstable/OwnValues.d.ts.map +1 -0
  27. package/dist/unstable/OwnValues.js +22 -0
  28. package/dist/unstable/OwnValues.js.map +1 -0
  29. package/dist/unstable/PresenceRecord.d.ts +176 -0
  30. package/dist/unstable/PresenceRecord.d.ts.map +1 -0
  31. package/dist/unstable/PresenceRecord.js +26 -0
  32. package/dist/unstable/PresenceRecord.js.map +1 -0
  33. package/dist/unstable/Reactivity.d.ts +29 -0
  34. package/dist/unstable/Reactivity.d.ts.map +1 -0
  35. package/dist/unstable/Reactivity.js +15 -0
  36. package/dist/unstable/Reactivity.js.map +1 -0
  37. package/dist/unstable/Report.d.ts +30 -0
  38. package/dist/unstable/Report.d.ts.map +1 -0
  39. package/dist/unstable/Report.js +66 -0
  40. package/dist/unstable/Report.js.map +1 -0
  41. package/dist/unstable/RetargetLegs.d.ts +189 -0
  42. package/dist/unstable/RetargetLegs.d.ts.map +1 -0
  43. package/dist/unstable/RetargetLegs.js +834 -0
  44. package/dist/unstable/RetargetLegs.js.map +1 -0
  45. package/dist/unstable/Spine.d.ts +696 -0
  46. package/dist/unstable/Spine.d.ts.map +1 -0
  47. package/dist/unstable/Spine.js +2617 -0
  48. package/dist/unstable/Spine.js.map +1 -0
  49. package/dist/unstable/Stops.d.ts +82 -0
  50. package/dist/unstable/Stops.d.ts.map +1 -0
  51. package/dist/unstable/Stops.js +149 -0
  52. package/dist/unstable/Stops.js.map +1 -0
  53. package/dist/unstable/Subject.d.ts +11 -0
  54. package/dist/unstable/Subject.d.ts.map +1 -0
  55. package/dist/unstable/Subject.js +12 -0
  56. package/dist/unstable/Subject.js.map +1 -0
  57. package/dist/unstable/Timelines.d.ts +51 -0
  58. package/dist/unstable/Timelines.d.ts.map +1 -0
  59. package/dist/unstable/Timelines.js +10 -0
  60. package/dist/unstable/Timelines.js.map +1 -0
  61. package/dist/unstable/VariableValues.d.ts +27 -0
  62. package/dist/unstable/VariableValues.d.ts.map +1 -0
  63. package/dist/unstable/VariableValues.js +19 -0
  64. package/dist/unstable/VariableValues.js.map +1 -0
  65. package/dist/unstable/VariantTarget.d.ts +106 -0
  66. package/dist/unstable/VariantTarget.d.ts.map +1 -0
  67. package/dist/unstable/VariantTarget.js +185 -0
  68. package/dist/unstable/VariantTarget.js.map +1 -0
  69. package/dist/unstable/VariantTree.d.ts +351 -0
  70. package/dist/unstable/VariantTree.d.ts.map +1 -0
  71. package/dist/unstable/VariantTree.js +362 -0
  72. package/dist/unstable/VariantTree.js.map +1 -0
  73. package/dist/unstable/WardicConfigValue.d.ts +89 -0
  74. package/dist/unstable/WardicConfigValue.d.ts.map +1 -0
  75. package/dist/unstable/WardicConfigValue.js +106 -0
  76. package/dist/unstable/WardicConfigValue.js.map +1 -0
  77. package/dist/unstable/WardicServices.d.ts +46 -0
  78. package/dist/unstable/WardicServices.d.ts.map +1 -0
  79. package/dist/unstable/WardicServices.js +72 -0
  80. package/dist/unstable/WardicServices.js.map +1 -0
  81. package/package.json +1 -1
  82. package/src/unstable/AnimationControls.ts +199 -0
  83. package/src/unstable/AppearHandoff.ts +81 -0
  84. package/src/unstable/Config.ts +326 -0
  85. package/src/unstable/FlushGate.ts +730 -0
  86. package/src/unstable/FrameTime.ts +52 -0
  87. package/src/unstable/MeasuredPairs.ts +56 -0
  88. package/src/unstable/OwnValues.ts +32 -0
  89. package/src/unstable/PresenceRecord.ts +202 -0
  90. package/src/unstable/Reactivity.ts +35 -0
  91. package/src/unstable/Report.ts +75 -0
  92. package/src/unstable/RetargetLegs.ts +1062 -0
  93. package/src/unstable/Spine.ts +3275 -0
  94. package/src/unstable/Stops.ts +221 -0
  95. package/src/unstable/Subject.ts +13 -0
  96. package/src/unstable/Timelines.ts +58 -0
  97. package/src/unstable/VariableValues.ts +27 -0
  98. package/src/unstable/VariantTarget.ts +246 -0
  99. package/src/unstable/VariantTree.ts +643 -0
  100. package/src/unstable/WardicConfigValue.ts +154 -0
  101. package/src/unstable/WardicServices.ts +125 -0
@@ -0,0 +1,730 @@
1
+ /**
2
+ * `makeFlushGate` — the deferred **Flush gate** (ADR-0006), framework-free and Environment-free in
3
+ * core, so every binding shares one (ADR-0031, decision 3). The binding hands in its `batch` and its
4
+ * sinks, and its Environment the edges it reads (`GateEnvironment`); the gate imports nothing from a
5
+ * framework.
6
+ *
7
+ * Per ADR-0006, per-frame writes never reach their element directly. Each source
8
+ * `write(id, partialValues)`s into a provider-owned gate that:
9
+ *
10
+ * 1. Accumulates *value-maps* (NOT already-projected Patches) per element,
11
+ * merging partials by key — so multiple sources can feed one element
12
+ * (e.g. a drag setting `x`/`y` while a spring drives `scale`, all
13
+ * collapsing into one grouped `transform`). Projecting per source would
14
+ * clobber the grouped transform.
15
+ * 2. Resolves the Renderer's PURE `project` ONCE at creation and uses it to
16
+ * turn each dirty element's merged value-map into a `Patch` exactly once
17
+ * per element per frame.
18
+ * 3. Commits each resulting Patch onto its element with the Renderer's `commit`, a plain
19
+ * call (ADR-0034) — one pass over the elements per frame, shared by every element: at the end of the
20
+ * Frame loop's tick, in the Refresh frame that computed the values (ADR-0033). No
21
+ * framework runs per frame: a binding's render carries an element's style only until its
22
+ * first commit (ADR-0021, decision 6), and after it only the keys the gate doesn't hold.
23
+ *
24
+ * Three locked design decisions (this session's grills):
25
+ * - FLUSHED at the end of the Frame loop's tick (ADR-0033): the gate registers a hook on
26
+ * the Environment's loop (`afterTick`), so everything a tick writes is applied at the end
27
+ * of that tick, inside the Clock's callback, and paints in that Refresh frame. A write
28
+ * made outside a tick (a drag's move, a `release` from a task, an effect a sink's hook ran,
29
+ * a Tier 2 `Stream` on `Clock.ticks` subscribed after the loop) still requests a
30
+ * Refresh frame, only if one is not already pending, and the hook withdraws that request
31
+ * when it flushes first. `flush` does NOT auto-reschedule, so an idle accumulator
32
+ * requests no frames — the next `write` does. The frames come from the Environment's
33
+ * `RefreshFrameSource` (ADR-0031): `@wardic/dom`'s is its runtime's frame callback. No binding
34
+ * asks its runtime for frames itself. A Tier 2 `Stream` that writes here paints in
35
+ * the loop's frame or the next one, by its subscription order (ADR-0033): run it on the
36
+ * loop (`Machine.run`) to paint with it.
37
+ * - ONE flush per frame: all dirty elements flush together. The one exception
38
+ * is `flushPass` (ADR-0018): a projection Measure pass's own writes are applied
39
+ * at the end of its task, so a new layout never paints without its projection.
40
+ * - ONE sink shape (ADR-0034): a sink is the element its patch is committed onto. The gate
41
+ * also removes a key its last patch had and this one doesn't (a dragged element's raise
42
+ * once it's dropped, ADR-0016 *Amendment (Reorder)*), restoring the element's own
43
+ * value, saved before the gate first wrote the key. Two hooks reach the binding,
44
+ * outside the commits, each in the binding's `batch` (ADR-0034, *Amendment (#209)*): the
45
+ * Starting-style switch before an element's first commit (`beforeFirstCommit`), and the keys
46
+ * the gate holds on the element whenever they change (`onHeld`), so the binding's `style`
47
+ * leaves them to Wardic.
48
+ *
49
+ * Observability (CONTEXT.md convention): the hot path (`write`/`flush`) is the
50
+ * per-frame work, so — exactly like core's per-frame writes and the Clock's
51
+ * `tick` — it stays quiet (no span, no per-call log, no metric). A flush that throws (a
52
+ * binding's hook, a commit) is reported (`Report.failure`) and the gate
53
+ * goes on, so it can't fail the Frame loop's tick it runs in (ADR-0033).
54
+ *
55
+ * Unstable, for Wardic's own packages: public, with no semver promise.
56
+ *
57
+ * @module
58
+ */
59
+ // Unstable: ADR-0071, decision 5. #672: dom's `internal/gate.ts`, moved for the spine to write through
60
+ // it in core; dom's `FlushGate` builds it with the DOM's edges (`DOM_GATE`) and gives it as a Layer.
61
+ import * as FrameLoop from "../FrameLoop.ts"
62
+ import * as RefreshFrameSource from "../RefreshFrameSource.ts"
63
+ import * as Renderer from "../Renderer.ts"
64
+ import * as Cause from "effect/Cause"
65
+ import * as Atom from "effect/reactivity/Atom"
66
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry"
67
+ import * as Effect from "effect/Effect"
68
+ import * as Exit from "effect/Exit"
69
+ import type * as Fiber from "effect/Fiber"
70
+ import * as Predicate from "effect/Predicate"
71
+ import * as UndefinedOr from "effect/UndefinedOr"
72
+ import * as Scope from "effect/Scope"
73
+ import * as Report from "./Report.ts"
74
+
75
+ /**
76
+ * Where a flushed `Patch` is delivered: committed onto `target` with the Renderer's `commit`,
77
+ * at flush time.
78
+ */
79
+ export interface FlushSink {
80
+ /** The element the patch is committed onto. */
81
+ readonly target: unknown
82
+ /**
83
+ * Called once, just before the element's first commit in a frame flush (not a Measure
84
+ * pass's `flushPass`), inside the binding's `batch` with every other element's switch that
85
+ * flush: a binding drops its Starting style from its `style` here,
86
+ * so its framework removes those keys and the commit writes the first frame in the same
87
+ * Refresh frame, with no paint in between.
88
+ */
89
+ readonly beforeFirstCommit?: (() => void) | undefined
90
+ /**
91
+ * Called with every key the gate now holds on the element, each time that set changes: after the
92
+ * gate restores a key it dropped, and before the commit that first
93
+ * writes a key. A binding whose `style` reaches the element leaves these keys out of it,
94
+ * so its framework never writes over Wardic's value (`style` is a key's fallback). Called in
95
+ * the binding's `batch`, with every other element's whose keys changed that flush, so what the
96
+ * binding changes reaches the element before the commit, a framework that applies an update later
97
+ * (Solid 2) included.
98
+ */
99
+ // ADR-0034, *Amendment (#209)*.
100
+ readonly onHeld?: ((keys: ReadonlyArray<string>) => void) | undefined
101
+ /**
102
+ * Called once per frame in which the element's values were committed, after every commit of that
103
+ * frame (Motion's `onUpdate`), with its values before
104
+ * projection (`x` as a number). The object is the element's own, reused each call: valid during
105
+ * the call, copied to keep. A Measure pass's commits are told at the frame flush after them, so
106
+ * a frame tells each element once. A write it makes is the next frame's. A throw is reported,
107
+ * and the others are still told.
108
+ */
109
+ readonly onCommit?: ((values: Readonly<Record<string, unknown>>) => void) | undefined
110
+ }
111
+
112
+ /** Accumulated pre-`project` state for one registered element. */
113
+ interface Entry {
114
+ /** Merged value-map (partials `Object.assign`ed in by key). */
115
+ readonly values: Record<string, unknown>
116
+ /** Where this element's projected Patch goes. */
117
+ readonly sink: FlushSink
118
+ /** Whether a `write` has landed since the last flush. */
119
+ dirty: boolean
120
+ /**
121
+ * The keys the gate holds on the element: its last patch's, each with the element's own
122
+ * value from before the gate first wrote it (`""` for none), to restore when the
123
+ * key drops out.
124
+ */
125
+ readonly committed: Map<string, string>
126
+ /** Its keys' live outputs (`valueOf`), or `undefined` while nothing asked for one. */
127
+ outputs: Map<string, Output> | undefined
128
+ /** The values its sink's `onCommit` is told, one object reused, made on the first call. */
129
+ latest: Record<string, unknown> | undefined
130
+ /**
131
+ * Whether its `onCommit` threw at its last call (#257 item 4): a run of throws is logged and
132
+ * reported at its first, so one that throws every frame logs once; a call that returns ends it.
133
+ */
134
+ failing: boolean
135
+ /** Its patch, projected this flush and committed once the binding has heard the keys held. */
136
+ patch: Renderer.Patch | undefined
137
+ }
138
+
139
+ /** One key's live output: its Atom, the value last set on it, and its mount in the registry. */
140
+ interface Output {
141
+ readonly atom: Atom.Writable<unknown>
142
+ last: unknown
143
+ readonly unmount: () => void
144
+ }
145
+
146
+ /** What the gate calls of a key's Timeline value (#240): its sync with the values drawn, and its cancel. */
147
+ // #672 (Q15): the gate names what it calls, so it reads no Timeline code; dom's TimelineValue meets it.
148
+ export interface GateTimeline {
149
+ readonly sync: (values: Readonly<Record<string, unknown>>) => void
150
+ readonly cancel: () => void
151
+ }
152
+
153
+ /**
154
+ * What the gate reads of its Environment's targets, and what it keeps from a sink: a target's value
155
+ * for a key before the gate first writes it there (`""` for none), which it gives back at the key's
156
+ * release, and the key its Renderer reserves for an element's Transform template, which `onCommit`
157
+ * never sees.
158
+ */
159
+ // #672 (PR2-Q1): the gate's two edges of its Environment, given by `FlushGate.make`, its only builder,
160
+ // so the gate reads none itself and moves to core as it is.
161
+ export interface GateEnvironment {
162
+ readonly valueBeforeOf: (target: unknown, key: string) => string
163
+ readonly templateKey: string
164
+ }
165
+
166
+ /** Each of `values` cancelled (#240). Per flush: a plain loop. */
167
+ const cancelEach = (values: Iterable<GateTimeline>): void => {
168
+ for (const value of values) value.cancel()
169
+ }
170
+
171
+ /** A Flush gate: what a binding registers its elements with and writes their values into, one per provider. */
172
+ export interface FlushGate {
173
+ /**
174
+ * Register an element under `id` with its `sink`. Returns an unregister fn
175
+ * that removes the element from the accumulator (a subsequent `write` is a
176
+ * no-op). `values` start its value-map, unflushed: drawn with its first `write`, so they never
177
+ * commit alone.
178
+ */
179
+ // #443: its Transform template, which mustn't take its Starting style off early.
180
+ readonly register: (id: string, sink: FlushSink, values?: Readonly<Record<string, unknown>>) => () => void
181
+ /**
182
+ * Merge `partial` into the element's value-map by key, mark it dirty, and
183
+ * schedule a flush: the end of the Frame loop's tick, for a write made in one, or else the
184
+ * next Refresh frame. A `write` for an unregistered (or unregistered-since) id
185
+ * is a no-op.
186
+ */
187
+ readonly write: (id: string, partial: Record<string, unknown>) => void
188
+ /**
189
+ * Run a projection **Measure pass** now and apply exactly what it wrote before
190
+ * returning. Only `write()`s made while
191
+ * `pass()` runs are recorded; each recorded entry is `project`ed and committed once, and
192
+ * marked clean. Everything else stays dirty for its flush. A write made by an effect a sink's
193
+ * hook runs (a Solid effect) takes the ordinary path. The Projection system calls it at the
194
+ * end of a task, so a new layout never paints without its projection.
195
+ */
196
+ readonly flushPass: (pass: () => void) => void
197
+ /**
198
+ * Hand `keys` back to the element's own style: drop each from the element's
199
+ * value-map and schedule a flush, which writes `restore[key]` (its Environment's text form) for a key it had
200
+ * written, or else the element's own value it overwrote, and tells the sink (`onHeld`). A key the
201
+ * entry doesn't hold, or an unknown id, is a no-op. A binding releases a key back at its `style`
202
+ * value, so a later `style` change shows at rest. A later `write` brings the key back. A property in
203
+ * `keep` (`transform` for its keys) is left as it's drawn when it drops out: another writer draws it next.
204
+ */
205
+ // `keep`: #665's PR 4, a Batch member's group handed back to its Batch, whose writer draws it from then on.
206
+ readonly release: (id: string, keys: ReadonlyArray<string>, restore?: Readonly<Record<string, string>>, keep?: ReadonlyArray<string>) => void
207
+ /**
208
+ * The element's value for `id`'s `key`, live: an `Atom` set as each write that
209
+ * changes it lands, so it's the value the next commit draws, before the Renderer projects it
210
+ * (`x` as a number, not a `transform`). Set at the write, not the commit, so a value derived
211
+ * from it (another key following it through a binding) is written in the same frame and
212
+ * commits with it. `undefined` before the key's first write, and once it's released or the
213
+ * element unregisters. One Atom for an id and a key, made on first ask, so per frame only the
214
+ * keys asked for cost anything.
215
+ */
216
+ readonly valueOf: (id: string, key: string) => Atom.Atom<unknown>
217
+ /**
218
+ * Run `key`'s Timeline value on `id`'s element (#240), or stop it (`undefined`): a binding sets one
219
+ * while the key shows its Live value, and clears it when an entry of the Override stack takes the
220
+ * key. The gate goes on writing the key: at each flush that commits the element, before the commit,
221
+ * it starts the value's animation over it, or cancels it while something else adds to its property
222
+ * (a projection, a Transform template, another transform key off its identity), so a frame shows one
223
+ * or the other. A cleared or replaced one is cancelled at the next flush; a released key's, an
224
+ * unregistered element's and a disposed gate's, at once. Setting one schedules a flush.
225
+ */
226
+ readonly timeline: (id: string, key: string, timeline: GateTimeline | undefined) => void
227
+ /**
228
+ * Call `fn` once, after the gate's next flush: the end of the Frame loop's tick, for a call
229
+ * made in one, else the next Refresh frame's, so what was written before it is on the elements.
230
+ * It schedules that flush if none is pending. A binding tells an animation's end here, as Motion's
231
+ * `onAnimationComplete` comes with the final value set. One that throws is reported, and the rest
232
+ * still run.
233
+ */
234
+ readonly afterFlush: (fn: () => void) => void
235
+ /** Takes the gate off the Frame loop, cancels a pending frame and clears what it held. The Layer's Scope calls it. */
236
+ // Wired into the provider's `onCleanup`.
237
+ readonly dispose: () => void
238
+ }
239
+
240
+ /** The gate as its spine and its binding use it: all but its `dispose`, which its Scope runs. */
241
+ // #672: named here, as dom's `FlushGate` names it, so the spine reads the gate's own types in core.
242
+ export type Shape = Omit<FlushGate, "dispose">
243
+
244
+ /** An element's commit target and hooks, given to `register`. */
245
+ export type Sink = FlushSink
246
+
247
+ /** What a flush gate needs from its Environment: the `Renderer`, the Frame loop it flushes at the end of each tick of, and the `RefreshFrameSource`. */
248
+ // ADR-0033; ADR-0031.
249
+ export type FlushGateServices = Renderer.Renderer | RefreshFrameSource.RefreshFrameSource | FrameLoop.FrameLoop | AtomRegistry.AtomRegistry
250
+
251
+ /**
252
+ * How the gate runs its Effects: synchronously, and forked. `FlushGate.make` builds one from its
253
+ * Layer's context, forking into its Scope (#132, ADR-0041); a test's `ManagedRuntime` is one too.
254
+ */
255
+ export interface FlushGateRuntime {
256
+ readonly runSync: <A, E>(effect: Effect.Effect<A, E, FlushGateServices>) => A
257
+ readonly runFork: <A, E>(effect: Effect.Effect<A, E, FlushGateServices>) => Fiber.Fiber<A, E>
258
+ /** The Scope it was built in: its own fibers live there, ended as it closes (#618). */
259
+ readonly scope: Scope.Scope
260
+ }
261
+
262
+ /** What a binding hands its flush gate. */
263
+ export interface FlushGateOptions {
264
+ /**
265
+ * Runs a flush's hooks together: calls `apply`, and returns once every update inside it has reached
266
+ * the elements, before the gate commits. Solid 1 passes its `batch`, Solid 2 runs `apply` then
267
+ * `flush()`, and React would pass `flushSync`, untried; a binding with nothing to batch passes
268
+ * `(apply) => apply()`. Called at most twice a flush: once for the starting-style switches
269
+ * (`beforeFirstCommit`) of the elements committing for the first time, before anything is read off the
270
+ * elements; and once for the held keys (`onHeld`) of the elements whose held keys changed.
271
+ */
272
+ // ADR-0031, decision 3, ADR-0034; *Amendment (#209)*.
273
+ readonly batch: (apply: () => void) => void
274
+ }
275
+
276
+ /**
277
+ * Build a flush gate against the provider's `runtime`, running each frame flush's Starting-style
278
+ * switches through the binding's `batch`.
279
+ *
280
+ * Resolves both ONCE here: `project` is pure and `commit` a plain call (both called directly at
281
+ * flush, ADR-0034), `requestFrame` /
282
+ * `cancelFrame` schedule and cancel the flush of a write made outside a tick, and the Frame
283
+ * loop's `afterTick` takes the gate's hook for its lifetime. All come from whichever env the
284
+ * provider was given (`DomLive` / `TestLive`), so the gate inherits that environment's
285
+ * grouping/unit logic, its Refresh frames and its loop with zero duplication.
286
+ */
287
+ export const makeFlushGate = (runtime: FlushGateRuntime, options: FlushGateOptions, environment: GateEnvironment): FlushGate => {
288
+ const { batch } = options
289
+ const { valueBeforeOf, templateKey } = environment
290
+ // Resolve the Renderer's two halves and the Refresh frame source exactly once at creation.
291
+ // `requestFrame` and `cancelFrame` are called detached, never as `frames.requestFrame(cb)`: a
292
+ // browser throws "Illegal invocation" when `requestAnimationFrame` runs with `this` bound to
293
+ // anything but the window (ADR-0031, decision 7).
294
+ const { commit, project, requestFrame, cancelFrame, afterTick } = runtime.runSync(
295
+ Effect.gen(function* () {
296
+ const { commit, project } = yield* Renderer.Renderer
297
+ const { requestFrame, cancelFrame } = yield* RefreshFrameSource.RefreshFrameSource
298
+ const { afterTick } = yield* FrameLoop.FrameLoop
299
+ return { commit, project, requestFrame, cancelFrame, afterTick }
300
+ }),
301
+ )
302
+
303
+ const accumulator = new Map<string, Entry>()
304
+ // Every live output asked for (`valueOf`), by id: an entry registered later picks its map up.
305
+ const outputsById = new Map<string, Map<string, Output>>()
306
+ const registry = runtime.runSync(AtomRegistry.AtomRegistry)
307
+ // Sinks waiting for their first commit's `beforeFirstCommit` (usually empty).
308
+ const firstCommits = new Set<string>()
309
+ let scheduled = false
310
+ // What `afterFlush` queued since the last flush, called at its end (#257).
311
+ let afterFlushes: Array<() => void> = []
312
+ // The pending Refresh frame's handle, while `scheduled`.
313
+ let frame: unknown
314
+ // The ids written while a `flushPass` pass runs; `undefined` otherwise.
315
+ let recording: Set<string> | undefined
316
+ // The entries committed since the last frame flush whose sink has an `onCommit` (#233).
317
+ const committedSince = new Set<Entry>()
318
+ // Each element's Timeline values by key (#240), and those let go of since its last flush, cancelled at
319
+ // its next: only the elements that have one, so the per-frame path checks their sizes alone.
320
+ const timelines = new Map<Entry, Map<string, GateTimeline>>()
321
+ const endings = new Map<Entry, Array<GateTimeline>>()
322
+ // A frame flush's entries, in order, prepared and waiting for their commit; and those whose
323
+ // keys held changed, which the binding hears first. Reused each flush: the per-frame path.
324
+ const prepared: Array<Entry> = []
325
+ const heldChanged: Array<Entry> = []
326
+
327
+ /**
328
+ * Project one dirty entry's patch and restore the keys it dropped (once per element per flush),
329
+ * marking it clean: into `into`, and into `held` when the keys it holds change and its sink
330
+ * hears them. Its commit waits for the binding's `batch` of those (ADR-0034, *Amendment
331
+ * (#209)*). Plain calls only: this is the per-frame path.
332
+ */
333
+ const prepare = (entry: Entry, into: Array<Entry>, held: Array<Entry>): void => {
334
+ const patch = project(entry.values)
335
+ entry.dirty = false
336
+ entry.patch = patch
337
+ into.push(entry)
338
+ const sink = entry.sink
339
+ const target = sink.target
340
+ const committed = entry.committed
341
+ const before = committed.size
342
+ let kept = 0
343
+ let added = false
344
+ for (const key in patch) {
345
+ if (committed.has(key)) {
346
+ kept++
347
+ continue
348
+ }
349
+ committed.set(key, valueBeforeOf(target, key))
350
+ added = true
351
+ }
352
+ // A key the last patch wrote and this one doesn't: the element gets its own value
353
+ // back. Only looked for when one dropped out (the usual frame keeps every key).
354
+ let restore: Renderer.Patch | undefined
355
+ if (kept < before) {
356
+ for (const [key, own] of committed) {
357
+ if (key in patch) continue
358
+ if (Predicate.isUndefined(restore)) restore = {}
359
+ restore[key] = own
360
+ committed.delete(key)
361
+ }
362
+ }
363
+ if (Predicate.isNotUndefined(restore)) commit(target, restore)
364
+ // The keys held changed (the usual frame changes none): the binding hears before the commit.
365
+ if ((added || Predicate.isNotUndefined(restore)) && Predicate.isNotUndefined(sink.onHeld)) held.push(entry)
366
+ }
367
+
368
+ /**
369
+ * Before a flush's commits (#240): cancel the Timeline values each element committing now let go of,
370
+ * and sync the rest with its values, so each starts or stops as nothing else adds to its property.
371
+ * An entry is committing while it holds a prepared patch. Kept beside the entries, not on them, so an
372
+ * element with none pays nothing per frame: the flush checks two sizes. Per flush: plain loops.
373
+ */
374
+ const syncTimelines = (): void => {
375
+ for (const [entry, ended] of endings) {
376
+ if (Predicate.isUndefined(entry.patch)) continue
377
+ endings.delete(entry)
378
+ cancelEach(ended)
379
+ }
380
+ for (const [entry, byKey] of timelines) {
381
+ if (Predicate.isUndefined(entry.patch)) continue
382
+ for (const value of byKey.values()) value.sync(entry.values)
383
+ }
384
+ }
385
+
386
+ /** Every Timeline value of `entry`, cancelled at once: its element is gone, or the gate is. */
387
+ const cancelTimelines = (entry: Entry): void => {
388
+ const ended = endings.get(entry)
389
+ endings.delete(entry)
390
+ if (Predicate.isNotUndefined(ended)) cancelEach(ended)
391
+ const byKey = timelines.get(entry)
392
+ timelines.delete(entry)
393
+ if (Predicate.isNotUndefined(byKey)) cancelEach(byKey.values())
394
+ }
395
+
396
+ /** Commit a prepared entry's patch onto its element. */
397
+ const commitPrepared = (entry: Entry): void => {
398
+ const patch = entry.patch
399
+ if (Predicate.isUndefined(patch)) return
400
+ entry.patch = undefined
401
+ commit(entry.sink.target, patch)
402
+ if (Predicate.isNotUndefined(entry.sink.onCommit)) committedSince.add(entry)
403
+ }
404
+
405
+ /**
406
+ * The prepared entries, committed, after the binding has heard the keys held change, together, in
407
+ * its `batch` (#209); both lists emptied for the next flush.
408
+ */
409
+ const commitAll = (entries: Array<Entry>, held: Array<Entry>): void => {
410
+ if (held.length > 0) batch(() => tellHeld(held))
411
+ for (let i = 0; i < entries.length; i++) commitPrepared(entries[i])
412
+ entries.length = 0
413
+ held.length = 0
414
+ }
415
+
416
+ /** Each entry's `onHeld`, with every key the gate holds on its element now. */
417
+ const tellHeld = (held: ReadonlyArray<Entry>): void => {
418
+ for (let i = 0; i < held.length; i++) {
419
+ const entry = held[i]
420
+ const onHeld = entry.sink.onHeld
421
+ if (Predicate.isNotUndefined(onHeld)) onHeld(Array.from(entry.committed.keys()))
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Tell each entry committed since the last frame flush, once, after every commit of this one
427
+ * (#233). Its values are copied into its own reused object, so its sink never holds the gate's.
428
+ */
429
+ const tellCommitted = (): void => {
430
+ for (const entry of committedSince) {
431
+ const onCommit = entry.sink.onCommit
432
+ if (Predicate.isUndefined(onCommit)) continue
433
+ let latest = entry.latest
434
+ if (Predicate.isUndefined(latest)) {
435
+ latest = {}
436
+ entry.latest = latest
437
+ }
438
+ for (const key in latest) if (!Object.hasOwn(entry.values, key)) delete latest[key]
439
+ Object.assign(latest, entry.values)
440
+ // Its Transform template rides in its values (#443), and isn't one: Motion's `onUpdate` never sees it.
441
+ delete latest[templateKey]
442
+ try {
443
+ onCommit(latest)
444
+ entry.failing = false
445
+ } catch (defect) {
446
+ if (entry.failing) continue
447
+ entry.failing = true
448
+ runtime.runFork(Report.failure("wardic.gate: an onCommit failed", Cause.die(defect)))
449
+ }
450
+ }
451
+ committedSince.clear()
452
+ }
453
+
454
+ /**
455
+ * The live outputs asked for of `entry`, each set where its value changed, as a write or a
456
+ * release lands: a value derived from one (a Live value of another key, through a binding) is
457
+ * written in the same frame, and commits with it. An unchanged one skips the registry. Plain
458
+ * calls: a write is the per-frame path.
459
+ */
460
+ const setOutputs = (entry: Entry): void => {
461
+ const outputs = entry.outputs
462
+ if (Predicate.isUndefined(outputs)) return
463
+ for (const [key, output] of outputs) {
464
+ const value = entry.values[key]
465
+ if (value === output.last) continue
466
+ output.last = value
467
+ registry.set(output.atom, value)
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Run `beforeFirstCommit` for each waiting entry about to commit (dirty), in the binding's
473
+ * `batch` before any commit, so the binding applies what it changes first. A wrap that never
474
+ * commits stays waiting, so this loops over the wraps still waiting, once per frame flush.
475
+ */
476
+ const runFirstCommits = (): void => {
477
+ for (const id of firstCommits) {
478
+ const entry = accumulator.get(id)
479
+ if (Predicate.isUndefined(entry) || !entry.dirty) continue
480
+ firstCommits.delete(id)
481
+ const hook = entry.sink.beforeFirstCommit
482
+ if (Predicate.isNotUndefined(hook)) hook()
483
+ }
484
+ }
485
+
486
+ const flush = (): void => {
487
+ scheduled = false
488
+ try {
489
+ // The switches first: an element's own values are read once its Starting style is gone.
490
+ if (firstCommits.size > 0) batch(runFirstCommits)
491
+ // Every dirty element, once. No auto-reschedule — the next write() does. A write()
492
+ // from an effect a sink's hook runs requests the next frame (it isn't stranded).
493
+ for (const entry of accumulator.values()) if (entry.dirty) prepare(entry, prepared, heldChanged)
494
+ if (timelines.size > 0 || endings.size > 0) syncTimelines()
495
+ commitAll(prepared, heldChanged)
496
+ if (committedSince.size > 0) tellCommitted()
497
+ } catch (defect) {
498
+ prepared.length = 0
499
+ heldChanged.length = 0
500
+ runtime.runFork(Report.failure("wardic.gate: a flush failed", Cause.die(defect)))
501
+ }
502
+ if (afterFlushes.length > 0) runAfterFlushes()
503
+ }
504
+
505
+ /** The calls `afterFlush` queued, each once, a new queue for any they make. */
506
+ const runAfterFlushes = (): void => {
507
+ const due = afterFlushes
508
+ afterFlushes = []
509
+ for (const fn of due) {
510
+ try {
511
+ fn()
512
+ } catch (defect) {
513
+ runtime.runFork(Report.failure("wardic.gate: an afterFlush call failed", Cause.die(defect)))
514
+ }
515
+ }
516
+ }
517
+
518
+ const afterFlush: FlushGate["afterFlush"] = (fn) => {
519
+ afterFlushes.push(fn)
520
+ scheduleFlush()
521
+ }
522
+
523
+ /**
524
+ * The end of the Frame loop's tick (ADR-0033): flush now, in the Refresh frame that computed
525
+ * the values, and withdraw the frame the first write since the last flush requested.
526
+ */
527
+ const flushTicked = (): undefined => {
528
+ if (!scheduled) return undefined
529
+ cancelFrame(frame)
530
+ flush()
531
+ return undefined
532
+ }
533
+
534
+ const scheduleFlush = (): void => {
535
+ if (scheduled) return
536
+ scheduled = true
537
+ frame = requestFrame(flush)
538
+ }
539
+
540
+ const register: FlushGate["register"] = (id, sink, values) => {
541
+ const entry: Entry = {
542
+ values: UndefinedOr.match(values, { onUndefined: () => ({}), onDefined: (start) => ({ ...start }) }),
543
+ sink,
544
+ dirty: false,
545
+ committed: new Map(),
546
+ outputs: outputsById.get(id),
547
+ latest: undefined,
548
+ failing: false,
549
+ patch: undefined,
550
+ }
551
+ // An entry the id had: its Timeline values end with it (#240).
552
+ const replaced = accumulator.get(id)
553
+ if (Predicate.isNotUndefined(replaced)) cancelTimelines(replaced)
554
+ accumulator.set(id, entry)
555
+ if (Predicate.isNotUndefined(sink.beforeFirstCommit)) firstCommits.add(id)
556
+ return () => {
557
+ cancelTimelines(entry)
558
+ accumulator.delete(id)
559
+ firstCommits.delete(id)
560
+ committedSince.delete(entry)
561
+ endOutputs(id)
562
+ }
563
+ }
564
+
565
+ /** `id`'s live outputs, each set to `undefined` and forgotten: its element is gone. */
566
+ const endOutputs = (id: string): void => {
567
+ const outputs = outputsById.get(id)
568
+ if (Predicate.isUndefined(outputs)) return
569
+ outputsById.delete(id)
570
+ for (const output of outputs.values()) {
571
+ registry.set(output.atom, undefined)
572
+ output.unmount()
573
+ }
574
+ }
575
+
576
+ /** `id`'s current value for `key`, or `undefined` for an unregistered id or a key it hasn't written. */
577
+ const committedValueOf = (id: string, key: string): unknown => {
578
+ const entry = accumulator.get(id)
579
+ if (Predicate.isUndefined(entry)) return undefined
580
+ return entry.values[key]
581
+ }
582
+
583
+ const valueOf: FlushGate["valueOf"] = (id, key) => {
584
+ let outputs = outputsById.get(id)
585
+ if (Predicate.isUndefined(outputs)) {
586
+ outputs = new Map()
587
+ outputsById.set(id, outputs)
588
+ const entry = accumulator.get(id)
589
+ if (Predicate.isNotUndefined(entry)) entry.outputs = outputs
590
+ }
591
+ const known = outputs.get(key)
592
+ if (Predicate.isNotUndefined(known)) return known.atom
593
+ // Made `undefined` and mounted until its element unregisters, not kept alive: a kept-alive
594
+ // Atom's node never leaves the registry, and one left behind reads `undefined` afresh.
595
+ const atom = Atom.make<unknown>(undefined)
596
+ const output: Output = { atom, last: undefined, unmount: registry.mount(atom) }
597
+ outputs.set(key, output)
598
+ const value = committedValueOf(id, key)
599
+ if (Predicate.isNotUndefined(value)) {
600
+ output.last = value
601
+ registry.set(atom, value)
602
+ }
603
+ return atom
604
+ }
605
+
606
+ const write: FlushGate["write"] = (id, partial) => {
607
+ const entry = accumulator.get(id)
608
+ if (Predicate.isUndefined(entry)) return
609
+ Object.assign(entry.values, partial)
610
+ entry.dirty = true
611
+ if (Predicate.isNotUndefined(recording)) recording.add(id)
612
+ scheduleFlush()
613
+ setOutputs(entry)
614
+ }
615
+
616
+ const flushPass: FlushGate["flushPass"] = (pass) => {
617
+ const written = new Set<string>()
618
+ recording = written
619
+ try {
620
+ pass()
621
+ } finally {
622
+ recording = undefined
623
+ }
624
+ if (written.size === 0) return
625
+ // No `beforeFirstCommit` here: a Measure pass may write only a node's projection, and
626
+ // dropping the Starting style then would leave its animated keys unset until the frame
627
+ // flush (a frame later for an element mounted inside a frame). The frame flush switches.
628
+ // A commit here is told at the frame flush (#233): the write that made it scheduled that flush.
629
+ // Its own lists: a pass may run from a hook the frame flush's `batch` runs.
630
+ const entries: Array<Entry> = []
631
+ const held: Array<Entry> = []
632
+ for (const id of written) {
633
+ const entry = accumulator.get(id)
634
+ if (Predicate.isNotUndefined(entry) && entry.dirty) prepare(entry, entries, held)
635
+ }
636
+ if (timelines.size > 0 || endings.size > 0) syncTimelines()
637
+ commitAll(entries, held)
638
+ }
639
+
640
+ // Per key per Retarget, as the Override stack takes a key and lets it go: statements (the hot path).
641
+ const timeline: FlushGate["timeline"] = (id, key, value) => {
642
+ const entry = accumulator.get(id)
643
+ if (Predicate.isUndefined(entry)) return
644
+ let byKey = timelines.get(entry)
645
+ let known: GateTimeline | undefined
646
+ if (Predicate.isNotUndefined(byKey)) known = byKey.get(key)
647
+ if (known === value) return
648
+ // The one it had is cancelled at the next flush, with the commit that draws the key without it.
649
+ if (Predicate.isNotUndefined(known)) {
650
+ const ending = endings.get(entry)
651
+ if (Predicate.isNotUndefined(ending)) ending.push(known)
652
+ if (Predicate.isUndefined(ending)) endings.set(entry, [known])
653
+ if (Predicate.isNotUndefined(byKey)) byKey.delete(key)
654
+ }
655
+ if (Predicate.isNotUndefined(value)) {
656
+ if (Predicate.isUndefined(byKey)) {
657
+ byKey = new Map()
658
+ timelines.set(entry, byKey)
659
+ }
660
+ byKey.set(key, value)
661
+ }
662
+ // An element left with none leaves the map, so the flush skips it.
663
+ if (Predicate.isNotUndefined(byKey) && byKey.size === 0) timelines.delete(entry)
664
+ entry.dirty = true
665
+ scheduleFlush()
666
+ }
667
+
668
+ /** `entry`'s Timeline values for `keys`, cancelled at once: those keys go back to the element's own style. */
669
+ const releaseTimelines = (entry: Entry, keys: ReadonlyArray<string>): void => {
670
+ const byKey = timelines.get(entry)
671
+ if (Predicate.isUndefined(byKey)) return
672
+ for (const key of keys) {
673
+ const value = byKey.get(key)
674
+ if (Predicate.isUndefined(value)) continue
675
+ byKey.delete(key)
676
+ value.cancel()
677
+ }
678
+ if (byKey.size === 0) timelines.delete(entry)
679
+ }
680
+
681
+ const release: FlushGate["release"] = (id, keys, restore, keep) => {
682
+ const entry = accumulator.get(id)
683
+ if (Predicate.isUndefined(entry)) return
684
+ releaseTimelines(entry, keys)
685
+ // A property another writer draws next: dropped from what's saved, so its drop-out writes nothing.
686
+ if (Predicate.isNotUndefined(keep)) for (const property of keep) entry.committed.delete(property)
687
+ let released = false
688
+ for (const key of keys) {
689
+ if (!Object.hasOwn(entry.values, key)) continue
690
+ delete entry.values[key]
691
+ released = true
692
+ // The drop-out path in `apply` writes the saved value back: make it the one handed in.
693
+ if (Predicate.isUndefined(restore)) continue
694
+ const value: string | undefined = restore[key]
695
+ if (Predicate.isNotUndefined(value) && entry.committed.has(key)) entry.committed.set(key, value)
696
+ }
697
+ if (!released) return
698
+ entry.dirty = true
699
+ scheduleFlush()
700
+ setOutputs(entry)
701
+ }
702
+
703
+ const dispose: FlushGate["dispose"] = () => {
704
+ // Off the loop first, so no tick flushes what follows; a failure reported, never thrown (#618).
705
+ const unhooked = Effect.runSyncExit(Scope.close(ticks, Exit.void))
706
+ if (Exit.isFailure(unhooked)) runtime.runFork(Report.failure("wardic.gate: its tick hook failed to close", unhooked.cause))
707
+ if (scheduled) {
708
+ cancelFrame(frame)
709
+ scheduled = false
710
+ }
711
+ for (const entry of accumulator.values()) cancelTimelines(entry)
712
+ timelines.clear()
713
+ endings.clear()
714
+ accumulator.clear()
715
+ firstCommits.clear()
716
+ committedSince.clear()
717
+ // The calls waiting on a flush that won't come: their provider is gone (#257).
718
+ afterFlushes = []
719
+ for (const id of [...outputsById.keys()]) endOutputs(id)
720
+ }
721
+
722
+ // The gate's hook on the loop, for the gate's lifetime: a child of the Scope it's built in, so a gate
723
+ // its `dispose` never reached is unhooked as that Scope closes.
724
+ const ticks = Scope.forkUnsafe(runtime.scope, "sequential")
725
+ runtime.runSync(afterTick(flushTicked).pipe(Scope.provide(ticks)))
726
+
727
+ return { register, write, flushPass, release, valueOf, afterFlush, timeline, dispose }
728
+ }
729
+
730
+