@motionscript/layout-grid 0.0.0-stage → 0.1.0-alpha.3

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 (132) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +201 -0
  3. package/dist/browser/chunks/chunk-LEUMKC3A.js +2 -0
  4. package/dist/browser/chunks/chunk-LEUMKC3A.js.map +7 -0
  5. package/dist/browser/index.js +2 -0
  6. package/dist/browser/index.js.map +7 -0
  7. package/dist/browser/kit.js +2 -0
  8. package/dist/browser/kit.js.map +7 -0
  9. package/dist/browser/manifest.json +12 -0
  10. package/dist/engine.d.ts +13 -0
  11. package/dist/engine.d.ts.map +1 -0
  12. package/dist/engine.js +13 -0
  13. package/dist/engine.js.map +1 -0
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +7 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/kit/index.d.ts +7 -0
  19. package/dist/kit/index.d.ts.map +1 -0
  20. package/dist/kit/index.js +7 -0
  21. package/dist/kit/index.js.map +1 -0
  22. package/dist/kit/item-effects.d.ts +37 -0
  23. package/dist/kit/item-effects.d.ts.map +1 -0
  24. package/dist/kit/item-effects.js +76 -0
  25. package/dist/kit/item-effects.js.map +1 -0
  26. package/dist/kit/layout-grid.d.ts +243 -0
  27. package/dist/kit/layout-grid.d.ts.map +1 -0
  28. package/dist/kit/layout-grid.js +542 -0
  29. package/dist/kit/layout-grid.js.map +1 -0
  30. package/dist/kit/order.d.ts +13 -0
  31. package/dist/kit/order.d.ts.map +1 -0
  32. package/dist/kit/order.js +43 -0
  33. package/dist/kit/order.js.map +1 -0
  34. package/dist/kit/random.d.ts +7 -0
  35. package/dist/kit/random.d.ts.map +1 -0
  36. package/dist/kit/random.js +29 -0
  37. package/dist/kit/random.js.map +1 -0
  38. package/dist/kit/slots/index.d.ts +22 -0
  39. package/dist/kit/slots/index.d.ts.map +1 -0
  40. package/dist/kit/slots/index.js +28 -0
  41. package/dist/kit/slots/index.js.map +1 -0
  42. package/dist/kit/slots/path-templates.d.ts +15 -0
  43. package/dist/kit/slots/path-templates.d.ts.map +1 -0
  44. package/dist/kit/slots/path-templates.js +113 -0
  45. package/dist/kit/slots/path-templates.js.map +1 -0
  46. package/dist/kit/slots/path.d.ts +45 -0
  47. package/dist/kit/slots/path.d.ts.map +1 -0
  48. package/dist/kit/slots/path.js +87 -0
  49. package/dist/kit/slots/path.js.map +1 -0
  50. package/dist/kit/slots/radial.d.ts +30 -0
  51. package/dist/kit/slots/radial.d.ts.map +1 -0
  52. package/dist/kit/slots/radial.js +45 -0
  53. package/dist/kit/slots/radial.js.map +1 -0
  54. package/dist/kit/slots/rectangular.d.ts +42 -0
  55. package/dist/kit/slots/rectangular.d.ts.map +1 -0
  56. package/dist/kit/slots/rectangular.js +79 -0
  57. package/dist/kit/slots/rectangular.js.map +1 -0
  58. package/dist/kit/slots/slot.d.ts +62 -0
  59. package/dist/kit/slots/slot.d.ts.map +1 -0
  60. package/dist/kit/slots/slot.js +41 -0
  61. package/dist/kit/slots/slot.js.map +1 -0
  62. package/dist/kit/slots/sphere.d.ts +36 -0
  63. package/dist/kit/slots/sphere.d.ts.map +1 -0
  64. package/dist/kit/slots/sphere.js +68 -0
  65. package/dist/kit/slots/sphere.js.map +1 -0
  66. package/dist/kit/stagger.d.ts +24 -0
  67. package/dist/kit/stagger.d.ts.map +1 -0
  68. package/dist/kit/stagger.js +90 -0
  69. package/dist/kit/stagger.js.map +1 -0
  70. package/dist/nodes.d.ts +15 -0
  71. package/dist/nodes.d.ts.map +1 -0
  72. package/dist/nodes.js +15 -0
  73. package/dist/nodes.js.map +1 -0
  74. package/dist/path-grid/index.d.ts +2 -0
  75. package/dist/path-grid/index.d.ts.map +1 -0
  76. package/dist/path-grid/index.js +2 -0
  77. package/dist/path-grid/index.js.map +1 -0
  78. package/dist/path-grid/path-grid.d.ts +82 -0
  79. package/dist/path-grid/path-grid.d.ts.map +1 -0
  80. package/dist/path-grid/path-grid.js +192 -0
  81. package/dist/path-grid/path-grid.js.map +1 -0
  82. package/dist/radial-grid/index.d.ts +2 -0
  83. package/dist/radial-grid/index.d.ts.map +1 -0
  84. package/dist/radial-grid/index.js +2 -0
  85. package/dist/radial-grid/index.js.map +1 -0
  86. package/dist/radial-grid/radial-grid.d.ts +51 -0
  87. package/dist/radial-grid/radial-grid.d.ts.map +1 -0
  88. package/dist/radial-grid/radial-grid.js +95 -0
  89. package/dist/radial-grid/radial-grid.js.map +1 -0
  90. package/dist/rectangular-grid/index.d.ts +2 -0
  91. package/dist/rectangular-grid/index.d.ts.map +1 -0
  92. package/dist/rectangular-grid/index.js +2 -0
  93. package/dist/rectangular-grid/index.js.map +1 -0
  94. package/dist/rectangular-grid/rectangular-grid.d.ts +79 -0
  95. package/dist/rectangular-grid/rectangular-grid.d.ts.map +1 -0
  96. package/dist/rectangular-grid/rectangular-grid.js +156 -0
  97. package/dist/rectangular-grid/rectangular-grid.js.map +1 -0
  98. package/dist/sphere-grid/index.d.ts +2 -0
  99. package/dist/sphere-grid/index.d.ts.map +1 -0
  100. package/dist/sphere-grid/index.js +2 -0
  101. package/dist/sphere-grid/index.js.map +1 -0
  102. package/dist/sphere-grid/sphere-grid.d.ts +68 -0
  103. package/dist/sphere-grid/sphere-grid.d.ts.map +1 -0
  104. package/dist/sphere-grid/sphere-grid.js +149 -0
  105. package/dist/sphere-grid/sphere-grid.js.map +1 -0
  106. package/package.json +70 -3
  107. package/registry.json +32 -0
  108. package/src/engine.ts +12 -0
  109. package/src/index.ts +6 -0
  110. package/src/kit/index.ts +6 -0
  111. package/src/kit/item-effects.ts +114 -0
  112. package/src/kit/layout-grid.ts +605 -0
  113. package/src/kit/order.ts +41 -0
  114. package/src/kit/random.ts +29 -0
  115. package/src/kit/slots/index.ts +39 -0
  116. package/src/kit/slots/path-templates.ts +120 -0
  117. package/src/kit/slots/path.ts +120 -0
  118. package/src/kit/slots/radial.ts +62 -0
  119. package/src/kit/slots/rectangular.ts +108 -0
  120. package/src/kit/slots/slot.ts +82 -0
  121. package/src/kit/slots/sphere.ts +94 -0
  122. package/src/kit/stagger.ts +96 -0
  123. package/src/nodes.ts +15 -0
  124. package/src/path-grid/index.ts +1 -0
  125. package/src/path-grid/path-grid.ts +213 -0
  126. package/src/radial-grid/index.ts +1 -0
  127. package/src/radial-grid/radial-grid.ts +90 -0
  128. package/src/rectangular-grid/index.ts +1 -0
  129. package/src/rectangular-grid/rectangular-grid.ts +160 -0
  130. package/src/sphere-grid/index.ts +1 -0
  131. package/src/sphere-grid/sphere-grid.ts +143 -0
  132. package/README.md +0 -4
