@motionscript/grids 0.1.0-alpha.7 → 0.1.0-alpha.9

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 (63) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/LICENSE +201 -201
  3. package/NOTICE +49 -48
  4. package/README.md +118 -118
  5. package/dist/browser/chunks/{chunk-J62D7EFZ.js → chunk-TYNFMZ3D.js} +1 -1
  6. package/dist/browser/chunks/chunk-TYNFMZ3D.js.map +7 -0
  7. package/dist/browser/index.js +1 -1
  8. package/dist/browser/index.js.map +1 -1
  9. package/dist/browser/kit.js +1 -1
  10. package/dist/browser/manifest.json +1 -1
  11. package/dist/engine.d.ts +1 -1
  12. package/dist/engine.js +1 -1
  13. package/dist/engine.js.map +1 -1
  14. package/dist/index.js.map +1 -1
  15. package/dist/kit/index.js.map +1 -1
  16. package/dist/kit/item-effects.js.map +1 -1
  17. package/dist/kit/item-grid.js.map +1 -1
  18. package/dist/kit/order.js.map +1 -1
  19. package/dist/kit/random.js.map +1 -1
  20. package/dist/kit/slots/index.js.map +1 -1
  21. package/dist/kit/slots/path-templates.js.map +1 -1
  22. package/dist/kit/slots/path.js.map +1 -1
  23. package/dist/kit/slots/radial.js.map +1 -1
  24. package/dist/kit/slots/rectangular.js.map +1 -1
  25. package/dist/kit/slots/slot.js.map +1 -1
  26. package/dist/kit/slots/sphere.js.map +1 -1
  27. package/dist/kit/stagger.js.map +1 -1
  28. package/dist/nodes.js.map +1 -1
  29. package/dist/path-grid/index.js.map +1 -1
  30. package/dist/path-grid/path-grid.js.map +1 -1
  31. package/dist/radial-grid/index.js.map +1 -1
  32. package/dist/radial-grid/radial-grid.js.map +1 -1
  33. package/dist/rectangular-grid/index.js.map +1 -1
  34. package/dist/rectangular-grid/rectangular-grid.js.map +1 -1
  35. package/dist/sphere-grid/index.js.map +1 -1
  36. package/dist/sphere-grid/sphere-grid.js.map +1 -1
  37. package/package.json +5 -4
  38. package/registry.json +32 -32
  39. package/src/engine.ts +12 -12
  40. package/src/index.ts +6 -6
  41. package/src/kit/index.ts +18 -18
  42. package/src/kit/item-effects.ts +114 -114
  43. package/src/kit/item-grid.ts +648 -648
  44. package/src/kit/order.ts +41 -41
  45. package/src/kit/random.ts +29 -29
  46. package/src/kit/slots/index.ts +39 -39
  47. package/src/kit/slots/path-templates.ts +120 -120
  48. package/src/kit/slots/path.ts +120 -120
  49. package/src/kit/slots/radial.ts +62 -62
  50. package/src/kit/slots/rectangular.ts +108 -108
  51. package/src/kit/slots/slot.ts +82 -82
  52. package/src/kit/slots/sphere.ts +94 -94
  53. package/src/kit/stagger.ts +96 -96
  54. package/src/nodes.ts +30 -30
  55. package/src/path-grid/index.ts +1 -1
  56. package/src/path-grid/path-grid.ts +186 -186
  57. package/src/radial-grid/index.ts +1 -1
  58. package/src/radial-grid/radial-grid.ts +81 -81
  59. package/src/rectangular-grid/index.ts +1 -1
  60. package/src/rectangular-grid/rectangular-grid.ts +145 -145
  61. package/src/sphere-grid/index.ts +1 -1
  62. package/src/sphere-grid/sphere-grid.ts +129 -129
  63. package/dist/browser/chunks/chunk-J62D7EFZ.js.map +0 -7
