@wardic/core 1.3.2 → 1.5.0-next.0

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 (237) hide show
  1. package/dist/Arc.d.ts +2 -2
  2. package/dist/Arc.js +1 -1
  3. package/dist/BaseValue.d.ts +11 -10
  4. package/dist/BaseValue.d.ts.map +1 -1
  5. package/dist/BaseValue.js +12 -15
  6. package/dist/BaseValue.js.map +1 -1
  7. package/dist/Batch.d.ts +15 -5
  8. package/dist/Batch.d.ts.map +1 -1
  9. package/dist/Batch.js +218 -20
  10. package/dist/Batch.js.map +1 -1
  11. package/dist/Clock.d.ts +7 -7
  12. package/dist/Clock.d.ts.map +1 -1
  13. package/dist/Clock.js +17 -16
  14. package/dist/Clock.js.map +1 -1
  15. package/dist/DefaultTransition.d.ts +3 -2
  16. package/dist/DefaultTransition.d.ts.map +1 -1
  17. package/dist/DefaultTransition.js +5 -3
  18. package/dist/DefaultTransition.js.map +1 -1
  19. package/dist/Drag.d.ts +24 -9
  20. package/dist/Drag.d.ts.map +1 -1
  21. package/dist/Drag.js +10 -10
  22. package/dist/Drag.js.map +1 -1
  23. package/dist/DragActivity.js +3 -3
  24. package/dist/DragRecognizer.d.ts +8 -6
  25. package/dist/DragRecognizer.d.ts.map +1 -1
  26. package/dist/DragRecognizer.js +51 -16
  27. package/dist/DragRecognizer.js.map +1 -1
  28. package/dist/Easing.d.ts +1 -1
  29. package/dist/Easing.js +1 -1
  30. package/dist/Frame.d.ts.map +1 -1
  31. package/dist/Frame.js +5 -3
  32. package/dist/Frame.js.map +1 -1
  33. package/dist/InputFeed.d.ts +1 -1
  34. package/dist/InputFeed.js +2 -2
  35. package/dist/InputSource.d.ts +9 -3
  36. package/dist/InputSource.d.ts.map +1 -1
  37. package/dist/InputSource.js +2 -2
  38. package/dist/InputSource.js.map +1 -1
  39. package/dist/Interpolator.d.ts +2 -2
  40. package/dist/Interpolator.js +2 -2
  41. package/dist/InterpolatorRegistry.d.ts +29 -15
  42. package/dist/InterpolatorRegistry.d.ts.map +1 -1
  43. package/dist/InterpolatorRegistry.js +17 -8
  44. package/dist/InterpolatorRegistry.js.map +1 -1
  45. package/dist/LiveValue.d.ts +7 -6
  46. package/dist/LiveValue.d.ts.map +1 -1
  47. package/dist/LiveValue.js +45 -14
  48. package/dist/LiveValue.js.map +1 -1
  49. package/dist/Machine.d.ts +7 -4
  50. package/dist/Machine.d.ts.map +1 -1
  51. package/dist/Machine.js +146 -45
  52. package/dist/Machine.js.map +1 -1
  53. package/dist/Playback.d.ts.map +1 -1
  54. package/dist/Playback.js +6 -1
  55. package/dist/Playback.js.map +1 -1
  56. package/dist/Projection.d.ts +8 -19
  57. package/dist/Projection.d.ts.map +1 -1
  58. package/dist/Projection.js +3 -19
  59. package/dist/Projection.js.map +1 -1
  60. package/dist/Recognizer.d.ts +1 -1
  61. package/dist/Recognizer.d.ts.map +1 -1
  62. package/dist/Recognizer.js +22 -7
  63. package/dist/Recognizer.js.map +1 -1
  64. package/dist/ReducedMotion.d.ts +4 -4
  65. package/dist/ReducedMotion.js +6 -6
  66. package/dist/Renderer.d.ts +5 -5
  67. package/dist/Renderer.js +6 -6
  68. package/dist/Renderer.js.map +1 -1
  69. package/dist/Reorder.d.ts +12 -2
  70. package/dist/Reorder.d.ts.map +1 -1
  71. package/dist/Reorder.js +65 -37
  72. package/dist/Reorder.js.map +1 -1
  73. package/dist/ScrollSource.d.ts +1 -1
  74. package/dist/ScrollSource.d.ts.map +1 -1
  75. package/dist/Sequence.d.ts +1 -1
  76. package/dist/SharedSource.d.ts +3 -3
  77. package/dist/SharedSource.js +5 -5
  78. package/dist/SharedSource.js.map +1 -1
  79. package/dist/Spring.d.ts.map +1 -1
  80. package/dist/Spring.js +2 -1
  81. package/dist/Spring.js.map +1 -1
  82. package/dist/Values.d.ts +2 -2
  83. package/dist/Values.js +1 -1
  84. package/dist/index.d.ts +1 -1
  85. package/dist/index.js +1 -1
  86. package/dist/internal/carried.d.ts +13 -0
  87. package/dist/internal/carried.d.ts.map +1 -0
  88. package/dist/internal/carried.js +23 -0
  89. package/dist/internal/carried.js.map +1 -0
  90. package/dist/internal/firstSteps.d.ts +66 -0
  91. package/dist/internal/firstSteps.d.ts.map +1 -0
  92. package/dist/internal/firstSteps.js +107 -0
  93. package/dist/internal/firstSteps.js.map +1 -0
  94. package/dist/internal/frameLoop.d.ts +1 -1
  95. package/dist/internal/frameLoop.d.ts.map +1 -1
  96. package/dist/internal/frameLoop.js +102 -81
  97. package/dist/internal/frameLoop.js.map +1 -1
  98. package/dist/internal/lerpsNumbers.d.ts +11 -0
  99. package/dist/internal/lerpsNumbers.d.ts.map +1 -0
  100. package/dist/internal/lerpsNumbers.js +38 -0
  101. package/dist/internal/lerpsNumbers.js.map +1 -0
  102. package/dist/internal/options.d.ts +7 -7
  103. package/dist/internal/options.d.ts.map +1 -1
  104. package/dist/internal/options.js +10 -10
  105. package/dist/internal/options.js.map +1 -1
  106. package/dist/internal/projectionRest.d.ts +22 -0
  107. package/dist/internal/projectionRest.d.ts.map +1 -0
  108. package/dist/internal/projectionRest.js +20 -0
  109. package/dist/internal/projectionRest.js.map +1 -0
  110. package/dist/internal/stepper.d.ts +13 -2
  111. package/dist/internal/stepper.d.ts.map +1 -1
  112. package/dist/internal/stepper.js +16 -1
  113. package/dist/internal/stepper.js.map +1 -1
  114. package/dist/internal/tracing.d.ts +1 -1
  115. package/dist/internal/tracing.js +1 -1
  116. package/dist/unstable/AnimationControls.d.ts +37 -38
  117. package/dist/unstable/AnimationControls.d.ts.map +1 -1
  118. package/dist/unstable/AnimationControls.js +39 -36
  119. package/dist/unstable/AnimationControls.js.map +1 -1
  120. package/dist/unstable/AppearHandoff.d.ts +5 -5
  121. package/dist/unstable/AppearHandoff.d.ts.map +1 -1
  122. package/dist/unstable/BatchCalls.d.ts +2 -2
  123. package/dist/unstable/BatchCalls.js +5 -5
  124. package/dist/unstable/Config.d.ts +19 -19
  125. package/dist/unstable/Config.d.ts.map +1 -1
  126. package/dist/unstable/FirstSteps.d.ts +25 -0
  127. package/dist/unstable/FirstSteps.d.ts.map +1 -0
  128. package/dist/unstable/FirstSteps.js +2 -0
  129. package/dist/unstable/FirstSteps.js.map +1 -0
  130. package/dist/unstable/FlushGate.d.ts +53 -51
  131. package/dist/unstable/FlushGate.d.ts.map +1 -1
  132. package/dist/unstable/FlushGate.js +56 -49
  133. package/dist/unstable/FlushGate.js.map +1 -1
  134. package/dist/unstable/FrameEffects.d.ts +2 -2
  135. package/dist/unstable/FrameEffects.js +2 -2
  136. package/dist/unstable/FrameTime.d.ts +1 -1
  137. package/dist/unstable/FrameTime.js +1 -1
  138. package/dist/unstable/Imperative.d.ts +29 -9
  139. package/dist/unstable/Imperative.d.ts.map +1 -1
  140. package/dist/unstable/Imperative.js +79 -47
  141. package/dist/unstable/Imperative.js.map +1 -1
  142. package/dist/unstable/OwnValues.js +1 -1
  143. package/dist/unstable/PresenceRecord.d.ts +31 -27
  144. package/dist/unstable/PresenceRecord.d.ts.map +1 -1
  145. package/dist/unstable/PresenceRecord.js +8 -8
  146. package/dist/unstable/PresenceRecord.js.map +1 -1
  147. package/dist/unstable/Projector.d.ts +34 -0
  148. package/dist/unstable/Projector.d.ts.map +1 -0
  149. package/dist/unstable/Projector.js +9 -0
  150. package/dist/unstable/Projector.js.map +1 -0
  151. package/dist/unstable/Report.d.ts +1 -1
  152. package/dist/unstable/Report.js +1 -1
  153. package/dist/unstable/RetargetLegs.d.ts +1 -1
  154. package/dist/unstable/RetargetLegs.d.ts.map +1 -1
  155. package/dist/unstable/RetargetLegs.js +9 -8
  156. package/dist/unstable/RetargetLegs.js.map +1 -1
  157. package/dist/unstable/Spine.d.ts +81 -72
  158. package/dist/unstable/Spine.d.ts.map +1 -1
  159. package/dist/unstable/Spine.js +171 -164
  160. package/dist/unstable/Spine.js.map +1 -1
  161. package/dist/unstable/Stops.d.ts +3 -3
  162. package/dist/unstable/Stops.js +4 -4
  163. package/dist/unstable/Subject.d.ts +2 -2
  164. package/dist/unstable/Subject.js +2 -2
  165. package/dist/unstable/Timelines.d.ts +11 -11
  166. package/dist/unstable/Timelines.d.ts.map +1 -1
  167. package/dist/unstable/Timelines.js +3 -3
  168. package/dist/unstable/VariantTarget.d.ts +7 -7
  169. package/dist/unstable/VariantTarget.d.ts.map +1 -1
  170. package/dist/unstable/VariantTarget.js +11 -11
  171. package/dist/unstable/VariantTarget.js.map +1 -1
  172. package/dist/unstable/VariantTree.d.ts +43 -36
  173. package/dist/unstable/VariantTree.d.ts.map +1 -1
  174. package/dist/unstable/VariantTree.js +34 -34
  175. package/dist/unstable/VariantTree.js.map +1 -1
  176. package/dist/unstable/WardicConfigValue.d.ts +13 -13
  177. package/dist/unstable/WardicConfigValue.d.ts.map +1 -1
  178. package/dist/unstable/WardicConfigValue.js +4 -4
  179. package/dist/unstable/WardicConfigValue.js.map +1 -1
  180. package/package.json +1 -1
  181. package/src/Arc.ts +3 -3
  182. package/src/BaseValue.ts +18 -21
  183. package/src/Batch.ts +236 -22
  184. package/src/Clock.ts +18 -17
  185. package/src/DefaultTransition.ts +5 -3
  186. package/src/Drag.ts +32 -14
  187. package/src/DragActivity.ts +3 -3
  188. package/src/DragRecognizer.ts +65 -23
  189. package/src/Easing.ts +1 -1
  190. package/src/Frame.ts +5 -3
  191. package/src/InputFeed.ts +2 -2
  192. package/src/InputSource.ts +12 -5
  193. package/src/Interpolator.ts +3 -3
  194. package/src/InterpolatorRegistry.ts +22 -13
  195. package/src/LiveValue.ts +47 -17
  196. package/src/Machine.ts +199 -61
  197. package/src/Playback.ts +5 -1
  198. package/src/Projection.ts +10 -28
  199. package/src/Recognizer.ts +24 -8
  200. package/src/ReducedMotion.ts +6 -6
  201. package/src/Renderer.ts +6 -6
  202. package/src/Reorder.ts +84 -38
  203. package/src/ScrollSource.ts +1 -1
  204. package/src/Sequence.ts +1 -1
  205. package/src/SharedSource.ts +5 -5
  206. package/src/Spring.ts +2 -1
  207. package/src/Values.ts +2 -2
  208. package/src/index.ts +1 -1
  209. package/src/internal/carried.ts +22 -0
  210. package/src/internal/firstSteps.ts +139 -0
  211. package/src/internal/frameLoop.ts +103 -87
  212. package/src/internal/lerpsNumbers.ts +53 -0
  213. package/src/internal/options.ts +10 -10
  214. package/src/internal/projectionRest.ts +31 -0
  215. package/src/internal/stepper.ts +20 -2
  216. package/src/internal/tracing.ts +1 -1
  217. package/src/unstable/AnimationControls.ts +59 -56
  218. package/src/unstable/AppearHandoff.ts +6 -6
  219. package/src/unstable/BatchCalls.ts +5 -5
  220. package/src/unstable/Config.ts +19 -19
  221. package/src/unstable/FirstSteps.ts +26 -0
  222. package/src/unstable/FlushGate.ts +92 -82
  223. package/src/unstable/FrameEffects.ts +2 -2
  224. package/src/unstable/FrameTime.ts +1 -1
  225. package/src/unstable/Imperative.ts +126 -56
  226. package/src/unstable/OwnValues.ts +1 -1
  227. package/src/unstable/PresenceRecord.ts +34 -30
  228. package/src/unstable/Projector.ts +45 -0
  229. package/src/unstable/Report.ts +1 -1
  230. package/src/unstable/RetargetLegs.ts +10 -9
  231. package/src/unstable/Spine.ts +210 -201
  232. package/src/unstable/Stops.ts +6 -6
  233. package/src/unstable/Subject.ts +2 -2
  234. package/src/unstable/Timelines.ts +12 -12
  235. package/src/unstable/VariantTarget.ts +13 -13
  236. package/src/unstable/VariantTree.ts +50 -43
  237. package/src/unstable/WardicConfigValue.ts +13 -13
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Reduced motion, as Motion does it: under it, a run's positional keys, the transforms and an element's
2
+ * Reduced motion, as Motion does it: under it, a run's positional keys, the transforms and a Subject's
3
3
  * position and size, land where the run would end, and every other key, an opacity or a colour, animates
