@wardic/core 1.0.0-rc.1 → 1.0.0-rc.10

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 (114) hide show
  1. package/dist/Batch.d.ts +244 -0
  2. package/dist/Batch.d.ts.map +1 -0
  3. package/dist/Batch.js +1862 -0
  4. package/dist/Batch.js.map +1 -0
  5. package/dist/Clock.d.ts.map +1 -1
  6. package/dist/Clock.js +20 -12
  7. package/dist/Clock.js.map +1 -1
  8. package/dist/DragRecognizer.d.ts +16 -1
  9. package/dist/DragRecognizer.d.ts.map +1 -1
  10. package/dist/DragRecognizer.js +87 -1
  11. package/dist/DragRecognizer.js.map +1 -1
  12. package/dist/Frame.d.ts +13 -0
  13. package/dist/Frame.d.ts.map +1 -1
  14. package/dist/Frame.js +2 -0
  15. package/dist/Frame.js.map +1 -1
  16. package/dist/FrameLoop.d.ts +12 -1
  17. package/dist/FrameLoop.d.ts.map +1 -1
  18. package/dist/FrameLoop.js +23 -1
  19. package/dist/FrameLoop.js.map +1 -1
  20. package/dist/InputSource.d.ts +21 -0
  21. package/dist/InputSource.d.ts.map +1 -1
  22. package/dist/InputSource.js.map +1 -1
  23. package/dist/LiveValue.d.ts +4 -3
  24. package/dist/LiveValue.d.ts.map +1 -1
  25. package/dist/LiveValue.js +7 -5
  26. package/dist/LiveValue.js.map +1 -1
  27. package/dist/Machine.d.ts +18 -4
  28. package/dist/Machine.d.ts.map +1 -1
  29. package/dist/Machine.js +96 -107
  30. package/dist/Machine.js.map +1 -1
  31. package/dist/Playback.d.ts +1 -1
  32. package/dist/Playback.d.ts.map +1 -1
  33. package/dist/Playback.js +18 -8
  34. package/dist/Playback.js.map +1 -1
  35. package/dist/Probe.d.ts +10 -49
  36. package/dist/Probe.d.ts.map +1 -1
  37. package/dist/Probe.js +7 -6
  38. package/dist/Probe.js.map +1 -1
  39. package/dist/Projection.d.ts +4 -3
  40. package/dist/Projection.d.ts.map +1 -1
  41. package/dist/Projection.js +5 -2
  42. package/dist/Projection.js.map +1 -1
  43. package/dist/Recognizer.d.ts +35 -2
  44. package/dist/Recognizer.d.ts.map +1 -1
  45. package/dist/Recognizer.js +211 -16
  46. package/dist/Recognizer.js.map +1 -1
  47. package/dist/Reorder.d.ts +3 -3
  48. package/dist/Reorder.d.ts.map +1 -1
  49. package/dist/Reorder.js +28 -14
  50. package/dist/Reorder.js.map +1 -1
  51. package/dist/ScrollSource.d.ts +62 -0
  52. package/dist/ScrollSource.d.ts.map +1 -0
  53. package/dist/ScrollSource.js +21 -0
  54. package/dist/ScrollSource.js.map +1 -0
  55. package/dist/Sequence.d.ts +7 -2
  56. package/dist/Sequence.d.ts.map +1 -1
  57. package/dist/Sequence.js +8 -2
  58. package/dist/Sequence.js.map +1 -1
  59. package/dist/SharedSource.d.ts +35 -15
  60. package/dist/SharedSource.d.ts.map +1 -1
  61. package/dist/SharedSource.js +84 -108
  62. package/dist/SharedSource.js.map +1 -1
  63. package/dist/index.d.ts +3 -1
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +3 -1
  66. package/dist/index.js.map +1 -1
  67. package/dist/internal/frameLoop.d.ts +33 -7
  68. package/dist/internal/frameLoop.d.ts.map +1 -1
  69. package/dist/internal/frameLoop.js +214 -38
  70. package/dist/internal/frameLoop.js.map +1 -1
  71. package/dist/internal/hearing.d.ts +13 -0
  72. package/dist/internal/hearing.d.ts.map +1 -0
  73. package/dist/internal/hearing.js +71 -0
  74. package/dist/internal/hearing.js.map +1 -0
  75. package/dist/internal/keyframes.d.ts +40 -0
  76. package/dist/internal/keyframes.d.ts.map +1 -0
  77. package/dist/internal/keyframes.js +70 -0
  78. package/dist/internal/keyframes.js.map +1 -0
  79. package/dist/internal/playhead.d.ts +16 -0
  80. package/dist/internal/playhead.d.ts.map +1 -0
  81. package/dist/internal/playhead.js +6 -0
  82. package/dist/internal/playhead.js.map +1 -0
  83. package/dist/internal/stepper.d.ts +6 -0
  84. package/dist/internal/stepper.d.ts.map +1 -1
  85. package/dist/internal/stepper.js +16 -0
  86. package/dist/internal/stepper.js.map +1 -1
  87. package/dist/internal/watch.d.ts +6 -0
  88. package/dist/internal/watch.d.ts.map +1 -1
  89. package/dist/internal/watch.js +7 -0
  90. package/dist/internal/watch.js.map +1 -1
  91. package/package.json +1 -1
  92. package/src/Batch.ts +2128 -0
  93. package/src/Clock.ts +29 -17
  94. package/src/DragRecognizer.ts +97 -2
  95. package/src/Frame.ts +16 -0
  96. package/src/FrameLoop.ts +24 -1
  97. package/src/InputSource.ts +25 -0
  98. package/src/LiveValue.ts +9 -7
  99. package/src/Machine.ts +106 -135
  100. package/src/Playback.ts +18 -15
  101. package/src/Probe.ts +16 -58
  102. package/src/Projection.ts +11 -5
  103. package/src/Recognizer.ts +242 -17
  104. package/src/Reorder.ts +39 -18
  105. package/src/ScrollSource.ts +68 -0
  106. package/src/Sequence.ts +20 -5
  107. package/src/SharedSource.ts +113 -146
  108. package/src/index.ts +3 -1
  109. package/src/internal/frameLoop.ts +246 -43
  110. package/src/internal/hearing.ts +76 -0
  111. package/src/internal/keyframes.ts +98 -0
  112. package/src/internal/playhead.ts +19 -0
  113. package/src/internal/stepper.ts +16 -0
  114. package/src/internal/watch.ts +15 -0
