@motionscript/charts 0.0.0-stage → 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +49 -0
  4. package/README.md +98 -3
  5. package/dist/bar-chart/bar-chart.d.ts +191 -0
  6. package/dist/bar-chart/bar-chart.d.ts.map +1 -0
  7. package/dist/bar-chart/bar-chart.js +431 -0
  8. package/dist/bar-chart/bar-chart.js.map +1 -0
  9. package/dist/bar-chart/category-axis.d.ts +71 -0
  10. package/dist/bar-chart/category-axis.d.ts.map +1 -0
  11. package/dist/bar-chart/category-axis.js +119 -0
  12. package/dist/bar-chart/category-axis.js.map +1 -0
  13. package/dist/bar-chart/chart-bars.d.ts +129 -0
  14. package/dist/bar-chart/chart-bars.d.ts.map +1 -0
  15. package/dist/bar-chart/chart-bars.js +181 -0
  16. package/dist/bar-chart/chart-bars.js.map +1 -0
  17. package/dist/bar-chart/index.d.ts +16 -0
  18. package/dist/bar-chart/index.d.ts.map +1 -0
  19. package/dist/bar-chart/index.js +12 -0
  20. package/dist/bar-chart/index.js.map +1 -0
  21. package/dist/bar-chart/shared.d.ts +146 -0
  22. package/dist/bar-chart/shared.d.ts.map +1 -0
  23. package/dist/bar-chart/shared.js +182 -0
  24. package/dist/bar-chart/shared.js.map +1 -0
  25. package/dist/browser/chunks/chunk-TJNHLQGV.js +2 -0
  26. package/dist/browser/chunks/chunk-TJNHLQGV.js.map +7 -0
  27. package/dist/browser/index.js +2 -0
  28. package/dist/browser/index.js.map +7 -0
  29. package/dist/browser/kit.js +2 -0
  30. package/dist/browser/kit.js.map +7 -0
  31. package/dist/browser/manifest.json +13 -0
  32. package/dist/engine.d.ts +29 -0
  33. package/dist/engine.d.ts.map +1 -0
  34. package/dist/engine.js +29 -0
  35. package/dist/engine.js.map +1 -0
  36. package/dist/index.d.ts +6 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +6 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/kit/cartesian.d.ts +44 -0
  41. package/dist/kit/cartesian.d.ts.map +1 -0
  42. package/dist/kit/cartesian.js +59 -0
  43. package/dist/kit/cartesian.js.map +1 -0
  44. package/dist/kit/chart-border.d.ts +27 -0
  45. package/dist/kit/chart-border.d.ts.map +1 -0
  46. package/dist/kit/chart-border.js +28 -0
  47. package/dist/kit/chart-border.js.map +1 -0
  48. package/dist/kit/chart-canvas.d.ts +67 -0
  49. package/dist/kit/chart-canvas.d.ts.map +1 -0
  50. package/dist/kit/chart-canvas.js +68 -0
  51. package/dist/kit/chart-canvas.js.map +1 -0
  52. package/dist/kit/chart-legend.d.ts +164 -0
  53. package/dist/kit/chart-legend.d.ts.map +1 -0
  54. package/dist/kit/chart-legend.js +163 -0
  55. package/dist/kit/chart-legend.js.map +1 -0
  56. package/dist/kit/entries.d.ts +17 -0
  57. package/dist/kit/entries.d.ts.map +1 -0
  58. package/dist/kit/entries.js +19 -0
  59. package/dist/kit/entries.js.map +1 -0
  60. package/dist/kit/motion.d.ts +48 -0
  61. package/dist/kit/motion.d.ts.map +1 -0
  62. package/dist/kit/motion.js +63 -0
  63. package/dist/kit/motion.js.map +1 -0
  64. package/dist/kit/paints.d.ts +10 -0
  65. package/dist/kit/paints.d.ts.map +1 -0
  66. package/dist/kit/paints.js +12 -0
  67. package/dist/kit/paints.js.map +1 -0
  68. package/dist/kit/shared.d.ts +302 -0
  69. package/dist/kit/shared.d.ts.map +1 -0
  70. package/dist/kit/shared.js +496 -0
  71. package/dist/kit/shared.js.map +1 -0
  72. package/dist/kit/vertical-axis.d.ts +86 -0
  73. package/dist/kit/vertical-axis.d.ts.map +1 -0
  74. package/dist/kit/vertical-axis.js +141 -0
  75. package/dist/kit/vertical-axis.js.map +1 -0
  76. package/dist/line-chart/chart-line.d.ts +74 -0
  77. package/dist/line-chart/chart-line.d.ts.map +1 -0
  78. package/dist/line-chart/chart-line.js +135 -0
  79. package/dist/line-chart/chart-line.js.map +1 -0
  80. package/dist/line-chart/chart-region.d.ts +46 -0
  81. package/dist/line-chart/chart-region.d.ts.map +1 -0
  82. package/dist/line-chart/chart-region.js +67 -0
  83. package/dist/line-chart/chart-region.js.map +1 -0
  84. package/dist/line-chart/horizontal-axis.d.ts +79 -0
  85. package/dist/line-chart/horizontal-axis.d.ts.map +1 -0
  86. package/dist/line-chart/horizontal-axis.js +129 -0
  87. package/dist/line-chart/horizontal-axis.js.map +1 -0
  88. package/dist/line-chart/index.d.ts +22 -0
  89. package/dist/line-chart/index.d.ts.map +1 -0
  90. package/dist/line-chart/index.js +19 -0
  91. package/dist/line-chart/index.js.map +1 -0
  92. package/dist/line-chart/line-chart.d.ts +200 -0
  93. package/dist/line-chart/line-chart.d.ts.map +1 -0
  94. package/dist/line-chart/line-chart.js +473 -0
  95. package/dist/line-chart/line-chart.js.map +1 -0
  96. package/dist/line-chart/shared.d.ts +171 -0
  97. package/dist/line-chart/shared.d.ts.map +1 -0
  98. package/dist/line-chart/shared.js +285 -0
  99. package/dist/line-chart/shared.js.map +1 -0
  100. package/dist/line-chart/x-scale.d.ts +77 -0
  101. package/dist/line-chart/x-scale.d.ts.map +1 -0
  102. package/dist/line-chart/x-scale.js +313 -0
  103. package/dist/line-chart/x-scale.js.map +1 -0
  104. package/dist/nodes.d.ts +17 -0
  105. package/dist/nodes.d.ts.map +1 -0
  106. package/dist/nodes.js +18 -0
  107. package/dist/nodes.js.map +1 -0
  108. package/dist/pie-chart/index.d.ts +18 -0
  109. package/dist/pie-chart/index.d.ts.map +1 -0
  110. package/dist/pie-chart/index.js +14 -0
  111. package/dist/pie-chart/index.js.map +1 -0
  112. package/dist/pie-chart/pie-chart.d.ts +152 -0
  113. package/dist/pie-chart/pie-chart.d.ts.map +1 -0
  114. package/dist/pie-chart/pie-chart.js +222 -0
  115. package/dist/pie-chart/pie-chart.js.map +1 -0
  116. package/dist/pie-chart/pie-legend.d.ts +113 -0
  117. package/dist/pie-chart/pie-legend.d.ts.map +1 -0
  118. package/dist/pie-chart/pie-legend.js +117 -0
  119. package/dist/pie-chart/pie-legend.js.map +1 -0
  120. package/dist/pie-chart/pie-ring.d.ts +304 -0
  121. package/dist/pie-chart/pie-ring.d.ts.map +1 -0
  122. package/dist/pie-chart/pie-ring.js +680 -0
  123. package/dist/pie-chart/pie-ring.js.map +1 -0
  124. package/dist/pie-chart/shared.d.ts +216 -0
  125. package/dist/pie-chart/shared.d.ts.map +1 -0
  126. package/dist/pie-chart/shared.js +246 -0
  127. package/dist/pie-chart/shared.js.map +1 -0
  128. package/package.json +72 -3
  129. package/registry.json +23 -0
  130. package/src/bar-chart/bar-chart.ts +542 -0
  131. package/src/bar-chart/category-axis.ts +162 -0
  132. package/src/bar-chart/chart-bars.ts +287 -0
  133. package/src/bar-chart/index.ts +31 -0
  134. package/src/bar-chart/shared.ts +354 -0
  135. package/src/engine.ts +28 -0
  136. package/src/index.ts +5 -0
  137. package/src/kit/cartesian.ts +81 -0
  138. package/src/kit/chart-border.ts +50 -0
  139. package/src/kit/chart-canvas.ts +122 -0
  140. package/src/kit/chart-legend.ts +229 -0
  141. package/src/kit/entries.ts +20 -0
  142. package/src/kit/motion.ts +90 -0
  143. package/src/kit/paints.ts +15 -0
  144. package/src/kit/shared.ts +782 -0
  145. package/src/kit/vertical-axis.ts +194 -0
  146. package/src/line-chart/chart-line.ts +156 -0
  147. package/src/line-chart/chart-region.ts +90 -0
  148. package/src/line-chart/horizontal-axis.ts +151 -0
  149. package/src/line-chart/index.ts +39 -0
  150. package/src/line-chart/line-chart.ts +598 -0
  151. package/src/line-chart/shared.ts +473 -0
  152. package/src/line-chart/x-scale.ts +382 -0
  153. package/src/nodes.ts +18 -0
  154. package/src/pie-chart/index.ts +37 -0
  155. package/src/pie-chart/pie-chart.ts +296 -0
  156. package/src/pie-chart/pie-legend.ts +169 -0
  157. package/src/pie-chart/pie-ring.ts +848 -0
  158. package/src/pie-chart/shared.ts +496 -0