@@ -1,648 +1,648 @@
1
- import {
2
- commandsFor,
3
- easeIn,
4
- easeInOut,
5
- easeOut,
6
- flowOps,
7
- insetsOps,
8
- Types,
9
- type ChildView,
10
- type InsetsResolved,
11
- type LayoutBox,
12
- type LayoutItem,
13
- type Measurer,
14
- type Node2D,
15
- type NodeFrame,
16
- type NodeView,
17
- type Piece,
18
- type Placement2D,
19
- type RenderContext,
20
- type Size2D,
21
- type SpaceCamera,
22
- type Timeline,
23
- type Values,
24
- } from "@motionscript/sdk"
25
-
26
- import {
27
- applyItemEffects,
28
- REVEAL_STYLES,
29
- WAVE_STYLES,
30
- type FocusState,
31
- type RevealState,
32
- type WaveState,
33
- } from "./item-effects"
34
- import { normalizeOrder, parseOrder, slotOfItem } from "./order"
35
- import { hashSeed, shuffled } from "./random"
36
- import { blendSlot, focalLengthOf, slotsOf, spreadSlot, type Arrangement, type Slot } from "./slots"
37
- import { STAGGER_ORDERS, staggerProgress, staggerRanks, type StaggerOrder } from "./stagger"
38
-
39
- /**
40
- * What every grid is built from: a container that places each of its children
41
- * in a slot of an arrangement — a rectangular grid, a ring, a path, a sphere.
42
- * Spread `state` and `commands` in, take `defaults`, hand `fields` the
43
- * {@link Arranger} that makes this grid's arrangement from its state, and pass
44
- * the finished component and its arranger through {@link define}.
45
- *
46
- * ## Children only
47
- *
48
- * The items are the children, in layer order. A child's slot is a parent
49
- * transform on it, so its own `x`/`y`/`rotation`/`scale` — and any command on
50
- * them — still work, relative to the slot. A group is one item; a grid of
51
- * grids is a grid of items that happen to be grids.
52
- *
53
- * ## One pass
54
- *
55
- * Every frame: measure the children, ask the arrangement for its slots (a pure
56
- * function of the state, the sizes and the clock), blend them from where a
57
- * transition is leaving, and layer on the per-item effects — reveal, wave,
58
- * focus. What is left is each child's box and slot, which the renderer,
59
- * picking and `global` all read, so a selection outline lands on the pixels
60
- * even on a sphere.
61
- *
62
- * ## Commands
63
- *
64
- * Every command is a pure function of time. The per-item ones stagger *inside*
65
- * their duration — a one-second reveal takes one second for four children or
66
- * four hundred — and write their per-item state into entries
67
- * (`revealState` and its siblings), which is what keeps them seekable. The ones
68
- * that change the arrangement itself (a reorder, a morph, a column count) keep
69
- * the arrangement they are leaving as data and blend each item from its old
70
- * slot to its new one.
71
- */
72
-
73
- /** An arrangement a grid is leaving, kept as data so its slots can be worked out afresh every frame. */
74
- export interface GridSnapshot {
75
- arrangement: Arrangement
76
- /** The grid the arrangement was borrowed from, or `""` for the grid's own. */
77
- source: string
78
- order: readonly number[]
79
- spread: number
80
- }
81
-
82
- /** A change of arrangement under way: where the items are coming from, and how far each has come. */
83
- export interface GridTransition {
84
- from: GridSnapshot
85
- /** Each item's eased, staggered progress, `0..1`. */
86
- mix: readonly number[]
87
- }
88
-
89
- /** The stagger options every per-item command takes. */
90
- export interface StaggerArgs {
91
- staggerOrder?: StaggerOrder
92
- /** `0..0.95`: how much of the command's length the items' offsets take up. */
93
- stagger?: number
94
- }
95
-
96
- /**
97
- * Every grid's document key — what a reference to "another grid" may name. A
98
- * `nodeRef` descriptor carries it as `nodeTypes`, for a host's picker to offer
99
- * only those.
100
- */
101
- export const ITEM_GRID_TYPES = ["rectangularGrid", "radialGrid", "pathGrid", "sphereGrid"] as const
102
-
103
- /** The stagger a move to new slots takes when its command states none. */
104
- export const TRANSITION_STAGGER = 0.3
105
-
106
- /** A reference to another node, a host's picker offering only `types`. Its fields read a view of it. */
107
- export function nodeRef(types: readonly string[]) {
108
- const described = { kind: "nodeRef", nodeTypes: types, animatable: false }
109
- return Types.custom<string, NodeView | null>("", described)
110
- }
111
-
112
- /** The stagger args every per-item command takes, `stagger` defaulting to `fallback`. */
113
- export function staggerArgs(fallback: number) {
114
- return {
115
- staggerOrder: Types.oneOf(STAGGER_ORDERS, { default: "index" }),
116
- stagger: Types.number(fallback, { min: 0, max: 0.95, step: 0.05 }),
117
- }
118
- }
119
-
120
- /**
121
- * A command arg a host fills in with `hint`, which a row may leave out: the
122
- * command then keeps what the grid has. A run arg's default is both what a
123
- * host offers and what an omitted arg means, so the hint rides on the arg's
124
- * description alone, and an omitted arg reads `undefined`.
125
- */
126
- export function hinted<T extends number | string>(hint: T, options: object = {}) {
127
- const described: Record<string, unknown> = { ...options, default: hint }
128
- return Types.custom<T | undefined>(undefined, described as never)
129
- }
130
-
131
- /** A command arg naming another node, a host's picker offering only `types`; left out, it reads `undefined`. */
132
- export function nodeRefArg(types: readonly string[]) {
133
- const described = { kind: "nodeRef", nodeTypes: types }
134
- return Types.custom<string | undefined>(undefined, described)
135
- }
136
-
137
- /** The state every grid shares. */
138
- export const state = {
139
- /** Items in slot order: slot `k` holds child `order[k]`. Empty is the children's own order. */
140
- order: Types.custom<number[]>([], { kind: "order", animatable: false }),
141
- /** `0` gathers every item at the centre, `1` is the arrangement, past `1` pushes them apart. */
142
- spread: Types.number(1, { min: 0, max: 3, step: 0.05 }),
143
- /** Another grid whose arrangement this one takes on — what `morphInto` animates. */
144
- arrangeLike: nodeRef(ITEM_GRID_TYPES),
145
- // What the per-item commands write. State rather than settings: a command
146
- // owns each while it runs, and a document has no reason to name them. Unset
147
- // until a command writes one, so a fresh node's row does not state them.
148
- revealState: Types.custom<RevealState | null | undefined>(undefined, { kind: "state", animatable: false }),
149
- waveState: Types.custom<WaveState | null | undefined>(undefined, { kind: "state", animatable: false }),
150
- focusState: Types.custom<FocusState | null | undefined>(undefined, { kind: "state", animatable: false }),
151
- transition: Types.custom<GridTransition | null | undefined>(undefined, { kind: "state", animatable: false }),
152
- /** The grid a transition's leaving arrangement was borrowed from, followed while the items travel. */
153
- transitionSource: Types.custom<string, NodeView | null, { readonly private: true }>("", { kind: "nodeRef", private: true }),
154
- }
155
-
156
- /** A grid's size is what its items come to, whether it was built with children or they arrive after it. */
157
- export const defaults = { width: "hug", height: "hug" } as const
158
-
159
- /** What a grid's commands read of its state, beyond its own arrangement's entries. */
160
- export type GridValues = Values<typeof state> & { readonly padding: InsetsResolved }
161
-
162
- /** What a grid's measure, layout and render read of its state, beyond its own arrangement's entries. */
163
- export type GridState = GridValues & {
164
- readonly width: LayoutItem["width"]
165
- readonly height: LayoutItem["height"]
166
- readonly children: readonly ChildView[]
167
- }
168
-
169
- /** What makes one grid's arrangement from its state: the rest of a grid is this module. */
170
- export interface Arranger<S = unknown> {
171
- /** This grid's own arrangement, for a content box of `box`. */
172
- arrangement(state: S, box: Size2D): Arrangement
173
- /** The room each item is measured in — the whole content box, unless the arrangement has cells. */
174
- itemSpace?(state: S, count: number, space: Size2D): Size2D
175
- }
176
-
177
- type GridComponent = { readonly key: string; readonly node: abstract new (...args: never[]) => object }
178
-
179
- const GRIDS = new Map<string, { readonly component: GridComponent; readonly arranger: Arranger<never> }>()
180
-
181
- /**
182
- * `component` as a grid: registers its `arranger`, which another grid borrowing
183
- * its arrangement or morphing into it reads it by, and which {@link isGrid} knows it by.
184
- */
185
- export function define<C extends GridComponent, S>(component: C, arranger: Arranger<S>): C {
186
- GRIDS.set(component.key, { component, arranger: arranger as Arranger<never> })
187
- return component
188
- }
189
-
190
- /** Whether `value` is a node of one of the grids {@link define} has seen. */
191
- export function isGrid(value: unknown): boolean {
192
- for (const { component } of GRIDS.values()) if (value instanceof component.node) return true
193
- return false
194
- }
195
-
196
- /** The grid's measure, layout and render, for `arranger`'s arrangement: spread them into the component. */
197
- export function fields<S>(arranger: Arranger<S>) {
198
- return {
199
- measure: (measurer: Measurer, s: GridState & S, children: readonly ChildView[]) => measure(measurer, s, children, arranger),
200
- layout: (box: LayoutBox, s: GridState & S, children: readonly ChildView[]) => layout(box, s, children, arranger),
201
- render: (ctx: RenderContext, s: GridState & S) => render(ctx, s, arranger),
202
- }
203
- }
204
-
205
- const NO_CONTENT: Size2D = { width: 0, height: 0 }
206
- const CENTRE = { x: 0, y: 0 }
207
-
208
- /** What `measure` found, for `layout` to reuse in the same pass. Keyed by the grid's state, one object per node. */
209
- const measured = new WeakMap<object, { space: Size2D; sizes: Size2D[] }>()
210
-
211
- export function measure<S>(measurer: Measurer, s: GridState & S, children: readonly ChildView[], arranger: Arranger<S>): Size2D {
212
- const constraints = { maxWidth: measurer.max.width, maxHeight: measurer.max.height }
213
- const padding = s.padding
214
- if (children.length === 0) {
215
- measured.delete(s)
216
- return flowOps.size(s, constraints, padding, NO_CONTENT)
217
- }
218
- const space = flowOps.contentBox(s, constraints, padding)
219
- const sizes = measureItems(children, space, s, arranger)
220
- measured.set(s, { space, sizes })
221
- const grid = { state: s, arranger, children, isSelf: sharesChildren(children) }
222
- const target = targetSlots(grid, sizes.length, sizes, space, measurer.time.total)
223
- return flowOps.size(s, constraints, padding, extentOf(target.slots, sizes, focalOf(s, target.arrangement)))
224
- }
225
-
226
- export function layout<S>(box: LayoutBox, s: GridState & S, children: readonly ChildView[], arranger: Arranger<S>): readonly Placement2D[] {
227
- const kept = measured.get(s)
228
- measured.delete(s)
229
- if (children.length === 0) return []
230
- const inner = insetsOps.insetBounds(box.width, box.height, s.padding)
231
- const sizes = kept && kept.sizes.length === children.length && sameSize(kept.space, inner)
232
- ? kept.sizes
233
- : measureItems(children, inner, s, arranger)
234
- const slots = resolve({ state: s, arranger, children, isSelf: sharesChildren(children) }, sizes, inner, box.time.total)
235
- return slots.map((slot, i) => placement(inner, slot, sizes[i]))
236
- }
237
-
238
- /**
239
- * A grid whose arrangement has depth is seen through a camera of its own,
240
- * which paints its items far to near — unless it already sits in a space (an
241
- * orbit camera, a 3D stage), where its items join that one and its camera.
242
- */
243
- export function render<S>(ctx: RenderContext, s: GridState & S, arranger: Arranger<S>): void {
244
- // With no items there is nothing to see through a camera.
245
- const focal = s.children.length === 0 ? 0 : focalOf(s, arrangementOf({ state: s, arranger, children: [], isSelf: () => false }, contentBox(ctx.size, s.padding)))
246
- if (focal > 0 && !ctx.inSpace) ctx.space(cameraAt(focal))
247
- else ctx.children()
248
- }
249
-
250
- /** A node's content box: its laid-out size inside its padding. */
251
- export function contentBoxOf(grid: Node2D): Size2D {
252
- const b = grid.layoutBounds
253
- return contentBox({ width: b.width, height: b.height }, grid.effectivePadding())
254
- }
255
-
256
- // ---- what commands share --------------------------------------------------
257
-
258
- type GridTimeline = Timeline<StaggerArgs, never>
259
-
260
- /**
261
- * Each item's slot in its arrangement as it stands, for a command being built,
262
- * at the clock commands are built against (the tree stands at time 0 while a
263
- * timeline compiles): what its stagger is ranked by.
264
- */
265
- export function itemSlots(timeline: Timeline<object, never>, s: GridValues, children: readonly ChildView[]): Slot[] {
266
- const grid = commandGrid(timeline, s, children)
267
- const sizes = children.map((child) => child.size)
268
- return targetSlots(grid, children.length, sizes, contentBox(timeline.node.size, s.padding), 0).slots
269
- }
270
-
271
- /** Each item's start in a stagger. A random order is seeded by the node's id, so it never changes between builds. */
272
- export function ranks(timeline: Timeline<object, never>, s: GridValues, children: readonly ChildView[], order: StaggerOrder | undefined): number[] {
273
- return staggerRanks(order ?? "index", itemSlots(timeline, s, children), hashSeed(timeline.node.id))
274
- }
275
-
276
- /**
277
- * Write `changes` to the arrangement and move each item from its slot in the
278
- * one being left to its slot in the new one, staggered.
279
- */
280
- export function transitionTo(
281
- timeline: GridTimeline,
282
- s: GridValues,
283
- children: readonly ChildView[],
284
- changes: Record<string, unknown>,
285
- stagger = TRANSITION_STAGGER,
286
- ): Piece {
287
- const from = snapshot(timeline, s, children)
288
- const ease = timeline.easing ?? easeInOut("cubic")
289
- const order = ranks(timeline, s, children, timeline.args.staggerOrder)
290
- const spread = timeline.args.stagger ?? stagger
291
- return timeline.animate((t) => {
292
- if (t >= 1) return { ...changes, transition: null, transitionSource: "" } as never
293
- const mix = order.map((rank) => ease(staggerProgress(rank, t, spread)))
294
- return { ...changes, transition: { from, mix }, transitionSource: from.source } as never
295
- }, { eased: false })
296
- }
297
-
298
- /** Emphasise the items `isFocus` picks and push the rest back. */
299
- export function focusOn(
300
- timeline: Timeline<object, never>,
301
- s: GridValues,
302
- isFocus: (item: number) => boolean,
303
- count: number,
304
- dim: number,
305
- grow: number,
306
- ): Piece {
307
- const from = s.focusState
308
- const target = Array.from({ length: count }, (_, i) => (isFocus(i) ? 1 : -1))
309
- const ease = timeline.easing ?? easeInOut("cubic")
310
- return timeline.animate((t) => {
311
- const e = ease(t)
312
- return {
313
- focusState: {
314
- dim: lerp(from?.dim ?? dim, dim, e),
315
- grow: lerp(from?.grow ?? grow, grow, e),
316
- values: target.map((v, i) => lerp(from?.values[i] ?? 0, v, e)),
317
- },
318
- } as never
319
- }, { eased: false })
320
- }
321
-
322
- // What the commands are typed against: the shared state, and the padding every node has.
323
- const GRID_STATE = { ...state, padding: Types.insets }
324
-
325
- export const commands = commandsFor(GRID_STATE, {
326
- /**
327
- * Bring the items in, one after another. Every item starts hidden, so place
328
- * it where the grid enters — or after a `conceal`.
329
- */
330
- reveal: {
331
- args: { style: Types.oneOf(REVEAL_STYLES, { default: "scale" }), ...staggerArgs(0.5) },
332
- run: (timeline, s, children) => {
333
- const style = timeline.args.style ?? "scale"
334
- const ease = timeline.easing ?? (style === "scale" || style === "flip" ? easeOut("back") : easeOut("cubic"))
335
- const order = ranks(timeline as never, s, children, timeline.args.staggerOrder)
336
- const stagger = timeline.args.stagger ?? 0.5
337
- return timeline.animate((t) => {
338
- if (t >= 1) return { revealState: null }
339
- return { revealState: { style, values: order.map((rank) => ease(staggerProgress(rank, t, stagger))) } }
340
- }, { eased: false })
341
- },
342
- },
343
- /** Take the items out, one after another — `reveal` in reverse. They stay hidden after. */
344
- conceal: {
345
- args: { style: Types.oneOf(REVEAL_STYLES, { default: "scale" }), ...staggerArgs(0.5) },
346
- run: (timeline, s, children) => {
347
- const style = timeline.args.style ?? "scale"
348
- const ease = timeline.easing ?? (style === "scale" || style === "flip" ? easeIn("back") : easeInOut("cubic"))
349
- const order = ranks(timeline as never, s, children, timeline.args.staggerOrder)
350
- const stagger = timeline.args.stagger ?? 0.5
351
- const from = s.revealState?.values
352
- return timeline.animate((t) => ({
353
- revealState: {
354
- style,
355
- values: order.map((rank, i) => (from?.[i] ?? 1) * (1 - ease(staggerProgress(rank, t, stagger)))),
356
- },
357
- }), { eased: false })
358
- },
359
- },
360
- /** Send a ripple through the items that swells each in turn and settles back. */
361
- wave: {
362
- args: {
363
- style: Types.oneOf(WAVE_STYLES, { default: "scale" }),
364
- amount: Types.number(0.3, { min: 0, max: 2, step: 0.05 }),
365
- ...staggerArgs(0.7),
366
- },
367
- run: (timeline, s, children) => {
368
- const style = timeline.args.style ?? "scale"
369
- const amount = timeline.args.amount ?? 0.3
370
- const ease = timeline.easing ?? easeInOut("sine")
371
- const order = ranks(timeline as never, s, children, timeline.args.staggerOrder)
372
- const stagger = timeline.args.stagger ?? 0.7
373
- return timeline.animate((t) => {
374
- if (t >= 1) return { waveState: null }
375
- return { waveState: { style, amount, values: order.map((rank) => Math.sin(Math.PI * ease(staggerProgress(rank, t, stagger)))) } }
376
- }, { eased: false })
377
- },
378
- },
379
- /** Bring one item (by its place in the layers, from 0) forward and push the rest back. */
380
- focus: {
381
- args: {
382
- item: Types.number(0, { min: 0, step: 1 }),
383
- dim: Types.number(0.7, { min: 0, max: 1, step: 0.05 }),
384
- grow: Types.number(0.15, { min: 0, max: 1, step: 0.05 }),
385
- },
386
- run: (timeline, s, children) => {
387
- const item = Math.round(timeline.args.item ?? 0)
388
- return focusOn(timeline as never, s, (i) => i === item, children.length, timeline.args.dim ?? 0.7, timeline.args.grow ?? 0.15)
389
- },
390
- },
391
- /** Bring every item back to even. */
392
- unfocus: (timeline, s) => {
393
- const from = s.focusState
394
- const ease = timeline.easing ?? easeInOut("cubic")
395
- return timeline.animate((t) => {
396
- if (t >= 1 || !from) return { focusState: null }
397
- const k = 1 - ease(t)
398
- return { focusState: { ...from, values: from.values.map((v) => v * k) } }
399
- }, { eased: false })
400
- },
401
- /** Gather the items toward the centre (`0`), back to the arrangement (`1`), or push them apart. */
402
- spreadTo: {
403
- args: { spread: Types.number(1, { min: 0, max: 3, step: 0.05 }) },
404
- run: (timeline) => timeline.tween({ spread: timeline.args.spread ?? 1 }),
405
- },
406
- /** Send every item to a random slot. The same `seed` always deals the same way. */
407
- shuffle: {
408
- args: { seed: Types.number(1, { min: 0, step: 1 }), ...staggerArgs(TRANSITION_STAGGER) },
409
- run: (timeline, s, children) => {
410
- const current = normalizeOrder(s.order, children.length)
411
- let next = shuffled(current, timeline.args.seed ?? 1)
412
- // A shuffle that deals everything back where it was would look like nothing happened.
413
- if (next.length > 1 && next.every((item, k) => item === current[k])) next = [...next.slice(1), next[0]]
414
- return transitionTo(timeline as never, s, children, { order: next })
415
- },
416
- },
417
- /** Two items trade places, by their place in the layers. */
418
- swap: {
419
- args: {
420
- first: Types.number(0, { min: 0, step: 1 }),
421
- second: Types.number(1, { min: 0, step: 1 }),
422
- ...staggerArgs(0),
423
- },
424
- run: (timeline, s, children) => {
425
- const order = normalizeOrder(s.order, children.length)
426
- const a = order.indexOf(Math.round(timeline.args.first ?? 0))
427
- const b = order.indexOf(Math.round(timeline.args.second ?? 1))
428
- if (a >= 0 && b >= 0) [order[a], order[b]] = [order[b], order[a]]
429
- return transitionTo(timeline as never, s, children, { order }, 0)
430
- },
431
- },
432
- /** Move the items into a new order — a list of layer indices, first slot first, like `"2, 0, 1"`. */
433
- reorder: {
434
- args: { order: Types.text(""), ...staggerArgs(TRANSITION_STAGGER) },
435
- run: (timeline, s, children) => {
436
- const order = normalizeOrder(parseOrder(timeline.args.order), children.length)
437
- return transitionTo(timeline as never, s, children, { order })
438
- },
439
- },
440
- /**
441
- * Move every item into another grid's arrangement — a grid into a ring, a ring
442
- * onto a sphere — and keep following it. An empty `target` morphs back to
443
- * this grid's own.
444
- */
445
- morphInto: {
446
- args: { target: nodeRefArg(ITEM_GRID_TYPES), ...staggerArgs(TRANSITION_STAGGER) },
447
- run: (timeline, s, children) => transitionTo(timeline as never, s, children, { arrangeLike: timeline.args.target ?? "" }),
448
- },
449
- })
450
-
451
- // ---- the one pass ------------------------------------------------------------
452
-
453
- interface Grid {
454
- readonly state: GridValues
455
- readonly arranger: Arranger<never>
456
- readonly children: readonly ChildView[]
457
- /** Whether a view is this grid itself, which borrows nothing from itself. */
458
- readonly isSelf: (view: NodeView) => boolean
459
- }
460
-
461
- function arrangerOf(key: string): Arranger<never> {
462
- const grid = GRIDS.get(key)
463
- if (!grid) throw new Error(`"${key}" is no grid: pass its component through ItemGrid.define.`)
464
- return grid.arranger
465
- }
466
-
467
- /** A grid `view` names, when it is one this kit can arrange and not the reader itself. */
468
- function gridIn(view: NodeView | null | undefined, grid: Grid): { view: NodeView; arranger: Arranger<never> } | null {
469
- if (!view) return null
470
- const found = GRIDS.get(view.key)
471
- if (!found || grid.isSelf(view)) return null
472
- return { view, arranger: found.arranger }
473
- }
474
-
475
- /** In layout, a view is this grid when it holds the same children: a child has one parent. */
476
- function sharesChildren(children: readonly ChildView[]): (view: NodeView) => boolean {
477
- return (view) => {
478
- if (children.length === 0) return false
479
- const theirs = (view.state as { readonly children?: readonly ChildView[] }).children
480
- return theirs?.[0] === children[0]
481
- }
482
- }
483
-
484
- function commandGrid(timeline: Timeline<object, never>, s: GridValues, children: readonly ChildView[]): Grid {
485
- return { state: s, arranger: arrangerOf(timeline.node.key), children, isSelf: (view) => view.id === timeline.node.id }
486
- }
487
-
488
- function snapshot(timeline: Timeline<object, never>, s: GridValues, children: readonly ChildView[]): GridSnapshot {
489
- const grid = commandGrid(timeline, s, children)
490
- const source = gridIn(s.arrangeLike, grid)
491
- return {
492
- arrangement: source
493
- ? source.arranger.arrangement(source.view.state as never, viewBox(source.view))
494
- : grid.arranger.arrangement(s as never, contentBox(timeline.node.size, s.padding)),
495
- source: source?.view.id ?? "",
496
- order: normalizeOrder(s.order, children.length),
497
- spread: s.spread,
498
- }
499
- }
500
-
501
- function measureItems(children: readonly ChildView[], space: Size2D, s: unknown, arranger: Arranger<never>): Size2D[] {
502
- const sizes = children.map((child) => child.measure(space))
503
- const cell = arranger.itemSpace ? arranger.itemSpace(s as never, children.length, space) : space
504
- if (cell === space) return sizes
505
- return children.map((child) => child.measure(cell))
506
- }
507
-
508
- /** The arrangement the grid is heading for: the one it borrows, or its own. */
509
- function arrangementOf(grid: Grid, box: Size2D): Arrangement {
510
- const source = gridIn(grid.state.arrangeLike, grid)
511
- return source ? source.arranger.arrangement(source.view.state as never, viewBox(source.view)) : grid.arranger.arrangement(grid.state as never, box)
512
- }
513
-
514
- /** Where each item sits in the arrangement it is heading for, before any transition or effect. */
515
- function targetSlots(grid: Grid, count: number, sizes: readonly Size2D[], box: Size2D, time: number): { slots: Slot[]; arrangement: Arrangement } {
516
- const s = grid.state
517
- const source = gridIn(s.arrangeLike, grid)
518
- const sourceBox = source ? viewBox(source.view) : box
519
- const arrangement = source ? source.arranger.arrangement(source.view.state as never, sourceBox) : grid.arranger.arrangement(s as never, box)
520
- let slots = slotsOf(arrangement, { count, sizes, box: sourceBox, time })
521
- if (source) slots = inFrame(source.view.frame, slots)
522
- const slotOf = slotOfItem(normalizeOrder(s.order, count))
523
- return { slots: slotOf.map((k) => spreadSlot(slots[k], s.spread)), arrangement }
524
- }
525
-
526
- /** Each item's final slot this frame: the target, blended from any transition, with its effects on. */
527
- function resolve(grid: Grid, sizes: readonly Size2D[], box: Size2D, time: number): Slot[] {
528
- const s = grid.state
529
- const count = sizes.length
530
- const slots = targetSlots(grid, count, sizes, box, time).slots
531
- const transition = s.transition
532
- if (transition) {
533
- const { from } = transition
534
- const named = from.source ? s.transitionSource : null
535
- const source = named && named.id === from.source && GRIDS.has(named.key) ? named : null
536
- const self = source !== null && grid.isSelf(source)
537
- const fromBox = source && !self ? viewBox(source) : box
538
- let leaving = slotsOf(from.arrangement, { count, sizes, box: fromBox, time })
539
- if (source && !self) leaving = inFrame(source.frame, leaving)
540
- const slotOf = slotOfItem(normalizeOrder(from.order, count))
541
- for (let i = 0; i < count; i++) {
542
- slots[i] = blendSlot(spreadSlot(leaving[slotOf[i]], from.spread), slots[i], transition.mix[i] ?? 1)
543
- }
544
- }
545
- const reveal = s.revealState
546
- const wave = s.waveState
547
- const focus = s.focusState
548
- if (reveal || wave || focus) {
549
- for (let i = 0; i < count; i++) applyItemEffects(slots[i], i, sizes[i], reveal, wave, focus)
550
- }
551
- return slots
552
- }
553
-
554
- /** The camera distance the grid is seen through: the target's, or, while a morph runs, the one it is leaving. */
555
- function focalOf(s: GridValues, target: Arrangement): number {
556
- // A morph into or out of depth keeps the camera for its whole length.
557
- return focalLengthOf(target) || (s.transition ? focalLengthOf(s.transition.from.arrangement) : 0)
558
- }
559
-
560
- function cameraAt(focal: number): SpaceCamera {
561
- return {
562
- perspective: focal,
563
- orbit: 0,
564
- elevation: 0,
565
- dolly: 0,
566
- lookAt: CENTRE,
567
- zoom: 1,
568
- heading: 0,
569
- viewportX: 0,
570
- viewportY: 0,
571
- }
572
- }
573
-
574
- /** A slot as a child's placement: its box centred on the slot, and the slot's transform when it has one. */
575
- function placement(inner: { x: number; y: number }, s: Slot, size: Size2D): Placement2D {
576
- const box = { x: inner.x + s.x, y: s.y - inner.y, width: size.width, height: size.height }
577
- if (s.rotation === 0 && s.scale === 1 && s.rotationX === 0 && s.rotationY === 0 && s.depth === 0 && s.opacity === 1) return box
578
- return {
579
- ...box,
580
- rotation: s.rotation,
581
- scale: s.scale,
582
- rotationX: s.rotationX,
583
- rotationY: s.rotationY,
584
- depth: s.depth,
585
- opacity: s.opacity,
586
- }
587
- }
588
-
589
- /** `slots`, laid out in another grid's frame, moved into this grid's. */
590
- function inFrame(frame: NodeFrame, slots: Slot[]): Slot[] {
591
- return slots.map((s) => {
592
- const p = rotateClockwise(s.x * frame.scale, s.y * frame.scale, frame.rotation)
593
- return {
594
- ...s,
595
- x: frame.x + p.x,
596
- y: frame.y + p.y,
597
- depth: s.depth * frame.scale,
598
- rotation: s.rotation + frame.rotation,
599
- scale: s.scale * frame.scale,
600
- }
601
- })
602
- }
603
-
604
- function viewBox(view: NodeView): Size2D {
605
- return contentBox(view.size, (view.state as { readonly padding: InsetsResolved }).padding)
606
- }
607
-
608
- /** A box of `size` inside `padding`: what a command reads as its grid's content box from `timeline.node.size`. */
609
- export function contentBox(size: Size2D, padding: InsetsResolved): Size2D {
610
- const inner = insetsOps.insetBounds(size.width, size.height, padding)
611
- return { width: inner.width, height: inner.height }
612
- }
613
-
614
- /** The box, centred on the grid, that holds every item where its slot puts it. */
615
- function extentOf(slots: readonly Slot[], sizes: readonly Size2D[], focal: number): Size2D {
616
- let halfWidth = 0
617
- let halfHeight = 0
618
- for (let i = 0; i < slots.length; i++) {
619
- const s = slots[i]
620
- const size = sizes[i]
621
- const rad = (s.rotation * Math.PI) / 180
622
- const cos = Math.abs(Math.cos(rad))
623
- const sin = Math.abs(Math.sin(rad))
624
- // What the camera does to a slot at depth, so a sphere hugs its front.
625
- const lens = focal > 0 && focal - s.depth > 1 ? focal / (focal - s.depth) : 1
626
- const w = ((size.width * cos + size.height * sin) / 2) * s.scale * lens
627
- const h = ((size.width * sin + size.height * cos) / 2) * s.scale * lens
628
- halfWidth = Math.max(halfWidth, Math.abs(s.x) * lens + w)
629
- halfHeight = Math.max(halfHeight, Math.abs(s.y) * lens + h)
630
- }
631
- return { width: halfWidth * 2, height: halfHeight * 2 }
632
- }
633
-
634
- function rotateClockwise(x: number, y: number, degrees: number): { x: number; y: number } {
635
- if (degrees === 0) return { x, y }
636
- const rad = (degrees * Math.PI) / 180
637
- const cos = Math.cos(rad)
638
- const sin = Math.sin(rad)
639
- return { x: x * cos + y * sin, y: -x * sin + y * cos }
640
- }
641
-
642
- function sameSize(a: Size2D, b: Size2D): boolean {
643
- return Math.abs(a.width - b.width) < 1e-6 && Math.abs(a.height - b.height) < 1e-6
644
- }
645
-
646
- function lerp(a: number, b: number, t: number): number {
647
- return a + (b - a) * t
648
- }
1
+ import {
2
+ commandsFor,
3
+ easeIn,
4
+ easeInOut,
5
+ easeOut,
6
+ flowOps,
7
+ insetsOps,
8
+ Types,
9
+ type ChildView,
10
+ type InsetsResolved,
11
+ type LayoutBox,
12
+ type LayoutItem,
13
+ type Measurer,
14
+ type Node2D,
15
+ type NodeFrame,
16
+ type NodeView,
17
+ type Piece,
18
+ type Placement2D,
19
+ type RenderContext,
20
+ type Size2D,
21
+ type SpaceCamera,
22
+ type Timeline,
23
+ type Values,
24
+ } from "@motionscript/sdk"
25
+
26
+ import {
27
+ applyItemEffects,
28
+ REVEAL_STYLES,
29
+ WAVE_STYLES,
30
+ type FocusState,
31
+ type RevealState,
32
+ type WaveState,
33
+ } from "./item-effects"
34
+ import { normalizeOrder, parseOrder, slotOfItem } from "./order"
35
+ import { hashSeed, shuffled } from "./random"
36
+ import { blendSlot, focalLengthOf, slotsOf, spreadSlot, type Arrangement, type Slot } from "./slots"
37
+ import { STAGGER_ORDERS, staggerProgress, staggerRanks, type StaggerOrder } from "./stagger"
38
+
39
+ /**
40
+ * What every grid is built from: a container that places each of its children
41
+ * in a slot of an arrangement — a rectangular grid, a ring, a path, a sphere.
42
+ * Spread `state` and `commands` in, take `defaults`, hand `fields` the
43
+ * {@link Arranger} that makes this grid's arrangement from its state, and pass
44
+ * the finished component and its arranger through {@link define}.
45
+ *
46
+ * ## Children only
47
+ *
48
+ * The items are the children, in layer order. A child's slot is a parent
49
+ * transform on it, so its own `x`/`y`/`rotation`/`scale` — and any command on
50
+ * them — still work, relative to the slot. A group is one item; a grid of
51
+ * grids is a grid of items that happen to be grids.
52
+ *
53
+ * ## One pass
54
+ *
55
+ * Every frame: measure the children, ask the arrangement for its slots (a pure
56
+ * function of the state, the sizes and the clock), blend them from where a
57
+ * transition is leaving, and layer on the per-item effects — reveal, wave,
58
+ * focus. What is left is each child's box and slot, which the renderer,
59
+ * picking and `global` all read, so a selection outline lands on the pixels
60
+ * even on a sphere.
61
+ *
62
+ * ## Commands
63
+ *
64
+ * Every command is a pure function of time. The per-item ones stagger *inside*
65
+ * their duration — a one-second reveal takes one second for four children or
66
+ * four hundred — and write their per-item state into entries
67
+ * (`revealState` and its siblings), which is what keeps them seekable. The ones
68
+ * that change the arrangement itself (a reorder, a morph, a column count) keep
69
+ * the arrangement they are leaving as data and blend each item from its old
70
+ * slot to its new one.
71
+ */
72
+
73
+ /** An arrangement a grid is leaving, kept as data so its slots can be worked out afresh every frame. */
74
+ export interface GridSnapshot {
75
+ arrangement: Arrangement
76
+ /** The grid the arrangement was borrowed from, or `""` for the grid's own. */
77
+ source: string
78
+ order: readonly number[]
79
+ spread: number
80
+ }
81
+
82
+ /** A change of arrangement under way: where the items are coming from, and how far each has come. */
83
+ export interface GridTransition {
84
+ from: GridSnapshot
85
+ /** Each item's eased, staggered progress, `0..1`. */
86
+ mix: readonly number[]
87
+ }
88
+
89
+ /** The stagger options every per-item command takes. */
90
+ export interface StaggerArgs {
91
+ staggerOrder?: StaggerOrder
92
+ /** `0..0.95`: how much of the command's length the items' offsets take up. */
93
+ stagger?: number
94
+ }
95
+
96
+ /**
97
+ * Every grid's document key — what a reference to "another grid" may name. A
98
+ * `nodeRef` descriptor carries it as `nodeTypes`, for a host's picker to offer
99
+ * only those.
100
+ */
101
+ export const ITEM_GRID_TYPES = ["rectangularGrid", "radialGrid", "pathGrid", "sphereGrid"] as const
102
+
103
+ /** The stagger a move to new slots takes when its command states none. */
104
+ export const TRANSITION_STAGGER = 0.3
105
+
106
+ /** A reference to another node, a host's picker offering only `types`. Its fields read a view of it. */
107
+ export function nodeRef(types: readonly string[]) {
108
+ const described = { kind: "nodeRef", nodeTypes: types, animatable: false }
109
+ return Types.custom<string, NodeView | null>("", described)
110
+ }
111
+
112
+ /** The stagger args every per-item command takes, `stagger` defaulting to `fallback`. */
113
+ export function staggerArgs(fallback: number) {
114
+ return {
115
+ staggerOrder: Types.oneOf(STAGGER_ORDERS, { default: "index" }),
116
+ stagger: Types.number(fallback, { min: 0, max: 0.95, step: 0.05 }),
117
+ }
118
+ }
119
+
120
+ /**
121
+ * A command arg a host fills in with `hint`, which a row may leave out: the
122
+ * command then keeps what the grid has. A run arg's default is both what a
123
+ * host offers and what an omitted arg means, so the hint rides on the arg's
124
+ * description alone, and an omitted arg reads `undefined`.
125
+ */
126
+ export function hinted<T extends number | string>(hint: T, options: object = {}) {
127
+ const described: Record<string, unknown> = { ...options, default: hint }
128
+ return Types.custom<T | undefined>(undefined, described as never)
129
+ }
130
+
131
+ /** A command arg naming another node, a host's picker offering only `types`; left out, it reads `undefined`. */
132
+ export function nodeRefArg(types: readonly string[]) {
133
+ const described = { kind: "nodeRef", nodeTypes: types }
134
+ return Types.custom<string | undefined>(undefined, described)
135
+ }
136
+
137
+ /** The state every grid shares. */
138
+ export const state = {
139
+ /** Items in slot order: slot `k` holds child `order[k]`. Empty is the children's own order. */
140
+ order: Types.custom<number[]>([], { kind: "order", animatable: false }),
141
+ /** `0` gathers every item at the centre, `1` is the arrangement, past `1` pushes them apart. */
142
+ spread: Types.number(1, { min: 0, max: 3, step: 0.05 }),
143
+ /** Another grid whose arrangement this one takes on — what `morphInto` animates. */
144
+ arrangeLike: nodeRef(ITEM_GRID_TYPES),
145
+ // What the per-item commands write. State rather than settings: a command
146
+ // owns each while it runs, and a document has no reason to name them. Unset
147
+ // until a command writes one, so a fresh node's row does not state them.
148
+ revealState: Types.custom<RevealState | null | undefined>(undefined, { kind: "state", animatable: false }),
149
+ waveState: Types.custom<WaveState | null | undefined>(undefined, { kind: "state", animatable: false }),
150
+ focusState: Types.custom<FocusState | null | undefined>(undefined, { kind: "state", animatable: false }),
151
+ transition: Types.custom<GridTransition | null | undefined>(undefined, { kind: "state", animatable: false }),
152
+ /** The grid a transition's leaving arrangement was borrowed from, followed while the items travel. */
153
+ transitionSource: Types.custom<string, NodeView | null, { readonly private: true }>("", { kind: "nodeRef", private: true }),
154
+ }
155
+
156
+ /** A grid's size is what its items come to, whether it was built with children or they arrive after it. */
157
+ export const defaults = { width: "hug", height: "hug" } as const
158
+
159
+ /** What a grid's commands read of its state, beyond its own arrangement's entries. */
160
+ export type GridValues = Values<typeof state> & { readonly padding: InsetsResolved }
161
+
162
+ /** What a grid's measure, layout and render read of its state, beyond its own arrangement's entries. */
163
+ export type GridState = GridValues & {
164
+ readonly width: LayoutItem["width"]
165
+ readonly height: LayoutItem["height"]
166
+ readonly children: readonly ChildView[]
167
+ }
168
+
169
+ /** What makes one grid's arrangement from its state: the rest of a grid is this module. */
170
+ export interface Arranger<S = unknown> {
171
+ /** This grid's own arrangement, for a content box of `box`. */
172
+ arrangement(state: S, box: Size2D): Arrangement
173
+ /** The room each item is measured in — the whole content box, unless the arrangement has cells. */
174
+ itemSpace?(state: S, count: number, space: Size2D): Size2D
175
+ }
176
+
177
+ type GridComponent = { readonly key: string; readonly node: abstract new (...args: never[]) => object }
178
+
179
+ const GRIDS = new Map<string, { readonly component: GridComponent; readonly arranger: Arranger<never> }>()
180
+
181
+ /**
182
+ * `component` as a grid: registers its `arranger`, which another grid borrowing
183
+ * its arrangement or morphing into it reads it by, and which {@link isGrid} knows it by.
184
+ */
185
+ export function define<C extends GridComponent, S>(component: C, arranger: Arranger<S>): C {
186
+ GRIDS.set(component.key, { component, arranger: arranger as Arranger<never> })
187
+ return component
188
+ }
189
+
190
+ /** Whether `value` is a node of one of the grids {@link define} has seen. */
191
+ export function isGrid(value: unknown): boolean {
192
+ for (const { component } of GRIDS.values()) if (value instanceof component.node) return true
193
+ return false
194
+ }
195
+
196
+ /** The grid's measure, layout and render, for `arranger`'s arrangement: spread them into the component. */
197
+ export function fields<S>(arranger: Arranger<S>) {
198
+ return {
199
+ measure: (measurer: Measurer, s: GridState & S, children: readonly ChildView[]) => measure(measurer, s, children, arranger),
200
+ layout: (box: LayoutBox, s: GridState & S, children: readonly ChildView[]) => layout(box, s, children, arranger),
201
+ render: (ctx: RenderContext, s: GridState & S) => render(ctx, s, arranger),
202
+ }
203
+ }
204
+
205
+ const NO_CONTENT: Size2D = { width: 0, height: 0 }
206
+ const CENTRE = { x: 0, y: 0 }
207
+
208
+ /** What `measure` found, for `layout` to reuse in the same pass. Keyed by the grid's state, one object per node. */
209
+ const measured = new WeakMap<object, { space: Size2D; sizes: Size2D[] }>()
210
+
211
+ export function measure<S>(measurer: Measurer, s: GridState & S, children: readonly ChildView[], arranger: Arranger<S>): Size2D {
212
+ const constraints = { maxWidth: measurer.max.width, maxHeight: measurer.max.height }
213
+ const padding = s.padding
214
+ if (children.length === 0) {
215
+ measured.delete(s)
216
+ return flowOps.size(s, constraints, padding, NO_CONTENT)
217
+ }
218
+ const space = flowOps.contentBox(s, constraints, padding)
219
+ const sizes = measureItems(children, space, s, arranger)
220
+ measured.set(s, { space, sizes })
221
+ const grid = { state: s, arranger, children, isSelf: sharesChildren(children) }
222
+ const target = targetSlots(grid, sizes.length, sizes, space, measurer.time.total)
223
+ return flowOps.size(s, constraints, padding, extentOf(target.slots, sizes, focalOf(s, target.arrangement)))
224
+ }
225
+
226
+ export function layout<S>(box: LayoutBox, s: GridState & S, children: readonly ChildView[], arranger: Arranger<S>): readonly Placement2D[] {
227
+ const kept = measured.get(s)
228
+ measured.delete(s)
229
+ if (children.length === 0) return []
230
+ const inner = insetsOps.insetBounds(box.width, box.height, s.padding)
231
+ const sizes = kept && kept.sizes.length === children.length && sameSize(kept.space, inner)
232
+ ? kept.sizes
233
+ : measureItems(children, inner, s, arranger)
234
+ const slots = resolve({ state: s, arranger, children, isSelf: sharesChildren(children) }, sizes, inner, box.time.total)
235
+ return slots.map((slot, i) => placement(inner, slot, sizes[i]))
236
+ }
237
+
238
+ /**
239
+ * A grid whose arrangement has depth is seen through a camera of its own,
240
+ * which paints its items far to near — unless it already sits in a space (an
241
+ * orbit camera, a 3D stage), where its items join that one and its camera.
242
+ */
243
+ export function render<S>(ctx: RenderContext, s: GridState & S, arranger: Arranger<S>): void {
244
+ // With no items there is nothing to see through a camera.
245
+ const focal = s.children.length === 0 ? 0 : focalOf(s, arrangementOf({ state: s, arranger, children: [], isSelf: () => false }, contentBox(ctx.size, s.padding)))
246
+ if (focal > 0 && !ctx.inSpace) ctx.space(cameraAt(focal))
247
+ else ctx.children()
248
+ }
249
+
250
+ /** A node's content box: its laid-out size inside its padding. */
251
+ export function contentBoxOf(grid: Node2D): Size2D {
252
+ const b = grid.layoutBounds
253
+ return contentBox({ width: b.width, height: b.height }, grid.effectivePadding())
254
+ }
255
+
256
+ // ---- what commands share --------------------------------------------------
257
+
258
+ type GridTimeline = Timeline<StaggerArgs, never>
259
+
260
+ /**
261
+ * Each item's slot in its arrangement as it stands, for a command being built,
262
+ * at the clock commands are built against (the tree stands at time 0 while a
263
+ * timeline compiles): what its stagger is ranked by.
264
+ */
265
+ export function itemSlots(timeline: Timeline<object, never>, s: GridValues, children: readonly ChildView[]): Slot[] {
266
+ const grid = commandGrid(timeline, s, children)
267
+ const sizes = children.map((child) => child.size)
268
+ return targetSlots(grid, children.length, sizes, contentBox(timeline.node.size, s.padding), 0).slots
269
+ }
270
+
271
+ /** Each item's start in a stagger. A random order is seeded by the node's id, so it never changes between builds. */
272
+ export function ranks(timeline: Timeline<object, never>, s: GridValues, children: readonly ChildView[], order: StaggerOrder | undefined): number[] {
273
+ return staggerRanks(order ?? "index", itemSlots(timeline, s, children), hashSeed(timeline.node.id))
274
+ }
275
+
276
+ /**
277
+ * Write `changes` to the arrangement and move each item from its slot in the
278
+ * one being left to its slot in the new one, staggered.
279
+ */
280
+ export function transitionTo(
281
+ timeline: GridTimeline,
282
+ s: GridValues,
283
+ children: readonly ChildView[],
284
+ changes: Record<string, unknown>,
285
+ stagger = TRANSITION_STAGGER,
286
+ ): Piece {
287
+ const from = snapshot(timeline, s, children)
288
+ const ease = timeline.easing ?? easeInOut("cubic")
289
+ const order = ranks(timeline, s, children, timeline.args.staggerOrder)
290
+ const spread = timeline.args.stagger ?? stagger
291
+ return timeline.animate((t) => {
292
+ if (t >= 1) return { ...changes, transition: null, transitionSource: "" } as never
293
+ const mix = order.map((rank) => ease(staggerProgress(rank, t, spread)))
294
+ return { ...changes, transition: { from, mix }, transitionSource: from.source } as never
295
+ }, { eased: false })
296
+ }
297
+
298
+ /** Emphasise the items `isFocus` picks and push the rest back. */
299
+ export function focusOn(
300
+ timeline: Timeline<object, never>,
301
+ s: GridValues,
302
+ isFocus: (item: number) => boolean,
303
+ count: number,
304
+ dim: number,
305
+ grow: number,
306
+ ): Piece {
307
+ const from = s.focusState
308
+ const target = Array.from({ length: count }, (_, i) => (isFocus(i) ? 1 : -1))
309
+ const ease = timeline.easing ?? easeInOut("cubic")
310
+ return timeline.animate((t) => {
311
+ const e = ease(t)
312
+ return {
313
+ focusState: {
314
+ dim: lerp(from?.dim ?? dim, dim, e),
315
+ grow: lerp(from?.grow ?? grow, grow, e),
316
+ values: target.map((v, i) => lerp(from?.values[i] ?? 0, v, e)),
317
+ },
318
+ } as never
319
+ }, { eased: false })
320
+ }
321
+
322
+ // What the commands are typed against: the shared state, and the padding every node has.
323
+ const GRID_STATE = { ...state, padding: Types.insets }
324
+
325
+ export const commands = commandsFor(GRID_STATE, {
326
+ /**
327
+ * Bring the items in, one after another. Every item starts hidden, so place
328
+ * it where the grid enters — or after a `conceal`.
329
+ */
330
+ reveal: {
331
+ args: { style: Types.oneOf(REVEAL_STYLES, { default: "scale" }), ...staggerArgs(0.5) },
332
+ run: (timeline, s, children) => {
333
+ const style = timeline.args.style ?? "scale"
334
+ const ease = timeline.easing ?? (style === "scale" || style === "flip" ? easeOut("back") : easeOut("cubic"))
335
+ const order = ranks(timeline as never, s, children, timeline.args.staggerOrder)
336
+ const stagger = timeline.args.stagger ?? 0.5
337
+ return timeline.animate((t) => {
338
+ if (t >= 1) return { revealState: null }
339
+ return { revealState: { style, values: order.map((rank) => ease(staggerProgress(rank, t, stagger))) } }
340
+ }, { eased: false })
341
+ },
342
+ },
343
+ /** Take the items out, one after another — `reveal` in reverse. They stay hidden after. */
344
+ conceal: {
345
+ args: { style: Types.oneOf(REVEAL_STYLES, { default: "scale" }), ...staggerArgs(0.5) },
346
+ run: (timeline, s, children) => {
347
+ const style = timeline.args.style ?? "scale"
348
+ const ease = timeline.easing ?? (style === "scale" || style === "flip" ? easeIn("back") : easeInOut("cubic"))
349
+ const order = ranks(timeline as never, s, children, timeline.args.staggerOrder)
350
+ const stagger = timeline.args.stagger ?? 0.5
351
+ const from = s.revealState?.values
352
+ return timeline.animate((t) => ({
353
+ revealState: {
354
+ style,
355
+ values: order.map((rank, i) => (from?.[i] ?? 1) * (1 - ease(staggerProgress(rank, t, stagger)))),
356
+ },
357
+ }), { eased: false })
358
+ },
359
+ },
360
+ /** Send a ripple through the items that swells each in turn and settles back. */
361
+ wave: {
362
+ args: {
363
+ style: Types.oneOf(WAVE_STYLES, { default: "scale" }),
364
+ amount: Types.number(0.3, { min: 0, max: 2, step: 0.05 }),
365
+ ...staggerArgs(0.7),
366
+ },
367
+ run: (timeline, s, children) => {
368
+ const style = timeline.args.style ?? "scale"
369
+ const amount = timeline.args.amount ?? 0.3
370
+ const ease = timeline.easing ?? easeInOut("sine")
371
+ const order = ranks(timeline as never, s, children, timeline.args.staggerOrder)
372
+ const stagger = timeline.args.stagger ?? 0.7
373
+ return timeline.animate((t) => {
374
+ if (t >= 1) return { waveState: null }
375
+ return { waveState: { style, amount, values: order.map((rank) => Math.sin(Math.PI * ease(staggerProgress(rank, t, stagger)))) } }
376
+ }, { eased: false })
377
+ },
378
+ },
379
+ /** Bring one item (by its place in the layers, from 0) forward and push the rest back. */
380
+ focus: {
381
+ args: {
382
+ item: Types.number(0, { min: 0, step: 1 }),
383
+ dim: Types.number(0.7, { min: 0, max: 1, step: 0.05 }),
384
+ grow: Types.number(0.15, { min: 0, max: 1, step: 0.05 }),
385
+ },
386
+ run: (timeline, s, children) => {
387
+ const item = Math.round(timeline.args.item ?? 0)
388
+ return focusOn(timeline as never, s, (i) => i === item, children.length, timeline.args.dim ?? 0.7, timeline.args.grow ?? 0.15)
389
+ },
390
+ },
391
+ /** Bring every item back to even. */
392
+ unfocus: (timeline, s) => {
393
+ const from = s.focusState
394
+ const ease = timeline.easing ?? easeInOut("cubic")
395
+ return timeline.animate((t) => {
396
+ if (t >= 1 || !from) return { focusState: null }
397
+ const k = 1 - ease(t)
398
+ return { focusState: { ...from, values: from.values.map((v) => v * k) } }
399
+ }, { eased: false })
400
+ },
401
+ /** Gather the items toward the centre (`0`), back to the arrangement (`1`), or push them apart. */
402
+ spreadTo: {
403
+ args: { spread: Types.number(1, { min: 0, max: 3, step: 0.05 }) },
404
+ run: (timeline) => timeline.tween({ spread: timeline.args.spread ?? 1 }),
405
+ },
406
+ /** Send every item to a random slot. The same `seed` always deals the same way. */
407
+ shuffle: {
408
+ args: { seed: Types.number(1, { min: 0, step: 1 }), ...staggerArgs(TRANSITION_STAGGER) },
409
+ run: (timeline, s, children) => {
410
+ const current = normalizeOrder(s.order, children.length)
411
+ let next = shuffled(current, timeline.args.seed ?? 1)
412
+ // A shuffle that deals everything back where it was would look like nothing happened.
413
+ if (next.length > 1 && next.every((item, k) => item === current[k])) next = [...next.slice(1), next[0]]
414
+ return transitionTo(timeline as never, s, children, { order: next })
415
+ },
416
+ },
417
+ /** Two items trade places, by their place in the layers. */
418
+ swap: {
419
+ args: {
420
+ first: Types.number(0, { min: 0, step: 1 }),
421
+ second: Types.number(1, { min: 0, step: 1 }),
422
+ ...staggerArgs(0),
423
+ },
424
+ run: (timeline, s, children) => {
425
+ const order = normalizeOrder(s.order, children.length)
426
+ const a = order.indexOf(Math.round(timeline.args.first ?? 0))
427
+ const b = order.indexOf(Math.round(timeline.args.second ?? 1))
428
+ if (a >= 0 && b >= 0) [order[a], order[b]] = [order[b], order[a]]
429
+ return transitionTo(timeline as never, s, children, { order }, 0)
430
+ },
431
+ },
432
+ /** Move the items into a new order — a list of layer indices, first slot first, like `"2, 0, 1"`. */
433
+ reorder: {
434
+ args: { order: Types.text(""), ...staggerArgs(TRANSITION_STAGGER) },
435
+ run: (timeline, s, children) => {
436
+ const order = normalizeOrder(parseOrder(timeline.args.order), children.length)
437
+ return transitionTo(timeline as never, s, children, { order })
438
+ },
439
+ },
440
+ /**
441
+ * Move every item into another grid's arrangement — a grid into a ring, a ring
442
+ * onto a sphere — and keep following it. An empty `target` morphs back to
443
+ * this grid's own.
444
+ */
445
+ morphInto: {
446
+ args: { target: nodeRefArg(ITEM_GRID_TYPES), ...staggerArgs(TRANSITION_STAGGER) },
447
+ run: (timeline, s, children) => transitionTo(timeline as never, s, children, { arrangeLike: timeline.args.target ?? "" }),
448
+ },
449
+ })
450
+
451
+ // ---- the one pass ------------------------------------------------------------
452
+
453
+ interface Grid {
454
+ readonly state: GridValues
455
+ readonly arranger: Arranger<never>
456
+ readonly children: readonly ChildView[]
457
+ /** Whether a view is this grid itself, which borrows nothing from itself. */
458
+ readonly isSelf: (view: NodeView) => boolean
459
+ }
460
+
461
+ function arrangerOf(key: string): Arranger<never> {
462
+ const grid = GRIDS.get(key)
463
+ if (!grid) throw new Error(`"${key}" is no grid: pass its component through ItemGrid.define.`)
464
+ return grid.arranger
465
+ }
466
+
467
+ /** A grid `view` names, when it is one this kit can arrange and not the reader itself. */
468
+ function gridIn(view: NodeView | null | undefined, grid: Grid): { view: NodeView; arranger: Arranger<never> } | null {
469
+ if (!view) return null
470
+ const found = GRIDS.get(view.key)
471
+ if (!found || grid.isSelf(view)) return null
472
+ return { view, arranger: found.arranger }
473
+ }
474
+
475
+ /** In layout, a view is this grid when it holds the same children: a child has one parent. */
476
+ function sharesChildren(children: readonly ChildView[]): (view: NodeView) => boolean {
477
+ return (view) => {
478
+ if (children.length === 0) return false
479
+ const theirs = (view.state as { readonly children?: readonly ChildView[] }).children
480
+ return theirs?.[0] === children[0]
481
+ }
482
+ }
483
+
484
+ function commandGrid(timeline: Timeline<object, never>, s: GridValues, children: readonly ChildView[]): Grid {
485
+ return { state: s, arranger: arrangerOf(timeline.node.key), children, isSelf: (view) => view.id === timeline.node.id }
486
+ }
487
+
488
+ function snapshot(timeline: Timeline<object, never>, s: GridValues, children: readonly ChildView[]): GridSnapshot {
489
+ const grid = commandGrid(timeline, s, children)
490
+ const source = gridIn(s.arrangeLike, grid)
491
+ return {
492
+ arrangement: source
493
+ ? source.arranger.arrangement(source.view.state as never, viewBox(source.view))
494
+ : grid.arranger.arrangement(s as never, contentBox(timeline.node.size, s.padding)),
495
+ source: source?.view.id ?? "",
496
+ order: normalizeOrder(s.order, children.length),
497
+ spread: s.spread,
498
+ }
499
+ }
500
+
501
+ function measureItems(children: readonly ChildView[], space: Size2D, s: unknown, arranger: Arranger<never>): Size2D[] {
502
+ const sizes = children.map((child) => child.measure(space))
503
+ const cell = arranger.itemSpace ? arranger.itemSpace(s as never, children.length, space) : space
504
+ if (cell === space) return sizes
505
+ return children.map((child) => child.measure(cell))
506
+ }
507
+
508
+ /** The arrangement the grid is heading for: the one it borrows, or its own. */
509
+ function arrangementOf(grid: Grid, box: Size2D): Arrangement {
510
+ const source = gridIn(grid.state.arrangeLike, grid)
511
+ return source ? source.arranger.arrangement(source.view.state as never, viewBox(source.view)) : grid.arranger.arrangement(grid.state as never, box)
512
+ }
513
+
514
+ /** Where each item sits in the arrangement it is heading for, before any transition or effect. */
515
+ function targetSlots(grid: Grid, count: number, sizes: readonly Size2D[], box: Size2D, time: number): { slots: Slot[]; arrangement: Arrangement } {
516
+ const s = grid.state
517
+ const source = gridIn(s.arrangeLike, grid)
518
+ const sourceBox = source ? viewBox(source.view) : box
519
+ const arrangement = source ? source.arranger.arrangement(source.view.state as never, sourceBox) : grid.arranger.arrangement(s as never, box)
520
+ let slots = slotsOf(arrangement, { count, sizes, box: sourceBox, time })
521
+ if (source) slots = inFrame(source.view.frame, slots)
522
+ const slotOf = slotOfItem(normalizeOrder(s.order, count))
523
+ return { slots: slotOf.map((k) => spreadSlot(slots[k], s.spread)), arrangement }
524
+ }
525
+
526
+ /** Each item's final slot this frame: the target, blended from any transition, with its effects on. */
527
+ function resolve(grid: Grid, sizes: readonly Size2D[], box: Size2D, time: number): Slot[] {
528
+ const s = grid.state
529
+ const count = sizes.length
530
+ const slots = targetSlots(grid, count, sizes, box, time).slots
531
+ const transition = s.transition
532
+ if (transition) {
533
+ const { from } = transition
534
+ const named = from.source ? s.transitionSource : null
535
+ const source = named && named.id === from.source && GRIDS.has(named.key) ? named : null
536
+ const self = source !== null && grid.isSelf(source)
537
+ const fromBox = source && !self ? viewBox(source) : box
538
+ let leaving = slotsOf(from.arrangement, { count, sizes, box: fromBox, time })
539
+ if (source && !self) leaving = inFrame(source.frame, leaving)
540
+ const slotOf = slotOfItem(normalizeOrder(from.order, count))
541
+ for (let i = 0; i < count; i++) {
542
+ slots[i] = blendSlot(spreadSlot(leaving[slotOf[i]], from.spread), slots[i], transition.mix[i] ?? 1)
543
+ }
544
+ }
545
+ const reveal = s.revealState
546
+ const wave = s.waveState
547
+ const focus = s.focusState
548
+ if (reveal || wave || focus) {
549
+ for (let i = 0; i < count; i++) applyItemEffects(slots[i], i, sizes[i], reveal, wave, focus)
550
+ }
551
+ return slots
552
+ }
553
+
554
+ /** The camera distance the grid is seen through: the target's, or, while a morph runs, the one it is leaving. */
555
+ function focalOf(s: GridValues, target: Arrangement): number {
556
+ // A morph into or out of depth keeps the camera for its whole length.
557
+ return focalLengthOf(target) || (s.transition ? focalLengthOf(s.transition.from.arrangement) : 0)
558
+ }
559
+
560
+ function cameraAt(focal: number): SpaceCamera {
561
+ return {
562
+ perspective: focal,
563
+ orbit: 0,
564
+ elevation: 0,
565
+ dolly: 0,
566
+ lookAt: CENTRE,
567
+ zoom: 1,
568
+ heading: 0,
569
+ viewportX: 0,
570
+ viewportY: 0,
571
+ }
572
+ }
573
+
574
+ /** A slot as a child's placement: its box centred on the slot, and the slot's transform when it has one. */
575
+ function placement(inner: { x: number; y: number }, s: Slot, size: Size2D): Placement2D {
576
+ const box = { x: inner.x + s.x, y: s.y - inner.y, width: size.width, height: size.height }
577
+ if (s.rotation === 0 && s.scale === 1 && s.rotationX === 0 && s.rotationY === 0 && s.depth === 0 && s.opacity === 1) return box
578
+ return {
579
+ ...box,
580
+ rotation: s.rotation,
581
+ scale: s.scale,
582
+ rotationX: s.rotationX,
583
+ rotationY: s.rotationY,
584
+ depth: s.depth,
585
+ opacity: s.opacity,
586
+ }
587
+ }
588
+
589
+ /** `slots`, laid out in another grid's frame, moved into this grid's. */
590
+ function inFrame(frame: NodeFrame, slots: Slot[]): Slot[] {
591
+ return slots.map((s) => {
592
+ const p = rotateClockwise(s.x * frame.scale, s.y * frame.scale, frame.rotation)
593
+ return {
594
+ ...s,
595
+ x: frame.x + p.x,
596
+ y: frame.y + p.y,
597
+ depth: s.depth * frame.scale,
598
+ rotation: s.rotation + frame.rotation,
599
+ scale: s.scale * frame.scale,
600
+ }
601
+ })
602
+ }
603
+
604
+ function viewBox(view: NodeView): Size2D {
605
+ return contentBox(view.size, (view.state as { readonly padding: InsetsResolved }).padding)
606
+ }
607
+
608
+ /** A box of `size` inside `padding`: what a command reads as its grid's content box from `timeline.node.size`. */
609
+ export function contentBox(size: Size2D, padding: InsetsResolved): Size2D {
610
+ const inner = insetsOps.insetBounds(size.width, size.height, padding)
611
+ return { width: inner.width, height: inner.height }
612
+ }
613
+
614
+ /** The box, centred on the grid, that holds every item where its slot puts it. */
615
+ function extentOf(slots: readonly Slot[], sizes: readonly Size2D[], focal: number): Size2D {
616
+ let halfWidth = 0
617
+ let halfHeight = 0
618
+ for (let i = 0; i < slots.length; i++) {
619
+ const s = slots[i]
620
+ const size = sizes[i]
621
+ const rad = (s.rotation * Math.PI) / 180
622
+ const cos = Math.abs(Math.cos(rad))
623
+ const sin = Math.abs(Math.sin(rad))
624
+ // What the camera does to a slot at depth, so a sphere hugs its front.
625
+ const lens = focal > 0 && focal - s.depth > 1 ? focal / (focal - s.depth) : 1
626
+ const w = ((size.width * cos + size.height * sin) / 2) * s.scale * lens
627
+ const h = ((size.width * sin + size.height * cos) / 2) * s.scale * lens
628
+ halfWidth = Math.max(halfWidth, Math.abs(s.x) * lens + w)
629
+ halfHeight = Math.max(halfHeight, Math.abs(s.y) * lens + h)
630
+ }
631
+ return { width: halfWidth * 2, height: halfHeight * 2 }
632
+ }
633
+
634
+ function rotateClockwise(x: number, y: number, degrees: number): { x: number; y: number } {
635
+ if (degrees === 0) return { x, y }
636
+ const rad = (degrees * Math.PI) / 180
637
+ const cos = Math.cos(rad)
638
+ const sin = Math.sin(rad)
639
+ return { x: x * cos + y * sin, y: -x * sin + y * cos }
640
+ }
641
+
642
+ function sameSize(a: Size2D, b: Size2D): boolean {
643
+ return Math.abs(a.width - b.width) < 1e-6 && Math.abs(a.height - b.height) < 1e-6
644
+ }
645
+
646
+ function lerp(a: number, b: number, t: number): number {
647
+ return a + (b - a) * t
648
+ }