4
4
  * as ever. `applies` says whether it's on, `split` divides a target by its Environment's
5
5
  * `PositionalKeys`, and `snap` lands the positional ones.
@@ -35,10 +35,10 @@ export type Config = "user" | "always" | "never"
35
35
 
36
36
  /**
37
37
  * Whether reduced motion applies under `config`, given whether the user prefers reduced motion. A binding
38
- * reads it as each element's animation starts.
38
+ * reads it as each Subject's animation starts.
39
39
  */
40
40
  export const applies = (config: Config, prefersReducedMotion: boolean): boolean => {
41
- // Per element at mount (#540): statements.
41
+ // Per Subject at mount (#540): statements.
42
42
  if (config === "always") return true
43
43
  if (config === "never") return false
44
44
  return prefersReducedMotion
@@ -48,9 +48,9 @@ export const applies = (config: Config, prefersReducedMotion: boolean): boolean
48
48
  export const isTransform = (key: string): boolean => Option.isSome(BaseValue.transformIdentity(key))
49
49
 
50
50
  /**
51
- * An Environment's Positional keys: the keys that move or resize its elements, which reduced motion lands
52
- * at once. Core names only the transforms (`transformsOnly`); an Environment adds its own, as `@wardic/dom`
53
- * adds the keys that size and place an element's box.
51
+ * An Environment's Positional keys: the keys that move or resize its Subjects, which reduced motion lands
52
+ * at once. Core names only its transforms (`transformsOnly`); an Environment adds its own, as `@wardic/dom`
53
+ * adds its own transform keys and the keys that size and place a Subject's box.
54
54
  */
55
55
  // CONTEXT.md; ADR-0029, ADR-0036; `@wardic/dom`'s `PositionalKeysDomLive`. A binding reads it
56
56
  // once, as it reads the Probe, and passes it to `split`.
package/src/Renderer.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * The Renderer: how an Environment writes animated values to what it draws, an element, a canvas
3
- * context, a native view. It has two halves: `project`, pure, turns a Frame's values into the
2
+ * The Renderer: how an Environment writes animated values to what it draws, its Subjects, such
3
+ * as a canvas context or a native view. It has two halves: `project`, pure, turns a Frame's values into the
4
4
  * Environment's own `Patch`, grouping keys as it likes; and `commit` writes a patch onto a target, now.
5
- * A binding writes its elements through its flush; `applyTo` writes a Frame stream outside one.
5
+ * A binding writes its Subjects through its flush; `applyTo` writes a Frame stream outside one.
6
6
  *
7
7
  * @example
8
8
  * import * as Renderer from "@wardic/core/Renderer"
@@ -25,11 +25,11 @@ import { traced } from "./internal/tracing.ts"
25
25
  export type Patch = Record<string, unknown>
26
26
 
27
27
  /**
28
- * An Environment's renderer. Both halves are plain functions, not Effects: they run once per element per
28
+ * An Environment's renderer. Both halves are plain functions, not Effects: they run once per Subject per
29
29
  * frame. `target` is the Environment's own, opaque to core.
30
30
  */
31
31
  // ADR-0002. `project` is pure, so the Starting style reuses it and no grouping or unit logic is
32
- // duplicated. The flush gate commits every binding element's patch once per Refresh frame (ADR-0006,
32
+ // duplicated. The flush gate commits every Subject's patch once per Refresh frame (ADR-0006,
33
33
  // ADR-0034); an Effect round trip per call would cost a fiber each (ADR-0034,
34
34
  // docs/agents/effect-first.md). `@wardic/dom`'s renderer takes an element as its target.
35
35
  export class Renderer extends Context.Service<Renderer, {
@@ -42,7 +42,7 @@ export class Renderer extends Context.Service<Renderer, {
42
42
  /**
43
43
  * Writes each Frame of `stream` onto `target`, projecting its values and committing them, one commit per
44
44
  * Frame: for a Frame stream outside a binding, a canvas's, a native view's, a test's. A binding's
45
- * elements go through its flush instead. `stream` gives Frames of a record of values, as
45
+ * Subjects go through its flush instead. `stream` gives Frames of a record of values, as
46
46
  * `Machine.springValues` and `Machine.animateValues` do.
47
47
  *
48
48
  * @example
package/src/Reorder.ts CHANGED
@@ -34,6 +34,7 @@ import * as Order from "effect/Order"
34
34
  import { type Pipeable, pipeArguments } from "effect/Pipeable"
35
35
  import * as Predicate from "effect/Predicate"
36
36
  import type { Invariant } from "effect/Types"
37
+ import * as UndefinedOr from "effect/UndefinedOr"
37
38
  import type * as Box from "./Box.ts"
38
39
  import type * as InputSource from "./InputSource.ts"
39
40
  import type * as Point from "./Point.ts"
@@ -43,7 +44,7 @@ import { dual } from "./internal/dual.ts"
43
44
  // Motion's Reorder/types.ts @ 16c6122. Tier 2 (ADR-0008): Effect-free, for binding and Environment authors.
44
45
  export type Axis = "x" | "y" | "xy"
45
46
 
46
- /** An item as `check` sees it: its value and its layout box, its place in the list, not where it paints while it's dragged. */
47
+ /** An item as `check` sees it: its value and its layout box, its place in the list, not where it's drawn while it's dragged. */
47
48
  // Motion's `ItemData` (Reorder/types.ts @ 16c6122). Tier 2 (ADR-0008).
48
49
  export interface ItemData<V> {
49
50
  /** The item's value in the list. */
@@ -76,9 +77,19 @@ export const moveItem = <T>(arr: ReadonlyArray<T>, fromIndex: number, toIndex: n
76
77
  const fromEnd = (index: number, length: number): number =>
77
78
  Bool.match(index < 0, { onTrue: () => length + index, onFalse: () => index })
78
79
 
79
- /** `value`'s index in `order`. */
80
- const indexOf = <V>(order: ReadonlyArray<ItemData<V>>, value: V): Option.Option<number> =>
81
- Arr.findFirstIndex(order, (item) => item.value === value)
80
+ /** `value`'s index in `order`, its items matched by `same`. */
81
+ const indexOf = <V>(order: ReadonlyArray<ItemData<V>>, value: V, same: Same<V>): Option.Option<number> =>
82
+ Arr.findFirstIndex(order, (item) => same(item.value, value))
83
+
84
+ /** Whether two values are one item. */
85
+ type Same<V> = (self: V, that: V) => boolean
86
+
87
+ /** Two values are one item when they're the same value: a group given no `key`'s. */
88
+ const identical = <V>(self: V, that: V): boolean => self === that
89
+
90
+ /** Whether two values are one item: by `key` where it's given, else by identity (probe: hooks-first, the Reorder round's KG1). */
91
+ const sameOf = <V>(key: ((value: V) => unknown) | undefined): Same<V> =>
92
+ UndefinedOr.match(key, { onUndefined: () => identical, onDefined: (keyOf) => (self: V, that: V) => keyOf(self) === keyOf(that) })
82
93
 
83
94
  /**
84
95
  * The order after the item holding `value` has been dragged `offset` from its place, moving at
@@ -92,6 +103,8 @@ const indexOf = <V>(order: ReadonlyArray<ItemData<V>>, value: V): Option.Option<
92
103
  * - **A grid** (`"xy"`), as Motion's: the dragged centre picks the nearest row. In another row, the item
93
104
  * goes before the first item whose centre is past it in `direction`; in its own, it steps one place
94
105
  * toward the nearest box.
106
+ *
107
+ * `value` is found in `order` by `same`: by identity unless it's given, as a group with a `key` gives it.
95
108
  */
96
109
  // The **Crossover**. Motion's Group.tsx compares by reference too. `"xy"` is Motion's `check`
97
110
  // (Reorder/utils/check-reorder.ts @ 16c61222c4166bbef5ff6ab0051192faa79fa8c8,
@@ -104,9 +117,9 @@ const indexOf = <V>(order: ReadonlyArray<ItemData<V>>, value: V): Option.Option<
104
117
  // far end in 30 px away from one (motion/react 13.4.6, every run in Chromium and Firefox:
105
118
  // .tmp/reorder/runs-*-{rtl,reverse}.json; framer-motion 13.0 sorted by position). In normal flow the two
106
119
  // rules pick the same neighbour. Tier 2 (ADR-0008): Effect-free, for binding and Environment authors.
107
- export const check = <V>(order: ReadonlyArray<ItemData<V>>, value: V, movement: Movement): ReadonlyArray<ItemData<V>> => {
120
+ export const check = <V>(order: ReadonlyArray<ItemData<V>>, value: V, movement: Movement, same: Same<V> = identical): ReadonlyArray<ItemData<V>> => {
108
121
  const { offset, velocity, axis, direction = "ltr" } = movement
109
- return Option.match(indexOf(order, value), {
122
+ return Option.match(indexOf(order, value, same), {
110
123
  onNone: () => order,
111
124
  onSome: (index) =>
112
125
  Match.value(axis).pipe(
@@ -212,7 +225,8 @@ interface Line<V> {
212
225
  readonly max: number
213
226
  }
214
227
 
215
- /** Motion's `"xy"` branch (check-reorder.ts:17-51 at 16c6122). */
228
+ /** Motion's `"xy"` branch. */
229
+ // `check-reorder.ts:17-51` at 16c6122.
216
230
  const checkReorderXY = <V>(
217
231
  order: ReadonlyArray<ItemData<V>>,
218
232
  index: number,
@@ -384,6 +398,12 @@ export interface GroupOptions<V> {
384
398
  readonly axis?: (() => Option.Option<Axis>) | undefined
385
399
  /** The group's inline direction, read at each drag's start: `"ltr"` when it's left out. */
386
400
  readonly direction?: (() => "ltr" | "rtl") | undefined
401
+ /**
402
+ * What makes two of the app's values one item, where its list makes them again (a refetch, a
403
+ * store's copy): matched by it, an item made again keeps its place, its drag and its keyboard lift.
404
+ * Left out, values match by identity.
405
+ */
406
+ readonly key?: ((value: V) => unknown) | undefined
387
407
  /**
388
408
  * Hears what happens, for a debug log: `reorder` { value, from, to, axis, direction } once per reorder,
389
409
  * `reorder waits` { value } once per wait for the boxes to be measured, `reorder start` { value, axis,
@@ -458,6 +478,12 @@ export interface Group<in out V> extends Pipeable, Inspectable.Inspectable {
458
478
  // Hidden from the public type (#618, F1): a caller that set them would break the group's state.
459
479
  interface State<V> extends Group<V> {
460
480
  readonly sources: Map<V, ItemSource>
481
+ /** Its item sources by their values' `key`, where it's given one: what a value made again is found by. */
482
+ readonly keyed: Map<unknown, ItemSource>
483
+ /** Whether two values are one item: by `key`, or by identity. */
484
+ readonly same: Same<V>
485
+ /** A value's item source: by its `key` where it's given, so a value made again finds it, else by the value. */
486
+ readonly find: (value: V) => ItemSource | undefined
461
487
  readonly gesture: MutableRef.MutableRef<Option.Option<Gesture<V>>>
462
488
  readonly lifted: MutableRef.MutableRef<Option.Option<Lift<V>>>
463
489
  }
@@ -496,13 +522,23 @@ const Proto = {
496
522
  // The registry is a plain `Map` keyed by value. Each sample builds the measured order (an entry per item
497
523
  // with a box), and a new order on a reorder: about 17 µs a sample on 1,000 items in Chromium, 11–12 of
498
524
  // them that build (#327).
499
- export const make = <V>(options: GroupOptions<V>): Group<V> =>
500
- Object.assign(Object.create(Proto), {
525
+ export const make = <V>(options: GroupOptions<V>): Group<V> => {
526
+ const sources = new Map<V, ItemSource>()
527
+ const keyed = new Map<unknown, ItemSource>()
528
+ return Object.assign(Object.create(Proto), {
501
529
  options,
502
- sources: new Map<V, ItemSource>(),
530
+ sources,
531
+ keyed,
532
+ same: sameOf(options.key),
533
+ find: findOf(options.key, sources, keyed),
503
534
  gesture: MutableRef.make(Option.none<Gesture<V>>()),
504
535
  lifted: MutableRef.make(Option.none<Lift<V>>()),
505
536
  })
537
+ }
538
+
539
+ /** How a group finds a value's item source, decided once: by its `key` where it's given, else by the value. */
540
+ const findOf = <V>(key: ((value: V) => unknown) | undefined, sources: Map<V, ItemSource>, keyed: Map<unknown, ItemSource>): ((value: V) => ItemSource | undefined) =>
541
+ UndefinedOr.match(key, { onUndefined: () => (value: V) => sources.get(value), onDefined: (keyOf) => (value: V) => keyed.get(keyOf(value)) })
506
542
 
507
543
  /** Whether `u` is a reorder group, made by `make`. */
508
544
  export const isGroup = (u: unknown): u is Group<unknown> => Predicate.hasProperty(u, TypeId)
@@ -521,7 +557,10 @@ const log = <V>(group: Group<V>, event: string, annotations: Record<string, unkn
521
557
 
522
558
  /** An item's box, while it is registered and has one. */
523
559
  const layoutOf = <V>(group: Group<V>, value: V): Option.Option<Box.Box> =>
524
- Option.flatMap(Option.fromUndefinedOr(group.sources.get(value)), (source) => source.layoutBox())
560
+ Option.flatMap(Option.fromUndefinedOr(sourceOf(group, value)), (source) => source.layoutBox())
561
+
562
+ /** `value`'s item source: by its `key` where the group is given one, so a value made again finds it. */
563
+ const sourceOf = <V>(group: Group<V>, value: V): ItemSource | undefined => stateOf(group).find(value)
525
564
 
526
565
  /** The measured order: each value with a box, and its index in `values`. */
527
566
  const measure = <V>(group: Group<V>, values: ReadonlyArray<V>): ReadonlyArray<Measured<V>> =>
@@ -556,11 +595,12 @@ const reorderOn = <V>(group: Group<V>, g: Gesture<V>, value: V, source: ItemSour
556
595
  if (waiting(group, g, value, source)) return
557
596
  const values = group.options.values()
558
597
  const measured = measure(group, values)
559
- const next = check(measured, value, { offset: source.dragOffset(), velocity, axis: g.axis, direction: g.direction })
598
+ const same = stateOf(group).same
599
+ const next = check(measured, value, { offset: source.dragOffset(), velocity, axis: g.axis, direction: g.direction }, same)
560
600
  if (next === measured) return
561
601
  const newValues = refill(values, measured, next)
562
602
  const indexIn = (list: ReadonlyArray<V>): number =>
563
- Option.getOrElse(Arr.findFirstIndex(list, (v) => v === value), () => -1)
603
+ Option.getOrElse(Arr.findFirstIndex(list, (v) => same(v, value)), () => -1)
564
604
  g.guard = Option.some(source.layoutVersion())
565
605
  g.waited = false
566
606
  log(group, "reorder", { value, from: indexIn(values), to: indexIn(newValues), axis: g.axis, direction: g.direction })
@@ -579,9 +619,14 @@ export const register: {
579
619
  <V>(value: V, source: ItemSource): (group: Group<V>) => () => void
580
620
  <V>(group: Group<V>, value: V, source: ItemSource): () => void
581
621
  } = dual(3, <V>(group: Group<V>, value: V, source: ItemSource): (() => void) => {
582
- stateOf(group).sources.set(value, source)
622
+ const state = stateOf(group)
623
+ state.sources.set(value, source)
624
+ // By its key too, where the group is given one: a value made again finds the source of the one before.
625
+ const key = UndefinedOr.map(group.options.key, (keyOf) => keyOf(value))
626
+ if (Predicate.isNotUndefined(group.options.key)) state.keyed.set(key, source)
583
627
  return () => {
584
- if (group.sources.get(value) === source) stateOf(group).sources.delete(value)
628
+ if (group.sources.get(value) === source) state.sources.delete(value)
629
+ if (state.keyed.get(key) === source) state.keyed.delete(key)
585
630
  }
586
631
  })
587
632
 
@@ -619,10 +664,10 @@ export const dragMove: {
619
664
  <V>(value: V, velocity: Point.Point): (group: Group<V>) => Point.Point
620
665
  <V>(group: Group<V>, value: V, velocity: Point.Point): Point.Point
621
666
  } = dual(3, <V>(group: Group<V>, value: V, velocity: Point.Point): Point.Point =>
622
- Option.match(Option.filter(MutableRef.get(stateOf(group).gesture), (g) => g.value === value), {
667
+ Option.match(Option.filter(MutableRef.get(stateOf(group).gesture), (g) => stateOf(group).same(g.value, value)), {
623
668
  onNone: () => ZERO,
624
669
  onSome: (g) => {
625
- Option.match(Option.fromUndefinedOr(group.sources.get(value)), {
670
+ Option.match(Option.fromUndefinedOr(sourceOf(group, value)), {
626
671
  onNone: constVoid,
627
672
  onSome: (source) => reorderOn(group, g, value, source, velocity),
628
673
  })
@@ -635,7 +680,7 @@ export const dragEnd: {
635
680
  <V>(value: V): (group: Group<V>) => void
636
681
  <V>(group: Group<V>, value: V): void
637
682
  } = dual(isGroup, <V>(group: Group<V>, value: V): void => {
638
- if (Option.exists(MutableRef.get(stateOf(group).gesture), (g) => g.value === value)) {
683
+ if (Option.exists(MutableRef.get(stateOf(group).gesture), (g) => stateOf(group).same(g.value, value))) {
639
684
  MutableRef.set(stateOf(group).gesture, Option.none())
640
685
  }
641
686
  })
@@ -654,13 +699,13 @@ export const move: {
654
699
  <V>(group: Group<V>, value: V, toIndex: number): Option.Option<Placement>
655
700
  } = dual(3, <V>(group: Group<V>, value: V, toIndex: number): Option.Option<Placement> => {
656
701
  const values = group.options.values()
657
- return Option.flatMap(Arr.findFirstIndex(values, (v) => v === value), (from) => {
702
+ return Option.flatMap(Arr.findFirstIndex(values, (v) => stateOf(group).same(v, value)), (from) => {
658
703
  const to = Math.min(Math.max(0, toIndex), values.length - 1)
659
- if (to === from) return placementIn(values, value, false)
704
+ if (to === from) return placementIn(group, values, value, false)
660
705
  log(group, "move", { value, from, to })
661
706
  const next = moveItem(values, from, to)
662
707
  group.options.onReorder(next)
663
- return placementIn(next, value, true)
708
+ return placementIn(group, next, value, true)
664
709
  })
665
710
  })
666
711
 
@@ -782,12 +827,12 @@ export interface Placement {
782
827
  readonly waiting: boolean
783
828
  }
784
829
 
785
- /** `value`'s placement in `values`, `None` when it isn't in it. */
786
- const placementIn = <V>(values: ReadonlyArray<V>, value: V, moved: boolean, waiting = false): Option.Option<Placement> =>
787
- Option.map(Arr.findFirstIndex(values, (v) => v === value), (index) => ({ position: index + 1, count: values.length, moved, waiting }))
830
+ /** `value`'s placement in `values`, `None` when it isn't in it: found as `group` matches its items. */
831
+ const placementIn = <V>(group: Group<V>, values: ReadonlyArray<V>, value: V, moved: boolean, waiting = false): Option.Option<Placement> =>
832
+ Option.map(Arr.findFirstIndex(values, (v) => stateOf(group).same(v, value)), (index) => ({ position: index + 1, count: values.length, moved, waiting }))
788
833
 
789
834
  /** The lifted item, when it's `value`. */
790
- const liftOf = <V>(group: Group<V>, value: V): Option.Option<Lift<V>> => Option.filter(MutableRef.get(stateOf(group).lifted), (lift) => lift.value === value)
835
+ const liftOf = <V>(group: Group<V>, value: V): Option.Option<Lift<V>> => Option.filter(MutableRef.get(stateOf(group).lifted), (lift) => stateOf(group).same(lift.value, value))
791
836
 
792
837
  /**
793
838
  * Lifts `value`'s item for a keyboard reorder: its axis and direction are fixed now, as a drag's are at
@@ -800,7 +845,7 @@ export const lift: {
800
845
  <V>(group: Group<V>, value: V): Option.Option<Placement>
801
846
  } = dual(isGroup, <V>(group: Group<V>, value: V): Option.Option<Placement> => {
802
847
  const values = group.options.values()
803
- return Option.map(placementIn(values, value, false), (placement) => {
848
+ return Option.map(placementIn(group, values, value, false), (placement) => {
804
849
  const axis = resolveAxis(group)
805
850
  const direction = directionOf(group)
806
851
  MutableRef.set(stateOf(group).lifted, Option.some({ value, origin: Arr.copy(values), axis, direction, guard: Option.none() }))
@@ -822,23 +867,23 @@ export const moveLifted: {
822
867
  } = dual(3, <V>(group: Group<V>, value: V, intent: Extract<KeyIntent, { readonly _tag: "Step" | "End" }>): Option.Option<Placement> =>
823
868
  Option.flatMap(liftOf(group, value), (l) => {
824
869
  const values = group.options.values()
825
- const source = group.sources.get(value)
870
+ const source = sourceOf(group, value)
826
871
  const version = Option.match(Option.fromUndefinedOr(source), { onNone: () => 0, onSome: (s) => s.layoutVersion() })
827
- if (Option.exists(l.guard, (guard) => version <= guard)) return placementIn(values, value, false, true)
872
+ if (Option.exists(l.guard, (guard) => version <= guard)) return placementIn(group, values, value, false, true)
828
873
  l.guard = Option.none()
829
874
  const measured = measure(group, values)
830
- return Option.flatMap(Arr.findFirstIndex(measured, (item) => item.value === value), (index) => {
875
+ return Option.flatMap(Arr.findFirstIndex(measured, (item) => stateOf(group).same(item.value, value)), (index) => {
831
876
  const target = Match.value(intent).pipe(
832
877
  Match.tag("Step", ({ arrow }) => arrowTarget(measured, index, arrow, l.axis, l.direction)),
833
878
  Match.tag("End", ({ end }) => Bool.match(end === "first", { onTrue: () => 0, onFalse: () => measured.length - 1 })),
834
879
  Match.exhaustive,
835
880
  )
836
- if (target === index) return placementIn(values, value, false)
881
+ if (target === index) return placementIn(group, values, value, false)
837
882
  const newValues = refill(values, measured, moveItem(measured, index, target))
838
883
  log(group, "keyboard step", { value, from: Arr.getUnsafe(measured, index).index, to: Arr.getUnsafe(measured, target).index })
839
884
  l.guard = Option.some(version)
840
885
  group.options.onReorder(newValues)
841
- return placementIn(newValues, value, true)
886
+ return placementIn(group, newValues, value, true)
842
887
  })
843
888
  }))
844
889
 
@@ -850,7 +895,7 @@ export const drop: {
850
895
  } = dual(isGroup, <V>(group: Group<V>, value: V): Option.Option<Placement> =>
851
896
  Option.flatMap(liftOf(group, value), () => {
852
897
  MutableRef.set(stateOf(group).lifted, Option.none())
853
- const placement = placementIn(group.options.values(), value, false)
898
+ const placement = placementIn(group, group.options.values(), value, false)
854
899
  log(group, "keyboard drop", { value, position: Option.map(placement, (p) => p.position) })
855
900
  return placement
856
901
  }))
@@ -867,10 +912,11 @@ export const cancel: {
867
912
  Option.flatMap(liftOf(group, value), (l) => {
868
913
  MutableRef.set(stateOf(group).lifted, Option.none())
869
914
  const values = group.options.values()
870
- const restored = restore(values, l.origin, value)
871
- if (Bool.not(sameOrder(restored, values))) group.options.onReorder(restored)
915
+ const same = stateOf(group).same
916
+ const restored = restore(values, l.origin, value, same)
917
+ if (Bool.not(Arr.makeEquivalence(same)(restored, values))) group.options.onReorder(restored)
872
918
  log(group, "keyboard cancel", { value })
873
- return placementIn(restored, value, false)
919
+ return placementIn(group, restored, value, false)
874
920
  }))
875
921
 
876
922
  /**
@@ -878,10 +924,10 @@ export const cancel: {
878
924
  * rest in their current order. Only the lifted item moved during the lift, so this is the lift's
879
925
  * order unless the app changed `values` (which drops the lift first).
880
926
  */
881
- const restore = <V>(values: ReadonlyArray<V>, origin: ReadonlyArray<V>, value: V): Array<V> =>
882
- Option.match(Arr.findFirstIndex(values, (v) => v === value), {
927
+ const restore = <V>(values: ReadonlyArray<V>, origin: ReadonlyArray<V>, value: V, same: Same<V>): Array<V> =>
928
+ Option.match(Arr.findFirstIndex(values, (v) => same(v, value)), {
883
929
  onNone: () => Arr.copy(values),
884
- onSome: (from) => moveItem(values, from, Option.getOrElse(Arr.findFirstIndex(origin, (v) => v === value), () => from)),
930
+ onSome: (from) => moveItem(values, from, Option.getOrElse(Arr.findFirstIndex(origin, (v) => same(v, value)), () => from)),
885
931
  })
886
932
 
887
933
  /** The lifted value, while a keyboard reorder runs. */
@@ -45,7 +45,7 @@ export interface Scroll {
45
45
  export interface Options {
46
46
  /** The scroll container: the Environment's own when left out. */
47
47
  readonly container?: unknown
48
- /** An element whose progress through the container `progress` reads, on `axis`. */
48
+ /** A Subject whose progress through the container `progress` reads, on `axis`. */
49
49
  readonly target?: unknown
50
50
  /**
51
51
  * Where on `axis` the target's progress runs, from 0 to 1, in the Environment's own terms, which it
package/src/Sequence.ts CHANGED
@@ -89,7 +89,7 @@ export type Transition =
89
89
  * each key's transition (a key without one runs on a 0.3 s `easeOut` tween), and where it starts.
90
90
  */
91
91
  export interface Segment<S> {
92
- /** What it animates: elements, or anything a binding animates, such as a callback's value. */
92
+ /** What it animates: Subjects, or anything a binding animates, such as a callback's value. */
93
93
  readonly subjects: ReadonlyArray<S>
94
94
  /** Each key's value, or its stops, or a function of each subject's index and count that gives them. */
95
95
  readonly target: Readonly<Record<string, Value>>
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Shared sources, for the Streams an Environment hands out: each hot and counted, so however many
3
3
  * subscribe, one underlying source runs, started by the first subscriber and stopped when the last one
4
- * leaves. `byTarget` keeps one per target, one observer on each element, and `make` one for the whole
4
+ * leaves. `byTarget` keeps one per target, one observer on each Subject, and `make` one for the whole
5
5
  * Environment. An Environment builds its sources with these, as `@wardic/dom` does, and `counted` shares
6
6
  * anything else it opens per target.
7
7
  *
@@ -18,7 +18,7 @@
18
18
  //
19
19
  // One shape under both constructors (#518, ADR-0067 *Amendment (#518)*, decision 3): a target's entry in
20
20
  // a `counted` map holds its subscribers' hearings and, while any subscriber holds it, a pump that runs the
21
- // cold source and hands each element to every hearing, which resumes a waiting subscriber inside the
21
+ // cold source and hands each value to every hearing, which resumes a waiting subscriber inside the
22
22
  // call, as the `PubSub` did. The first subscriber opens the entry and starts the pump; the
23
23
  // last one's release interrupts it, and the cold source's finalizers run (a listener is removed). The
24
24
  // source's end ends every subscriber, and its failure fails them (#618, decision 6). It replaced a
@@ -47,12 +47,12 @@ interface Held<V> {
47
47
  /**
48
48
  * Values shared by key and counted: the first hold of a key opens its value with `open`, later holds
49
49
  * share it, and the last one's release closes it with `close`. A key is held by identity and never
50
- * hashed, so a DOM node is its own key. `open` runs inline, so it mustn't wait.
50
+ * hashed, so a Subject is its own key. `open` runs inline, so it mustn't wait.
51
51
  *
52
52
  * @example
53
53
  * // One listener set per container, however many readers hold it
54
54
  * const containers = SharedSource.counted(
55
- * (container: Element) => ({ remove: listenTo(container) }),
55
+ * (container: object) => ({ remove: listenTo(container) }),
56
56
  * (listening) => Effect.sync(listening.remove),
57
57
  * )
58
58
  * const listening = yield* containers(list) // held until the current Scope closes
@@ -93,7 +93,7 @@ interface Fanned<A> {
93
93
  /** A fresh source's entry, with no subscriber, no pump and no end. */
94
94
  const fanned = <A>(): Fanned<A> => ({ hearings: new Set(), pump: Option.none(), ended: Option.none() })
95
95
 
96
- /** The pump: `acquire`'s source, each element to every subscriber; its end, kept and handed to each. */
96
+ /** The pump: `acquire`'s source, each value to every subscriber; its end, kept and handed to each. */
97
97
  const pumpOf = <A>(entry: Fanned<A>, acquire: Effect.Effect<Stream.Stream<A>, never, Scope.Scope>): Effect.Effect<void> =>
98
98
  Effect.scoped(
99
99
  Effect.flatMap(acquire, (source) => Stream.runForEach(source, (a) => Effect.sync(() => Iter.forEach(entry.hearings, (hearing) => hearing.hear(a))))),
package/src/Spring.ts CHANGED
@@ -178,10 +178,11 @@ const ROOT_ITERATIONS = Arr.range(1, 11)
178
178
 
179
179
  /**
180
180
  * The stiffness and damping (mass 1) of a spring that settles in `duration` seconds with `bounce`:
181
- * Motion's `findSpring`, ported (`motion-dom`'s `spring.ts`, at 16c6122), at velocity 0, as Motion
181
+ * Motion's `findSpring`, ported, at velocity 0, as Motion
182
182
  * solves it, so an inherited velocity can't throw its parameters off. Newton's method from Motion's
183
183
  * first guess, 12 iterations; one that fails (NaN) falls back to Motion's 100 / 10.
184
184
  */
185
+ // `motion-dom`'s `spring.ts`, at 16c6122.
185
186
  const solveDuration = (duration: number, bounce: number): { readonly stiffness: number; readonly damping: number } => {
186
187
  const ratio = ratioOf(bounce)
187
188
  const seconds = within(duration, MIN_DURATION, MAX_DURATION)
package/src/Values.ts CHANGED
@@ -22,7 +22,7 @@ export type Values = Record<string, number | string>
22
22
  /** A named animation state's values. */
23
23
  export type Variant = Record<string, number | string>
24
24
 
25
- /** Named animation states, which the elements of a component tree share by name. */
25
+ /** Named animation states, which the Subjects of a component tree share by name. */
26
26
  export type Variants = Record<string, Variant>
27
27
 
28
28
  /** A bag's keys by kind: its numbers, which a spring moves, and its strings, which are blended by a progress. */
@@ -45,7 +45,7 @@ export const split = (values: Readonly<Values>): Split => ({
45
45
 
46
46
  /**
47
47
  * `self`'s values for the keys `keysFrom` has, leaving out a key `self` lacks or holds `undefined` for:
48
- * where an animation's keys start, from the element's values for the keys it animates to.
48
+ * where an animation's keys start, from the Subject's values for the keys it animates to.
49
49
  *
50
50
  * @example
51
51
  * const from = Values.pick(current, target) // current's values for target's keys
package/src/index.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * `DefaultTransition`) are each `X.X`, with the shared constructors the Environments build on
11
11
  * (`Clock.layer`, `Clock.fromRefreshFrames`, `InputSource.heldPointer`, `InputFeed.byTarget`,
12
12
  * `InterpolatorRegistry.layer`, `FrameLoop.layer`, `DefaultTransition.layerOneSpring`). Each module's
13
- * page is at https://wardic.dev/reference/core.
13
+ * reference is at https://wardic.dev/reference/core.
14
14
  */
15
15
  // A module per data type or CONTEXT.md term: ADR-0028. Primitives as machines, run as Streams or on
16
16
  // the Frame loop: ADR-0001, ADR-0027. Design decisions and the glossary: `docs/adr/` and `CONTEXT.md`.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * A value a service carries beside its stable shape, under a key of its own: how core hands Wardic's own code
3
+ * what a stable service doesn't say, with no member added to the service.
4
+ *
5
+ * @internal
6
+ */
7
+ // #1030 (a Renderer's projector, `unstable/Projector.ts`) and #1036 (the registry's number check,
8
+ // `internal/lerpsNumbers.ts`). A spread of the service keeps what it carries: a symbol key is copied too.
9
+ import * as Option from "effect/Option"
10
+ import * as Predicate from "effect/Predicate"
11
+
12
+ /** `self`, carrying `value` under `key`. */
13
+ export const carry = <S extends object>(self: S, key: symbol, value: unknown): S => ({ ...self, [key]: value })
14
+
15
+ /** What `self` carries under `key`, when `is` holds of it; `None` otherwise. */
16
+ export const carriedOf = <A>(self: object, key: symbol, is: Predicate.Refinement<unknown, A>): Option.Option<A> => {
17
+ // Per leg (#460): statements.
18
+ if (!Predicate.hasProperty(self, key)) return Option.none()
19
+ const value = self[key]
20
+ if (!is(value)) return Option.none()
21
+ return Option.some(value)
22
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The late-frame rule for a run's first steps, on plain numbers: a run takes none of a long task's time from
3
+ * before it began. A long task delays a frame, a **Late frame**. Stamped when it was due, the frame is told late
4
+ * by its lag (its callback ran past the line after its timestamp), and the next frame's dt holds the task's time:
5
+ * a run made in the task leaves the frame's lateness out of its second step, and one made in its Late window and
6
+ * first stepped at a later tick, out of its first. Stamped near when it ran, the frame's own gap from the one
7
+ * before holds the task's time, as the gap after a frame told late does: a frame whose gap is more than one and a
8
+ * half of the frames' interval is late by the rest (`lateByGap`), and a run's first step there leaves its
9
+ * lateness out, one interval.
10
+ *
11
+ * A run keeps one number, what it owes (`owed`): `NaN` until its first step, or less than 0 for one made in the
12
+ * Late window of a frame told late by its lag, by the frame's lateness (`madeOwing`); then its first frame's
13
+ * lateness, which its second step leaves out; then 0. A run that owes 0 steps at the tick's dt.
14
+ *
15
+ * @internal
16
+ */
17
+ // #1028 (ADR-0027 *Amendment (#1028)*): #1026's rule, out of the Frame loop's entries, so a Batch's members,
18
+ // on one run, keep it per member. The Frame loop carries a `Reader` of its ticks for them (`internal/carried.ts`).
19
+ // Per frame, for a run or a member that owes: plain math. #1050 (ADR-0027 *Amendment (#1050)*): a frame told late by
20
+ // its gap, in place of #1048's line a run waited past, which missed a run made late in the task: WebKit and Gecko
21
+ // stamp a late frame near when it ran, so its lag never tells it. #1053: "late", where #1050 said "held", which is
22
+ // Foldkit's **Held frame** (CONTEXT.md).
23
+ import * as Option from "effect/Option"
24
+ import * as Predicate from "effect/Predicate"
25
+ import * as Clock from "../Clock.ts"
26
+ import { carriedOf, carry } from "./carried.ts"
27
+
28
+ /** `dt`, less `left` seconds left out of it: `floor` at least, and never more than `dt`. */
29
+ const leavingOut = (dt: number, left: number, floor: number): number => Math.min(dt, Math.max(dt - left, floor))
30
+
31
+ /** A 60 Hz frame, in ms: the Frame loop takes one for a gap it hasn't timed. */
32
+ export const NOMINAL_FRAME_MS = Clock.NOMINAL_DT * 1000
33
+
34
+ /** A 30 Hz frame, in ms: the longest interval `intervalOf` gives, so late frames one after another don't lift it. */
35
+ const SLOWEST_FRAME_MS = 1000 / 30
36
+
37
+ /** The median of `a`, `b` and `c`. */
38
+ const medianOf3 = (a: number, b: number, c: number): number => Math.max(Math.min(a, b), Math.min(Math.max(a, b), c))
39
+
40
+ /**
41
+ * The frames' interval, in ms, from the last five gaps between their timestamps, `gap` and the four before it,
42
+ * newest first: their median, so neither a late frame's long gap nor a short one after it moves it, and a 30 Hz
43
+ * frame at most.
44
+ */
45
+ // The median of five: of the four before, the least and the most can't be it, so it's the median of the two
46
+ // between them and `gap`.
47
+ export const intervalOf = (gap: number, before1: number, before2: number, before3: number, before4: number): number =>
48
+ Math.min(
49
+ medianOf3(Math.max(Math.min(before1, before2), Math.min(before3, before4)), Math.min(Math.max(before1, before2), Math.max(before3, before4)), gap),
50
+ SLOWEST_FRAME_MS,
51
+ )
52
+
53
+ /** How late a frame whose callback ran `lag` ms after its timestamp is by its lag, in ms: all of it, past `line`; else 0. */
54
+ export const lateByLag = (lag: number, line: number): number => {
55
+ if (lag > line) return lag
56
+ return 0
57
+ }
58
+
59
+ /**
60
+ * How late a frame `gap` ms after the one before is by its gap, in ms, on frames `interval` ms apart: what its gap
61
+ * is longer than one interval, once that's more than half of one; else 0.
62
+ */
63
+ export const lateByGap = (gap: number, interval: number): number => {
64
+ const longer = gap - interval
65
+ if (longer > interval / 2) return longer
66
+ return 0
67
+ }
68
+
69
+ /** What a run made now owes: its first step, made in a frame `madeLate` seconds late by its lag, or in one on time. */
70
+ export const madeOwing = (madeLate: number): number => {
71
+ if (madeLate > 0) return -madeLate
72
+ return Number.NaN
73
+ }
74
+
75
+ /**
76
+ * The dt of a step of a run that owes `owed` (not 0), in a frame `lateByGap` seconds late by its gap, on frames
77
+ * `interval` seconds apart: its second, `dt` less its first frame's lateness by its lag; its first, `dt` less its
78
+ * frame's lateness by its gap, or less what it owes of a frame told late by its lag, for one made in that frame's
79
+ * Late window and stepped at a later tick, whichever is more, and one interval at least. That frame's own Late
80
+ * step leaves only `lateByGap` out: its dt doesn't hold the frame's lateness by its lag.
81
+ */
82
+ export const owingDt = (owed: number, dt: number, lateStep: boolean, lateByGap: number, interval: number): number => {
83
+ if (owed > 0) return leavingOut(dt, owed, Clock.NOMINAL_DT)
84
+ return leavingOut(dt, Math.max(lateByGap, owedLateByLag(owed, lateStep)), interval)
85
+ }
86
+
87
+ /**
88
+ * What a run's first step owes of a frame told late by its lag, in seconds: what a run made in its Late window
89
+ * owes, at a later tick; nothing at that frame's own Late step, whose dt doesn't hold it, or for a run that owes
90
+ * `NaN`.
91
+ */
92
+ const owedLateByLag = (owed: number, lateStep: boolean): number => {
93
+ if (owed < 0 && !lateStep) return -owed
94
+ return 0
95
+ }
96
+
97
+ /** What a run that owed `owed` owes after a step in a frame `lateByLag` seconds late by its lag: that, after its first; else nothing. */
98
+ export const owedAfter = (owed: number, lateByLag: number): number => {
99
+ if (owed > 0) return 0
100
+ return lateByLag
101
+ }
102
+
103
+ /**
104
+ * The Frame loop's ticks as the rule reads them, for a run that keeps it per member: what one made now owes,
105
+ * and the dt of a step of one that owes, in the tick or Late step running now. Stateless: it reads the loop.
106
+ */
107
+ export interface Reader {
108
+ /** What a member made now owes (`madeOwing`): 0, nothing, where the loop tells no late frame. */
109
+ readonly madeOwing: () => number
110
+ /**
111
+ * The dt of a step, now, of a member that owes `owed` (not 0): `owingDt`'s. A step in a tick's Late window,
112
+ * after its steps, is a Late step: the loop's own, or one a run takes there itself.
113
+ */
114
+ readonly owingDt: (owed: number, dt: number) => number
115
+ /** What a member that owed `owed` owes after its step now: `owedAfter`'s. */
116
+ readonly owedAfter: (owed: number) => number
117
+ }
118
+
119
+ /** A `Reader` under which nothing owes: for a loop that carries none, so its runs step at the tick's dt. */
120
+ export const owingNothing: Reader = {
121
+ madeOwing: () => 0,
122
+ owingDt: (_owed, dt) => dt,
123
+ owedAfter: () => 0,
124
+ }
125
+
126
+ /** Where the Frame loop carries its `Reader`, under a key no other module can name. */
127
+ const KEY: unique symbol = Symbol("@wardic/core/internal/firstSteps")
128
+
129
+ /** Whether a value is what `carrying` carries. Only `carrying` writes `KEY`, so its fields are read as they are. */
130
+ const isReader = Predicate.and(
131
+ Predicate.hasProperty("madeOwing"),
132
+ Predicate.and(Predicate.hasProperty("owingDt"), Predicate.hasProperty("owedAfter")),
133
+ ) as Predicate.Refinement<unknown, Reader>
134
+
135
+ /** `loop`, carrying `reader`. */
136
+ export const carrying = <L extends object>(loop: L, reader: Reader): L => carry(loop, KEY, reader)
137
+
138
+ /** The `Reader` `loop` carries: `None` for a loop that carries none (one a test makes of its own). */
139
+ export const readerOf = (loop: object): Option.Option<Reader> => carriedOf(loop, KEY, isReader)