@wardic/dom 1.0.1 → 1.1.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 (57) hide show
  1. package/dist/Appear.d.ts +3 -2
  2. package/dist/Appear.d.ts.map +1 -1
  3. package/dist/Appear.js +4 -3
  4. package/dist/Appear.js.map +1 -1
  5. package/dist/FlushGate.d.ts.map +1 -1
  6. package/dist/FlushGate.js +4 -3
  7. package/dist/FlushGate.js.map +1 -1
  8. package/dist/TimelineValue.d.ts +18 -0
  9. package/dist/TimelineValue.d.ts.map +1 -0
  10. package/dist/TimelineValue.js +20 -0
  11. package/dist/TimelineValue.js.map +1 -0
  12. package/dist/index.d.ts +13 -5
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +10 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/internal/appear.d.ts +10 -4
  17. package/dist/internal/appear.d.ts.map +1 -1
  18. package/dist/internal/appear.js +18 -8
  19. package/dist/internal/appear.js.map +1 -1
  20. package/dist/internal/drag-defaults.js +4 -1
  21. package/dist/internal/drag-defaults.js.map +1 -1
  22. package/dist/internal/gate.d.ts +11 -0
  23. package/dist/internal/gate.d.ts.map +1 -1
  24. package/dist/internal/gate.js +114 -2
  25. package/dist/internal/gate.js.map +1 -1
  26. package/dist/internal/projection.d.ts.map +1 -1
  27. package/dist/internal/projection.js +8 -7
  28. package/dist/internal/projection.js.map +1 -1
  29. package/dist/internal/renderer.d.ts +13 -0
  30. package/dist/internal/renderer.d.ts.map +1 -1
  31. package/dist/internal/renderer.js +21 -0
  32. package/dist/internal/renderer.js.map +1 -1
  33. package/dist/internal/runner.d.ts +4 -3
  34. package/dist/internal/runner.d.ts.map +1 -1
  35. package/dist/internal/runner.js +19 -5
  36. package/dist/internal/runner.js.map +1 -1
  37. package/dist/internal/scroll.d.ts +17 -0
  38. package/dist/internal/scroll.d.ts.map +1 -1
  39. package/dist/internal/scroll.js +23 -15
  40. package/dist/internal/scroll.js.map +1 -1
  41. package/dist/internal/timeline.d.ts +56 -0
  42. package/dist/internal/timeline.d.ts.map +1 -0
  43. package/dist/internal/timeline.js +389 -0
  44. package/dist/internal/timeline.js.map +1 -0
  45. package/package.json +3 -3
  46. package/src/Appear.ts +4 -2
  47. package/src/FlushGate.ts +4 -3
  48. package/src/TimelineValue.ts +19 -0
  49. package/src/index.ts +15 -5
  50. package/src/internal/appear.ts +20 -8
  51. package/src/internal/drag-defaults.ts +4 -4
  52. package/src/internal/gate.ts +110 -2
  53. package/src/internal/projection.ts +8 -7
  54. package/src/internal/renderer.ts +22 -0
  55. package/src/internal/runner.ts +20 -6
  56. package/src/internal/scroll.ts +32 -15
  57. package/src/internal/timeline.ts +480 -0