@@ -0,0 +1,296 @@
1
+ import {
2
+ Rect,
3
+ Types,
4
+ component2d,
5
+ easeOut,
6
+ type ChildView,
7
+ type DataRecord,
8
+ type NodeOf,
9
+ // Named so this component's emitted type reaches `Node2D` through the sdk, not core.
10
+ type Node2D,
11
+ type Node2DProps,
12
+ type Timeline,
13
+ } from "@motionscript/sdk"
14
+
15
+ import { asParts, fresh } from "../kit/entries"
16
+ import { beats, type Beat } from "../kit/motion"
17
+ import { clampUnit } from "../kit/shared"
18
+ import { PieLegend } from "./pie-legend"
19
+ import { PieRing } from "./pie-ring"
20
+ import {
21
+ DEFAULT_PIE_CHART_THEME,
22
+ lerpPieChartTheme,
23
+ resolvePieChartTheme,
24
+ resolvePieSlices,
25
+ type PieChartConfig,
26
+ type PieChartTheme,
27
+ type PieLabelMode,
28
+ type PieLabelPlacement,
29
+ type PieSlice,
30
+ } from "./shared"
31
+
32
+ export interface PieChartProps extends Node2DProps {
33
+ /** One row per slice — a plain record of field name to value. */
34
+ data: DataRecord[]
35
+ /** Key into each row for its slice caption, used on the labels and the legend. */
36
+ categoryField: string
37
+ /** Key into each row for its slice magnitude — the wedge's share of the ring. */
38
+ valueField: string
39
+ /**
40
+ * The chart's visual theme — slice palette, ring geometry, label and centre
41
+ * type, legend. Every branch is optional and deep-merged onto
42
+ * {@link DEFAULT_PIE_CHART_THEME}.
43
+ */
44
+ theme?: PieChartTheme
45
+ /** What the ring's labels say. */
46
+ labelMode?: PieLabelMode
47
+ /** Where they sit: inside their wedge, outside on a leader, or nowhere. */
48
+ labelPlacement?: PieLabelPlacement
49
+ /** Whether the legend column beside the ring is drawn at all. */
50
+ showLegend?: boolean
51
+ /** Gap between the ring and the legend, in px. */
52
+ gap?: number
53
+ /** Text set in the ring's hole — see `revealCenter`. */
54
+ centerLabel?: string
55
+ /** Smaller second line under {@link centerLabel}. */
56
+ centerCaption?: string
57
+ /**
58
+ * Whether the hole's summary is drawn at rest. `true` (the default) is the
59
+ * plain answer; a scene that wants the conclusion to land on a later beat sets
60
+ * this `false` and runs `revealCenter` when it gets there.
61
+ */
62
+ showCenter?: boolean
63
+ }
64
+
65
+ /** What the selection reads: the rows, how they are cut, and the pops the commands move. */
66
+ export interface PieChartValues {
67
+ readonly data: DataRecord[]
68
+ readonly categoryField: string
69
+ readonly valueField: string
70
+ readonly theme: PieChartConfig
71
+ readonly pops: number[]
72
+ }
73
+
74
+ /**
75
+ * How `enter` divides its duration: the wedges sweeping in, then the labels and
76
+ * the legend arriving together. Shares of the whole, so they sum to 1.
77
+ */
78
+ const SWEEP_SHARE = 0.65
79
+ const LABEL_SHARE = 0.35
80
+
81
+ const SLICE_ARG = Types.number(0, { min: 0, step: 1 })
82
+
83
+ /** The slices the ring and the legend draw, resolved from the rows and the palette. */
84
+ function slicesOf(s: PieChartValues): PieSlice[] {
85
+ return resolvePieSlices(s.data, s.categoryField, s.valueField, s.theme.sliceFills)
86
+ }
87
+
88
+ /** How far slice `index` is pushed out, in `[0, 1]`. */
89
+ function popAt(s: PieChartValues, index: number): number {
90
+ return clampUnit(s.pops[index] ?? 0)
91
+ }
92
+
93
+ /** Whether slice `index` is grown out past the ring's rim: past half way, so a slice mid-swell is not yet counted. */
94
+ export function isSliceSelected(s: PieChartValues, index: number): boolean {
95
+ return popAt(s, index) > 0.5
96
+ }
97
+
98
+ /**
99
+ * How far each slice is dimmed by the selection, one entry per slice: 1 while
100
+ * nothing is out, and for the selected slice itself; falling toward the theme's
101
+ * `dimOpacity` for the rest in proportion to how far the selection has grown.
102
+ */
103
+ function sliceDims(s: PieChartValues): number[] {
104
+ let focus = 0
105
+ for (let i = 0; i < s.data.length; i++) focus = Math.max(focus, popAt(s, i))
106
+ const dim = s.theme.spotlight.dimOpacity
107
+ if (focus <= 0) return s.data.map(() => 1)
108
+ return s.data.map((_, i) => 1 - (1 - clampUnit(dim)) * focus * (1 - popAt(s, i)))
109
+ }
110
+
111
+ type AnyTimeline = Timeline<any, any>
112
+
113
+ /**
114
+ * Every slice's pop eased from where it is to what `pop` asks for. A move that
115
+ * changes nothing still takes its slot, writing nothing.
116
+ */
117
+ function popping(timeline: AnyTimeline, s: PieChartValues, pop: (index: number) => number) {
118
+ const from = s.data.map((_, i) => popAt(s, i))
119
+ const targets = s.data.map((_, i) => clampUnit(pop(i)))
120
+ if (from.every((value, i) => value === targets[i])) return timeline.wait(timeline.duration)
121
+ return timeline.animate((t) => ({ pops: from.map((value, i) => value + (targets[i] - value) * t) }))
122
+ }
123
+
124
+ /** The ring and the legend, found through the chart's children: the last row of them is the one it built. */
125
+ function partsOf(children: readonly ChildView[]) {
126
+ for (let i = children.length - 1; i >= 0; i--) {
127
+ const row = children[i]
128
+ const ring = Rect.is(row) ? row.children.find(PieRing.is) : undefined
129
+ if (ring) return { ring, legend: row.children.find(PieLegend.is) ?? null }
130
+ }
131
+ return null
132
+ }
133
+
134
+ /**
135
+ * A pie or donut chart, composed from two parts laid out by a horizontal-flow
136
+ * {@link Rect} — the ring filling whatever the hugging legend leaves, both
137
+ * centred:
138
+ *
139
+ * - {@link PieRing} — the wedges, each sized by its share of the total, with its
140
+ * label inside its own band or pinned outside on a leader line, and the
141
+ * summary in the hole.
142
+ * - {@link PieLegend} — a column of swatch-and-caption rows naming each slice.
143
+ *
144
+ * **One mark per row, not per column**: a pie's palette is indexed by row and
145
+ * there is nothing to hide, since dropping a slice would re-cut every other
146
+ * wedge. `selectSlice` and its siblings are what a pie has instead — a slice
147
+ * swells out of the ring and everything else dims behind it.
148
+ *
149
+ * **Resting state is the finished chart**; `enter` arms every part on its first
150
+ * frame. The one exception is the hole's summary, which a scene can hold back
151
+ * with `showCenter: false`, because it is usually the chart's *conclusion*.
152
+ */
153
+ export const PieChart = component2d({
154
+ key: "pieChart",
155
+ state: {
156
+ data: fresh<DataRecord[]>(() => []),
157
+ categoryField: "",
158
+ valueField: "",
159
+ theme: Types.custom<PieChartTheme, PieChartConfig>(DEFAULT_PIE_CHART_THEME, { resolve: resolvePieChartTheme, lerp: lerpPieChartTheme }),
160
+ labelMode: Types.custom<PieLabelMode>("percent"),
161
+ labelPlacement: Types.custom<PieLabelPlacement>("leader"),
162
+ gap: 40,
163
+ centerLabel: "",
164
+ centerCaption: "",
165
+ /**
166
+ * How far each slice is pushed out of the ring, `0`–`1` per index. Held here
167
+ * rather than on the ring because two parts read it: the wedges grow out by
168
+ * it, and the legend entries dim by it. Seeded flush, one to a row.
169
+ */
170
+ pops: fresh<number[]>(() => []),
171
+ /** Read as the chart is built: the legend is a part the chart builds or doesn't. */
172
+ showLegend: Types.boolean(true, { animatable: false }),
173
+ /** Read as the chart is built: whether the hole's summary is drawn at rest. */
174
+ showCenter: Types.boolean(true, { animatable: false }),
175
+ },
176
+ defaults: {
177
+ // Its parts fill it; a node made of them would hug them.
178
+ width: "fill",
179
+ height: "fill",
180
+ pops: (state) => slicesOf(state).map(() => 0),
181
+ },
182
+ allowedChildren: [],
183
+ // The slice *structure* (one label and one legend row per row) is read once;
184
+ // the slices themselves, their paint and the selection are bound, so a theme
185
+ // tween re-paints and a `set` of `data` re-cuts the wedges.
186
+ children: (state) => {
187
+ const theme = () => state.theme
188
+ const slices = () => slicesOf(state)
189
+ const parts: Node2D[] = [
190
+ new PieRing({
191
+ width: "fill",
192
+ height: "fill",
193
+ slices,
194
+ ring: () => theme().ring,
195
+ label: () => theme().label,
196
+ centerStyle: () => theme().center,
197
+ labelMode: state.labelMode,
198
+ labelPlacement: state.labelPlacement,
199
+ pops: () => state.pops,
200
+ dimOpacity: () => theme().spotlight.dimOpacity,
201
+ centerLabel: state.centerLabel,
202
+ centerCaption: state.centerCaption,
203
+ centerReveal: state.showCenter === false ? 0 : 1,
204
+ }) as unknown as Node2D,
205
+ ]
206
+ if (state.showLegend !== false) {
207
+ parts.push(
208
+ new PieLegend({
209
+ slices,
210
+ legend: () => theme().legend,
211
+ dims: () => sliceDims(state),
212
+ // The column's spacing is the theme's as the chart was built, like the
213
+ // entries' type and chips.
214
+ gap: state.theme.legend.itemGap / 3,
215
+ padding: state.theme.legend.padding,
216
+ }) as unknown as Node2D
217
+ )
218
+ }
219
+ const row = new Rect({ flow: "horizontal", width: "fill", height: "fill", gap: state.gap, align: "center", children: parts })
220
+ return asParts([row as unknown as Node2D])
221
+ },
222
+ commands: {
223
+ /**
224
+ * Animate the whole chart in: the wedges sweep in clockwise from the theme's
225
+ * `startAngle`, then the labels fade up and the legend staggers in together.
226
+ * Its first frame arms the wedges, the labels and the legend; the hole's
227
+ * summary keeps its own signal. `duration` is the **whole** entrance.
228
+ */
229
+ enter: {
230
+ args: {},
231
+ // Held from the chart's arrival, so it never shows finished ahead of its draw.
232
+ entrance: true,
233
+ easing: easeOut(),
234
+ run: (timeline, _state, children) => {
235
+ const parts = partsOf(children)
236
+ if (!parts) return timeline.wait(timeline.duration)
237
+ const { ring, legend } = parts
238
+ const sweep = timeline.duration * SWEEP_SHARE
239
+ const labels = timeline.duration * LABEL_SHARE
240
+ const at0 = (piece: Beat["piece"]): Beat => ({ at: 0, duration: 0, piece })
241
+ return beats(timeline, [
242
+ at0(ring.to({ growth: 0, labelReveal: 0 })),
243
+ ...(legend ? [at0(legend.run("arm"))] : []),
244
+ { at: 0, duration: sweep, piece: ring.run("sweep") },
245
+ { at: sweep, duration: labels, piece: ring.run("revealLabels") },
246
+ ...(legend ? [{ at: sweep, duration: labels, piece: legend.run("enter") }] : []),
247
+ ])
248
+ },
249
+ },
250
+ /**
251
+ * Fade the hole's summary up. Held out of `enter` on purpose: what sits in a
252
+ * donut's hole is usually the chart's conclusion, so the scene lands it on
253
+ * its own beat. Pair it with `showCenter: false`.
254
+ */
255
+ revealCenter: {
256
+ args: {},
257
+ easing: easeOut(),
258
+ run: (timeline, _state, children) => partsOf(children)?.ring.run("revealCenter") ?? timeline.wait(timeline.duration),
259
+ },
260
+ /** Grow slice `index` out past the ring's rim and dim the rest, leaving any other selected slice where it is. */
261
+ selectSlice: {
262
+ args: { sliceIndex: SLICE_ARG },
263
+ easing: easeOut(),
264
+ run: (timeline, state) => {
265
+ const index = timeline.args.sliceIndex
266
+ return popping(timeline, state, (i) => (i === index ? 1 : popAt(state, i)))
267
+ },
268
+ },
269
+ /** Settle slice `index` back flush with the ring. */
270
+ deselectSlice: {
271
+ args: { sliceIndex: SLICE_ARG },
272
+ easing: easeOut(),
273
+ run: (timeline, state) => {
274
+ const index = timeline.args.sliceIndex
275
+ return popping(timeline, state, (i) => (i === index ? 0 : popAt(state, i)))
276
+ },
277
+ },
278
+ /** Move the focus to slice `index` alone, settling whatever else was out. */
279
+ selectOnlySlice: {
280
+ args: { sliceIndex: SLICE_ARG },
281
+ easing: easeOut(),
282
+ run: (timeline, state) => {
283
+ const index = timeline.args.sliceIndex
284
+ return popping(timeline, state, (i) => (i === index ? 1 : 0))
285
+ },
286
+ },
287
+ /** Settle every slice flush and bring the whole chart back to full. */
288
+ clearSelection: {
289
+ args: {},
290
+ easing: easeOut(),
291
+ run: (timeline, state) => popping(timeline, state, () => 0),
292
+ },
293
+ },
294
+ })
295
+
296
+ export type PieChart = NodeOf<typeof PieChart>
@@ -0,0 +1,169 @@
1
+ import {
2
+ Flow,
3
+ Paint,
4
+ Rect,
5
+ Shapes,
6
+ Text,
7
+ Types,
8
+ component2d,
9
+ textOps,
10
+ type NodeOf,
11
+ type RectProps,
12
+ // Named so the column's emitted type reaches the Rect surface it spreads through the sdk, not core.
13
+ type Alignment as _Alignment,
14
+ type CornerRadiusResolved as _CornerRadiusResolved,
15
+ type CornerStyleResolved as _CornerStyleResolved,
16
+ type Fill as _Fill,
17
+ type FillResolved as _FillResolved,
18
+ type FlowMode as _FlowMode,
19
+ type FlowResolved as _FlowResolved,
20
+ type GapSize as _GapSize,
21
+ type Node2D as _Node2D,
22
+ type Node2DProps as _Node2DProps,
23
+ type RectCornerRadius as _RectCornerRadius,
24
+ type RectCornerStyle as _RectCornerStyle,
25
+ type Shadow as _Shadow,
26
+ type ShadowResolved as _ShadowResolved,
27
+ type Stroke as _Stroke,
28
+ type StrokeResolved as _StrokeResolved,
29
+ type Vector2 as _Vector2,
30
+ } from "@motionscript/sdk"
31
+
32
+ import { fresh } from "../kit/entries"
33
+ import { armed, arrival, arrivalOf, arrivalsEntry, beats, frameEase, type Arrival } from "../kit/motion"
34
+ import {
35
+ DEFAULT_LEGEND,
36
+ clampUnit,
37
+ type LegendConfig,
38
+ } from "../kit/shared"
39
+ import type { PieSlice } from "./shared"
40
+
41
+ export interface PieLegendProps extends RectProps {
42
+ /** One entry per slice, in ring order. */
43
+ slices: PieSlice[]
44
+ /** Padding, caption style, gaps, and swatch geometry — see {@link LegendConfig}. */
45
+ legend: LegendConfig
46
+ /**
47
+ * Per-slice opacity multiplier, by index — the same signal that dims the ring,
48
+ * so an entry fades in step with the wedge it names. Missing entries read as 1.
49
+ */
50
+ dims: number[]
51
+ }
52
+
53
+ /** How far an entry starts to the right of its slot when it enters, in px. */
54
+ const SLIDE = 16
55
+
56
+ /**
57
+ * The legend of a {@link PieChart}: a **vertical-flow column** of entries, one per
58
+ * slice, each pairing the slice's caption with its colour swatch.
59
+ *
60
+ * A column rather than the cartesian charts' row, because it sits *beside* the
61
+ * ring rather than beneath the plot — a pie is as tall as it is wide, so the
62
+ * space it leaves over is a vertical strip. It is otherwise the same entry: the
63
+ * swatch carries the colour, the caption reads in the legend's neutral ink, and
64
+ * both take the shared {@link LegendConfig}.
65
+ *
66
+ * There is no show/hide here. A pie's marks are its *rows*, and a row that
67
+ * shouldn't be in the chart shouldn't be in the table — removing one would
68
+ * silently re-cut every other wedge's share, which is a different chart rather
69
+ * than the same chart with something hidden. Selection is what a pie has
70
+ * instead, and it arrives through {@link PieLegendProps.dims}.
71
+ */
72
+ export const PieLegend = component2d({
73
+ key: "pieLegend",
74
+ state: {
75
+ ...Paint.state,
76
+ ...Flow.state,
77
+ ...Shapes.corners,
78
+ slices: fresh<PieSlice[]>(() => []),
79
+ legend: Types.custom<LegendConfig>(DEFAULT_LEGEND),
80
+ dims: fresh<number[]>(() => []),
81
+ arrivals: arrivalsEntry(),
82
+ },
83
+ // A column, for the reason `ChartLegend` gives for its row: a `Rect` given no
84
+ // flow lays its children out `freeform`, every caption on top of the last.
85
+ defaults: {
86
+ flow: "vertical",
87
+ align: "centerLeft",
88
+ width: "hug",
89
+ height: "hug",
90
+ gap: (state) => state.legend.itemGap / 3,
91
+ padding: (state) => state.legend.padding,
92
+ },
93
+ // One entry per slice, ordered top → bottom. The selection dim rides a wrapper
94
+ // rather than the entry itself, so the entrance can animate the entry's own
95
+ // opacity without the two fighting over one value — opacity multiplies down
96
+ // the tree, which is exactly the composition wanted here.
97
+ children: (state) => {
98
+ const marker = state.legend.markerStyle
99
+ return state.slices.map((_, index) =>
100
+ Rect({
101
+ width: "hug",
102
+ height: "hug",
103
+ flow: "freeform",
104
+ opacity: () => clampUnit(state.dims[index] ?? 1),
105
+ children: [
106
+ Rect({
107
+ flow: "horizontal",
108
+ gap: 12,
109
+ align: "center",
110
+ width: "hug",
111
+ height: "hug",
112
+ opacity: () => arrivalOf(state.arrivals, index).opacity,
113
+ x: () => arrivalOf(state.arrivals, index).shift,
114
+ children: [
115
+ Rect({
116
+ width: marker.height,
117
+ height: marker.height,
118
+ cornerRadius: marker.borderRadius,
119
+ fill: () => state.slices[index]?.fill ?? "white",
120
+ stroke: marker.stroke,
121
+ shadow: marker.shadow,
122
+ }),
123
+ Text({
124
+ ...textOps.styleProps(state.legend.textStyle),
125
+ text: () => state.slices[index]?.category ?? "",
126
+ }),
127
+ ],
128
+ }),
129
+ ],
130
+ })
131
+ )
132
+ },
133
+ commands: {
134
+ ...Paint.commands,
135
+ /**
136
+ * Every entry at its pre-entrance state, shifted right and transparent: what
137
+ * a chart shows ahead of this legend's own beat in its entrance, since
138
+ * `enter` arms the entries only on its first frame.
139
+ */
140
+ arm: (timeline, state) =>
141
+ timeline.animate(() => ({ arrivals: armed([...state.slices.keys()], { opacity: 0, shift: SLIDE }) })),
142
+ /**
143
+ * Slide + fade every entry in from the right, staggered top-to-bottom. Its
144
+ * first frame arms them all: shifted right and transparent.
145
+ *
146
+ * The timeline's duration is the **whole** entrance: the stagger is carved
147
+ * out of it rather than added on top, so the command takes exactly the time
148
+ * the timeline laid out for it.
149
+ */
150
+ enter: (timeline, state) => {
151
+ const count = state.slices.length
152
+ if (count === 0) return timeline.wait(timeline.duration)
153
+ const from: Arrival = { opacity: 0, shift: SLIDE }
154
+ const arm = timeline.animate(() => ({ arrivals: armed([...state.slices.keys()], from) }))
155
+ // Each gap is a fifth of an entry's own move, the rhythm the axes use;
156
+ // solved for from the budget rather than added to it.
157
+ const per = timeline.duration / (1 + Math.max(0, count - 1) / 5)
158
+ const step = per / 5
159
+ const ease = frameEase(timeline)
160
+ const entries = state.slices.map((_, i) => ({ at: i * step, duration: per, piece: arrival(timeline, i, from, ease) }))
161
+ return timeline.together([arm, beats(timeline, entries)])
162
+ },
163
+ },
164
+ measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),
165
+ layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),
166
+ render: (ctx, state) => Paint.draw(ctx, state, Shapes.rect(ctx.size, state)),
167
+ })
168
+
169
+ export type PieLegend = NodeOf<typeof PieLegend>