@@ -6,7 +6,7 @@
6
6
  * Primitive's per-frame cost.
7
7
  *
8
8
  * - **A run** is `run(machine, sink)`: an entry added, its Frames handed to `sink` from the loop's
9
- * next tick, and its settled Frame returned. `acquireUseRelease` removes the entry on every
9
+ * next tick (or its Late step, below), and its settled Frame returned. `acquireUseRelease` removes the entry on every
10
10
  * exit (a settle, an interruption, a defect), so interrupting a run removes it at once. A run
11
11
  * given a token (`run(machine, sink, { supersede })`, #200) joins it, and `Supersede.end` takes
12
12
  * it off at once too, completing its fiber with `Superseded`: no interrupt, and no interrupt
@@ -17,23 +17,33 @@
17
17
  * a Retarget (a removal, then an add, in one call) keeps it, and the Clock goes idle at its
18
18
  * next Refresh frame. The Layer's `Scope` closing interrupts it.
19
19
  * - **A tick** steps the entries the tick began with: an entry added during it (from a sink)
20
- * waits for the next tick, and one removed during it gets no Frame. It steps them in add
20
+ * isn't stepped by it, and one removed during it gets no Frame. It steps them in add
21
21
  * order, those added with `runLast` after all the others (ADR-0027, *Amendment (#137)*). A step or sink that
22
22
  * throws ends only its own run (`Exit.die`); a failure of the loop itself fails every run
23
23
  * still on it, and the next run starts a fresh burst. That includes a run a continuation
24
24
  * starts while the ending burst resumes its runs (#81).
25
- * - **The end of a tick** calls each `afterTick` hook, after every step and sink and the
26
- * continuations of the runs that settled in it, the tick that ends a burst included. The flush
25
+ * - **The end of a tick** calls each `afterTick` hook, with the tick's dt, after every step and sink
26
+ * and the continuations of the runs that settled in it, the tick that ends a burst included. The flush
27
27
  * gate flushes there, so a value paints in the Refresh frame that computed it (ADR-0033). A run
28
28
  * a hook starts keeps the burst: whether it ends is counted after the hooks (#209).
29
+ * - **The Late window** runs from a tick's first step until a microtask the tick queues at its end
30
+ * (ADR-0027 *Amendment (#680)*): what starts in it is drawn in that tick's Refresh frame, after the
31
+ * tick. A run `run` added in it, during the tick or in a microtask the tick's own code queued (Solid
32
+ * 2's effects, a promise it resolved), takes its **Late step** in that microtask: one step at the
33
+ * tick's dt, and the hooks again, so the frame paints it, not its origin. A round whose steps or hooks
34
+ * add more runs is followed by another, at most `MAX_LATE_ROUNDS`; the rest step at the next tick. A
35
+ * `runLast` run takes none: the projection's coordinator, its one caller, would step again the nodes
36
+ * an after-tick Measure pass already stepped. One the tick stepped steps again at dt 0 after a round
37
+ * that stepped a `run` run, so it reads what that round wrote.
38
+ * `inLateWindow()` reads it, for the projection's Measure pass (ADR-0018 *Amendment (#673)*).
29
39
  *
30
40
  * Observability: a span per run, named after its Primitive (`machine.span`), and one per burst
31
41
  * (`wardic.frameloop`). A run's `<name>: start` debug log, annotated with its span's attributes,
32
- * built only when a Debug log would be kept (#542). Per tick, no span or log: a gauge of running
33
- * animations and a histogram of ms per tick, each one `updateUnsafe` (ADR-0027, decision 6), and the
34
- * runs that settled or failed in it, counted as they end and added at its end by the loop's own
35
- * `afterTick` hook, its first (#542). The histogram ends before the hooks, so it measures the steps
36
- * alone, not the gate's flush (ADR-0033).
42
+ * built only when a Debug log would be kept (#542). Per tick, no span or log. With the metrics an app
43
+ * gives (`FrameLoop.layerMetrics`, #518): a gauge of running animations and a histogram of ms per tick,
44
+ * each one `updateUnsafe` (ADR-0027, decision 6), and the runs that settled or failed in it, counted as
45
+ * they end and added at its end by the loop's own `afterTick` hook, its first (#542). The histogram ends
46
+ * before the hooks, so it measures the steps alone, not the gate's flush (ADR-0033).
37
47
  *
38
48
  * A run's span is opened without a stack frame (ADR-0040, decision 3): `useSpan` with the span as
39
49
  * the `ParentSpan`, not `withSpan`, whose frame Effect stamps on an interrupted run's cause and
@@ -43,8 +53,8 @@
43
53
  * The dev check for non-finite Frames (`CheckFrames`, ADR-0030 decision 7) is a sink wrapper a
44
54
  * run gets at its start when the check is on, so the tick is the same either way.
45
55
  *
46
- * Internal (ADR-0028, decision 11): the service's shape (`run`, `afterTick`) and `make`, behind
47
- * `FrameLoop.layer`.
56
+ * Internal (ADR-0028, decision 11): the service's shape (`run`, `runLast`, `afterTick`,
57
+ * `inLateWindow`) and `make`, behind `FrameLoop.layer`.
48
58
  */
49
59
  import * as Arr from "effect/Array"
50
60
  import * as Bool from "effect/Boolean"
@@ -54,16 +64,18 @@ import * as Data from "effect/Data"
54
64
  import * as Deferred from "effect/Deferred"
55
65
  import * as Effect from "effect/Effect"
56
66
  import * as Exit from "effect/Exit"
67
+ import type * as Fiber from "effect/Fiber"
57
68
  import * as FiberHandle from "effect/FiberHandle"
58
69
  import { constUndefined, identity } from "effect/Function"
59
70
  import * as LogLevel from "effect/LogLevel"
60
- import * as Metric from "effect/Metric"
71
+ import type * as Metric from "effect/Metric"
61
72
  import * as Option from "effect/Option"
62
73
  import * as Predicate from "effect/Predicate"
63
74
  import * as References from "effect/References"
64
75
  import type * as Scope from "effect/Scope"
65
76
  import * as Stream from "effect/Stream"
66
77
  import * as Tracer from "effect/Tracer"
78
+ import * as UndefinedOr from "effect/UndefinedOr"
67
79
  import * as Clock from "../Clock.ts"
68
80
  import type * as Frame from "../Frame.ts"
69
81
  import * as Supersede from "../Supersede.ts"
@@ -74,6 +86,8 @@ import { isTraced, traced } from "./tracing.ts"
74
86
  // @wardic/core compiles against ES2022 alone, which does not declare `performance` (see
75
87
  // refresh-frame-clock.ts). It is a host global in every Environment Wardic targets.
76
88
  declare const performance: { readonly now: () => number }
89
+ // The same for `queueMicrotask` (see Microtask.ts): the Late window's end (#680).
90
+ declare const queueMicrotask: (callback: () => void) => void
77
91
 
78
92
  /** A run's options: the token it joins, so its caller can end it with others. */
79
93
  // #200.
@@ -92,7 +106,7 @@ export interface Run {
92
106
  export interface Shape {
93
107
  /**
94
108
  * Runs `machine` on the loop, handing each of its Frames to `sink`, from the loop's next tick until it
95
- * settles. Succeeds with the settled Frame; a machine that never settles, `chase`, runs until it's
109
+ * settles; added in the loop's Late window, from its Late step there. Succeeds with the settled Frame; a machine that never settles, `chase`, runs until it's
96
110
  * interrupted or superseded. Dies with the defect if its step or its sink throws. Interrupting it
97
111
  * removes it at once.
98
112
  *
@@ -105,22 +119,33 @@ export interface Shape {
105
119
  /**
106
120
  * `run`, but stepped after every run `run` added, in each tick: for a machine that reads what the
107
121
  * others' sinks wrote in the same tick. Among themselves, these runs step in the order they were added.
122
+ * One added in the Late window takes no Late step: its first step is the next tick. One the tick
123
+ * stepped steps again at dt 0 after a Late round that stepped a `run` run.
108
124
  */
109
125
  // ADR-0027, *Amendment (#137)*: the projection's coordinator is the one caller.
110
126
  readonly runLast: Run
111
127
  /**
112
- * Calls `hook` at the end of every tick, after every run's step and sink and the continuations of the
113
- * runs that settled in it, until the `Scope` closes. Hooks run in the order they were added. A plain
114
- * call, typed like a `Sink`, so a hook that returns an Effect doesn't compile. A hook doesn't throw:
115
- * one that does fails the tick, and with it every run on the loop.
128
+ * Calls `hook` at the end of every tick, with the tick's seconds, after every run's step and sink and
129
+ * the continuations of the runs that settled in it, and again after each of its Late rounds, until the
130
+ * `Scope` closes. Hooks run in the order they were added. A plain call, typed like a `Sink`, so a hook
131
+ * that returns an Effect doesn't compile. A hook doesn't throw: one that does fails the tick, and with
132
+ * it every run on the loop.
116
133
  */
117
- // ADR-0033: the flush gate is the one caller.
118
- readonly afterTick: (hook: () => undefined) => Effect.Effect<void, never, Scope.Scope>
134
+ // ADR-0033: the flush gate's flush. The tick's dt: ADR-0027 *Amendment (#673)*, for the projection's
135
+ // after-tick pass. Again after a Late round (#680), so the gate flushes what the round wrote.
136
+ readonly afterTick: (hook: (dt: number) => undefined) => Effect.Effect<void, never, Scope.Scope>
137
+ /**
138
+ * Whether the **Late window** is open now: from a tick's first step until the microtask it queued at
139
+ * its end has run. What's written then is drawn in that tick's Refresh frame, after the tick.
140
+ */
141
+ // ADR-0027 *Amendment (#680)* (was `ticking()`, #673): the projection's Measure pass reads it at a
142
+ // trigger, to know it will run after its frame's tick.
143
+ readonly inLateWindow: () => boolean
119
144
  }
120
145
 
121
146
  /** One hook on the loop's ticks, one object per `afterTick`, so removing it removes only that one. */
122
147
  interface Hook {
123
- readonly hook: () => undefined
148
+ readonly hook: (dt: number) => undefined
124
149
  }
125
150
 
126
151
  /** One run on the loop. */
@@ -133,14 +158,37 @@ interface Entry {
133
158
  /** Completed by the loop: the settled Frame, the defect, or an interruption; or by its token, `Superseded` (#200). */
134
159
  readonly settled: Deferred.Deferred<Frame.Frame<unknown> | Supersede.Superseded>
135
160
  removed: boolean
161
+ /**
162
+ * Added in the Late window and not yet stepped (#680): a `run` run's Late step is due; a `runLast` run
163
+ * waits for the next tick, and the dt-0 step leaves it out.
164
+ */
165
+ late: boolean
166
+ /** Its span, when traced: marked `late` at its Late step (#680). */
167
+ readonly span: Tracer.Span | undefined
168
+ }
169
+
170
+ /** How many Late rounds a window runs before the rest wait for the next tick: the Measure pass's cap (#680). */
171
+ const MAX_LATE_ROUNDS = 5
172
+
173
+ /**
174
+ * The Frame loop's metrics: the running animations, the runs that settled and failed, and each tick's
175
+ * ms. None unless an app gives them (`FrameLoop.layerMetrics`, #518), so an app that reads none ships and
176
+ * updates none.
177
+ */
178
+ export interface Metrics {
179
+ readonly animations: Metric.Gauge<number>
180
+ readonly settled: Metric.Counter<number>
181
+ readonly failed: Metric.Counter<number>
182
+ readonly tickMs: Metric.Histogram<number>
136
183
  }
137
184
 
138
- const animations = Metric.gauge("wardic_frameloop_animations", { description: "Primitives running on the Frame loop" })
139
- const settledRuns = Metric.counter("wardic_frameloop_settled", { description: "Runs on the Frame loop that settled" })
140
- const failedRuns = Metric.counter("wardic_frameloop_failed", { description: "Runs on the Frame loop that failed" })
141
- const tickMs = Metric.histogram("wardic_frameloop_tick_ms", {
142
- description: "Milliseconds the Frame loop spends on one tick",
143
- boundaries: Metric.linearBoundaries({ start: 0, width: 0.5, count: 32 }),
185
+ /**
186
+ * Where a run's fiber finds the metrics. The loop takes them from the first run that has them: an app
187
+ * gives them beside its Environment, which the loop's own build doesn't see, as `CheckFrames` is read.
188
+ */
189
+ // #518, ADR-0067 *Amendment (#518)*, decision 2.
190
+ export const MetricsGiven: Context.Reference<Metrics | undefined> = Context.Reference<Metrics | undefined>("@wardic/core/FrameLoop/Metrics", {
191
+ defaultValue: constUndefined,
144
192
  })
145
193
 
146
194
  /**
@@ -255,10 +303,25 @@ export const make = Effect.fnUntraced(
255
303
  // ending burst is still in `burst`, so the loop tracks its burst itself rather than asking the
256
304
  // handle (#81).
257
305
  let bursting = false
306
+ // The Late window (ADR-0027 *Amendment (#680)*): open from a tick's first step until the microtask
307
+ // queued at its end has run. `windowQueued` keeps one microtask per window, however many ticks open
308
+ // it before a checkpoint (a test firing frames back to back).
309
+ let windowOpen = false
310
+ let windowQueued = false
311
+ // The dt of the tick that opened the window: a Late step's.
312
+ let windowDt = 0
313
+ // The `run` runs added in the window, in add order: their Late step is due. The `runLast` runs added
314
+ // in it take none, and are marked only so the dt-0 step leaves them out: they step at the next tick.
315
+ const lateFirst: Array<Entry> = []
316
+ const lateLast: Array<Entry> = []
317
+ // A hook that threw in a Late round: the burst it interrupts ends every run with it (#680, Q15).
318
+ let lateFailure: Cause.Cause<never> | undefined
258
319
  // The runs the loop ended since it last counted (#542): a settle or a failure, into the counters
259
320
  // once per tick. An interruption is neither, nor a superseded run, which the loop doesn't end.
260
321
  let settledCount = 0
261
322
  let failedCount = 0
323
+ // The metrics, once a run brings them (#518).
324
+ let metrics: Metrics | undefined
262
325
 
263
326
  /** End `entry`'s run: removed, counted, and its fiber resumed with `exit` (inline, within the tick). */
264
327
  const end = (entry: Entry, exit: Exit.Exit<Frame.Frame<unknown>>): void => {
@@ -270,8 +333,10 @@ export const make = Effect.fnUntraced(
270
333
 
271
334
  /** The runs ended since the last count, into the counters: once per tick, and as a burst ends. */
272
335
  const countEnds = (): undefined => {
273
- if (settledCount > 0) settledRuns.updateUnsafe(settledCount, buildContext)
274
- if (failedCount > 0) failedRuns.updateUnsafe(failedCount, buildContext)
336
+ if (Predicate.isNotUndefined(metrics)) {
337
+ if (settledCount > 0) metrics.settled.updateUnsafe(settledCount, buildContext)
338
+ if (failedCount > 0) metrics.failed.updateUnsafe(failedCount, buildContext)
339
+ }
275
340
  settledCount = 0
276
341
  failedCount = 0
277
342
  return undefined
@@ -317,8 +382,16 @@ export const make = Effect.fnUntraced(
317
382
  // The first lane's loops stay inline in `tick`: moved into a function shared with the last lane,
318
383
  // Node's `chase/loop` ran 55% slower (`bench:core`, ADR-0027 *Amendment (#137)*).
319
384
  const tick = (dt: number): boolean => {
320
- const t0 = performance.now()
321
- // Both counts before any step: a run added during the tick, to either lane, waits for the next.
385
+ // A window this tick finds open is the last frame's, its checkpoint not yet run (back-to-back
386
+ // frames in a test): its runs are on the lanes, so this tick steps them.
387
+ if (lateFirst.length + lateLast.length > 0) dropLate()
388
+ windowOpen = true
389
+ windowDt = dt
390
+ // The tick's start, read only for the metrics' histogram (#518).
391
+ let t0 = 0
392
+ if (Predicate.isNotUndefined(metrics)) t0 = performance.now()
393
+ // Both counts before any step: a run added during the tick isn't stepped by it. A `run` run takes its
394
+ // Late step at the window's end, a `runLast` run waits for the next tick (#680).
322
395
  const count = entries.length
323
396
  const lastCount = lastEntries.length
324
397
  for (let i = 0; i < count; i++) {
@@ -344,18 +417,125 @@ export const make = Effect.fnUntraced(
344
417
  }
345
418
  entries.length = kept
346
419
  if (lastEntries.length > 0) kept += compactLast()
347
- animations.updateUnsafe(kept, buildContext)
348
- tickMs.updateUnsafe(performance.now() - t0, buildContext)
420
+ if (Predicate.isNotUndefined(metrics)) {
421
+ metrics.animations.updateUnsafe(kept, buildContext)
422
+ metrics.tickMs.updateUnsafe(performance.now() - t0, buildContext)
423
+ }
349
424
  // The end of the tick: everything for this Refresh frame is written (ADR-0033). After
350
425
  // `tickMs`, which stays the cost of the steps alone.
351
426
  const ended = hooks
352
- for (let i = 0; i < ended.length; i++) ended[i].hook()
427
+ for (let i = 0; i < ended.length; i++) ended[i].hook(dt)
428
+ // The window stays open to the end of this frame's microtasks, which take the Late steps (#680).
429
+ if (!windowQueued) {
430
+ windowQueued = true
431
+ queueMicrotask(endLateWindow)
432
+ }
353
433
  // The burst ends with no run left, counted after the hooks: one a hook started (the flush
354
- // gate's, running a binding's batch, #209) takes its first step at the next tick.
434
+ // gate's, running a binding's batch, #209) takes its Late step and starts the next burst.
355
435
  return entries.length + lastEntries.length === 0
356
436
  }
357
437
 
358
- const afterTick = (hook: () => undefined): Effect.Effect<void, never, Scope.Scope> => {
438
+ /** Clear the Late lists: each run on them steps at the next tick. */
439
+ const dropLate = (): void => {
440
+ for (let i = 0; i < lateFirst.length; i++) lateFirst[i].late = false
441
+ for (let i = 0; i < lateLast.length; i++) lateLast[i].late = false
442
+ lateFirst.length = 0
443
+ lateLast.length = 0
444
+ }
445
+
446
+ /** Drop `list`'s first `count` entries in place, keeping the rest's order. */
447
+ const dropFirst = (list: Array<Entry>, count: number): void => {
448
+ const left = list.length - count
449
+ for (let i = 0; i < left; i++) list[i] = list[i + count]
450
+ list.length = left
451
+ }
452
+
453
+ /** One step of `entry` at `dt`: its Frame to its sink, its settle, or its defect, as a tick's. */
454
+ const stepOne = (entry: Entry, dt: number): void => {
455
+ try {
456
+ const frame = entry.step(dt)
457
+ entry.sink(frame)
458
+ if (entry.settles && frame.done) end(entry, Exit.succeed(frame))
459
+ } catch (defect) {
460
+ end(entry, dieNamed(entry.name, defect))
461
+ }
462
+ }
463
+
464
+ /** `entry`'s Late step, at the last tick's dt, its span marked. */
465
+ const lateStep = (entry: Entry): boolean => {
466
+ entry.late = false
467
+ if (entry.removed) return false
468
+ if (Predicate.isNotUndefined(entry.span)) entry.span.attribute("late", true)
469
+ stepOne(entry, windowDt)
470
+ return true
471
+ }
472
+
473
+ /**
474
+ * One Late round: the first lane's due runs, then, when one of them stepped, the last lane's runs the
475
+ * tick stepped again at dt 0, so they read what it wrote (#137's reads, Q9), then every hook. What the
476
+ * round adds is the next round's.
477
+ */
478
+ const lateRound = (): void => {
479
+ const firstCount = lateFirst.length
480
+ let stepped = 0
481
+ for (let i = 0; i < firstCount; i++) if (lateStep(lateFirst[i])) stepped++
482
+ if (stepped > 0) {
483
+ const count = lastEntries.length
484
+ for (let i = 0; i < count; i++) {
485
+ const entry = lastEntries[i]
486
+ if (entry.removed || entry.late) continue
487
+ stepOne(entry, 0)
488
+ }
489
+ }
490
+ dropFirst(lateFirst, firstCount)
491
+ const again = hooks
492
+ for (let i = 0; i < again.length; i++) again[i].hook(windowDt)
493
+ }
494
+
495
+ /**
496
+ * The Late window's end, the microtask its tick queued: the Late rounds, then the window closes. A run
497
+ * left past the cap steps at the next tick. A hook that throws ends every run, as in a tick (Q15).
498
+ */
499
+ const endLateWindow = (): void => {
500
+ windowQueued = false
501
+ if (!windowOpen) return
502
+ let rounds = 0
503
+ try {
504
+ while (lateFirst.length > 0 && rounds < MAX_LATE_ROUNDS) {
505
+ rounds++
506
+ lateRound()
507
+ }
508
+ } catch (defect) {
509
+ failLate(defect)
510
+ return
511
+ }
512
+ // Past the cap, the first lane's rest step at the next tick; the last lane's were never due.
513
+ if (lateFirst.length + lateLast.length > 0) dropLate()
514
+ windowOpen = false
515
+ }
516
+
517
+ /**
518
+ * A hook threw in a Late round, outside the burst's stream: the burst is interrupted, and its end
519
+ * fails every run with the defect, as a hook that throws in a tick fails it (#680, Q15).
520
+ */
521
+ const failLate = (defect: unknown): void => {
522
+ lateFailure = Cause.die(defect)
523
+ const fiber = burstFiber()
524
+ if (Predicate.isNotUndefined(fiber)) {
525
+ fiber.interruptUnsafe()
526
+ return
527
+ }
528
+ endAll(Exit.void)
529
+ }
530
+
531
+ /** The burst's fiber, if one holds the subscription. */
532
+ const burstFiber = (): Fiber.Fiber<void, unknown> | undefined => {
533
+ const state = burst.state
534
+ if (state._tag === "Closed") return undefined
535
+ return state.fiber
536
+ }
537
+
538
+ const afterTick = (hook: (dt: number) => undefined): Effect.Effect<void, never, Scope.Scope> => {
359
539
  const added: Hook = { hook }
360
540
  return Effect.acquireRelease(
361
541
  Effect.sync(() => {
@@ -375,12 +555,22 @@ export const make = Effect.fnUntraced(
375
555
  * the runs it ends are still starting, not waiting. Not the per-frame path.
376
556
  */
377
557
  const endAll = (exit: Exit.Exit<void>): void => {
378
- const ending = endingOf(exit)
558
+ // A Late round's hook threw (#680, Q15): this burst was interrupted for it, and its runs end with it.
559
+ const failure = lateFailure
560
+ lateFailure = undefined
561
+ const ending = UndefinedOr.match(failure, { onUndefined: () => endingOf(exit), onDefined: (cause) => Exit.failCause(cause) })
562
+ const failed = Bool.or(Exit.isFailure(exit), Predicate.isNotUndefined(failure))
379
563
  bursting = false
564
+ // A burst that failed closes the window: no later call is in it (#673, TK3; #680). One that ran out
565
+ // of runs leaves it open, so a run started after its last tick, in its frame, takes its Late step.
566
+ if (failed) {
567
+ windowOpen = false
568
+ dropLate()
569
+ }
380
570
  Arr.forEach(Arr.appendAll(entries.splice(0), lastEntries.splice(0)), (entry) => {
381
571
  if (!entry.removed) end(entry, ending)
382
572
  })
383
- animations.updateUnsafe(0, buildContext)
573
+ if (Predicate.isNotUndefined(metrics)) metrics.animations.updateUnsafe(0, buildContext)
384
574
  countEnds()
385
575
  }
386
576
 
@@ -413,14 +603,16 @@ export const make = Effect.fnUntraced(
413
603
  * installed (ADR-0040, *Amendment (#460)*): an app's, the devtools', a test's. Effect's default
414
604
  * records a span nothing reads, a leg's largest cost after its machine.
415
605
  */
416
- const runIn = (lane: Array<Entry>): Run =>
606
+ const runIn = (lane: Array<Entry>, late: Array<Entry>): Run =>
417
607
  (<F extends Frame.Frame<unknown>>(machine: Machine.Machine<F>, sink: FrameLoop.Sink<F>, options?: RunOptions) =>
418
608
  Effect.withFiber((fiber) => {
419
609
  // Its start log only when a Debug log would be kept (#542): Effect's own rule, read once.
420
610
  const logged = !LogLevel.isGreaterThan(fiber.getRef(References.MinimumLogLevel), "Debug")
421
- if (!isTraced(fiber)) return added(lane, machine, sink, options, undefined, logged)
611
+ // The metrics from the first run whose fiber has them (#518); none is read once they're in.
612
+ if (Predicate.isUndefined(metrics)) metrics = fiber.getRef(MetricsGiven)
613
+ if (!isTraced(fiber)) return added(lane, late, machine, sink, options, undefined, logged)
422
614
  return Effect.useSpan(machine.span.name, { attributes: machine.span.attributes }, (span) =>
423
- Effect.provideService(added(lane, machine, sink, options, span, logged), Tracer.ParentSpan, span))
615
+ Effect.provideService(added(lane, late, machine, sink, options, span, logged), Tracer.ParentSpan, span))
424
616
  })) as Run
425
617
 
426
618
  /**
@@ -429,6 +621,7 @@ export const make = Effect.fnUntraced(
429
621
  */
430
622
  const added = <F extends Frame.Frame<unknown>>(
431
623
  lane: Array<Entry>,
624
+ late: Array<Entry>,
432
625
  machine: Machine.Machine<F>,
433
626
  sink: FrameLoop.Sink<F>,
434
627
  options: RunOptions | undefined,
@@ -438,7 +631,7 @@ export const make = Effect.fnUntraced(
438
631
  // Per run, a leg each (#460, compose once): Effect's calls data-first, the steps statements.
439
632
  const run = Effect.acquireUseRelease(
440
633
  // `CheckFrames` from the caller's fiber, once per run: with it off, the sink as it is.
441
- Effect.flatMap(Effect.service(CheckFrames), (check) => entered(lane, machine, sink, options, check)),
634
+ Effect.flatMap(Effect.service(CheckFrames), (check) => entered(lane, late, machine, sink, options, check, span)),
442
635
  settledOf as (entry: Entry) => Effect.Effect<F | Supersede.Superseded>,
443
636
  (entry, exit) =>
444
637
  Effect.sync(() => {
@@ -452,13 +645,18 @@ export const make = Effect.fnUntraced(
452
645
  return Effect.annotateLogs(Effect.andThen(Effect.logDebug(`${machine.span.name}: start`), run), machine.span.attributes)
453
646
  }
454
647
 
455
- /** A run's entry on `lane` (and in its token, given one), and the burst started for it. */
648
+ /**
649
+ * A run's entry on `lane` (and in its token, given one), and the burst started for it. Added in the
650
+ * Late window, it's on `late` too: its Late step is due (#680).
651
+ */
456
652
  const entered = <F extends Frame.Frame<unknown>>(
457
653
  lane: Array<Entry>,
654
+ late: Array<Entry>,
458
655
  machine: Machine.Machine<F>,
459
656
  sink: FrameLoop.Sink<F>,
460
657
  options: RunOptions | undefined,
461
658
  check: boolean,
659
+ span: Tracer.Span | undefined,
462
660
  ): Effect.Effect<Entry> => {
463
661
  // A closed Environment takes no runs: nothing would tick them.
464
662
  if (burst.state._tag === "Closed") return Effect.interrupt
@@ -471,13 +669,18 @@ export const make = Effect.fnUntraced(
471
669
  settles: machine.settles,
472
670
  settled: Deferred.makeUnsafe<Frame.Frame<unknown> | Supersede.Superseded>(),
473
671
  removed: false,
672
+ late: windowOpen,
673
+ span,
474
674
  }
475
675
  lane.push(entry)
676
+ if (entry.late) late.push(entry)
476
677
  if (Predicate.isNotUndefined(options)) joinSupersede(options.supersede, entry)
477
678
  return Effect.as(startBurst, entry)
478
679
  }
479
680
 
480
- return { run: runIn(entries), runLast: runIn(lastEntries), afterTick } satisfies Shape
681
+ const inLateWindow = (): boolean => windowOpen
682
+
683
+ return { run: runIn(entries, lateFirst), runLast: runIn(lastEntries, lateLast), afterTick, inLateWindow } satisfies Shape
481
684
  },
482
685
  (self) => traced(self, "wardic.frameloop.make"),
483
686
  )
@@ -0,0 +1,76 @@
1
+ /**
2
+ * A subscriber's hearing: its own Stream, fed by plain calls. `hear` hands it a value and `end` ends it,
3
+ * or fails it with its source's failure. A consumer waiting on the Stream is resumed inside the call, as a
4
+ * `PubSub`'s subscriber was, never through the Effect scheduler (ADR-0017, decision 3), and a busy one
5
+ * takes everything handed since, together, at its next pull.
6
+ */
7
+ // #518, ADR-0067 *Amendment (#518)*, decision 3: under `Clock.ticks` and `SharedSource`, where a `PubSub` per
8
+ // source put its code in every app. Not a `Queue`: its offer schedules a release of its takers on the
9
+ // scheduler, a task a frame, even when they're released at once.
10
+ import * as Arr from "effect/Array"
11
+ import * as Cause from "effect/Cause"
12
+ import * as Effect from "effect/Effect"
13
+ import * as Exit from "effect/Exit"
14
+ import * as Option from "effect/Option"
15
+ import * as Predicate from "effect/Predicate"
16
+ import * as Stream from "effect/Stream"
17
+
18
+ export interface Hearing<A> {
19
+ /** Hands the Stream `a`. */
20
+ readonly hear: (a: A) => void
21
+ /** Ends the Stream after what it was handed: failed with `exit`'s failure, else ended. An interruption ends it. */
22
+ readonly end: (exit: Exit.Exit<void>) => void
23
+ /** What it was handed, in order, until its end. */
24
+ readonly stream: Stream.Stream<A>
25
+ }
26
+
27
+ /** A pull's end: the source's failure, else the Stream's end. An interruption ends it. */
28
+ const endOf = (exit: Exit.Exit<void>): Effect.Effect<never, Cause.Done> => {
29
+ if (Exit.isSuccess(exit)) return Cause.done()
30
+ if (Cause.hasInterruptsOnly(exit.cause)) return Cause.done()
31
+ return Effect.failCause(exit.cause)
32
+ }
33
+
34
+ /** A fresh hearing, handed nothing yet. */
35
+ export const make = <A>(): Hearing<A> => {
36
+ let heard: Array<A> = []
37
+ let ended: Option.Option<Exit.Exit<void>> = Option.none()
38
+ // The waiting pull's settle, while one waits. Per tick on the Clock's: a statement check, no Option.
39
+ let waiting: (() => boolean) | undefined
40
+ const wake = (): void => {
41
+ if (Predicate.isUndefined(waiting)) return
42
+ const resume = waiting
43
+ waiting = undefined
44
+ resume()
45
+ }
46
+ const take: Effect.Effect<Arr.NonEmptyReadonlyArray<A>, Cause.Done> = Effect.callback((resume) => {
47
+ // What it was handed since, or its end: whether there was either to resume with.
48
+ const settle = (): boolean => {
49
+ if (Arr.isReadonlyArrayNonEmpty(heard)) {
50
+ const taken = heard
51
+ heard = []
52
+ resume(Effect.succeed(taken))
53
+ return true
54
+ }
55
+ if (Option.isNone(ended)) return false
56
+ resume(endOf(ended.value))
57
+ return true
58
+ }
59
+ if (settle()) return
60
+ waiting = settle
61
+ return Effect.sync(() => {
62
+ waiting = undefined
63
+ })
64
+ })
65
+ return {
66
+ hear: (a) => {
67
+ heard.push(a)
68
+ wake()
69
+ },
70
+ end: (exit) => {
71
+ ended = Option.some(exit)
72
+ wake()
73
+ },
74
+ stream: Stream.fromPull(Effect.succeed(take)),
75
+ }
76
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Keyframes' and `animate`'s bags resolved (#429): the repeat modifiers, a run of repeats, and a
3
+ * keyframes bag's easings and times, checked once a bag. `Machine`'s `animate`, `keyframes` and
4
+ * `keyframesValues` read them, and a Batch's keyframes (#665), which step each member's key by hand.
5
+ * Not importable from outside core (`package.json`'s `"./internal/*": null`).
6
+ */
7
+ // Moved out of Machine.ts for the Batch (#665, Q36): Machine imports them back.
8
+ import * as Arr from "effect/Array"
9
+ import * as Bool from "effect/Boolean"
10
+ import * as Easing from "../Easing.ts"
11
+ import type { KeyframesOptions } from "../Machine.ts"
12
+ import { array, boolean, cachedResolver, field, finite, literals, nonEmptyArray, nonNegative, number, optionalField, refine, union } from "./options.ts"
13
+ import { EaseDefinition, type ResolvedRun, type ResolvedTween, resolvedTweenOf, TweenFields } from "./stepper.ts"
14
+
15
+ const NOT_REPEAT = "Expected a whole number of repeats, 0 or above, or Infinity"
16
+
17
+ /** A repeat count: a whole number, 0 or above, or `Infinity` to loop forever. */
18
+ const Repeat = refine(number, (n) => n === Infinity || (Number.isInteger(n) && n >= 0) || NOT_REPEAT)
19
+
20
+ /** The repeat modifiers (`Machine.Modifiers`), resolved: as given, defaults filled in. */
21
+ export interface ResolvedModifiers {
22
+ readonly repeat: number
23
+ readonly repeatDelay: number
24
+ readonly repeatType: "loop" | "reverse" | "mirror"
25
+ readonly reverse: boolean
26
+ }
27
+
28
+ /** The repeat modifiers' fields (#66): `animate`'s bag and `keyframes`' (#429) add them to a tween's. */
29
+ export const ModifierFields = {
30
+ repeat: field(Repeat, 0),
31
+ repeatDelay: field(nonNegative, 0),
32
+ repeatType: field(literals(["loop", "reverse", "mirror"]), "loop"),
33
+ reverse: field(boolean, false),
34
+ }
35
+
36
+ /** A decoded bag's run: its tween played `repeat + 1` times, with its tween's `delay` 0 (held outside, by `delay`). */
37
+ export const resolvedRunOf = (tween: ResolvedTween, modifiers: ResolvedModifiers): ResolvedRun => {
38
+ const cycle = tween.duration + modifiers.repeatDelay
39
+ return {
40
+ tween: { ...tween, delay: 0 },
41
+ repeats: modifiers.repeat,
42
+ gap: modifiers.repeatDelay,
43
+ cycle,
44
+ total: cycle * (modifiers.repeat + 1) - modifiers.repeatDelay,
45
+ reverses: modifiers.repeatType === "reverse",
46
+ mirrors: modifiers.repeatType === "mirror",
47
+ }
48
+ }
49
+
50
+ /** `keyframes`' bag resolved (#429): its run (its tween's `delay` 0), an easing per Interval, and each stop's place in time. */
51
+ export interface ResolvedKeyframes extends ResolvedModifiers {
52
+ readonly run: ResolvedRun
53
+ readonly delay: number
54
+ readonly seconds: number
55
+ readonly eases: Arr.NonEmptyReadonlyArray<Easing.Easing>
56
+ readonly times: ReadonlyArray<number> | undefined
57
+ }
58
+
59
+ /** One `ease` or several (#360): a list is an array whose first item isn't a number, which a bézier's is. */
60
+ const EaseOrList = union([EaseDefinition, nonEmptyArray(EaseDefinition)])
61
+
62
+ /** Whether `times` run from 0 to 1, none before the one ahead of it. */
63
+ const inOrder = (times: ReadonlyArray<number>): boolean => {
64
+ // The pairs only once every time is in range (#460, Q8).
65
+ if (!Arr.every(times, (time) => Bool.and(time >= 0, time <= 1))) return false
66
+ return Arr.every(Arr.zip(times, Arr.drop(times, 1)), ([before, after]) => after >= before)
67
+ }
68
+
69
+ const NOT_IN_ORDER = "Expected times from 0 to 1, in order"
70
+
71
+ /** Each stop's place in time (#429): numbers from 0 to 1, in order. */
72
+ const Times = refine(array(finite), (times) => inOrder(times) || NOT_IN_ORDER)
73
+
74
+ /**
75
+ * `keyframes`' bag (#66): a tween's fields, its `ease` one Definition or one per Interval (#360), its
76
+ * `times` and the repeat modifiers (#429), checked once a bag.
77
+ */
78
+ export const resolveKeyframes: (options: KeyframesOptions) => ResolvedKeyframes = cachedResolver(
79
+ { ...TweenFields, ...ModifierFields, ease: field(EaseOrList, Easing.linear), times: optionalField(Times) },
80
+ (decoded): ResolvedKeyframes => {
81
+ const list: Arr.NonEmptyReadonlyArray<Easing.Definition> = Bool.match(Bool.and(Arr.isArray(decoded.ease), Bool.not(Easing.isBezier(decoded.ease))), {
82
+ onTrue: () => decoded.ease as Arr.NonEmptyReadonlyArray<Easing.Definition>,
83
+ onFalse: (): Arr.NonEmptyReadonlyArray<Easing.Definition> => [decoded.ease as Easing.Definition],
84
+ })
85
+ const tween = resolvedTweenOf({ ...decoded, ease: list[0] })
86
+ return {
87
+ run: resolvedRunOf(tween, decoded),
88
+ delay: tween.delay,
89
+ seconds: tween.seconds,
90
+ eases: Arr.map(list, Easing.resolve),
91
+ times: decoded.times,
92
+ repeat: decoded.repeat,
93
+ repeatDelay: decoded.repeatDelay,
94
+ repeatType: decoded.repeatType,
95
+ reverse: decoded.reverse,
96
+ }
97
+ },
98
+ )