@motionscript/charts 0.1.0-alpha.3 → 0.1.0-alpha.5

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 (93) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/LICENSE +201 -201
  3. package/NOTICE +48 -0
  4. package/README.md +85 -0
  5. package/dist/bar-chart/bar-chart.d.ts +28 -13
  6. package/dist/bar-chart/bar-chart.d.ts.map +1 -1
  7. package/dist/bar-chart/bar-chart.js +60 -56
  8. package/dist/bar-chart/bar-chart.js.map +1 -1
  9. package/dist/bar-chart/category-axis.js.map +1 -1
  10. package/dist/bar-chart/chart-bars.js.map +1 -1
  11. package/dist/bar-chart/index.js.map +1 -1
  12. package/dist/bar-chart/shared.d.ts +3 -3
  13. package/dist/bar-chart/shared.js +3 -3
  14. package/dist/bar-chart/shared.js.map +1 -1
  15. package/dist/browser/chunks/chunk-5ZPBV6BU.js +2 -0
  16. package/dist/browser/chunks/chunk-5ZPBV6BU.js.map +7 -0
  17. package/dist/browser/index.js +1 -1
  18. package/dist/browser/index.js.map +3 -3
  19. package/dist/browser/kit.js +1 -1
  20. package/dist/browser/manifest.json +3 -2
  21. package/dist/engine.js.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/kit/chart-border.js.map +1 -1
  24. package/dist/kit/chart-canvas.js.map +1 -1
  25. package/dist/kit/chart-legend.d.ts +4 -25
  26. package/dist/kit/chart-legend.d.ts.map +1 -1
  27. package/dist/kit/chart-legend.js +31 -55
  28. package/dist/kit/chart-legend.js.map +1 -1
  29. package/dist/kit/shared.d.ts +29 -6
  30. package/dist/kit/shared.d.ts.map +1 -1
  31. package/dist/kit/shared.js +64 -8
  32. package/dist/kit/shared.js.map +1 -1
  33. package/dist/kit/vertical-axis.js.map +1 -1
  34. package/dist/line-chart/chart-line.d.ts +2 -2
  35. package/dist/line-chart/chart-line.js.map +1 -1
  36. package/dist/line-chart/chart-region.js.map +1 -1
  37. package/dist/line-chart/horizontal-axis.js.map +1 -1
  38. package/dist/line-chart/index.js.map +1 -1
  39. package/dist/line-chart/line-chart.d.ts +9 -1
  40. package/dist/line-chart/line-chart.d.ts.map +1 -1
  41. package/dist/line-chart/line-chart.js +32 -8
  42. package/dist/line-chart/line-chart.js.map +1 -1
  43. package/dist/line-chart/shared.d.ts +3 -3
  44. package/dist/line-chart/shared.d.ts.map +1 -1
  45. package/dist/line-chart/shared.js +19 -4
  46. package/dist/line-chart/shared.js.map +1 -1
  47. package/dist/line-chart/x-scale.d.ts +1 -1
  48. package/dist/line-chart/x-scale.js +1 -1
  49. package/dist/line-chart/x-scale.js.map +1 -1
  50. package/dist/nodes.js.map +1 -1
  51. package/dist/pie-chart/index.js.map +1 -1
  52. package/dist/pie-chart/pie-chart.d.ts +2 -2
  53. package/dist/pie-chart/pie-chart.d.ts.map +1 -1
  54. package/dist/pie-chart/pie-chart.js +9 -7
  55. package/dist/pie-chart/pie-chart.js.map +1 -1
  56. package/dist/pie-chart/pie-legend.js +4 -4
  57. package/dist/pie-chart/pie-legend.js.map +1 -1
  58. package/dist/pie-chart/pie-ring.d.ts +13 -4
  59. package/dist/pie-chart/pie-ring.d.ts.map +1 -1
  60. package/dist/pie-chart/pie-ring.js +44 -14
  61. package/dist/pie-chart/pie-ring.js.map +1 -1
  62. package/dist/pie-chart/shared.d.ts +3 -3
  63. package/dist/pie-chart/shared.js +3 -3
  64. package/dist/pie-chart/shared.js.map +1 -1
  65. package/package.json +6 -5
  66. package/registry.json +23 -23
  67. package/src/bar-chart/bar-chart.ts +820 -814
  68. package/src/bar-chart/category-axis.ts +177 -177
  69. package/src/bar-chart/chart-bars.ts +310 -310
  70. package/src/bar-chart/index.ts +31 -31
  71. package/src/bar-chart/shared.ts +354 -354
  72. package/src/engine.ts +26 -26
  73. package/src/index.ts +5 -5
  74. package/src/kit/chart-border.ts +61 -61
  75. package/src/kit/chart-canvas.ts +157 -157
  76. package/src/kit/chart-legend.ts +245 -250
  77. package/src/kit/shared.ts +733 -675
  78. package/src/kit/vertical-axis.ts +224 -224
  79. package/src/line-chart/chart-line.ts +208 -208
  80. package/src/line-chart/chart-region.ts +135 -135
  81. package/src/line-chart/horizontal-axis.ts +202 -202
  82. package/src/line-chart/index.ts +39 -39
  83. package/src/line-chart/line-chart.ts +961 -929
  84. package/src/line-chart/shared.ts +473 -459
  85. package/src/line-chart/x-scale.ts +367 -367
  86. package/src/nodes.ts +20 -20
  87. package/src/pie-chart/index.ts +37 -37
  88. package/src/pie-chart/pie-chart.ts +383 -381
  89. package/src/pie-chart/pie-legend.ts +159 -159
  90. package/src/pie-chart/pie-ring.ts +935 -903
  91. package/src/pie-chart/shared.ts +490 -490
  92. package/dist/browser/chunks/chunk-RMHQ6GYU.js +0 -2
  93. package/dist/browser/chunks/chunk-RMHQ6GYU.js.map +0 -7