@@ -0,0 +1,480 @@
1
+ /**
2
+ * Timeline values (#240, CONTEXT.md): a Live value derived from a container's scroll by ranges alone,
3
+ * which the browser draws with the scroll itself, on a native `ScrollTimeline` or `ViewTimeline`, over
4
+ * the inline value the gate goes on writing. Where the native timeline is inactive (a container that
5
+ * doesn't overflow, a target not laid out), the inline value shows, and a value it lets go of shows
6
+ * the gate's at once.
7
+ *
8
+ * What runs on a native timeline (ADR-0043 *Amendment (#240)*):
9
+ * - **Keys:** those drawn into `opacity`, `filter`, `clip-path` or `transform` (a `transform` string,
10
+ * or a transform key while nothing else adds to the element's `transform`): what a browser can run
11
+ * on its compositor, as Motion's `acceleratedValues` (14.10.1).
12
+ * - **Sources:** a progress with no offset (a `ScrollTimeline`); a target's progress over two stops
13
+ * whose container edges are `start` or `end` (a `ViewTimeline` on Motion 14's `entry-crossing` /
14
+ * `exit-crossing` ranges, `offset-to-range.ts`), the target the timeline's own subject, measured as
15
+ * Wardic measures it; how far the container is scrolled, through a `transform` (a `ScrollTimeline`
16
+ * over a px range).
17
+ * - **Derivations:** the source itself, or one `transform` of it that clamps, blends by the registry
18
+ * and whose input only rises or only falls, and whose outputs CSS blends as the registry does.
19
+ *
20
+ * Its keyframes are Wardic's own values, projected as the gate projects them: at the domain's ends, at
21
+ * each stop, and, through an eased stretch, at {@link SAMPLES} points, so the browser blends only
22
+ * between near neighbours. Built once, when it's made; the animation, each time it starts.
23
+ *
24
+ * Wardic reads a target's offsets and lengths in whole pixels (`offsetTop`, `clientHeight`), a native
25
+ * timeline the layout's own: on a layout of fractional pixels they part by under a pixel of scroll.
26
+ *
27
+ * Observability: per flush, quiet (no span, no log).
28
+ */
29
+ import type * as InterpolatorRegistry from "@wardic/core/InterpolatorRegistry"
30
+ import * as LiveValue from "@wardic/core/LiveValue"
31
+ import * as Projection from "@wardic/core/Projection"
32
+ import type * as ScrollSource from "@wardic/core/ScrollSource"
33
+ import * as Arr from "effect/Array"
34
+ import * as Bool from "effect/Boolean"
35
+ import * as Effect from "effect/Effect"
36
+ import { constant, constTrue } from "effect/Function"
37
+ import * as Num from "effect/Number"
38
+ import * as Option from "effect/Option"
39
+ import * as Order from "effect/Order"
40
+ import * as Predicate from "effect/Predicate"
41
+ import * as Rec from "effect/Record"
42
+ import * as Str from "effect/String"
43
+ import * as UndefinedOr from "effect/UndefinedOr"
44
+ import type * as ScrollOffset from "../ScrollOffset.ts"
45
+ import { addsToTransform, project, transformFunctionOf } from "./renderer.ts"
46
+ import { clientLengthOf, isHTMLElement, offsetOf, pageOf, positionOf, resolvesOn } from "./scroll.ts"
47
+
48
+ /**
49
+ * A key's Timeline value on one element: its native animation, run while its key shows it and nothing
50
+ * else draws its property. The gate syncs it at each flush that commits the element, before the commit.
51
+ */
52
+ export interface TimelineValue {
53
+ /** The key it draws. */
54
+ readonly key: string
55
+ /**
56
+ * Run its animation, or stop it, for the element's values now: it runs while nothing else adds to
57
+ * its property (for `transform`, no other transform key off its identity, no projection, no
58
+ * Transform template; for `opacity`, no projection). Per flush: plain statements.
59
+ */
60
+ readonly sync: (values: Readonly<Record<string, unknown>>) => void
61
+ /** Stop its animation, and its watch on the sizes its direction reads. A later `sync` starts it again. */
62
+ readonly cancel: () => void
63
+ }
64
+
65
+ /** The points sampled inside each eased stretch, so the browser blends only between near neighbours. */
66
+ const SAMPLES = 64
67
+
68
+ /** How far a keyframe segment's middle may sit off its ends' blend: a share of that number's range across the keyframes. */
69
+ const MIDDLE_TOLERANCE = 1e-3
70
+
71
+ /** What a middle may sit off its ends' blend where its number doesn't change: floating point's rounding. */
72
+ const ROUNDING = 1e-9
73
+
74
+ /**
75
+ * The properties a Timeline value draws, as the gate's patch names them, each to its keyframe name, and
76
+ * the CSS functions a value of it may hold: those CSS blends argument by argument, as the registry
77
+ * blends numbers. Not `matrix()`, `matrix3d()`, `rotate3d()` or `perspective()`, which CSS blends by
78
+ * decomposing; not `drop-shadow()`, whose colour CSS blends premultiplied.
79
+ */
80
+ const PROPERTIES: Readonly<Record<string, { readonly name: string; readonly functions: ReadonlySet<string> }>> = {
81
+ opacity: { name: "opacity", functions: new Set() },
82
+ transform: {
83
+ name: "transform",
84
+ functions: new Set(["translate", "translateX", "translateY", "translateZ", "translate3d", "scale", "scaleX", "scaleY", "scaleZ", "scale3d", "rotate", "rotateX", "rotateY", "rotateZ", "skew", "skewX", "skewY"]),
85
+ },
86
+ filter: { name: "filter", functions: new Set(["blur", "brightness", "contrast", "grayscale", "hue-rotate", "invert", "opacity", "saturate", "sepia"]) },
87
+ clipPath: { name: "clipPath", functions: new Set(["inset", "circle", "ellipse", "polygon"]) },
88
+ "clip-path": { name: "clipPath", functions: new Set(["inset", "circle", "ellipse", "polygon"]) },
89
+ }
90
+
91
+ /** A number in a CSS value, for its shape. */
92
+ const NUMBER = /-?\d*\.?\d+(?:e[+-]?\d+)?/gi
93
+
94
+ /** A CSS function's name in a value. */
95
+ const FUNCTION = /([a-z][a-z0-9-]*)\(/gi
96
+
97
+ /** Where a value's keyframes run: their domain, on what native timeline, over what range, and in which direction now. */
98
+ interface Plan {
99
+ /** What the value reads at the first keyframe and at the last: a progress, or a scroll in px. */
100
+ readonly from: number
101
+ readonly to: number
102
+ /** Its native timeline, made or found when it starts. */
103
+ readonly nativeTimeline: () => AnimationTimeline
104
+ /** The range's ends, forwards; none for the native timeline's own. */
105
+ readonly range: Option.Option<readonly [string, string]>
106
+ /** Whether it plays reversed now: a target's offset whose direction depends on the sizes. */
107
+ readonly reversed: () => boolean
108
+ /** The elements whose resize can flip it: none for a fixed direction. */
109
+ readonly watch: ReadonlyArray<Element>
110
+ /** Whether a window resize can flip it too: the page's own length is the window's. */
111
+ readonly watchesWindow: boolean
112
+ }
113
+
114
+ /** A container's or target's native timelines, one an axis. */
115
+ type ByAxis<T> = { x?: T; y?: T }
116
+
117
+ // Module state (#460, Q7): a cache keyed by what it caches, held weakly. One `ScrollTimeline` a
118
+ // container and an axis, shared by every value on it, as Motion's `get-timeline.ts`.
119
+ const scrollTimelines = new WeakMap<Element, ByAxis<ScrollTimeline>>()
120
+ // Module state (#460, Q7): a cache keyed by what it caches, held weakly. One `ViewTimeline` a target and
121
+ // an axis: its scroller is the target's own.
122
+ const viewTimelines = new WeakMap<Element, ByAxis<ViewTimeline>>()
123
+
124
+ /** `cache`'s native timeline for `element` on `axis`, made by `make` the first time. */
125
+ const cachedTimeline = <T>(cache: WeakMap<Element, ByAxis<T>>, element: Element, axis: "x" | "y", make: () => T): T => {
126
+ const byAxis = UndefinedOr.match(cache.get(element), {
127
+ onDefined: (known) => known,
128
+ onUndefined: () => {
129
+ const made: ByAxis<T> = {}
130
+ cache.set(element, made)
131
+ return made
132
+ },
133
+ })
134
+ return UndefinedOr.match(byAxis[axis], {
135
+ onDefined: (known) => known,
136
+ onUndefined: () => {
137
+ const made = make()
138
+ byAxis[axis] = made
139
+ return made
140
+ },
141
+ })
142
+ }
143
+
144
+ const scrollTimelineOf = (container: Element, axis: "x" | "y"): ScrollTimeline =>
145
+ cachedTimeline(scrollTimelines, container, axis, () => new ScrollTimeline({ source: container, axis }))
146
+
147
+ // `inset: 0px`: the range is the scrollport's, as Wardic measures it, whatever the container's `scroll-padding`.
148
+ const viewTimelineOf = (target: Element, axis: "x" | "y"): ViewTimeline =>
149
+ cachedTimeline(viewTimelines, target, axis, () => new ViewTimeline({ subject: target, axis, inset: "0px" }))
150
+
151
+ /** Whether the browser has the native timeline a source needs: a `ViewTimeline` for a target, a `ScrollTimeline` for the rest. */
152
+ const supports = (name: "ScrollTimeline" | "ViewTimeline"): boolean => Predicate.hasProperty(globalThis, name)
153
+
154
+ /** Whether the browser runs an animation over a range of its native timeline (`rangeStart`, `rangeEnd`), not the whole of it. */
155
+ const supportsRanges = (): boolean => Predicate.hasProperty(Animation.prototype, "rangeStart")
156
+
157
+ /** A stop, probed: its target fraction, its container fraction, and its px. */
158
+ type Intersection = readonly [target: number, container: number, px: number]
159
+
160
+ /**
161
+ * A stop's {@link Intersection}: its position is linear in the target's and the container's lengths, so
162
+ * probing it gives them (Motion's `toIntersection`). `None` in a viewport unit, which can resolve to 0px.
163
+ */
164
+ const intersectionOf = (stop: ScrollOffset.Stop): Option.Option<Intersection> =>
165
+ Bool.match(Str.includes("v")(String(stop)), {
166
+ onTrue: () => Option.none(),
167
+ onFalse: () => {
168
+ const px = positionOf(stop, 0, 0, 0)
169
+ return Option.some([positionOf(stop, 0, 1, 0) - px, px - positionOf(stop, 1, 0, 0), px] as const)
170
+ },
171
+ })
172
+
173
+ /** A stop's named range offset: a target fraction crossing the container's end (`entry-crossing`) or start (`exit-crossing`), with no px. */
174
+ const crossingOf = ([t, c, px]: Intersection): Option.Option<string> =>
175
+ Bool.match(Bool.and(px === 0, Bool.or(c === 0, c === 1)), {
176
+ onTrue: () => Option.some(`${Bool.match(c === 1, { onTrue: () => "entry", onFalse: () => "exit" })}-crossing ${t * 100}%`),
177
+ onFalse: () => Option.none(),
178
+ })
179
+
180
+ /**
181
+ * An offset's `ViewTimeline` range (Motion 14's `offsetToViewTimelineRange`): its two stops' named
182
+ * offsets, and `a`, `b`, with which it runs forwards while `a × target length + b × container length`
183
+ * isn't below 0. `None` for any other offset.
184
+ */
185
+ const rangeOfOffset = (offset: ScrollOffset.ScrollOffset): Option.Option<{ readonly points: readonly [string, string]; readonly a: number; readonly b: number }> => {
186
+ if (offset.length !== 2) return Option.none()
187
+ return Option.flatMap(Option.all([intersectionOf(offset[0]), intersectionOf(offset[1])]), ([start, end]) =>
188
+ Option.flatMap(Option.all([crossingOf(start), crossingOf(end)]), (points) => {
189
+ const a = end[0] - start[0]
190
+ const b = start[1] - end[1]
191
+ return Bool.match(Bool.or(a !== 0, b !== 0), { onTrue: () => Option.some({ points, a, b }), onFalse: () => Option.none() })
192
+ }))
193
+ }
194
+
195
+ /**
196
+ * Whether a target's `ViewTimeline` measures it as Wardic does: neither fixed nor sticky, with no
197
+ * border or scrollbar on `axis` (a `ViewTimeline` measures the border box, Wardic the client size),
198
+ * its timeline's scroller the container. Read once, as it's made: a target that changes after reads as
199
+ * it was.
200
+ */
201
+ const measuresAsWardic = (target: HTMLElement, container: Element, axis: "x" | "y"): boolean => {
202
+ const position = getComputedStyle(target).position
203
+ if (Bool.or(position === "fixed", position === "sticky")) return false
204
+ const outer = Bool.match(axis === "y", { onTrue: () => target.offsetHeight, onFalse: () => target.offsetWidth })
205
+ if (outer !== clientLengthOf(target, axis)) return false
206
+ // Made here, and kept for its start: a target's one `ViewTimeline` an axis.
207
+ return viewTimelineOf(target, axis).source === container
208
+ }
209
+
210
+ /** The plan for a value read through a target's offset on its own axis: a `ViewTimeline`, where one measures it as Wardic does. */
211
+ const viewPlanOf = (scroll: ScrollSource.Options, container: Element, axis: "x" | "y"): Option.Option<Plan> => {
212
+ // Each check reads what the one before allows: no native timeline is made in a browser with none.
213
+ const subject = Option.filter(Option.fromUndefinedOr(scroll.target as Element | undefined), isHTMLElement)
214
+ if (Option.isNone(subject)) return Option.none()
215
+ const target = subject.value
216
+ if (Bool.not(supports("ViewTimeline"))) return Option.none()
217
+ if (Bool.not(supportsRanges())) return Option.none()
218
+ const range = rangeOfOffset(offsetOf(scroll))
219
+ if (Option.isNone(range)) return Option.none()
220
+ if (Bool.not(measuresAsWardic(target, container, axis))) return Option.none()
221
+ const { points, a, b } = range.value
222
+ // Its direction depends on the sizes only where a and b pull apart (Motion's `All`, a target shorter
223
+ // or longer than the container); `Any`'s never changes.
224
+ const flips = a * b < 0
225
+ return Option.some<Plan>({
226
+ from: 0,
227
+ to: 1,
228
+ nativeTimeline: () => viewTimelineOf(target, axis),
229
+ range: Option.some(points),
230
+ reversed: () => a * clientLengthOf(target, axis) + b * clientLengthOf(container, axis) < 0,
231
+ watch: Bool.match(flips, { onTrue: (): ReadonlyArray<Element> => [target, container], onFalse: () => [] }),
232
+ watchesWindow: Bool.and(flips, container === pageOf()),
233
+ })
234
+ }
235
+
236
+ const FORWARDS = constant(false)
237
+
238
+ /** A `ScrollTimeline` plan over `from` to `to`, on `range`, where the browser has what it needs. */
239
+ const scrollPlanOf = (container: Element, axis: "x" | "y", from: number, to: number, range: Option.Option<readonly [string, string]>): Option.Option<Plan> => {
240
+ if (Bool.not(supports("ScrollTimeline"))) return Option.none()
241
+ if (Bool.and(Option.isSome(range), Bool.not(supportsRanges()))) return Option.none()
242
+ return Option.some<Plan>({ from, to, nativeTimeline: () => scrollTimelineOf(container, axis), range, reversed: FORWARDS, watch: [], watchesWindow: false })
243
+ }
244
+
245
+ /** Where `derivation`'s keyframes run, over `stops` (its transform's input), or `None` where no native timeline can run it. */
246
+ const planOf = (derivation: LiveValue.ScrollDerivation, stops: ReadonlyArray<number>): Option.Option<Plan> => {
247
+ const { scroll, read, axis } = derivation
248
+ const container = UndefinedOr.match(scroll.container as Element | undefined, { onUndefined: pageOf, onDefined: (given) => given })
249
+ if (read === "current") {
250
+ // How far it's scrolled, through a transform: a px range over the stops, from the scroll's start.
251
+ if (Arr.isReadonlyArrayEmpty(stops)) return Option.none()
252
+ const from = Math.max(0, Math.min(...stops))
253
+ const to = Math.max(...stops)
254
+ if (to <= from) return Option.none()
255
+ return scrollPlanOf(container, axis, from, to, Option.some([`${from}px`, `${to}px`] as const))
256
+ }
257
+ // A progress through offsets on its own axis needs a target; else it's the container's plain progress.
258
+ return Bool.match(resolvesOn(scroll, axis), {
259
+ onTrue: () => viewPlanOf(scroll, container, axis),
260
+ onFalse: () => scrollPlanOf(container, axis, 0, 1, Option.none()),
261
+ })
262
+ }
263
+
264
+ /** Whether `input` only rises or only falls, two stops or more. */
265
+ const isMonotonic = (input: ReadonlyArray<number>): boolean => {
266
+ if (input.length < 2) return false
267
+ const steps = Arr.zipWith(input, Arr.drop(input, 1), (a, b) => b - a)
268
+ if (Arr.every(steps, Num.isGreaterThan(0))) return true
269
+ return Arr.every(steps, Num.isLessThan(0))
270
+ }
271
+
272
+ /** Whether a native timeline can hold `step`: it clamps, the registry blends its outputs, numbers or strings, one a stop, and its input only rises or only falls. */
273
+ const isRunnable = (step: LiveValue.ScrollTransform): boolean => {
274
+ if (Bool.or(Bool.not(step.clamp), step.mixed)) return false
275
+ if (step.input.length !== step.output.length) return false
276
+ if (Bool.not(Arr.every(step.output, Predicate.or(Predicate.isNumber, Predicate.isString)))) return false
277
+ return isMonotonic(step.input)
278
+ }
279
+
280
+ /** A value's points: the stops its keyframes must hold, whether it's eased between them, and its value at each point it reads. */
281
+ interface Valued {
282
+ readonly stops: ReadonlyArray<number>
283
+ readonly eased: boolean
284
+ readonly at: (v: number) => unknown
285
+ }
286
+
287
+ const ITSELF: Valued = { stops: [], eased: false, at: (v) => v }
288
+
289
+ /** `derivation`'s value at each point it reads: the source itself, or its one transform, which the registry blends. `None` for a chain, or a transform a native timeline can't hold. */
290
+ const valueOfDerivation: (derivation: LiveValue.ScrollDerivation) => Effect.Effect<Option.Option<Valued>, never, InterpolatorRegistry.InterpolatorRegistry> = Effect.fnUntraced(
291
+ function* (derivation: LiveValue.ScrollDerivation) {
292
+ const { transforms, read } = derivation
293
+ if (transforms.length === 0) {
294
+ // A scroll distance itself grows with the content: only its progress, 0 to 1, runs on its own.
295
+ if (read === "current") return Option.none()
296
+ return Option.some(ITSELF)
297
+ }
298
+ if (transforms.length > 1) return Option.none()
299
+ const step = transforms[0]
300
+ if (Bool.not(isRunnable(step))) return Option.none()
301
+ const options = Option.match(step.ease, { onNone: () => ({}), onSome: (ease) => ({ ease }) })
302
+ const at = yield* LiveValue.interpolate(step.input, step.output as ReadonlyArray<number | string>, options)
303
+ return Option.some<Valued>({ stops: step.input, eased: Option.isSome(step.ease), at })
304
+ },
305
+ )
306
+
307
+ /** The points a value's keyframes sit at: the domain's ends, each stop inside it, and through each eased stretch, {@link SAMPLES} more. */
308
+ const pointsOf = (plan: Plan, { stops, eased }: Valued): ReadonlyArray<number> => {
309
+ const sorted = Arr.sort(stops, Order.Number)
310
+ const inner = Bool.match(eased, {
311
+ onTrue: () => Arr.flatMap(Arr.zip(sorted, Arr.drop(sorted, 1)), ([a, b]) => Arr.makeBy(SAMPLES, (k) => a + ((b - a) * (k + 1)) / (SAMPLES + 1))),
312
+ onFalse: () => [],
313
+ })
314
+ return Arr.dedupe(Arr.sort(Arr.filter([plan.from, plan.to, ...sorted, ...inner], Num.between({ minimum: plan.from, maximum: plan.to })), Order.Number))
315
+ }
316
+
317
+ /** A value's shape: what's left with its numbers taken out. */
318
+ const shapeOf = (css: string | number): string => String(css).replace(NUMBER, "#")
319
+
320
+ /** A value's numbers, in order. */
321
+ const numbersOf = (css: string | number): ReadonlyArray<number> => Arr.map(Arr.fromIterable(String(css).matchAll(NUMBER)), (m) => Number(m[0]))
322
+
323
+ /** Whether every CSS function in `css` is one `functions` holds. */
324
+ const holdsOnly = (functions: ReadonlySet<string>, css: string | number): boolean =>
325
+ Arr.every(Arr.fromIterable(String(css).matchAll(FUNCTION)), (m) => functions.has(m[1] as string))
326
+
327
+ /**
328
+ * `key`'s value `v` as a keyframe draws it: its property and its CSS. A transform key as its own
329
+ * function (`translateX(0px)`, never `none`), anything else as the gate projects it. `None` for a
330
+ * property a Timeline value doesn't draw.
331
+ */
332
+ const drawnOf = (key: string, v: unknown): Option.Option<readonly [string, string | number]> =>
333
+ Option.match(transformFunctionOf(key, v), {
334
+ onSome: (css) => Option.some(["transform", css] as const),
335
+ onNone: () => {
336
+ const patch = project({ [key]: v })
337
+ const properties = Rec.keys(patch)
338
+ if (properties.length !== 1) return Option.none()
339
+ const property = properties[0]
340
+ return Option.map(Rec.get(PROPERTIES, property), () => [property, patch[property] as string | number] as const)
341
+ },
342
+ })
343
+
344
+ /**
345
+ * Whether the browser, blending each pair of neighbouring keyframes, draws what Wardic does between
346
+ * them: every value holds only the functions CSS blends argument by argument for its property; Wardic's
347
+ * own value halfway is the same shape as its ends; and each of its numbers is the ends' average, within
348
+ * {@link MIDDLE_TOLERANCE} of that number's range. A blend the registry makes otherwise (a switch between
349
+ * `0px` and `50%`) or a curve too sharp for the samples (an elastic) fails it.
350
+ */
351
+ const blendsAsWardic = (functions: ReadonlySet<string>, values: ReadonlyArray<string | number>, middles: ReadonlyArray<string | number>): boolean => {
352
+ const all = [...values, ...middles]
353
+ if (Bool.not(Arr.every(all, (css) => holdsOnly(functions, css)))) return false
354
+ const shape = shapeOf(values[0])
355
+ if (Bool.not(Arr.every(all, (css) => shapeOf(css) === shape))) return false
356
+ const numbers = Arr.map(values, numbersOf)
357
+ const spans = Arr.map(numbers[0], (_, k) => {
358
+ const column = Arr.map(numbers, (ns) => ns[k])
359
+ return Math.max(...column) - Math.min(...column)
360
+ })
361
+ return Arr.every(middles, (middle, i) =>
362
+ Arr.every(numbersOf(middle), (n, k) => Math.abs(n - (numbers[i][k] + numbers[i + 1][k]) / 2) <= MIDDLE_TOLERANCE * spans[k] + ROUNDING))
363
+ }
364
+
365
+ /**
366
+ * The keyframes for `key`: Wardic's value at each point, as {@link drawnOf} draws it, and the property
367
+ * they draw. `None` when the values draw more than one property, or one a Timeline value doesn't draw,
368
+ * or when the browser's blend between them isn't Wardic's ({@link blendsAsWardic}).
369
+ */
370
+ const keyframesOf = (key: string, plan: Plan, points: ReadonlyArray<number>, at: (v: number) => unknown) =>
371
+ Option.flatMap(Option.all(Arr.map(points, (p) => drawnOf(key, at(p)))), (drawn) => {
372
+ const properties = Arr.dedupe(Arr.map(drawn, ([property]) => property))
373
+ if (properties.length !== 1) return Option.none()
374
+ const property = PROPERTIES[properties[0]]
375
+ const values = Arr.map(drawn, ([, css]) => css)
376
+ const middles = Option.all(Arr.map(Arr.zip(points, Arr.drop(points, 1)), ([a, b]) => drawnOf(key, at((a + b) / 2))))
377
+ if (Option.isNone(middles)) return Option.none()
378
+ if (Bool.not(Arr.every(middles.value, ([middle]) => PROPERTIES[middle] === property))) return Option.none()
379
+ if (Bool.not(blendsAsWardic(property.functions, values, Arr.map(middles.value, ([, css]) => css)))) return Option.none()
380
+ const keyframes = Arr.map(points, (p, i): Keyframe => ({ offset: (p - plan.from) / (plan.to - plan.from), [property.name]: values[i] }))
381
+ return Option.some({ property: property.name, keyframes })
382
+ })
383
+
384
+ /** Whether nothing but `key` adds to `transform` among `values`. Per flush: statements. */
385
+ const transformAloneOf = (key: string) => (values: Readonly<Record<string, unknown>>): boolean => {
386
+ for (const other in values) {
387
+ if (other !== key && addsToTransform(other, values[other])) return false
388
+ }
389
+ return true
390
+ }
391
+
392
+ /** Whether no projection draws the element: its Crossfade's opacity is the projection's. Per flush. */
393
+ const noProjection = (values: Readonly<Record<string, unknown>>): boolean => !Object.hasOwn(values, Projection.KEY)
394
+
395
+ /** Whether nothing but `key` adds to `property` among `values`, by property: the rest have no other writer. Chosen once a value. */
396
+ const ALONE: Readonly<Record<string, (key: string) => (values: Readonly<Record<string, unknown>>) => boolean>> = {
397
+ transform: transformAloneOf,
398
+ opacity: constant(noProjection),
399
+ }
400
+
401
+ const aloneOf = (property: string, key: string): ((values: Readonly<Record<string, unknown>>) => boolean) =>
402
+ Option.match(Rec.get(ALONE, property), { onNone: () => constTrue, onSome: (alone) => alone(key) })
403
+
404
+ /**
405
+ * A Timeline value for `key` on `element`, as `derivation` derives it from a scroll: its native
406
+ * animation, started by its first `sync`. `None` where it can't run on a native timeline as Wardic draws
407
+ * it (above): a browser with no scroll timelines or ranges, an element that isn't an HTML element, a key,
408
+ * a source or a derivation it doesn't take.
409
+ */
410
+ export const make: (
411
+ derivation: LiveValue.ScrollDerivation,
412
+ element: Element,
413
+ key: string,
414
+ ) => Effect.Effect<Option.Option<TimelineValue>, never, InterpolatorRegistry.InterpolatorRegistry> = Effect.fnUntraced(
415
+ function* (derivation: LiveValue.ScrollDerivation, element: Element, key: string) {
416
+ if (Bool.not(isHTMLElement(element))) return Option.none()
417
+ const value = yield* valueOfDerivation(derivation)
418
+ if (Option.isNone(value)) return Option.none()
419
+ const plan = planOf(derivation, value.value.stops)
420
+ if (Option.isNone(plan)) return Option.none()
421
+ const drawn = keyframesOf(key, plan.value, pointsOf(plan.value, value.value), value.value.at)
422
+ if (Option.isNone(drawn)) return Option.none()
423
+ return Option.some(timelineValueOf(element as HTMLElement, key, plan.value, drawn.value.keyframes, aloneOf(drawn.value.property, key)))
424
+ },
425
+ )
426
+
427
+ /** The Timeline value itself: its animation, started and stopped by `sync`, started again the other way where its direction flips. */
428
+ const timelineValueOf = (element: HTMLElement, key: string, plan: Plan, keyframes: ReadonlyArray<Keyframe>, alone: (values: Readonly<Record<string, unknown>>) => boolean): TimelineValue => {
429
+ let animation: Animation | undefined
430
+ let reversed = false
431
+ let sizes: ResizeObserver | undefined
432
+ const animate = (): void => {
433
+ reversed = plan.reversed()
434
+ const options: KeyframeAnimationOptions = {
435
+ timeline: plan.nativeTimeline(),
436
+ fill: "both",
437
+ direction: Bool.match(reversed, { onTrue: () => "reverse", onFalse: () => "normal" }),
438
+ }
439
+ // Reversed, its range runs from the second stop to the first, with progress played backwards (Motion's).
440
+ if (Option.isSome(plan.range)) {
441
+ const [start, end] = plan.range.value
442
+ options.rangeStart = Bool.match(reversed, { onTrue: () => end, onFalse: () => start })
443
+ options.rangeEnd = Bool.match(reversed, { onTrue: () => start, onFalse: () => end })
444
+ }
445
+ animation = element.animate(keyframes as Array<Keyframe>, options)
446
+ }
447
+ /** A resize that flips its direction starts it again, the other way. */
448
+ const recheck = (): void => {
449
+ if (Predicate.isUndefined(animation)) return
450
+ if (plan.reversed() === reversed) return
451
+ animation.cancel()
452
+ animate()
453
+ }
454
+ const start = (): void => {
455
+ animate()
456
+ if (plan.watchesWindow) window.addEventListener("resize", recheck)
457
+ if (Arr.isReadonlyArrayEmpty(plan.watch)) return
458
+ const watch = new ResizeObserver(recheck)
459
+ Arr.forEach(plan.watch, (box) => watch.observe(box))
460
+ sizes = watch
461
+ }
462
+ const cancel = (): void => {
463
+ if (Predicate.isNotUndefined(sizes)) sizes.disconnect()
464
+ sizes = undefined
465
+ if (plan.watchesWindow) window.removeEventListener("resize", recheck)
466
+ if (Predicate.isNotUndefined(animation)) animation.cancel()
467
+ animation = undefined
468
+ }
469
+ return {
470
+ key,
471
+ sync: (values) => {
472
+ if (alone(values)) {
473
+ if (Predicate.isUndefined(animation)) start()
474
+ return
475
+ }
476
+ if (Predicate.isNotUndefined(animation)) cancel()
477
+ },
478
+ cancel,
479
+ }
480
+ }