@@ -0,0 +1,605 @@
1
+ import {
2
+ command,
3
+ easeIn,
4
+ easeInOut,
5
+ easeOut,
6
+ flowOps,
7
+ insetsOps,
8
+ Node2D,
9
+ property,
10
+ sizeInputOps,
11
+ type BoxBounds,
12
+ type ChildPlacement,
13
+ type Command,
14
+ type CommandArgs,
15
+ type MeasureContext2D,
16
+ type EasingFunction,
17
+ type Node2DProps,
18
+ type Size2D,
19
+ type SizeConstraints,
20
+ type SpaceCamera,
21
+ } from "@motionscript/sdk"
22
+
23
+ import {
24
+ applyItemEffects,
25
+ REVEAL_STYLES,
26
+ WAVE_STYLES,
27
+ type FocusState,
28
+ type RevealState,
29
+ type RevealStyle,
30
+ type WaveState,
31
+ type WaveStyle,
32
+ } from "./item-effects"
33
+ import { normalizeOrder, parseOrder, slotOfItem } from "./order"
34
+ import { hashSeed, shuffled } from "./random"
35
+ import { blendSlot, focalLengthOf, slotsOf, spreadSlot, type Arrangement, type Slot } from "./slots"
36
+ import { STAGGER_ORDERS, staggerProgress, staggerRanks, type StaggerOrder } from "./stagger"
37
+
38
+ /** An arrangement a grid is leaving, kept as data so its slots can be worked out afresh every frame. */
39
+ export interface GridSnapshot {
40
+ arrangement: Arrangement
41
+ /** The grid the arrangement was borrowed from, or `""` for the grid's own. */
42
+ source: string
43
+ order: readonly number[]
44
+ spread: number
45
+ }
46
+
47
+ /** A change of arrangement under way: where the items are coming from, and how far each has come. */
48
+ export interface GridTransition {
49
+ from: GridSnapshot
50
+ /** Each item's eased, staggered progress, `0..1`. */
51
+ mix: readonly number[]
52
+ }
53
+
54
+ export interface LayoutGridProps extends Node2DProps {
55
+ /** Items in slot order: slot `k` holds child `order[k]`. Empty is the children's own order. */
56
+ order: number[]
57
+ /** `0` gathers every item at the centre, `1` is the arrangement, past `1` pushes them apart. */
58
+ spread: number
59
+ /** Another grid whose arrangement this one takes on — what {@link LayoutGrid.morphInto} animates. */
60
+ arrangeLike: string
61
+ // What the per-item commands write. State rather than settings: a command
62
+ // owns each while it runs, and a document has no reason to name them.
63
+ revealState: RevealState | null
64
+ waveState: WaveState | null
65
+ focusState: FocusState | null
66
+ transition: GridTransition | null
67
+ }
68
+
69
+ /** What a command that moves the items to new slots is built from. */
70
+ export interface TransitionArgs {
71
+ data?: StaggerArgs
72
+ duration: number
73
+ easing?: EasingFunction
74
+ }
75
+
76
+ /** The stagger options every per-item command takes. */
77
+ export interface StaggerArgs {
78
+ staggerOrder?: StaggerOrder
79
+ /** `0..0.95`: how much of the command's length the items' offsets take up. */
80
+ stagger?: number
81
+ }
82
+
83
+ /** `@command` descriptors for {@link StaggerArgs}, `stagger` defaulting to `fallback`. */
84
+ export function staggerArgs(fallback: number) {
85
+ return [
86
+ { key: "staggerOrder", kind: "enum", options: STAGGER_ORDERS, default: "index" },
87
+ { key: "stagger", min: 0, max: 0.95, step: 0.05, default: fallback },
88
+ ] as const
89
+ }
90
+
91
+ /**
92
+ * Every grid's document key — what a reference to "another grid" may name. A
93
+ * `nodeRef` descriptor carries it as `nodeTypes`, for a host's picker to offer
94
+ * only those.
95
+ */
96
+ export const LAYOUT_GRID_TYPES = ["rectangularGrid", "radialGrid", "pathGrid", "sphereGrid"] as const
97
+
98
+ /** The stagger a move to new slots takes when its command states none. */
99
+ export const TRANSITION_STAGGER = 0.3
100
+
101
+ const NO_CONTENT: Size2D = { width: 0, height: 0 }
102
+ const CENTRE = { x: 0, y: 0 }
103
+
104
+ /**
105
+ * The base of every grid: a container that places each of its children in a
106
+ * slot of an arrangement — a rectangular grid, a ring, a path, a sphere.
107
+ *
108
+ * ## Children only
109
+ *
110
+ * The items are the children, in layer order. A child's slot is a parent
111
+ * transform on it, so its own `x`/`y`/`rotation`/`scale` — and any command on
112
+ * them — still work, relative to the slot. A group is one item; a grid of
113
+ * grids is a grid of items that happen to be grids.
114
+ *
115
+ * ## One pass
116
+ *
117
+ * Every frame: measure the children, ask the arrangement for its slots (a pure
118
+ * function of the props, the sizes and the clock), blend them from where a
119
+ * transition is leaving, and layer on the per-item effects — reveal, wave,
120
+ * focus. What is left is each child's box and {@link ChildPlacement}, which the
121
+ * renderer, picking and `global` all read, so a selection outline lands on
122
+ * the pixels even on a sphere.
123
+ *
124
+ * ## Commands
125
+ *
126
+ * Every command is a pure function of time, like the rest of the library. The
127
+ * per-item ones stagger *inside* their duration — a one-second reveal takes one
128
+ * second for four children or four hundred — and write their per-item state
129
+ * into props ({@link revealState} and its siblings), which is what keeps them
130
+ * seekable. The ones that change the arrangement itself (a reorder, a morph, a
131
+ * column count) keep the arrangement they are leaving as data and blend each
132
+ * item from its old slot to its new one.
133
+ */
134
+ export abstract class LayoutGrid<P extends LayoutGridProps = LayoutGridProps> extends Node2D<P> {
135
+ @property({ default: [], kind: "order", animatable: false }) declare order: number[]
136
+ @property({ default: 1, min: 0, max: 3, step: 0.05 }) declare spread: number
137
+ @property({ default: "", kind: "nodeRef", nodeTypes: LAYOUT_GRID_TYPES, animatable: false }) declare arrangeLike: string
138
+ // Unset until a command writes one, so a fresh node's row does not state them.
139
+ @property({ default: undefined, kind: "state", animatable: false }) declare revealState: RevealState | null | undefined
140
+ @property({ default: undefined, kind: "state", animatable: false }) declare waveState: WaveState | null | undefined
141
+ @property({ default: undefined, kind: "state", animatable: false }) declare focusState: FocusState | null | undefined
142
+ @property({ default: undefined, kind: "state", animatable: false }) declare transition: GridTransition | null | undefined
143
+
144
+ /**
145
+ * Bring the items in, one after another. Every item starts hidden, so place
146
+ * it where the grid enters — or after a {@link conceal}.
147
+ */
148
+ @command({ args: [{ key: "style", kind: "enum", options: REVEAL_STYLES, default: "scale" }, ...staggerArgs(0.5)] })
149
+ reveal(args: CommandArgs<{ style?: RevealStyle } & StaggerArgs> & { duration: number }): Command<LayoutGridProps> {
150
+ const style = args.data?.style ?? "scale"
151
+ const ease = args.easing ?? (style === "scale" || style === "flip" ? easeOut("back") : easeOut("cubic"))
152
+ const ranks = this._ranks(args.data?.staggerOrder)
153
+ const stagger = args.data?.stagger ?? 0.5
154
+ return this.command<LayoutGridProps>((t) => {
155
+ if (t >= 1) return { revealState: null }
156
+ return { revealState: { style, values: ranks.map((rank) => ease(staggerProgress(rank, t, stagger))) } }
157
+ }, args.duration)
158
+ }
159
+
160
+ /** Take the items out, one after another — {@link reveal} in reverse. They stay hidden after. */
161
+ @command({ args: [{ key: "style", kind: "enum", options: REVEAL_STYLES, default: "scale" }, ...staggerArgs(0.5)] })
162
+ conceal(args: CommandArgs<{ style?: RevealStyle } & StaggerArgs> & { duration: number }): Command<LayoutGridProps> {
163
+ const style = args.data?.style ?? "scale"
164
+ const ease = args.easing ?? (style === "scale" || style === "flip" ? easeIn("back") : easeInOut("cubic"))
165
+ const ranks = this._ranks(args.data?.staggerOrder)
166
+ const stagger = args.data?.stagger ?? 0.5
167
+ const from = this.revealState?.values
168
+ return this.command<LayoutGridProps>((t) => ({
169
+ revealState: {
170
+ style,
171
+ values: ranks.map((rank, i) => (from?.[i] ?? 1) * (1 - ease(staggerProgress(rank, t, stagger)))),
172
+ },
173
+ }), args.duration)
174
+ }
175
+
176
+ /** Send a ripple through the items that swells each in turn and settles back. */
177
+ @command({
178
+ args: [
179
+ { key: "style", kind: "enum", options: WAVE_STYLES, default: "scale" },
180
+ { key: "amount", min: 0, max: 2, step: 0.05, default: 0.3 },
181
+ ...staggerArgs(0.7),
182
+ ],
183
+ })
184
+ wave(args: CommandArgs<{ style?: WaveStyle; amount?: number } & StaggerArgs> & { duration: number }): Command<LayoutGridProps> {
185
+ const style = args.data?.style ?? "scale"
186
+ const amount = args.data?.amount ?? 0.3
187
+ const ease = args.easing ?? easeInOut("sine")
188
+ const ranks = this._ranks(args.data?.staggerOrder)
189
+ const stagger = args.data?.stagger ?? 0.7
190
+ return this.command<LayoutGridProps>((t) => {
191
+ if (t >= 1) return { waveState: null }
192
+ return {
193
+ waveState: {
194
+ style,
195
+ amount,
196
+ values: ranks.map((rank) => Math.sin(Math.PI * ease(staggerProgress(rank, t, stagger)))),
197
+ },
198
+ }
199
+ }, args.duration)
200
+ }
201
+
202
+ /** Bring one item (by its place in the layers, from 0) forward and push the rest back. */
203
+ @command({
204
+ args: [
205
+ { key: "item", min: 0, step: 1, default: 0 },
206
+ { key: "dim", min: 0, max: 1, step: 0.05, default: 0.7 },
207
+ { key: "grow", min: 0, max: 1, step: 0.05, default: 0.15 },
208
+ ],
209
+ })
210
+ focus(args: CommandArgs<{ item?: number; dim?: number; grow?: number }> & { duration: number }): Command<LayoutGridProps> {
211
+ const n = this._itemCount()
212
+ const item = Math.round(args.data?.item ?? 0)
213
+ return this._focusOn((i) => i === item, n, args)
214
+ }
215
+
216
+ /** Bring every item back to even. */
217
+ @command()
218
+ unfocus(args: CommandArgs<Record<string, never>> & { duration: number }): Command<LayoutGridProps> {
219
+ const from = this.focusState
220
+ const ease = args.easing ?? easeInOut("cubic")
221
+ return this.command<LayoutGridProps>((t) => {
222
+ if (t >= 1 || !from) return { focusState: null }
223
+ const k = 1 - ease(t)
224
+ return { focusState: { ...from, values: from.values.map((v) => v * k) } }
225
+ }, args.duration)
226
+ }
227
+
228
+ /** Gather the items toward the centre (`0`), back to the arrangement (`1`), or push them apart. */
229
+ @command({ args: [{ key: "spread", min: 0, max: 3, step: 0.05, default: 1 }] })
230
+ spreadTo(args: CommandArgs<{ spread: number }> & { duration: number }): Command<P> {
231
+ return this.to({ data: { spread: args.data?.spread ?? 1 } as Partial<P>, duration: args.duration, easing: args.easing })
232
+ }
233
+
234
+ /** Send every item to a random slot. The same `seed` always deals the same way. */
235
+ @command({ args: [{ key: "seed", min: 0, step: 1, default: 1 }, ...staggerArgs(TRANSITION_STAGGER)] })
236
+ shuffle(args: CommandArgs<{ seed?: number } & StaggerArgs> & { duration: number }): Command<P> {
237
+ const current = normalizeOrder(this.order, this._itemCount())
238
+ let next = shuffled(current, args.data?.seed ?? 1)
239
+ // A shuffle that deals everything back where it was would look like nothing happened.
240
+ if (next.length > 1 && next.every((item, k) => item === current[k])) next = [...next.slice(1), next[0]]
241
+ return this._transitionTo({ order: next } as Partial<P>, args)
242
+ }
243
+
244
+ /** Two items trade places, by their place in the layers. */
245
+ @command({
246
+ args: [
247
+ { key: "first", min: 0, step: 1, default: 0 },
248
+ { key: "second", min: 0, step: 1, default: 1 },
249
+ ...staggerArgs(0),
250
+ ],
251
+ })
252
+ swap(args: CommandArgs<{ first?: number; second?: number } & StaggerArgs> & { duration: number }): Command<P> {
253
+ const order = normalizeOrder(this.order, this._itemCount())
254
+ const a = order.indexOf(Math.round(args.data?.first ?? 0))
255
+ const b = order.indexOf(Math.round(args.data?.second ?? 1))
256
+ if (a >= 0 && b >= 0) [order[a], order[b]] = [order[b], order[a]]
257
+ return this._transitionTo({ order } as Partial<P>, args, 0)
258
+ }
259
+
260
+ /** Move the items into a new order — a list of layer indices, first slot first, like `"2, 0, 1"`. */
261
+ @command({ args: [{ key: "order", kind: "text", default: "" }, ...staggerArgs(TRANSITION_STAGGER)] })
262
+ reorder(args: CommandArgs<{ order?: string | number[] } & StaggerArgs> & { duration: number }): Command<P> {
263
+ const order = normalizeOrder(parseOrder(args.data?.order), this._itemCount())
264
+ return this._transitionTo({ order } as Partial<P>, args)
265
+ }
266
+
267
+ /**
268
+ * Move every item into another grid's arrangement — a grid into a ring, a ring
269
+ * onto a sphere — and keep following it. An empty `target` morphs back to
270
+ * this grid's own.
271
+ */
272
+ @command({ args: [{ key: "target", kind: "nodeRef", nodeTypes: LAYOUT_GRID_TYPES }, ...staggerArgs(TRANSITION_STAGGER)] })
273
+ morphInto(args: CommandArgs<{ target?: string } & StaggerArgs> & { duration: number }): Command<P> {
274
+ return this._transitionTo({ arrangeLike: args.data?.target ?? "" } as Partial<P>, args)
275
+ }
276
+
277
+ /** This grid's own arrangement, for a content box of `box`. */
278
+ protected abstract arrangementFor(box: Size2D): Arrangement
279
+
280
+ // A grid's size is what its items come to. The base's rule — hug only when
281
+ // built with children — would have a grid from a document, whose children
282
+ // arrive after it, fill its parent instead.
283
+ protected override applyDefaultSize(props?: { readonly width?: unknown; readonly height?: unknown }): void {
284
+ if (!props || props.width === undefined) this.applyProp("width", "hug", { tween: sizeInputOps.lerp })
285
+ if (!props || props.height === undefined) this.applyProp("height", "hug", { tween: sizeInputOps.lerp })
286
+ }
287
+
288
+ /** The room each item is measured in — the whole content box, unless an arrangement has cells. */
289
+ protected itemSpace(_count: number, space: Size2D, _sizes?: readonly Size2D[]): Size2D {
290
+ return space
291
+ }
292
+
293
+ override measure(constraints: SizeConstraints, scope: MeasureContext2D): Partial<Size2D> {
294
+ this.lastMeasure = { constraints, measurer: scope }
295
+ const padding = this.effectivePadding()
296
+ const items = this.flowChildren()
297
+ if (items.length === 0) {
298
+ this._measured = null
299
+ return flowOps.size(this, constraints, padding, NO_CONTENT)
300
+ }
301
+ const space = flowOps.contentBox(this, constraints, padding)
302
+ const sizes = this._measureItems(items, space, scope)
303
+ this._measured = { space, sizes }
304
+ return flowOps.size(this, constraints, padding, extentOf(this._targetSlots(items.length, sizes, space).slots, sizes, this._focal))
305
+ }
306
+
307
+ protected override layoutChildren(rect: BoxBounds, scope: MeasureContext2D): void {
308
+ this._placements.clear()
309
+ const items = this.flowChildren()
310
+ if (items.length === 0) {
311
+ this._slots = []
312
+ this._sizes = []
313
+ this._focal = 0
314
+ return
315
+ }
316
+ const inner = insetsOps.insetBounds(rect.width, rect.height, this.effectivePadding())
317
+ const measured = this._measured
318
+ this._measured = null
319
+ const sizes = measured && measured.sizes.length === items.length && sameSize(measured.space, inner)
320
+ ? measured.sizes
321
+ : this._measureItems(items, inner, scope)
322
+ const slots = this._resolve(sizes, inner)
323
+ this._slots = slots
324
+ this._sizes = sizes
325
+ for (let i = 0; i < items.length; i++) {
326
+ const s = slots[i]
327
+ items[i].layout({ x: inner.x + s.x, y: inner.y - s.y, width: sizes[i].width, height: sizes[i].height }, scope)
328
+ if (s.rotation !== 0 || s.scale !== 1 || s.rotationX !== 0 || s.rotationY !== 0 || s.depth !== 0 || s.opacity !== 1) {
329
+ this._placements.set(items[i], {
330
+ rotation: s.rotation,
331
+ scale: s.scale,
332
+ rotationX: s.rotationX,
333
+ rotationY: s.rotationY,
334
+ depth: s.depth,
335
+ opacity: s.opacity,
336
+ })
337
+ }
338
+ }
339
+ }
340
+
341
+ override _placementOf(child: Node2D): ChildPlacement | null {
342
+ return this._placements.get(child) ?? null
343
+ }
344
+
345
+ /**
346
+ * A grid whose arrangement has depth is seen through a camera of its own,
347
+ * which paints its items far to near — unless it already sits in a space (an
348
+ * orbit camera, a 3D stage), where its items join that one and its camera.
349
+ */
350
+ override _spaceCamera(): SpaceCamera | null {
351
+ const focal = this._focal
352
+ if (focal <= 0 || this._inSpace()) return null
353
+ return {
354
+ perspective: focal,
355
+ orbit: 0,
356
+ elevation: 0,
357
+ dolly: 0,
358
+ lookAt: CENTRE,
359
+ zoom: 1,
360
+ heading: 0,
361
+ viewportX: 0,
362
+ viewportY: 0,
363
+ }
364
+ }
365
+
366
+ private readonly _placements = new Map<Node2D, ChildPlacement>()
367
+ /** What {@link measure} found, for {@link layoutChildren} to reuse in the same pass. */
368
+ private _measured: { space: Size2D; sizes: Size2D[] } | null = null
369
+ /** Each item's slot from the last layout — what a command ranks its stagger by. */
370
+ private _slots: Slot[] = []
371
+ /** Each item's size from the last layout. */
372
+ private _sizes: readonly Size2D[] = []
373
+ /** The last layout's camera distance, `0` while flat. */
374
+ private _focal = 0
375
+ private _borrowCache: { id: string; grid: LayoutGrid } | null = null
376
+
377
+ /** How many items a command built now will act on. */
378
+ protected _itemCount(): number {
379
+ return this.flowChildren().length
380
+ }
381
+
382
+ /** Each item's slot as it stands, for a command being built — the last layout's where it still fits. */
383
+ protected _itemSlots(): Slot[] {
384
+ const n = this._itemCount()
385
+ if (this._slots.length === n) return this._slots
386
+ const sizes = new Array<Size2D>(n).fill({ width: 100, height: 100 })
387
+ return this._targetSlots(n, sizes, contentBoxOf(this)).slots
388
+ }
389
+
390
+ /** The item sizes the last layout found. */
391
+ protected _itemSizes(): readonly Size2D[] {
392
+ return this._sizes.length === this._itemCount() ? this._sizes : []
393
+ }
394
+
395
+ /** Each item's start in a stagger. A random order is seeded by the node's id, so it never changes between builds. */
396
+ protected _ranks(order: StaggerOrder | undefined): number[] {
397
+ return staggerRanks(order ?? "index", this._itemSlots(), hashSeed(this.id))
398
+ }
399
+
400
+ /**
401
+ * Write `changes` to the arrangement and move each item from its slot in the
402
+ * one being left to its slot in the new one, staggered.
403
+ */
404
+ protected _transitionTo(changes: Partial<P>, args: TransitionArgs, stagger = TRANSITION_STAGGER): Command<P> {
405
+ const from = this._snapshot()
406
+ const ease = args.easing ?? easeInOut("cubic")
407
+ const ranks = this._ranks(args.data?.staggerOrder)
408
+ const spread = args.data?.stagger ?? stagger
409
+ return this.command<P>((t) => {
410
+ if (t >= 1) return { ...changes, transition: null } as Partial<P>
411
+ const mix = ranks.map((rank) => ease(staggerProgress(rank, t, spread)))
412
+ return { ...changes, transition: { from, mix } } as Partial<P>
413
+ }, args.duration)
414
+ }
415
+
416
+ /** Emphasise the items `isFocus` picks and push the rest back. */
417
+ protected _focusOn(
418
+ isFocus: (item: number) => boolean,
419
+ count: number,
420
+ args: CommandArgs<{ dim?: number; grow?: number }> & { duration: number },
421
+ ): Command<LayoutGridProps> {
422
+ const from = this.focusState
423
+ const dim = args.data?.dim ?? 0.7
424
+ const grow = args.data?.grow ?? 0.15
425
+ const target = Array.from({ length: count }, (_, i) => (isFocus(i) ? 1 : -1))
426
+ const ease = args.easing ?? easeInOut("cubic")
427
+ return this.command<LayoutGridProps>((t) => {
428
+ const e = ease(t)
429
+ return {
430
+ focusState: {
431
+ dim: lerp(from?.dim ?? dim, dim, e),
432
+ grow: lerp(from?.grow ?? grow, grow, e),
433
+ values: target.map((v, i) => lerp(from?.values[i] ?? 0, v, e)),
434
+ },
435
+ }
436
+ }, args.duration)
437
+ }
438
+
439
+ private _snapshot(): GridSnapshot {
440
+ const source = this._borrowed()
441
+ return {
442
+ arrangement: source ? source.arrangementFor(contentBoxOf(source)) : this.arrangementFor(contentBoxOf(this)),
443
+ source: source?.id ?? "",
444
+ order: normalizeOrder(this.order, this._itemCount()),
445
+ spread: this.spread,
446
+ }
447
+ }
448
+
449
+ private _measureItems(items: readonly Node2D[], space: Size2D, scope: MeasureContext2D): Size2D[] {
450
+ const measured = flowOps.measure({}, items, space, scope).sizes
451
+ const cell = this.itemSpace(items.length, space, measured)
452
+ if (cell === space) return [...measured]
453
+ return [...flowOps.measure({}, items, cell, scope).sizes]
454
+ }
455
+
456
+ /** Where each item sits in the arrangement it is heading for, before any transition or effect. */
457
+ private _targetSlots(count: number, sizes: readonly Size2D[], box: Size2D): { slots: Slot[]; arrangement: Arrangement } {
458
+ const source = this._borrowed()
459
+ const arrangement = source ? source.arrangementFor(contentBoxOf(source)) : this.arrangementFor(box)
460
+ let slots = slotsOf(arrangement, { count, sizes, box: source ? contentBoxOf(source) : box, time: this.time.total })
461
+ if (source) slots = this._fromGrid(source, slots)
462
+ const slotOf = slotOfItem(normalizeOrder(this.order, count))
463
+ return { slots: slotOf.map((k) => spreadSlot(slots[k], this.spread)), arrangement }
464
+ }
465
+
466
+ /** Each item's final slot this frame: the target, blended from any transition, with its effects on. */
467
+ private _resolve(sizes: readonly Size2D[], box: Size2D): Slot[] {
468
+ const count = sizes.length
469
+ const target = this._targetSlots(count, sizes, box)
470
+ const slots = target.slots
471
+ let focal = focalLengthOf(target.arrangement)
472
+ const transition = this.transition
473
+ if (transition) {
474
+ const { from } = transition
475
+ const source = from.source ? this._gridById(from.source) : null
476
+ const fromBox = source ? contentBoxOf(source) : box
477
+ let leaving = slotsOf(from.arrangement, { count, sizes, box: fromBox, time: this.time.total })
478
+ if (source && source !== this) leaving = this._fromGrid(source, leaving)
479
+ const slotOf = slotOfItem(normalizeOrder(from.order, count))
480
+ for (let i = 0; i < count; i++) {
481
+ slots[i] = blendSlot(spreadSlot(leaving[slotOf[i]], from.spread), slots[i], transition.mix[i] ?? 1)
482
+ }
483
+ // A morph into or out of depth keeps the camera for its whole length.
484
+ focal = focal || focalLengthOf(from.arrangement)
485
+ }
486
+ this._focal = focal
487
+ const reveal = this.revealState
488
+ const wave = this.waveState
489
+ const focus = this.focusState
490
+ if (reveal || wave || focus) {
491
+ for (let i = 0; i < count; i++) applyItemEffects(slots[i], i, sizes[i], reveal, wave, focus)
492
+ }
493
+ return slots
494
+ }
495
+
496
+ /** Whether an ancestor places this grid in a space, as `spaceFrameOf` walks it. */
497
+ private _inSpace(): boolean {
498
+ for (let n = this.parent; n; n = n.parent) {
499
+ if (n._spaceCamera()) return true
500
+ if (!n._rendersChildrenInSpace()) return false
501
+ }
502
+ return false
503
+ }
504
+
505
+ /** The grid {@link arrangeLike} names, when it names another grid in this tree. */
506
+ private _borrowed(): LayoutGrid | null {
507
+ const id = this.arrangeLike
508
+ if (!id || id === this.id) return null
509
+ return this._gridById(id)
510
+ }
511
+
512
+ private _gridById(id: string): LayoutGrid | null {
513
+ if (id === this.id) return this
514
+ const cached = this._borrowCache
515
+ if (cached && cached.id === id && cached.grid.mounted) return cached.grid
516
+ const found = findNode2D(this, id)
517
+ const grid = found instanceof LayoutGrid ? found : null
518
+ this._borrowCache = grid ? { id, grid } : null
519
+ return grid
520
+ }
521
+
522
+ /** `slots`, laid out in `source`'s frame, moved into this grid's. */
523
+ private _fromGrid(source: LayoutGrid, slots: Slot[]): Slot[] {
524
+ const frame = frameIn(this, source)
525
+ return slots.map((s) => {
526
+ const p = rotateClockwise(s.x * frame.scale, s.y * frame.scale, frame.rotation)
527
+ return {
528
+ ...s,
529
+ x: frame.x + p.x,
530
+ y: frame.y + p.y,
531
+ depth: s.depth * frame.scale,
532
+ rotation: s.rotation + frame.rotation,
533
+ scale: s.scale * frame.scale,
534
+ }
535
+ })
536
+ }
537
+ }
538
+
539
+ /** A node's content box: its laid-out size inside its padding. */
540
+ export function contentBoxOf(grid: Node2D): Size2D {
541
+ const b = grid.layoutBounds
542
+ const inner = insetsOps.insetBounds(b.width, b.height, grid.effectivePadding())
543
+ return { width: inner.width, height: inner.height }
544
+ }
545
+
546
+ /** The box, centred on the grid, that holds every item where its slot puts it. */
547
+ function extentOf(slots: readonly Slot[], sizes: readonly Size2D[], focal: number): Size2D {
548
+ let halfWidth = 0
549
+ let halfHeight = 0
550
+ for (let i = 0; i < slots.length; i++) {
551
+ const s = slots[i]
552
+ const size = sizes[i]
553
+ const rad = (s.rotation * Math.PI) / 180
554
+ const cos = Math.abs(Math.cos(rad))
555
+ const sin = Math.abs(Math.sin(rad))
556
+ // What the camera does to a slot at depth, so a sphere hugs its front.
557
+ const lens = focal > 0 && focal - s.depth > 1 ? focal / (focal - s.depth) : 1
558
+ const w = ((size.width * cos + size.height * sin) / 2) * s.scale * lens
559
+ const h = ((size.width * sin + size.height * cos) / 2) * s.scale * lens
560
+ halfWidth = Math.max(halfWidth, Math.abs(s.x) * lens + w)
561
+ halfHeight = Math.max(halfHeight, Math.abs(s.y) * lens + h)
562
+ }
563
+ return { width: halfWidth * 2, height: halfHeight * 2 }
564
+ }
565
+
566
+ function rotateClockwise(x: number, y: number, degrees: number): { x: number; y: number } {
567
+ if (degrees === 0) return { x, y }
568
+ const rad = (degrees * Math.PI) / 180
569
+ const cos = Math.cos(rad)
570
+ const sin = Math.sin(rad)
571
+ return { x: x * cos + y * sin, y: -x * sin + y * cos }
572
+ }
573
+
574
+ function sameSize(a: Size2D, b: Size2D): boolean {
575
+ return Math.abs(a.width - b.width) < 1e-6 && Math.abs(a.height - b.height) < 1e-6
576
+ }
577
+
578
+ function lerp(a: number, b: number, t: number): number {
579
+ return a + (b - a) * t
580
+ }
581
+
582
+ /** The 2D node `id` names in the tree `from` is in, or `null`. */
583
+ export function findNode2D(from: Node2D, id: string): Node2D | null {
584
+ let root: Node2D = from
585
+ while (root.parent) root = root.parent
586
+ return findIn(root, id)
587
+ }
588
+
589
+ function findIn(at: Node2D, id: string): Node2D | null {
590
+ if (at.id === id) return at
591
+ for (const child of at.children) {
592
+ const found = findIn(child, id)
593
+ if (found) return found
594
+ }
595
+ return null
596
+ }
597
+
598
+ /** Where `node`'s frame sits in `grid`'s: offset, turn and scale, y-up. */
599
+ export function frameIn(grid: Node2D, node: Node2D): { x: number; y: number; rotation: number; scale: number } {
600
+ const there = node.global
601
+ const here = grid.global
602
+ const inverse = here.scale === 0 ? 0 : 1 / here.scale
603
+ const offset = rotateClockwise((there.x - here.x) * inverse, (there.y - here.y) * inverse, -here.rotation)
604
+ return { x: offset.x, y: offset.y, rotation: there.rotation - here.rotation, scale: there.scale * inverse }
605
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * A grid's `order` lists items in slot order: slot `k` holds item `order[k]`.
3
+ * These keep it a permutation whatever it was written as — a stale entry past
4
+ * the count, a repeat, or nothing at all — so a child added or removed never
5
+ * leaves a slot empty or two items in one.
6
+ */
7
+
8
+ /** `order` repaired into a permutation of `0..count-1`: its valid entries first, then the rest in item order. */
9
+ export function normalizeOrder(order: readonly number[] | undefined, count: number): number[] {
10
+ const out: number[] = []
11
+ const taken = new Array<boolean>(count).fill(false)
12
+ for (const entry of order ?? []) {
13
+ const item = Math.round(entry)
14
+ if (item >= 0 && item < count && !taken[item]) {
15
+ taken[item] = true
16
+ out.push(item)
17
+ }
18
+ }
19
+ for (let item = 0; item < count; item++) if (!taken[item]) out.push(item)
20
+ return out
21
+ }
22
+
23
+ /** For each item, the slot it sits in. */
24
+ export function slotOfItem(order: readonly number[]): number[] {
25
+ const slots = new Array<number>(order.length)
26
+ order.forEach((item, slot) => {
27
+ slots[item] = slot
28
+ })
29
+ return slots
30
+ }
31
+
32
+ /** An order written as `"2, 0, 1"` or as numbers. */
33
+ export function parseOrder(value: unknown): number[] {
34
+ if (Array.isArray(value)) return value.map(Number).filter(Number.isFinite)
35
+ if (typeof value !== "string") return []
36
+ return value
37
+ .split(/[\s,]+/)
38
+ .filter((part) => part !== "")
39
+ .map(Number)
40
+ .filter(Number.isFinite)
41
+ }
@@ -0,0 +1,29 @@
1
+ /** A seeded generator in `[0, 1)` — mulberry32, so a shuffle is the same on every frame and every machine. */
2
+ export function seededRandom(seed: number): () => number {
3
+ let a = Math.floor(seed) >>> 0
4
+ return () => {
5
+ a = (a + 0x6d2b79f5) >>> 0
6
+ let t = a
7
+ t = Math.imul(t ^ (t >>> 15), t | 1)
8
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
9
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
10
+ }
11
+ }
12
+
13
+ /** `values` in a seeded random order. */
14
+ export function shuffled<T>(values: readonly T[], seed: number): T[] {
15
+ const out = [...values]
16
+ const random = seededRandom(seed)
17
+ for (let i = out.length - 1; i > 0; i--) {
18
+ const j = Math.floor(random() * (i + 1))
19
+ ;[out[i], out[j]] = [out[j], out[i]]
20
+ }
21
+ return out
22
+ }
23
+
24
+ /** A stable number for a string — a node's id, so its "random" stagger never changes between builds. */
25
+ export function hashSeed(text: string): number {
26
+ let h = 2166136261
27
+ for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619)
28
+ return h >>> 0
29
+ }