@@ -1,381 +1,383 @@
1
- import {
2
- Rect,
3
- command,
4
- node,
5
- Node2D,
6
- easeOut,
7
- property,
8
- type Command,
9
- type CommandArgs,
10
- type DataRecord,
11
- type EasingFunction,
12
- type NodeConfig,
13
- type Node2DProps,
14
- } from "@motionscript/sdk"
15
-
16
- import { clampUnit } from "../kit/shared"
17
- import { PieLegend } from "./pie-legend"
18
- import { PieRing } from "./pie-ring"
19
- import {
20
- DEFAULT_PIE_CHART_THEME,
21
- lerpPieChartTheme,
22
- resolvePieChartTheme,
23
- resolvePieSlices,
24
- type PieChartConfig,
25
- type PieChartTheme,
26
- type PieLabelMode,
27
- type PieLabelPlacement,
28
- type PieSlice,
29
- } from "./shared"
30
- import {
31
- asCommand,
32
- hold,
33
- sequence as sequenceOf,
34
- together,
35
- } from "@motionscript/sdk/component"
36
-
37
- export interface PieChartProps extends Node2DProps {
38
- /** One row per slice — a plain record of field name to value. */
39
- data: DataRecord[]
40
- /** Key into each row for its slice caption, used on the labels and the legend. */
41
- categoryField: string
42
- /** Key into each row for its slice magnitude — the wedge's share of the ring. */
43
- valueField: string
44
- /**
45
- * The chart's visual theme — slice palette, ring geometry, label and centre
46
- * type, legend. Every branch is optional and deep-merged onto
47
- * {@link DEFAULT_PIE_CHART_THEME}.
48
- */
49
- theme?: PieChartTheme
50
- /** What the ring's labels say. */
51
- labelMode?: PieLabelMode
52
- /** Where they sit: inside their wedge, outside on a leader, or nowhere. */
53
- labelPlacement?: PieLabelPlacement
54
- /** Whether the legend column beside the ring is drawn at all. */
55
- showLegend?: boolean
56
- /** Gap between the ring and the legend, in px. */
57
- gap?: number
58
- /** Text set in the ring's hole — see {@link revealCenter}. */
59
- centerLabel?: string
60
- /** Smaller second line under {@link centerLabel}. */
61
- centerCaption?: string
62
- /**
63
- * Whether the hole's summary is drawn at rest. `true` (the default) is the
64
- * plain answer; a scene that wants the conclusion to land on a later beat sets
65
- * this `false` and calls {@link revealCenter} when it gets there.
66
- */
67
- showCenter?: boolean
68
- }
69
-
70
- /**
71
- * How {@link PieChart.enter} divides its duration: the wedges sweeping in, then
72
- * the labels and the legend arriving together. Shares of the whole, so they sum
73
- * to 1 — the entrance takes exactly the time it was given, for the reason spelt
74
- * out on `LineChart.enter`.
75
- */
76
- const SWEEP_SHARE = 0.65
77
- const LABEL_SHARE = 0.35
78
-
79
- /** What the selection commands move: the chart's own {@link PieChart.pops}. */
80
- type SlicePops = { pops: number[] }
81
-
82
- /**
83
- * A pie or donut chart, composed from two independent parts rather than one
84
- * monolithic draw — the third of the chart family, built the same way as the
85
- * line and bar charts beside it:
86
- *
87
- * - {@link PieRing} — the wedges, each sized by its share of the total, with its
88
- * label set inside its own band or pinned outside on a leader line, and the
89
- * summary in the hole. The only part of the family that draws a path.
90
- * - {@link PieLegend} — a column of swatch-and-caption rows naming each slice.
91
- *
92
- * The two are laid out by a plain horizontal-flow {@link Rect}: the ring fills whatever the
93
- * hugging legend leaves, both centred, so the chart re-flows if its box changes.
94
- *
95
- * **One mark per row, not per column** — which is what makes this the odd one of
96
- * the three. A line or a bar chart plots *series*, so its colours belong to
97
- * columns and hiding one is a sensible thing to ask for. A pie plots rows, so its
98
- * palette is indexed by row and there is nothing to hide: dropping a slice would
99
- * silently re-cut every other wedge's share, which is a different chart rather
100
- * than the same chart with a series switched off. {@link selectSlice} and its
101
- * siblings are what a pie has instead — a slice swells out of the ring, its hole
102
- * edge staying put, and everything else dims behind it.
103
- *
104
- * **Resting state is the finished chart** — the same bargain the other two make:
105
- * the studio paints a node's Initial state on a paused canvas, so a chart that
106
- * only appeared once a command had run would be edited blind. {@link enter} arms
107
- * every part back to its pre-entrance state before animating. The one exception
108
- * is the hole's summary, which a scene can hold back with `showCenter: false`
109
- * because it is usually the chart's *conclusion* rather than part of its setup.
110
- */
111
- @node({
112
- key: "pieChart",
113
- parentKey: "node",
114
- forkable: true,
115
- layout: {
116
- children: "freeform",
117
- defaultWidthMode: "fixed",
118
- defaultHeightMode: "fixed",
119
- acceptsChildren: true,
120
- },
121
- seed: {
122
- width: 680,
123
- height: 480,
124
- },
125
- })
126
- export class PieChart extends Node2D<PieChartProps> {
127
- @property({ default: () => [] as DataRecord[] }) declare data: DataRecord[]
128
- @property({ default: "" }) declare categoryField: string
129
- @property({ default: "" }) declare valueField: string
130
- @property({
131
- default: DEFAULT_PIE_CHART_THEME,
132
- mapper: resolvePieChartTheme,
133
- tween: lerpPieChartTheme,
134
- })
135
- declare theme: PieChartTheme
136
- @property({ default: "percent" }) declare labelMode: PieLabelMode
137
- @property({ default: "leader" }) declare labelPlacement: PieLabelPlacement
138
- @property({ default: 40 }) declare gap: number
139
- @property({ default: "" }) declare centerLabel: string
140
- @property({ default: "" }) declare centerCaption: string
141
-
142
- /**
143
- * How far each slice is currently pushed out of the ring, `0`–`1` per index.
144
- *
145
- * Held here rather than on the ring because two parts read it: the wedges grow
146
- * out by it, and the legend entries dim by it. One signal, one tween, and the
147
- * two can't drift.
148
- */
149
- @property({ default: () => [] as number[] }) declare pops: number[]
150
-
151
- // ---- Part handles (built in the constructor) --------------------------
152
- private ring: PieRing
153
- private legend: PieLegend | null = null
154
-
155
- /** `this.theme` read back through its *resolved* shape — see `LineChart.theme`. */
156
- private get resolvedTheme(): PieChartConfig {
157
- return this.theme as unknown as PieChartConfig
158
- }
159
-
160
- /** The slices the ring and the legend draw, resolved from the rows and the palette. */
161
- private get slices(): PieSlice[] {
162
- return resolvePieSlices(
163
- this.data,
164
- this.categoryField,
165
- this.valueField,
166
- this.resolvedTheme.sliceFills
167
- )
168
- }
169
-
170
- /**
171
- * How far each slice is dimmed by the current selection, one entry per slice —
172
- * 1 while nothing is selected, and for the selected slice itself; falling
173
- * toward the theme's `dimOpacity` for the rest in proportion to how far the
174
- * selection has grown.
175
- */
176
- private sliceDims(): number[] {
177
- let focus = 0
178
- for (let i = 0; i < this.data.length; i++) {
179
- focus = Math.max(focus, this.popAt(i))
180
- }
181
- const dim = this.resolvedTheme.spotlight.dimOpacity
182
- if (focus <= 0) return this.data.map(() => 1)
183
- return this.data.map(
184
- (_, i) => 1 - (1 - clampUnit(dim)) * focus * (1 - this.popAt(i))
185
- )
186
- }
187
-
188
- /** How far slice `index` is currently pushed out, in `[0, 1]`. */
189
- private popAt(index: number): number {
190
- return clampUnit(this.pops[index] ?? 0)
191
- }
192
-
193
- constructor(props?: NodeConfig<PieChart, PieChartProps>) {
194
- super(props)
195
-
196
- // The whole chart is composed from plain props/`data` — no context needed,
197
- // so the parts are built here (super() applied the props above). The slice
198
- // *structure* (one wedge and one legend row each) is read once, like every
199
- // other chart's series list; everything the parts draw with is passed as a
200
- // closure, so `chart.to({ theme })` genuinely re-paints the ring.
201
- const slices = this.slices
202
- const showLegend = props?.showLegend !== false
203
- this.pops = slices.map(() => 0)
204
-
205
- this.ring = new PieRing({
206
- width: "fill",
207
- height: "fill",
208
- slices,
209
- ring: () => this.resolvedTheme.ring,
210
- label: () => this.resolvedTheme.label,
211
- centerStyle: () => this.resolvedTheme.center,
212
- labelMode: this.labelMode,
213
- labelPlacement: this.labelPlacement,
214
- pops: () => this.pops,
215
- dimOpacity: () => this.resolvedTheme.spotlight.dimOpacity,
216
- centerLabel: this.centerLabel,
217
- centerCaption: this.centerCaption,
218
- centerReveal: props?.showCenter === false ? 0 : 1,
219
- })
220
-
221
- const children: Node2D[] = [this.ring]
222
- if (showLegend) {
223
- this.legend = new PieLegend({
224
- slices,
225
- legend: () => this.resolvedTheme.legend,
226
- dims: () => this.sliceDims(),
227
- })
228
- children.push(this.legend)
229
- }
230
-
231
- this.add(
232
- new Rect({ flow: "horizontal",
233
- width: "fill",
234
- height: "fill",
235
- gap: this.gap,
236
- align: "center",
237
- children,
238
- })
239
- )
240
- }
241
-
242
- // ---- Orchestrated entrance --------------------------------------------
243
-
244
- /**
245
- * Prime every part at its pre-entrance state — no wedges swept, no labels, the
246
- * legend shifted and transparent.
247
- *
248
- * Called by {@link enter} before its first frame so nothing flashes ahead of
249
- * its beat. Idempotent, and public so a scene can hide a chart ahead of time
250
- * without starting the entrance. The hole's summary is deliberately untouched:
251
- * it has its own signal, so a scene that set it up to land later keeps that.
252
- */
253
- arm(): void {
254
- this.ring.set({ growth: 0, labelReveal: 0 })
255
- this.legend?.arm()
256
- }
257
-
258
- /**
259
- * Animate the whole chart in: the wedges sweep in clockwise from the theme's
260
- * `startAngle`, then the labels fade up and the legend staggers in together.
261
- *
262
- * `duration` is the **whole** entrance; the phases are shares of it.
263
- */
264
- @command()
265
- enter(
266
- args: CommandArgs<Record<string, never>> & { duration: number }
267
- ): Command<Record<string, never>> {
268
- const duration = args.duration
269
- const easing = args.easing ?? easeOut()
270
- this.arm()
271
-
272
- return asCommand(
273
- sequenceOf(
274
- this.ring.sweep({ duration: duration * SWEEP_SHARE, easing }),
275
- together(
276
- this.ring.revealLabels({ duration: duration * LABEL_SHARE, easing }),
277
- this.legend
278
- ? this.legend.enter({ duration: duration * LABEL_SHARE, easing })
279
- : hold(duration * LABEL_SHARE)
280
- )
281
- ),
282
- duration
283
- )
284
- }
285
-
286
- /**
287
- * Fade the hole's summary up.
288
- *
289
- * Held out of {@link enter} on purpose: what sits in a donut's hole is usually
290
- * the chart's conclusion, so the scene lands it on the beat it belongs to
291
- * rather than giving it away with the first frame. Pair it with
292
- * `showCenter: false`, which is what leaves the hole clear to begin with.
293
- */
294
- @command()
295
- revealCenter(
296
- args: CommandArgs<Record<string, never>> & { duration?: number } = {}
297
- ): Command<{ centerReveal: number }> {
298
- return this.ring.revealCenter({ duration: args.duration ?? 0.6, easing: args.easing ?? easeOut() })
299
- }
300
-
301
- // ---- Selection ---------------------------------------------------------
302
-
303
- /** True when slice `index` is currently grown out past the ring's rim. */
304
- isSelected(index: number): boolean {
305
- return this.popAt(index) > 0.5
306
- }
307
-
308
- /**
309
- * Grow slice `index` out past the ring's rim and dim the rest of the chart
310
- * behind it, leaving any other selected slice where it is.
311
- */
312
- @command({ args: [{ key: "sliceIndex", kind: "number", default: 0, min: 0, step: 1 }] })
313
- selectSlice(
314
- args: CommandArgs<{ sliceIndex: number }> & { duration?: number }
315
- ): Command<SlicePops> {
316
- const { sliceIndex: index } = args.data as { sliceIndex: number }
317
- const duration = args.duration ?? 0.45
318
- const easing = args.easing ?? easeOut()
319
- return this.tweenPops((i) => (i === index ? 1 : this.popAt(i)), duration, easing)
320
- }
321
-
322
- /** Settle slice `index` back flush with the ring. */
323
- @command({ args: [{ key: "sliceIndex", kind: "number", default: 0, min: 0, step: 1 }] })
324
- deselectSlice(
325
- args: CommandArgs<{ sliceIndex: number }> & { duration?: number }
326
- ): Command<SlicePops> {
327
- const { sliceIndex: index } = args.data as { sliceIndex: number }
328
- const duration = args.duration ?? 0.45
329
- const easing = args.easing ?? easeOut()
330
- return this.tweenPops((i) => (i === index ? 0 : this.popAt(i)), duration, easing)
331
- }
332
-
333
- /** Move the focus to slice `index` alone, settling whatever else was out. */
334
- @command({ args: [{ key: "sliceIndex", kind: "number", default: 0, min: 0, step: 1 }] })
335
- selectOnlySlice(
336
- args: CommandArgs<{ sliceIndex: number }> & { duration?: number }
337
- ): Command<SlicePops> {
338
- const { sliceIndex: index } = args.data as { sliceIndex: number }
339
- const duration = args.duration ?? 0.45
340
- const easing = args.easing ?? easeOut()
341
- return this.tweenPops((i) => (i === index ? 1 : 0), duration, easing)
342
- }
343
-
344
- /** Settle every slice flush and bring the whole chart back to full. */
345
- @command()
346
- clearSelection(
347
- args: CommandArgs<Record<string, never>> & { duration?: number } = {}
348
- ): Command<SlicePops> {
349
- const duration = args.duration ?? 0.45
350
- const easing = args.easing ?? easeOut()
351
- return this.tweenPops(() => 0, duration, easing)
352
- }
353
-
354
- /**
355
- * Ease every slice's pop from where it is now to what `pop` asks for.
356
- *
357
- * Consumes its full duration even when nothing moves: in the studio a
358
- * command's duration is what the timeline lays out and what its parallel
359
- * siblings are timed against, so a no-op that took no frames would pull
360
- * everything after it forward.
361
- *
362
- * `from` and the targets are read when the command is *built*, which for a
363
- * driven scene is with the node in the state its own start time implies — so a
364
- * select that follows another starts from where that one left the ring.
365
- */
366
- private tweenPops(
367
- pop: (index: number) => number,
368
- duration: number,
369
- easing: EasingFunction
370
- ): Command<SlicePops> {
371
- const from = this.data.map((_, i) => this.popAt(i))
372
- const targets = this.data.map((_, i) => clampUnit(pop(i)))
373
- if (from.every((value, i) => value === targets[i])) return this.command<SlicePops>(() => ({}), duration)
374
-
375
- return this.command<SlicePops>(
376
- (t) => ({ pops: from.map((value, i) => value + (targets[i] - value) * t) }),
377
- duration,
378
- easing
379
- )
380
- }
381
- }
1
+ import {
2
+ Rect,
3
+ command,
4
+ node,
5
+ Node2D,
6
+ easeOut,
7
+ property,
8
+ type Command,
9
+ type CommandArgs,
10
+ type DataRecord,
11
+ type EasingFunction,
12
+ type NodeConfig,
13
+ type Node2DProps,
14
+ } from "@motionscript/sdk"
15
+
16
+ import { clampUnit } from "../kit/shared"
17
+ import { PieLegend } from "./pie-legend"
18
+ import { PieRing } from "./pie-ring"
19
+ import {
20
+ DEFAULT_PIE_CHART_THEME,
21
+ lerpPieChartTheme,
22
+ resolvePieChartTheme,
23
+ resolvePieSlices,
24
+ type PieChartConfig,
25
+ type PieChartTheme,
26
+ type PieLabelMode,
27
+ type PieLabelPlacement,
28
+ type PieSlice,
29
+ } from "./shared"
30
+ import {
31
+ asCommand,
32
+ hold,
33
+ sequence as sequenceOf,
34
+ together,
35
+ } from "@motionscript/sdk/component"
36
+
37
+ export interface PieChartProps extends Node2DProps {
38
+ /** One row per slice — a plain record of field name to value. */
39
+ data: DataRecord[]
40
+ /** Key into each row for its slice caption, used on the labels and the legend. */
41
+ categoryField: string
42
+ /** Key into each row for its slice magnitude — the wedge's share of the ring. */
43
+ valueField: string
44
+ /**
45
+ * The chart's visual theme — slice palette, ring geometry, label and centre
46
+ * type, legend. Every branch is optional and deep-merged onto
47
+ * {@link DEFAULT_PIE_CHART_THEME}.
48
+ */
49
+ theme?: PieChartTheme
50
+ /** What the ring's labels say. */
51
+ labelMode?: PieLabelMode
52
+ /** Where they sit: inside their wedge, outside on a leader, or nowhere. */
53
+ labelPlacement?: PieLabelPlacement
54
+ /** Whether the legend column beside the ring is drawn at all. */
55
+ showLegend?: boolean
56
+ /** Gap between the ring and the legend, in px. */
57
+ gap?: number
58
+ /** Text set in the ring's hole — see {@link revealCenter}. */
59
+ centerLabel?: string
60
+ /** Smaller second line under {@link centerLabel}. */
61
+ centerCaption?: string
62
+ /**
63
+ * Whether the hole's summary is drawn at rest. `true` (the default) is the
64
+ * plain answer; a scene that wants the conclusion to land on a later beat sets
65
+ * this `false` and calls {@link revealCenter} when it gets there.
66
+ */
67
+ showCenter?: boolean
68
+ }
69
+
70
+ /**
71
+ * How {@link PieChart.enter} divides its duration: the wedges sweeping in, then
72
+ * the labels and the legend arriving together. Shares of the whole, so they sum
73
+ * to 1 — the entrance takes exactly the time it was given, for the reason spelt
74
+ * out on `LineChart.enter`.
75
+ */
76
+ const SWEEP_SHARE = 0.65
77
+ const LABEL_SHARE = 0.35
78
+
79
+ /** What the selection commands move: the chart's own {@link PieChart.pops}. */
80
+ type SlicePops = { pops: number[] }
81
+
82
+ /**
83
+ * A pie or donut chart, composed from two independent parts rather than one
84
+ * monolithic draw — the third of the chart family, built the same way as the
85
+ * line and bar charts beside it:
86
+ *
87
+ * - {@link PieRing} — the wedges, each sized by its share of the total, with its
88
+ * label set inside its own band or pinned outside on a leader line, and the
89
+ * summary in the hole. The only part of the family that draws a path.
90
+ * - {@link PieLegend} — a column of swatch-and-caption rows naming each slice.
91
+ *
92
+ * The two are laid out by a plain horizontal-flow {@link Rect}: the ring fills whatever the
93
+ * hugging legend leaves, both centred, so the chart re-flows if its box changes.
94
+ *
95
+ * **One mark per row, not per column** — which is what makes this the odd one of
96
+ * the three. A line or a bar chart plots *series*, so its colours belong to
97
+ * columns and hiding one is a sensible thing to ask for. A pie plots rows, so its
98
+ * palette is indexed by row and there is nothing to hide: dropping a slice would
99
+ * silently re-cut every other wedge's share, which is a different chart rather
100
+ * than the same chart with a series switched off. {@link selectSlice} and its
101
+ * siblings are what a pie has instead — a slice swells out of the ring, its hole
102
+ * edge staying put, and everything else dims behind it.
103
+ *
104
+ * **Resting state is the finished chart** — the same bargain the other two make:
105
+ * an editor paints a node's Initial state on a paused canvas, so a chart that
106
+ * only appeared once a command had run would be edited blind. {@link enter} arms
107
+ * every part back to its pre-entrance state before animating. The one exception
108
+ * is the hole's summary, which a scene can hold back with `showCenter: false`
109
+ * because it is usually the chart's *conclusion* rather than part of its setup.
110
+ */
111
+ @node({
112
+ key: "pieChart",
113
+ parentKey: "node",
114
+ forkable: true,
115
+ layout: {
116
+ children: "freeform",
117
+ defaultWidthMode: "fixed",
118
+ defaultHeightMode: "fixed",
119
+ acceptsChildren: true,
120
+ },
121
+ seed: {
122
+ width: 680,
123
+ height: 480,
124
+ },
125
+ })
126
+ export class PieChart extends Node2D<PieChartProps> {
127
+ @property({ default: () => [] as DataRecord[] }) declare data: DataRecord[]
128
+ @property({ default: "" }) declare categoryField: string
129
+ @property({ default: "" }) declare valueField: string
130
+ @property({
131
+ default: DEFAULT_PIE_CHART_THEME,
132
+ mapper: resolvePieChartTheme,
133
+ tween: lerpPieChartTheme,
134
+ })
135
+ declare theme: PieChartTheme
136
+ @property({ default: "percent" }) declare labelMode: PieLabelMode
137
+ @property({ default: "leader" }) declare labelPlacement: PieLabelPlacement
138
+ @property({ default: 40 }) declare gap: number
139
+ @property({ default: "" }) declare centerLabel: string
140
+ @property({ default: "" }) declare centerCaption: string
141
+
142
+ /**
143
+ * How far each slice is currently pushed out of the ring, `0`–`1` per index.
144
+ *
145
+ * Held here rather than on the ring because two parts read it: the wedges grow
146
+ * out by it, and the legend entries dim by it. One signal, one tween, and the
147
+ * two can't drift.
148
+ */
149
+ @property({ default: () => [] as number[] }) declare pops: number[]
150
+
151
+ // ---- Part handles (built in the constructor) --------------------------
152
+ private ring: PieRing
153
+ private legend: PieLegend | null = null
154
+
155
+ /** `this.theme` read back through its *resolved* shape — see `LineChart.theme`. */
156
+ private get resolvedTheme(): PieChartConfig {
157
+ return this.theme as unknown as PieChartConfig
158
+ }
159
+
160
+ /** The slices the ring and the legend draw, resolved from the rows and the palette. */
161
+ private get slices(): PieSlice[] {
162
+ return resolvePieSlices(
163
+ this.data,
164
+ this.categoryField,
165
+ this.valueField,
166
+ this.resolvedTheme.sliceFills
167
+ )
168
+ }
169
+
170
+ /**
171
+ * How far each slice is dimmed by the current selection, one entry per slice —
172
+ * 1 while nothing is selected, and for the selected slice itself; falling
173
+ * toward the theme's `dimOpacity` for the rest in proportion to how far the
174
+ * selection has grown.
175
+ */
176
+ private sliceDims(): number[] {
177
+ let focus = 0
178
+ for (let i = 0; i < this.data.length; i++) {
179
+ focus = Math.max(focus, this.popAt(i))
180
+ }
181
+ const dim = this.resolvedTheme.spotlight.dimOpacity
182
+ if (focus <= 0) return this.data.map(() => 1)
183
+ return this.data.map(
184
+ (_, i) => 1 - (1 - clampUnit(dim)) * focus * (1 - this.popAt(i))
185
+ )
186
+ }
187
+
188
+ /** How far slice `index` is currently pushed out, in `[0, 1]`. */
189
+ private popAt(index: number): number {
190
+ return clampUnit(this.pops[index] ?? 0)
191
+ }
192
+
193
+ constructor(props?: NodeConfig<PieChart, PieChartProps>) {
194
+ super(props)
195
+
196
+ // The whole chart is composed from plain props/`data` — no context needed,
197
+ // so the parts are built here (super() applied the props above). The slice
198
+ // *structure* (one label and one legend row per row of `data`) is read once,
199
+ // like every other chart's series list; everything the parts draw with,
200
+ // including the slices themselves and the paint they take from the palette,
201
+ // is passed as a closure, so `chart.to({ theme })` genuinely re-paints the
202
+ // ring and the swatches and a `set` of `data` re-cuts the wedges.
203
+ const slices = this.slices
204
+ const showLegend = props?.showLegend !== false
205
+ this.pops = slices.map(() => 0)
206
+
207
+ this.ring = new PieRing({
208
+ width: "fill",
209
+ height: "fill",
210
+ slices: () => this.slices,
211
+ ring: () => this.resolvedTheme.ring,
212
+ label: () => this.resolvedTheme.label,
213
+ centerStyle: () => this.resolvedTheme.center,
214
+ labelMode: this.labelMode,
215
+ labelPlacement: this.labelPlacement,
216
+ pops: () => this.pops,
217
+ dimOpacity: () => this.resolvedTheme.spotlight.dimOpacity,
218
+ centerLabel: this.centerLabel,
219
+ centerCaption: this.centerCaption,
220
+ centerReveal: props?.showCenter === false ? 0 : 1,
221
+ })
222
+
223
+ const children: Node2D[] = [this.ring]
224
+ if (showLegend) {
225
+ this.legend = new PieLegend({
226
+ slices: () => this.slices,
227
+ legend: () => this.resolvedTheme.legend,
228
+ dims: () => this.sliceDims(),
229
+ })
230
+ children.push(this.legend)
231
+ }
232
+
233
+ this.add(
234
+ new Rect({ flow: "horizontal",
235
+ width: "fill",
236
+ height: "fill",
237
+ gap: this.gap,
238
+ align: "center",
239
+ children,
240
+ })
241
+ )
242
+ }
243
+
244
+ // ---- Orchestrated entrance --------------------------------------------
245
+
246
+ /**
247
+ * Prime every part at its pre-entrance state — no wedges swept, no labels, the
248
+ * legend shifted and transparent.
249
+ *
250
+ * Called by {@link enter} before its first frame so nothing flashes ahead of
251
+ * its beat. Idempotent, and public so a scene can hide a chart ahead of time
252
+ * without starting the entrance. The hole's summary is deliberately untouched:
253
+ * it has its own signal, so a scene that set it up to land later keeps that.
254
+ */
255
+ arm(): void {
256
+ this.ring.set({ growth: 0, labelReveal: 0 })
257
+ this.legend?.arm()
258
+ }
259
+
260
+ /**
261
+ * Animate the whole chart in: the wedges sweep in clockwise from the theme's
262
+ * `startAngle`, then the labels fade up and the legend staggers in together.
263
+ *
264
+ * `duration` is the **whole** entrance; the phases are shares of it.
265
+ */
266
+ @command()
267
+ enter(
268
+ args: CommandArgs<Record<string, never>> & { duration: number }
269
+ ): Command<Record<string, never>> {
270
+ const duration = args.duration
271
+ const easing = args.easing ?? easeOut()
272
+ this.arm()
273
+
274
+ return asCommand(
275
+ sequenceOf(
276
+ this.ring.sweep({ duration: duration * SWEEP_SHARE, easing }),
277
+ together(
278
+ this.ring.revealLabels({ duration: duration * LABEL_SHARE, easing }),
279
+ this.legend
280
+ ? this.legend.enter({ duration: duration * LABEL_SHARE, easing })
281
+ : hold(duration * LABEL_SHARE)
282
+ )
283
+ ),
284
+ duration
285
+ )
286
+ }
287
+
288
+ /**
289
+ * Fade the hole's summary up.
290
+ *
291
+ * Held out of {@link enter} on purpose: what sits in a donut's hole is usually
292
+ * the chart's conclusion, so the scene lands it on the beat it belongs to
293
+ * rather than giving it away with the first frame. Pair it with
294
+ * `showCenter: false`, which is what leaves the hole clear to begin with.
295
+ */
296
+ @command()
297
+ revealCenter(
298
+ args: CommandArgs<Record<string, never>> & { duration?: number } = {}
299
+ ): Command<{ centerReveal: number }> {
300
+ return this.ring.revealCenter({ duration: args.duration ?? 0.6, easing: args.easing ?? easeOut() })
301
+ }
302
+
303
+ // ---- Selection ---------------------------------------------------------
304
+
305
+ /** True when slice `index` is currently grown out past the ring's rim. */
306
+ isSelected(index: number): boolean {
307
+ return this.popAt(index) > 0.5
308
+ }
309
+
310
+ /**
311
+ * Grow slice `index` out past the ring's rim and dim the rest of the chart
312
+ * behind it, leaving any other selected slice where it is.
313
+ */
314
+ @command({ args: [{ key: "sliceIndex", kind: "number", default: 0, min: 0, step: 1 }] })
315
+ selectSlice(
316
+ args: CommandArgs<{ sliceIndex: number }> & { duration?: number }
317
+ ): Command<SlicePops> {
318
+ const { sliceIndex: index } = args.data as { sliceIndex: number }
319
+ const duration = args.duration ?? 0.45
320
+ const easing = args.easing ?? easeOut()
321
+ return this.tweenPops((i) => (i === index ? 1 : this.popAt(i)), duration, easing)
322
+ }
323
+
324
+ /** Settle slice `index` back flush with the ring. */
325
+ @command({ args: [{ key: "sliceIndex", kind: "number", default: 0, min: 0, step: 1 }] })
326
+ deselectSlice(
327
+ args: CommandArgs<{ sliceIndex: number }> & { duration?: number }
328
+ ): Command<SlicePops> {
329
+ const { sliceIndex: index } = args.data as { sliceIndex: number }
330
+ const duration = args.duration ?? 0.45
331
+ const easing = args.easing ?? easeOut()
332
+ return this.tweenPops((i) => (i === index ? 0 : this.popAt(i)), duration, easing)
333
+ }
334
+
335
+ /** Move the focus to slice `index` alone, settling whatever else was out. */
336
+ @command({ args: [{ key: "sliceIndex", kind: "number", default: 0, min: 0, step: 1 }] })
337
+ selectOnlySlice(
338
+ args: CommandArgs<{ sliceIndex: number }> & { duration?: number }
339
+ ): Command<SlicePops> {
340
+ const { sliceIndex: index } = args.data as { sliceIndex: number }
341
+ const duration = args.duration ?? 0.45
342
+ const easing = args.easing ?? easeOut()
343
+ return this.tweenPops((i) => (i === index ? 1 : 0), duration, easing)
344
+ }
345
+
346
+ /** Settle every slice flush and bring the whole chart back to full. */
347
+ @command()
348
+ clearSelection(
349
+ args: CommandArgs<Record<string, never>> & { duration?: number } = {}
350
+ ): Command<SlicePops> {
351
+ const duration = args.duration ?? 0.45
352
+ const easing = args.easing ?? easeOut()
353
+ return this.tweenPops(() => 0, duration, easing)
354
+ }
355
+
356
+ /**
357
+ * Ease every slice's pop from where it is now to what `pop` asks for.
358
+ *
359
+ * Consumes its full duration even when nothing moves: in an editor a
360
+ * command's duration is what the timeline lays out and what its parallel
361
+ * siblings are timed against, so a no-op that took no frames would pull
362
+ * everything after it forward.
363
+ *
364
+ * `from` and the targets are read when the command is *built*, which for a
365
+ * driven scene is with the node in the state its own start time implies — so a
366
+ * select that follows another starts from where that one left the ring.
367
+ */
368
+ private tweenPops(
369
+ pop: (index: number) => number,
370
+ duration: number,
371
+ easing: EasingFunction
372
+ ): Command<SlicePops> {
373
+ const from = this.data.map((_, i) => this.popAt(i))
374
+ const targets = this.data.map((_, i) => clampUnit(pop(i)))
375
+ if (from.every((value, i) => value === targets[i])) return this.command<SlicePops>(() => ({}), duration)
376
+
377
+ return this.command<SlicePops>(
378
+ (t) => ({ pops: from.map((value, i) => value + (targets[i] - value) * t) }),
379
+ duration,
380
+ easing
381
+ )
382
+ }
383
+ }