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

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 (154) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/LICENSE +201 -201
  3. package/NOTICE +48 -0
  4. package/README.md +99 -0
  5. package/dist/bar-chart/bar-chart.d.ts +93 -231
  6. package/dist/bar-chart/bar-chart.d.ts.map +1 -1
  7. package/dist/bar-chart/bar-chart.js +378 -565
  8. package/dist/bar-chart/bar-chart.js.map +1 -1
  9. package/dist/bar-chart/category-axis.d.ts +24 -41
  10. package/dist/bar-chart/category-axis.d.ts.map +1 -1
  11. package/dist/bar-chart/category-axis.js +93 -115
  12. package/dist/bar-chart/category-axis.js.map +1 -1
  13. package/dist/bar-chart/chart-bars.d.ts +36 -70
  14. package/dist/bar-chart/chart-bars.d.ts.map +1 -1
  15. package/dist/bar-chart/chart-bars.js +156 -210
  16. package/dist/bar-chart/chart-bars.js.map +1 -1
  17. package/dist/bar-chart/index.d.ts +2 -2
  18. package/dist/bar-chart/index.d.ts.map +1 -1
  19. package/dist/bar-chart/index.js +1 -1
  20. package/dist/bar-chart/index.js.map +1 -1
  21. package/dist/bar-chart/shared.d.ts +6 -6
  22. package/dist/bar-chart/shared.d.ts.map +1 -1
  23. package/dist/bar-chart/shared.js +6 -6
  24. package/dist/bar-chart/shared.js.map +1 -1
  25. package/dist/browser/chunks/chunk-XROBIRQK.js +2 -0
  26. package/dist/browser/chunks/chunk-XROBIRQK.js.map +7 -0
  27. package/dist/browser/index.js +1 -1
  28. package/dist/browser/index.js.map +3 -3
  29. package/dist/browser/kit.js +1 -1
  30. package/dist/browser/manifest.json +3 -2
  31. package/dist/engine.d.ts +8 -6
  32. package/dist/engine.d.ts.map +1 -1
  33. package/dist/engine.js +8 -6
  34. package/dist/engine.js.map +1 -1
  35. package/dist/index.js.map +1 -1
  36. package/dist/kit/cartesian.d.ts +44 -0
  37. package/dist/kit/cartesian.d.ts.map +1 -0
  38. package/dist/kit/cartesian.js +59 -0
  39. package/dist/kit/cartesian.js.map +1 -0
  40. package/dist/kit/chart-border.d.ts +8 -11
  41. package/dist/kit/chart-border.d.ts.map +1 -1
  42. package/dist/kit/chart-border.js +15 -32
  43. package/dist/kit/chart-border.js.map +1 -1
  44. package/dist/kit/chart-canvas.d.ts +23 -21
  45. package/dist/kit/chart-canvas.d.ts.map +1 -1
  46. package/dist/kit/chart-canvas.js +33 -90
  47. package/dist/kit/chart-canvas.js.map +1 -1
  48. package/dist/kit/chart-legend.d.ts +79 -88
  49. package/dist/kit/chart-legend.d.ts.map +1 -1
  50. package/dist/kit/chart-legend.js +137 -186
  51. package/dist/kit/chart-legend.js.map +1 -1
  52. package/dist/kit/entries.d.ts +17 -0
  53. package/dist/kit/entries.d.ts.map +1 -0
  54. package/dist/kit/entries.js +19 -0
  55. package/dist/kit/entries.js.map +1 -0
  56. package/dist/kit/motion.d.ts +48 -0
  57. package/dist/kit/motion.d.ts.map +1 -0
  58. package/dist/kit/motion.js +63 -0
  59. package/dist/kit/motion.js.map +1 -0
  60. package/dist/kit/paints.d.ts +10 -0
  61. package/dist/kit/paints.d.ts.map +1 -0
  62. package/dist/kit/paints.js +12 -0
  63. package/dist/kit/paints.js.map +1 -0
  64. package/dist/kit/shared.d.ts +59 -8
  65. package/dist/kit/shared.d.ts.map +1 -1
  66. package/dist/kit/shared.js +105 -10
  67. package/dist/kit/shared.js.map +1 -1
  68. package/dist/kit/vertical-axis.d.ts +36 -61
  69. package/dist/kit/vertical-axis.d.ts.map +1 -1
  70. package/dist/kit/vertical-axis.js +97 -132
  71. package/dist/kit/vertical-axis.js.map +1 -1
  72. package/dist/line-chart/chart-line.d.ts +27 -53
  73. package/dist/line-chart/chart-line.d.ts.map +1 -1
  74. package/dist/line-chart/chart-line.js +89 -120
  75. package/dist/line-chart/chart-line.js.map +1 -1
  76. package/dist/line-chart/chart-region.d.ts +14 -14
  77. package/dist/line-chart/chart-region.d.ts.map +1 -1
  78. package/dist/line-chart/chart-region.js +26 -64
  79. package/dist/line-chart/chart-region.js.map +1 -1
  80. package/dist/line-chart/horizontal-axis.d.ts +32 -56
  81. package/dist/line-chart/horizontal-axis.d.ts.map +1 -1
  82. package/dist/line-chart/horizontal-axis.js +85 -123
  83. package/dist/line-chart/horizontal-axis.js.map +1 -1
  84. package/dist/line-chart/index.d.ts +2 -2
  85. package/dist/line-chart/index.d.ts.map +1 -1
  86. package/dist/line-chart/index.js +1 -1
  87. package/dist/line-chart/index.js.map +1 -1
  88. package/dist/line-chart/line-chart.d.ts +111 -311
  89. package/dist/line-chart/line-chart.d.ts.map +1 -1
  90. package/dist/line-chart/line-chart.js +403 -639
  91. package/dist/line-chart/line-chart.js.map +1 -1
  92. package/dist/line-chart/shared.d.ts +6 -6
  93. package/dist/line-chart/shared.d.ts.map +1 -1
  94. package/dist/line-chart/shared.js +22 -7
  95. package/dist/line-chart/shared.js.map +1 -1
  96. package/dist/line-chart/x-scale.d.ts +1 -1
  97. package/dist/line-chart/x-scale.js +1 -1
  98. package/dist/line-chart/x-scale.js.map +1 -1
  99. package/dist/nodes.d.ts +6 -9
  100. package/dist/nodes.d.ts.map +1 -1
  101. package/dist/nodes.js +7 -9
  102. package/dist/nodes.js.map +1 -1
  103. package/dist/pie-chart/index.d.ts +2 -2
  104. package/dist/pie-chart/index.d.ts.map +1 -1
  105. package/dist/pie-chart/index.js +1 -1
  106. package/dist/pie-chart/index.js.map +1 -1
  107. package/dist/pie-chart/pie-chart.d.ts +77 -134
  108. package/dist/pie-chart/pie-chart.d.ts.map +1 -1
  109. package/dist/pie-chart/pie-chart.js +199 -268
  110. package/dist/pie-chart/pie-chart.js.map +1 -1
  111. package/dist/pie-chart/pie-legend.d.ts +54 -31
  112. package/dist/pie-chart/pie-legend.d.ts.map +1 -1
  113. package/dist/pie-chart/pie-legend.js +93 -107
  114. package/dist/pie-chart/pie-legend.js.map +1 -1
  115. package/dist/pie-chart/pie-ring.d.ts +142 -122
  116. package/dist/pie-chart/pie-ring.d.ts.map +1 -1
  117. package/dist/pie-chart/pie-ring.js +333 -361
  118. package/dist/pie-chart/pie-ring.js.map +1 -1
  119. package/dist/pie-chart/shared.d.ts +3 -3
  120. package/dist/pie-chart/shared.js +3 -3
  121. package/dist/pie-chart/shared.js.map +1 -1
  122. package/package.json +6 -5
  123. package/registry.json +23 -23
  124. package/src/bar-chart/bar-chart.ts +534 -814
  125. package/src/bar-chart/category-axis.ts +162 -177
  126. package/src/bar-chart/chart-bars.ts +288 -310
  127. package/src/bar-chart/index.ts +31 -31
  128. package/src/bar-chart/shared.ts +354 -354
  129. package/src/engine.ts +28 -26
  130. package/src/index.ts +5 -5
  131. package/src/kit/cartesian.ts +81 -0
  132. package/src/kit/chart-border.ts +50 -61
  133. package/src/kit/chart-canvas.ts +122 -157
  134. package/src/kit/chart-legend.ts +229 -250
  135. package/src/kit/entries.ts +20 -0
  136. package/src/kit/motion.ts +90 -0
  137. package/src/kit/paints.ts +15 -0
  138. package/src/kit/shared.ts +782 -675
  139. package/src/kit/vertical-axis.ts +194 -224
  140. package/src/line-chart/chart-line.ts +181 -208
  141. package/src/line-chart/chart-region.ts +106 -135
  142. package/src/line-chart/horizontal-axis.ts +166 -202
  143. package/src/line-chart/index.ts +39 -39
  144. package/src/line-chart/line-chart.ts +585 -929
  145. package/src/line-chart/shared.ts +473 -459
  146. package/src/line-chart/x-scale.ts +367 -367
  147. package/src/nodes.ts +18 -20
  148. package/src/pie-chart/index.ts +37 -37
  149. package/src/pie-chart/pie-chart.ts +293 -381
  150. package/src/pie-chart/pie-legend.ts +169 -159
  151. package/src/pie-chart/pie-ring.ts +848 -903
  152. package/src/pie-chart/shared.ts +490 -490
  153. package/dist/browser/chunks/chunk-RMHQ6GYU.js +0 -2
  154. package/dist/browser/chunks/chunk-RMHQ6GYU.js.map +0 -7
@@ -1,814 +1,534 @@
1
- import {
2
- command,
3
- node,
4
- Node2D,
5
- Rect,
6
- easeOut,
7
- property,
8
- type CommandArgs,
9
- type DataRecord,
10
- type Command,
11
- type EasingFunction,
12
- type NodeConfig,
13
- type Node2DProps,
14
- } from "@motionscript/sdk"
15
-
16
- import { ChartBorder } from "../kit/chart-border"
17
- import { ChartCanvas } from "../kit/chart-canvas"
18
- import { ChartLegend } from "../kit/chart-legend"
19
- import { VerticalAxis } from "../kit/vertical-axis"
20
- import {
21
- clampUnit,
22
- formatMarker,
23
- lerpAxisDomain,
24
- markerValues,
25
- num,
26
- resolveAxisDomain,
27
- type AxisDomainConfig,
28
- type Range,
29
- } from "../kit/shared"
30
- import { formatNumber } from "@motionscript/sdk/component"
31
- import {
32
- asCommand,
33
- drive,
34
- hold,
35
- sequence as sequenceOf,
36
- together,
37
- type Seekable,
38
- } from "@motionscript/sdk/component"
39
- import { CategoryAxis } from "./category-axis"
40
- import { ChartBars, type BarGeometry } from "./chart-bars"
41
- import {
42
- DEFAULT_BAR_CHART_THEME,
43
- barCategories,
44
- barSpans,
45
- lerpBarChartTheme,
46
- resolveBarChartTheme,
47
- resolveBarFill,
48
- resolveBarScale,
49
- stackCapIndex,
50
- type BarChartConfig,
51
- type BarChartTheme,
52
- type BarSeries,
53
- } from "./shared"
54
-
55
- export interface BarChartProps extends Node2DProps {
56
- /** One row per category — a plain record of field name to value. */
57
- data: DataRecord[]
58
- /**
59
- * Key into each row for its category caption, drawn beneath the baseline.
60
- * Named `categoryField` rather than `category` for the same reason the line
61
- * chart's is `xField`: it names a *column*, not a value.
62
- */
63
- categoryField: string
64
- /** One entry per bar series: which column it plots, its `label`, its `fill`. */
65
- series: BarSeries[]
66
- /**
67
- * When `true` every category's series stack into one column; when `false`
68
- * (the default) each series gets its own bar, grouped side by side within the
69
- * category's slot.
70
- */
71
- stacked?: boolean
72
- /** The value axis's domain: caption, scale range, and tick placement. */
73
- valueAxis?: AxisDomainConfig
74
- /** The category axis's domain. Only its `label` is read — the slots are the rows. */
75
- categoryAxis?: AxisDomainConfig
76
- /**
77
- * The chart's visual theme — bar palette and geometry, axis furniture, plot
78
- * panel paint, legend, value figures. Every branch is optional and deep-merged
79
- * onto {@link DEFAULT_BAR_CHART_THEME}.
80
- */
81
- theme?: BarChartTheme
82
- /** Whether the legend row below the plot is drawn at all. */
83
- showLegend?: boolean
84
- /** Whether each column prints the figure it plots. */
85
- showValues?: boolean
86
- }
87
-
88
- /**
89
- * Layout constants for the composition, all in px — the line chart's, so the two
90
- * sit at the same size in the same box and a scene can swap one for the other
91
- * without re-tuning its layout.
92
- */
93
- /** Left gutter reserved for the value axis markers. */
94
- const Y_AXIS_GUTTER = 64
95
- /** Bottom gutter (within the chart area) reserved for the category captions. */
96
- const X_AXIS_GUTTER = 40
97
- /** Height reserved below the chart area for the legend row. */
98
- const LEGEND_GUTTER = 56
99
- /** Extra left/bottom room when an axis caption is shown. */
100
- const Y_LABEL_GUTTER = 34
101
- const X_LABEL_GUTTER = 30
102
- /** Headroom above the plot, so a column reaching the top marker isn't flush to it. */
103
- const TOP_HEADROOM = 24
104
- /** Right gutter so the last slot isn't flush with the box edge. */
105
- const RIGHT_GUTTER = 20
106
-
107
- /** How far the legend starts below its slot when it enters, in px. */
108
- const LEGEND_SLIDE = 20
109
-
110
- /**
111
- * How {@link BarChart.enter} divides its duration between its three beats: the
112
- * axes arriving, the columns rising, and the legend coming up. Shares of the
113
- * whole, so they must sum to 1 — the entrance takes exactly the time it was
114
- * given, for the reason spelt out on `LineChart.enter`.
115
- */
116
- /**
117
- * The signals the bar chart's own commands move, as props types.
118
- *
119
- * Written out rather than reusing `BarChartProps` because these are signals of
120
- * the chart's own — how far the columns have risen, and which category is lit —
121
- * rather than part of what an author states about it. Same reason the line chart
122
- * types its `RegionState` separately.
123
- */
124
- type CategorySpotlight = { spotlight: number | null; spotlightReveal: number }
125
- type BarGrowth = { growth: number }
126
-
127
- const AXES_SHARE = 0.35
128
- const BARS_SHARE = 0.5
129
- const LEGEND_SHARE = 0.15
130
-
131
- /**
132
- * A grouped or stacked bar chart, composed from independent parts rather than
133
- * one monolithic draw — the sibling of the {@link LineChart} family, built the
134
- * same way and out of several of the same pieces:
135
- *
136
- * - `ChartCanvas` — the plot panel with a horizontal grid, under everything.
137
- * - `VerticalAxis` — the numeric value markers, staggering in bottom-to-top.
138
- * - {@link CategoryAxis} — the row of names beneath the baseline, one per row of
139
- * the data, staggering in left-to-right.
140
- * - {@link ChartBars} (one per series) — that series' column in every category,
141
- * plus the figures printed on them.
142
- * - `ChartLegend` — a row of entries below the chart, one per series.
143
- *
144
- * The parts are laid out from this node's `layoutBounds` exactly as the line
145
- * chart's are: a left gutter for the value axis, a bottom gutter for the
146
- * captions, the plot filling what's left, and the legend row beneath the whole
147
- * thing. Every child's position and size is bound reactively, so the chart
148
- * re-flows if its box changes, and the bars read the same resolved scale the
149
- * axis does, so a column's end lands exactly on its marker.
150
- *
151
- * **Resting state is the finished chart** — the same bargain the line chart
152
- * makes: the studio paints a node's Initial state on a paused canvas, so a chart
153
- * that only appeared once a command had run would be edited blind. {@link enter}
154
- * arms every part back to its pre-entrance state before animating.
155
- *
156
- * **Zero is always on the scale** (see `barValueExtent`), and the columns
157
- * grow about it rather than about the plot floor, so a negative value draws
158
- * downward out of the same `growth` signal that draws a positive one up.
159
- *
160
- * Past the entrance, two things move the chart:
161
- * {@link showSeries}/{@link hideSeries}/{@link spotlightSeries} pick out a
162
- * *series* — and hiding one **reflows the group**, the remaining columns
163
- * widening into the space as it goes, rather than leaving a hole where it was —
164
- * while {@link spotlightCategory}/{@link clearCategory} pick out a *column of
165
- * the table*, dimming every other category and its caption with it.
166
- */
167
- @node({
168
- key: "barChart",
169
- parentKey: "node",
170
- forkable: true,
171
- layout: {
172
- children: "freeform",
173
- defaultWidthMode: "fixed",
174
- defaultHeightMode: "fixed",
175
- acceptsChildren: true,
176
- },
177
- seed: {
178
- width: 760,
179
- height: 460,
180
- },
181
- })
182
- export class BarChart extends Node2D<BarChartProps> {
183
- @property({ default: () => [] as DataRecord[] }) declare data: DataRecord[]
184
- @property({ default: "" }) declare categoryField: string
185
- @property({ default: () => [] as BarSeries[] }) declare series: BarSeries[]
186
- @property({ default: false }) declare stacked: boolean
187
- /**
188
- * The value axis's domain (label/range/ticks), tweenable and mappable exactly
189
- * as the line chart's axes are: the mapper merges a partial input onto the
190
- * previous resolved domain and the tween interpolates numerically, so
191
- * `chart.to({ data: { valueAxis: { range: [0, 10] } }, duration: 1 })` smoothly
192
- * rescales every column. The axis *label* text is captured once at construction.
193
- */
194
- @property({
195
- default: {},
196
- mapper: resolveAxisDomain,
197
- tween: lerpAxisDomain,
198
- })
199
- declare valueAxis: AxisDomainConfig
200
- @property({
201
- default: {},
202
- mapper: resolveAxisDomain,
203
- tween: lerpAxisDomain,
204
- })
205
- declare categoryAxis: AxisDomainConfig
206
- @property({
207
- default: DEFAULT_BAR_CHART_THEME,
208
- mapper: resolveBarChartTheme,
209
- tween: lerpBarChartTheme,
210
- })
211
- declare theme: BarChartTheme
212
-
213
- /**
214
- * Global rise of every column in `[0, 1]`, measured about the baseline: 0
215
- * collapses them all onto it, 1 draws them at full length. Each
216
- * {@link ChartBars}' own `growth` is bound to this, so tweening this one
217
- * signal raises the whole chart in proportion.
218
- */
219
- @property({ default: 1 }) declare growth: number
220
-
221
- /**
222
- * How much of the slot each series currently claims, one entry per series.
223
- *
224
- * A *weight* rather than a boolean, because that is what makes hiding a series
225
- * an animation instead of a jump: the grouped columns divide the slot in
226
- * proportion to these, so tweening one to 0 has the remaining columns widen
227
- * into the space as it shrinks away, and a stacked segment's contribution to
228
- * the stack fades out with it. Seeded from each series' `enabled` field.
229
- */
230
- @property({ default: () => [] as number[] }) declare weights: number[]
231
-
232
- /**
233
- * The category currently spotlit, or `null` for none. Held as a plain reactive
234
- * value rather than a tweened one: the *choice* snaps, and the animation is
235
- * {@link spotlightReveal} dimming everything else.
236
- */
237
- @property({ default: null }) declare spotlight: number | null
238
-
239
- /** How far the category spotlight is drawn in, `[0, 1]`. */
240
- @property({ default: 0 }) declare spotlightReveal: number
241
-
242
- // ---- Part handles (built in the constructor) --------------------------
243
- private vAxis: VerticalAxis
244
- private cAxis: CategoryAxis
245
- private legend: ChartLegend | null = null
246
- private barSets: ChartBars[] = []
247
-
248
- /**
249
- * `this.theme` read back through its *resolved* shape — the same
250
- * loose-declared/resolved-stored idiom as a shape's `fill`/`stroke`, and as
251
- * the line chart's own theme.
252
- */
253
- private get resolvedTheme(): BarChartConfig {
254
- return this.theme as unknown as BarChartConfig
255
- }
256
-
257
- // ---- Derived scale ----------------------------------------------------
258
-
259
- /** Fallback marker count when the value axis states no ticks. */
260
- private static readonly DEFAULT_MARKERS = 5
261
-
262
- private get valueScale(): Range {
263
- const divisions =
264
- (this.valueAxis.ticks?.length ?? BarChart.DEFAULT_MARKERS) - 1
265
- return resolveBarScale(
266
- this.data,
267
- this.series,
268
- this.stacked,
269
- this.valueAxis.range,
270
- divisions
271
- )
272
- }
273
-
274
- /**
275
- * A value written down as this chart's value axis says — the axis ticks and
276
- * the figures printed on the columns both read through here, so the two
277
- * cannot disagree about what a number looks like.
278
- */
279
- private valueLabel(value: number): string {
280
- const pattern = this.valueAxis.format
281
- return pattern === undefined
282
- ? formatMarker(value)
283
- : formatNumber(value, pattern)
284
- }
285
-
286
- /** The value axis ticks: the explicit ones, else five across the scale. */
287
- private get resolvedMarkers(): number[] {
288
- return (
289
- this.valueAxis.ticks ??
290
- markerValues(this.valueScale, BarChart.DEFAULT_MARKERS - 1)
291
- )
292
- }
293
-
294
- // ---- Plot geometry, all derived from layoutBounds -----------------------
295
-
296
- private get hasValueLabel(): boolean {
297
- return this.valueAxis.label !== ""
298
- }
299
- private get hasCategoryLabel(): boolean {
300
- return this.categoryAxis.label !== ""
301
- }
302
-
303
- private get leftInset(): number {
304
- return Y_AXIS_GUTTER + (this.hasValueLabel ? Y_LABEL_GUTTER : 0)
305
- }
306
- private get bottomInset(): number {
307
- return X_AXIS_GUTTER + (this.hasCategoryLabel ? X_LABEL_GUTTER : 0)
308
- }
309
-
310
- /** The plot rectangle in node space: `{ left, right, top, bottom }` (y-up). */
311
- private plotBox(): {
312
- left: number
313
- right: number
314
- top: number
315
- bottom: number
316
- } {
317
- const W = this.layoutBounds.width
318
- const H = this.layoutBounds.height
319
- const areaTop = H / 2
320
- const areaBottom = -H / 2 + (this.legend ? LEGEND_GUTTER : 0)
321
- const left = -W / 2 + this.leftInset
322
- const right = W / 2 - RIGHT_GUTTER
323
- const top = areaTop - TOP_HEADROOM
324
- const bottom = areaBottom + this.bottomInset
325
- return { left, right, top, bottom }
326
- }
327
-
328
- /** Width and height of the plot, in px. */
329
- private plotSize(): { w: number; h: number } {
330
- const { left, right, top, bottom } = this.plotBox()
331
- return { w: right - left, h: top - bottom }
332
- }
333
-
334
- /** Map a value onto the plot's **centred** pixel space (origin at its centre, y-up). */
335
- private valueToY(value: number): number {
336
- const [min, max] = this.valueScale
337
- const { h } = this.plotSize()
338
- if (max <= min) return -h / 2
339
- return ((value - min) / (max - min) - 0.5) * h
340
- }
341
-
342
- /**
343
- * Pixel y of the line every column grows from.
344
- *
345
- * Zero, clamped onto the scale — so an author who *did* crop the axis to
346
- * `[40, 100]` gets columns rising from the plot floor rather than from a
347
- * baseline off the bottom of the panel.
348
- */
349
- private get baselinePx(): number {
350
- const [min, max] = this.valueScale
351
- return this.valueToY(Math.min(Math.max(0, min), max))
352
- }
353
-
354
- // ---- Slot geometry ----------------------------------------------------
355
-
356
- /** Width of one category's slot across the plot. */
357
- private get slotWidth(): number {
358
- const n = this.data.length
359
- return n > 0 ? this.plotSize().w / n : 0
360
- }
361
-
362
- /** Centre x of category `i`'s slot, in the plot's centred space. */
363
- private slotCenter(index: number): number {
364
- return -this.plotSize().w / 2 + this.slotWidth * (index + 0.5)
365
- }
366
-
367
- /** The part of a slot the columns fill — the rest is the channel between categories. */
368
- private get slotInner(): number {
369
- return this.slotWidth * clampUnit(this.resolvedTheme.bar.slotFill)
370
- }
371
-
372
- /** Series `i`'s live share of the slot; 0 once it has been hidden. */
373
- private weightAt(index: number): number {
374
- return Math.max(0, this.weights[index] ?? 1)
375
- }
376
-
377
- /** Total live share across the series — the slot's inner width divides by this. */
378
- private get totalWeight(): number {
379
- let sum = 0
380
- for (let i = 0; i < this.series.length; i++) sum += this.weightAt(i)
381
- return sum > 0 ? sum : 1
382
- }
383
-
384
- /** Live share of every series *before* `index`, for the grouped offset. */
385
- private weightBefore(index: number): number {
386
- let sum = 0
387
- for (let i = 0; i < index; i++) sum += this.weightAt(i)
388
- return sum
389
- }
390
-
391
- /**
392
- * Series `index`'s columns, mapped into the plot's centred pixel space.
393
- *
394
- * Both modes come out of one walk over the rows: a grouped series divides the
395
- * slot with its siblings and every column runs from zero, a stacked one takes
396
- * the whole slot and each column runs from the running total below it. The
397
- * live {@link weights} scale the grouped widths and the stacked contributions
398
- * alike, which is what lets `hideSeries` reflow rather than punch a hole.
399
- */
400
- private seriesBars(index: number): BarGeometry[] {
401
- const series = this.series[index]
402
- if (!series) return []
403
- const stacked = this.stacked
404
- const inner = this.slotInner
405
- const gap = this.resolvedTheme.bar.groupGap
406
- const unit = inner / this.totalWeight
407
- const weight = this.weightAt(index)
408
-
409
- return this.data.map((row, rowIndex) => {
410
- // The stack is built from the *live* contributions, so a series fading out
411
- // lowers the segments above it as it goes instead of dropping them by a
412
- // step when it finally switches off. A grouped row needs no such scaling —
413
- // there its weight moves the column's width, not its length.
414
- const spans = barSpans(
415
- stacked ? this.weightedRow(row) : row,
416
- this.series,
417
- stacked
418
- )
419
- const span = spans[index] ?? { from: 0, to: 0, value: 0 }
420
- const cap = stacked ? stackCapIndex(row, this.series) : index
421
-
422
- const slotLeft = this.slotCenter(rowIndex) - inner / 2
423
- const x = stacked
424
- ? this.slotCenter(rowIndex)
425
- : slotLeft + unit * this.weightBefore(index) + (unit * weight) / 2
426
- const width = stacked
427
- ? inner
428
- : Math.max(0, unit * weight - (this.series.length > 1 ? gap : 0))
429
-
430
- return {
431
- x,
432
- width,
433
- from: this.valueToY(span.from),
434
- to: this.valueToY(span.to),
435
- round: cap === index,
436
- // The figure printed is the row's own value, not the weighted one — a
437
- // series on its way out should not be seen counting down.
438
- value: num(row, series.field),
439
- }
440
- })
441
- }
442
-
443
- /**
444
- * `row` with each series' value scaled by that series' live {@link weights}
445
- * entry — what the stacked spans are measured from.
446
- */
447
- private weightedRow(row: DataRecord): DataRecord {
448
- const scaled: DataRecord = { ...row }
449
- this.series.forEach((s, i) => {
450
- const value = row[s.field]
451
- if (typeof value === "number") scaled[s.field] = value * this.weightAt(i)
452
- })
453
- return scaled
454
- }
455
-
456
- /**
457
- * How far each category is dimmed by the spotlight, one entry per row —
458
- * 1 while nothing is spotlit, falling to the theme's `dimOpacity` for every
459
- * category but the chosen one as the reveal climbs.
460
- */
461
- private categoryDims(): number[] {
462
- const focus = clampUnit(this.spotlightReveal)
463
- const dim = this.resolvedTheme.spotlight.dimOpacity
464
- const chosen = this.spotlight
465
- return this.data.map((_, i) =>
466
- focus <= 0 || chosen === i ? 1 : 1 - (1 - dim) * focus
467
- )
468
- }
469
-
470
- // ---- Build ------------------------------------------------------------
471
-
472
- constructor(props?: NodeConfig<BarChart, BarChartProps>) {
473
- super(props)
474
-
475
- // The whole chart is composed from plain props/`data` — no context needed,
476
- // so the parts are built here (super() applied the props above). Everything
477
- // a *leaf* reads live in `renderSelf` — each series' geometry, paint and
478
- // dim, the panel's fill, the border's stroke — is passed as a closure rather
479
- // than a snapshot, so `chart.to({ theme })` and
480
- // `chart.to({ valueAxis: { range } })` genuinely animate the drawn chart.
481
- const enabled = this.series.map((s) => s.enabled ?? true)
482
- this.weights = enabled.map((on) => (on ? 1 : 0))
483
- const showLegend = props?.showLegend !== false
484
- const showValues = props?.showValues === true
485
-
486
- this.vAxis = new VerticalAxis({
487
- range: () => this.valueScale,
488
- markers: () => this.resolvedMarkers,
489
- axis: () => this.resolvedTheme.yAxis,
490
- label: this.valueAxis.label ?? "",
491
- width: "hug",
492
- height: "fill",
493
- })
494
- this.vAxis.labelFor = (value) => this.valueLabel(value)
495
-
496
- this.cAxis = new CategoryAxis({
497
- categories: barCategories(this.data, this.categoryField),
498
- axis: () => this.resolvedTheme.xAxis,
499
- label: this.categoryAxis.label ?? "",
500
- dims: () => this.categoryDims(),
501
- width: "fill",
502
- height: "hug",
503
- })
504
-
505
- this.barSets = this.series.map(
506
- (s, i) =>
507
- new ChartBars({
508
- bars: () => this.seriesBars(i),
509
- baseline: () => this.baselinePx,
510
- fill: () => resolveBarFill(this.resolvedTheme.seriesFills, s, i),
511
- barStroke: () => this.resolvedTheme.bar.stroke,
512
- barShadow: () => this.resolvedTheme.bar.shadow,
513
- cornerRadius: () => this.resolvedTheme.bar.cornerRadius,
514
- growth: () => this.growth,
515
- dims: () => this.categoryDims(),
516
- showValues,
517
- valueStyle: this.resolvedTheme.valueStyle,
518
- enabled: enabled[i],
519
- })
520
- )
521
- // The figures on the columns are the same numbers the value axis ticks, so
522
- // they read through the same format.
523
- for (const set of this.barSets) set.labelFor = (value) => this.valueLabel(value)
524
-
525
- if (showLegend) {
526
- this.legend = new ChartLegend({
527
- series: this.series,
528
- swatches: () =>
529
- this.series.map((s, i) =>
530
- resolveBarFill(this.resolvedTheme.seriesFills, s, i)
531
- ),
532
- legend: () => this.resolvedTheme.legend,
533
- })
534
- }
535
-
536
- const plot = new Rect({
537
- clip: true,
538
- children: [
539
- new ChartCanvas({
540
- fill: () => this.resolvedTheme.plotArea.fill,
541
- shadow: () => this.resolvedTheme.plotArea.shadow,
542
- xGridStroke: () => this.resolvedTheme.xAxis.lineStyle,
543
- yGridStroke: () => this.resolvedTheme.yAxis.lineStyle,
544
- // No vertical rules: the horizontal axis is categorical, so there is
545
- // no numeric position along it for a grid line to mark. The channel
546
- // between slots does that job, and better.
547
- xMarkers: [],
548
- yMarkers: () => this.resolvedMarkers,
549
- xExtent: () => [0, 1] as Range,
550
- yExtent: () => this.valueScale,
551
- }),
552
- ...this.barSets,
553
- new ChartBorder({
554
- stroke: () => this.resolvedTheme.plotArea.stroke,
555
- }),
556
- ],
557
- })
558
-
559
- // Invisible twin of the value axis, reserving the same left gutter under the
560
- // plot so the category row starts at the plot's left edge rather than the
561
- // chart's — and so a caption lands under the columns it names.
562
- const gutterSpacer = new VerticalAxis({
563
- opacity: 0,
564
- range: () => this.valueScale,
565
- markers: () => this.resolvedMarkers,
566
- axis: () => this.resolvedTheme.yAxis,
567
- label: this.valueAxis.label ?? "",
568
- width: "hug",
569
- height: 0,
570
- })
571
-
572
- const below: Node2D[] = [this.cAxis]
573
- if (this.legend) below.push(this.legend)
574
-
575
- this.add(
576
- new Rect({ flow: "vertical",
577
- width: "fill",
578
- height: "fill",
579
- children: [
580
- new Rect({ flow: "horizontal",
581
- height: "fill",
582
- width: "fill",
583
- children: [this.vAxis, plot],
584
- }),
585
- new Rect({ flow: "horizontal",
586
- width: "fill",
587
- children: [
588
- gutterSpacer,
589
- new Rect({ flow: "vertical", width: "fill", gap: 20, children: below }),
590
- ],
591
- }),
592
- ],
593
- })
594
- )
595
- }
596
-
597
- // ---- Orchestrated entrance --------------------------------------------
598
-
599
- /**
600
- * Prime every part at its pre-entrance state — axis markers and captions
601
- * shifted and transparent, columns collapsed onto the baseline, legend dropped
602
- * and transparent.
603
- *
604
- * Called by {@link enter} before its first frame so nothing flashes ahead of
605
- * its beat. Idempotent, and public so a scene can hide a chart ahead of time
606
- * without starting the entrance.
607
- */
608
- arm(): void {
609
- this.vAxis.arm()
610
- this.cAxis.arm()
611
- this.growth = 0
612
- this.legend?.set({ opacity: 0, y: -LEGEND_SLIDE })
613
- }
614
-
615
- /**
616
- * Animate the whole chart in: the two axes stagger their markers and captions
617
- * in, the columns rise from the baseline, and the legend fades up last.
618
- *
619
- * `duration` is the **whole** entrance. The phases are shares of it, not
620
- * multiples — a command that declares 1.4 seconds has to take 1.4 seconds,
621
- * because that is the slot the timeline lays out for it, the length its
622
- * parallel siblings are timed against, and its contribution to the scene's own
623
- * duration.
624
- */
625
- @command()
626
- enter(args: CommandArgs<Record<string, never>> & { duration: number }): Command<Record<string, never>> {
627
- const { duration } = args
628
- const easing = args.easing ?? easeOut()
629
- this.arm()
630
-
631
- return asCommand(
632
- sequenceOf(
633
- together(
634
- this.vAxis.enter({ data: { slide: 24 }, duration: duration * AXES_SHARE, easing }),
635
- this.cAxis.enter({ data: { slide: 24 }, duration: duration * AXES_SHARE, easing })
636
- ),
637
- this.riseBars(duration * BARS_SHARE, easing),
638
- ...(this.legend
639
- ? [this.legend.to({ data: { opacity: 1, y: 0 }, duration: duration * LEGEND_SHARE, easing })]
640
- : [])
641
- ),
642
- duration
643
- )
644
- }
645
-
646
- /** Tween {@link growth} `0 → 1`, raising every column about the baseline. */
647
- private riseBars(
648
- duration: number,
649
- easing: EasingFunction
650
- ): Command<BarGrowth> {
651
- // No priming to 0 first: the value at `t` is a function of `t`, so a repeat
652
- // call re-raises by definition rather than by having reset something.
653
- return this.command<BarGrowth>((t) => ({ growth: t }), duration, easing)
654
- }
655
-
656
- /**
657
- * Show series `index`: bring its columns back, the group reflowing to make
658
- * room as they arrive, in lockstep with its legend entry growing in.
659
- */
660
- @command({ args: [{ key: "seriesIndex", kind: "series", default: 0, min: 0, step: 1 }] })
661
- showSeries(args: CommandArgs<{ seriesIndex: number }>): Command<Record<string, never>> {
662
- const { seriesIndex = 0 } = args.data ?? {}
663
- return this.toggleSeries(seriesIndex, 1, args.duration ?? 0.35, args.easing ?? easeOut())
664
- }
665
-
666
- /**
667
- * Hide series `index`: its columns narrow away (or, stacked, sink out of the
668
- * stack) while the rest of the group widens into the space, its legend entry
669
- * shrinking beside them — the mirror of {@link showSeries}.
670
- */
671
- @command({ args: [{ key: "seriesIndex", kind: "series", default: 0, min: 0, step: 1 }] })
672
- hideSeries(args: CommandArgs<{ seriesIndex: number }>): Command<Record<string, never>> {
673
- const { seriesIndex = 0 } = args.data ?? {}
674
- return this.toggleSeries(seriesIndex, 0, args.duration ?? 0.35, args.easing ?? easeOut())
675
- }
676
-
677
- /**
678
- * Move series `index`'s slot share to `target`, with its legend entry.
679
- *
680
- * One method for both directions, so the pair cannot drift apart. `enabled`
681
- * rides in the same value as the weight rather than being set before or after,
682
- * which is what makes arriving at a time backwards show what arriving forwards
683
- * does.
684
- */
685
- private toggleSeries(
686
- index: number,
687
- target: number,
688
- duration: number,
689
- easing: EasingFunction
690
- ): Command<Record<string, never>> {
691
- const bars = this.barSets[index]
692
- if (!bars) return asCommand(hold(duration))
693
-
694
- return asCommand(
695
- together(
696
- this.tweenWeight(index, target, duration, easing),
697
- drive(duration, (t) => {
698
- const share = t >= 1 ? target : Math.max(target, 1 - t)
699
- bars.set({ enabled: target > 0 || share > 0 })
700
- }),
701
- ...(this.legend
702
- ? [
703
- target > 0
704
- ? this.legend.showSeries({ data: { index }, duration, easing })
705
- : this.legend.hideSeries({ data: { index }, duration, easing }),
706
- ]
707
- : [])
708
- ),
709
- duration
710
- )
711
- }
712
-
713
- /**
714
- * Fade out every other series — its columns **and its legend entry** — to
715
- * focus attention on `index`, which comes back to full. Nothing moves, so the
716
- * group doesn't reflow.
717
- */
718
- @command({ args: [{ key: "seriesIndex", kind: "series", default: 0, min: 0, step: 1 }] })
719
- spotlightSeries(args: CommandArgs<{ seriesIndex: number }>): Command<Record<string, never>> {
720
- const { seriesIndex = 0 } = args.data ?? {}
721
- const duration = args.duration ?? 0.35
722
- const easing = args.easing ?? easeOut()
723
- const dim = this.resolvedTheme.spotlight.dimOpacity
724
- return asCommand(
725
- together(
726
- ...this.barSets.map((bars, i) =>
727
- bars.to({ data: { opacity: i === seriesIndex ? 1 : dim }, duration, easing })
728
- ),
729
- ...(this.legend
730
- ? [this.legend.spotlightSeries({ data: { index: seriesIndex }, duration, easing })]
731
- : [])
732
- ),
733
- duration
734
- )
735
- }
736
-
737
- /** Ease series `index`'s slot share toward `target`, reflowing the group. */
738
- private tweenWeight(
739
- index: number,
740
- target: number,
741
- duration: number,
742
- easing: EasingFunction
743
- ): Seekable {
744
- // Read through `weightAt` rather than off the array, so a chart whose stored
745
- // weights are short (or absent) still tweens from the 1 it is drawing at.
746
- const from = this.series.map((_, i) => this.weightAt(i))
747
- const start = from[index] ?? 1
748
- if (start === target) return hold(duration)
749
-
750
- return drive(duration, (t) => {
751
- const next = [...from]
752
- next[index] = start + (target - start) * easing(t)
753
- this.weights = next
754
- })
755
- }
756
-
757
- // ---- Per-category ------------------------------------------------------
758
-
759
- /**
760
- * Spotlight one **category** — one column of the table rather than one series:
761
- * every other category's bars and its caption fade to the theme's
762
- * `dimOpacity`, and the chosen one stays full.
763
- *
764
- * The counterpart of the line chart's `spotlightRegion`, and the same shape of
765
- * thing: it picks out a slice of the plot without changing what is drawn.
766
- * Calling it while another category is already lit moves the focus directly —
767
- * only the dimming changes, so there is nothing to retract first.
768
- */
769
- @command({ args: [{ key: "categoryIndex", kind: "number", default: 0, min: 0, step: 1 }] })
770
- spotlightCategory(args: CommandArgs<{ categoryIndex: number }>): Command<CategorySpotlight> {
771
- const { categoryIndex = 0 } = args.data ?? {}
772
- const duration = args.duration ?? 0.4
773
- const easing = args.easing ?? easeOut()
774
- if (categoryIndex < 0 || categoryIndex >= this.data.length) return this.holdSpotlight(duration)
775
- const from = this.spotlightReveal
776
- // Which category is lit is part of the value, set from the first frame: the
777
- // focus moves directly, so unlike the line chart's region there is nothing to
778
- // retract before it.
779
- return this.command<CategorySpotlight>(
780
- (t) => ({ spotlight: categoryIndex, spotlightReveal: from + (1 - from) * t }),
781
- duration,
782
- easing
783
- )
784
- }
785
-
786
- /**
787
- * Drop the category spotlight, bringing every category back to full. A no-op
788
- * when nothing is lit — but it still takes its slot on the timeline, for the
789
- * reason `LineChart.clearRegion` does.
790
- */
791
- @command()
792
- clearCategory(args: CommandArgs<Record<string, never>>): Command<CategorySpotlight> {
793
- const duration = args.duration ?? 0.4
794
- const easing = args.easing ?? easeOut()
795
- const from = this.spotlightReveal
796
- if (from === 0) return this.holdSpotlight(duration)
797
-
798
- // The lit category is held until the fade lands — cleared at `t === 1` rather
799
- // than up front, or there would be nothing left to fade.
800
- return this.command<CategorySpotlight>(
801
- (t) =>
802
- t >= 1
803
- ? { spotlight: null, spotlightReveal: 0 }
804
- : { spotlightReveal: from * (1 - t) },
805
- duration,
806
- easing
807
- )
808
- }
809
-
810
- /** The no-op both of the above return — see {@link hold}. */
811
- private holdSpotlight(duration: number): Command<CategorySpotlight> {
812
- return this.command<CategorySpotlight>(() => ({}), duration)
813
- }
814
- }
1
+ import {
2
+ Rect,
3
+ Types,
4
+ component2d,
5
+ easeOut,
6
+ type ChildView,
7
+ type DataRecord,
8
+ type EntryOptions,
9
+ type NodeOf,
10
+ // Named so this component's emitted type reaches `Node2D` through the sdk, not core.
11
+ type Node2D,
12
+ type Node2DProps,
13
+ type Size2D,
14
+ type Timeline,
15
+ } from "@motionscript/sdk"
16
+ import { formatNumber } from "@motionscript/sdk/component"
17
+
18
+ import { cartesianFrame, cartesianViews, laidOutSize } from "../kit/cartesian"
19
+ import { ChartBorder } from "../kit/chart-border"
20
+ import { ChartCanvas } from "../kit/chart-canvas"
21
+ import { ChartLegend } from "../kit/chart-legend"
22
+ import { asParts, fresh } from "../kit/entries"
23
+ import { beats, type Beat } from "../kit/motion"
24
+ import { VerticalAxis } from "../kit/vertical-axis"
25
+ import {
26
+ clampUnit,
27
+ formatMarker,
28
+ lerpAxisDomain,
29
+ lerpAxisEntry,
30
+ markerStep,
31
+ markerValues,
32
+ num,
33
+ resolveAxisDomain,
34
+ settleAxisDomain,
35
+ type AxisDomainConfig,
36
+ type Range,
37
+ } from "../kit/shared"
38
+ import { CategoryAxis } from "./category-axis"
39
+ import { ChartBars, type BarGeometry } from "./chart-bars"
40
+ import {
41
+ DEFAULT_BAR_CHART_THEME,
42
+ barCategories,
43
+ barSpans,
44
+ lerpBarChartTheme,
45
+ resolveBarChartTheme,
46
+ resolveBarFill,
47
+ resolveBarScale,
48
+ stackCapIndex,
49
+ type BarChartConfig,
50
+ type BarChartTheme,
51
+ type BarSeries,
52
+ } from "./shared"
53
+
54
+ export interface BarChartProps extends Node2DProps {
55
+ /** One row per category — a plain record of field name to value. */
56
+ data: DataRecord[]
57
+ /**
58
+ * Key into each row for its category caption, drawn beneath the baseline.
59
+ * Named `categoryField` rather than `category` for the same reason the line
60
+ * chart's is `xField`: it names a *column*, not a value.
61
+ */
62
+ categoryField: string
63
+ /** One entry per bar series: which column it plots, its `label`, its `fill`. */
64
+ series: BarSeries[]
65
+ /**
66
+ * When `true` every category's series stack into one column; when `false`
67
+ * (the default) each series gets its own bar, grouped side by side within the
68
+ * category's slot.
69
+ */
70
+ stacked?: boolean
71
+ /** The value axis's domain: caption, scale range, and tick placement. */
72
+ valueAxis?: AxisDomainConfig
73
+ /** The category axis's domain. Only its `label` is read — the slots are the rows. */
74
+ categoryAxis?: AxisDomainConfig
75
+ /**
76
+ * The chart's visual theme — bar palette and geometry, axis furniture, plot
77
+ * panel paint, legend, value figures. Every branch is optional and deep-merged
78
+ * onto {@link DEFAULT_BAR_CHART_THEME}.
79
+ */
80
+ theme?: BarChartTheme
81
+ /** Whether the legend row below the plot is drawn at all. */
82
+ showLegend?: boolean
83
+ /** Whether each column prints the figure it plots. */
84
+ showValues?: boolean
85
+ }
86
+
87
+ /** What a bar chart plots, as its entries hold it. */
88
+ export interface BarChartValues {
89
+ readonly data: DataRecord[]
90
+ readonly series: BarSeries[]
91
+ readonly stacked: boolean
92
+ readonly valueAxis: AxisDomainConfig
93
+ }
94
+
95
+ /** The value axis's domain with its range and ticks resolved. */
96
+ export type BarChartDomain = AxisDomainConfig & { readonly range: Range; readonly ticks: number[] }
97
+
98
+ /** The argument every per-series command takes: an index into `series`, offered by name. */
99
+ const SERIES_ARG = Types.custom<number, number, EntryOptions & { readonly min: number; readonly step: number }>(0, { kind: "series", min: 0, step: 1 })
100
+
101
+ /** How far the legend starts below its slot when it enters, in px. */
102
+ const LEGEND_SLIDE = 20
103
+
104
+ /** Fallback marker count when the value axis states no ticks. */
105
+ const DEFAULT_MARKERS = 5
106
+
107
+ /**
108
+ * How `enter` divides its duration between its three beats: the axes arriving,
109
+ * the columns rising, and the legend coming up. Shares of the whole, so they
110
+ * must sum to 1.
111
+ */
112
+ const AXES_SHARE = 0.35
113
+ const BARS_SHARE = 0.5
114
+ const LEGEND_SHARE = 0.15
115
+
116
+ /** What the geometry reads: what the chart plots, its theme and the signals its commands move. */
117
+ interface BarState extends BarChartValues {
118
+ readonly theme: BarChartConfig
119
+ readonly weights: number[]
120
+ readonly spotlight: number | null
121
+ readonly spotlightReveal: number
122
+ }
123
+
124
+ /** The value axis with its range and ticks resolved: the explicit ones, else five across the scale. */
125
+ function drawnValue(s: BarChartValues, domain: AxisDomainConfig): AxisDomainConfig {
126
+ const divisions = (domain.ticks?.length ?? DEFAULT_MARKERS) - 1
127
+ const range = resolveBarScale(s.data, s.series, s.stacked, domain.range, divisions)
128
+ return { ...domain, range, ticks: domain.ticks ?? markerValues(range, DEFAULT_MARKERS - 1) }
129
+ }
130
+
131
+ /** The value axis as a bar chart draws it now, an auto range or tick row read back as itself. */
132
+ export function barChartDomain(s: BarChartValues): BarChartDomain {
133
+ return settleAxisDomain(s.valueAxis, (d) => drawnValue(s, d)) as BarChartDomain
134
+ }
135
+
136
+ /**
137
+ * A value written down as this chart's value axis says: the ticks and the
138
+ * figures printed on the columns both read through here, so the two cannot
139
+ * disagree about what a number looks like.
140
+ */
141
+ function valueLabel(s: BarChartValues, domain: BarChartDomain, value: number): string {
142
+ const pattern = s.valueAxis.format
143
+ return pattern === undefined ? formatMarker(value, markerStep(domain.ticks)) : formatNumber(value, pattern)
144
+ }
145
+
146
+ /** A value on the plot's **centred** pixel space (origin at its centre, y-up). */
147
+ function valueToY(domain: BarChartDomain, plot: Size2D, value: number): number {
148
+ const [min, max] = domain.range
149
+ if (max <= min) return -plot.height / 2
150
+ return ((value - min) / (max - min) - 0.5) * plot.height
151
+ }
152
+
153
+ /**
154
+ * Pixel y of the line every column grows from: zero clamped onto the scale, so
155
+ * a cropped axis grows its columns from the plot floor.
156
+ */
157
+ function baselinePx(domain: BarChartDomain, plot: Size2D): number {
158
+ const [min, max] = domain.range
159
+ return valueToY(domain, plot, Math.min(Math.max(0, min), max))
160
+ }
161
+
162
+ /** Series `i`'s live share of the slot; 0 once it has been hidden. */
163
+ function weightAt(s: BarState, index: number): number {
164
+ return Math.max(0, s.weights[index] ?? 1)
165
+ }
166
+
167
+ /** `row` with each series' value scaled by its live weight: what the stacked spans are measured from. */
168
+ function weightedRow(s: BarState, row: DataRecord): DataRecord {
169
+ const scaled: DataRecord = { ...row }
170
+ s.series.forEach((series, i) => {
171
+ const value = row[series.field]
172
+ if (typeof value === "number") scaled[series.field] = value * weightAt(s, i)
173
+ })
174
+ return scaled
175
+ }
176
+
177
+ /**
178
+ * Series `index`'s columns, mapped into the plot's centred pixel space. A
179
+ * grouped series divides the slot with its siblings by their live weights, a
180
+ * stacked one takes the whole slot and runs from the running total below it,
181
+ * so hiding a series reflows rather than punching a hole.
182
+ */
183
+ function seriesBars(s: BarState, index: number, plot: Size2D, captioned: boolean): BarGeometry[] {
184
+ const series = s.series[index]
185
+ if (!series) return []
186
+ const domain = barChartDomain(s)
187
+ const n = s.data.length
188
+ const slotWidth = n > 0 ? plot.width / n : 0
189
+ const slotCenter = (i: number) => -plot.width / 2 + slotWidth * (i + 0.5)
190
+ const inner = slotWidth * clampUnit(s.theme.bar.slotFill)
191
+ const gap = s.theme.bar.groupGap
192
+ let total = 0
193
+ for (let i = 0; i < s.series.length; i++) total += weightAt(s, i)
194
+ const unit = inner / (total > 0 ? total : 1)
195
+ const weight = weightAt(s, index)
196
+ let before = 0
197
+ for (let i = 0; i < index; i++) before += weightAt(s, i)
198
+
199
+ return s.data.map((row, rowIndex) => {
200
+ // The stack is built from the *live* contributions, so a series fading out
201
+ // lowers the segments above it as it goes.
202
+ const spans = barSpans(s.stacked ? weightedRow(s, row) : row, s.series, s.stacked)
203
+ const span = spans[index] ?? { from: 0, to: 0, value: 0 }
204
+ const cap = s.stacked ? stackCapIndex(row, s.series) : index
205
+ const slotLeft = slotCenter(rowIndex) - inner / 2
206
+ const x = s.stacked ? slotCenter(rowIndex) : slotLeft + unit * before + (unit * weight) / 2
207
+ const width = s.stacked ? inner : Math.max(0, unit * weight - (s.series.length > 1 ? gap : 0))
208
+ // The figure printed is the row's own value, not the weighted one.
209
+ const value = num(row, series.field)
210
+ return {
211
+ x,
212
+ width,
213
+ from: valueToY(domain, plot, span.from),
214
+ to: valueToY(domain, plot, span.to),
215
+ round: cap === index,
216
+ value,
217
+ ...(captioned && { caption: valueLabel(s, domain, value) }),
218
+ }
219
+ })
220
+ }
221
+
222
+ /**
223
+ * How far each category is dimmed by the spotlight, one entry per row: 1 while
224
+ * nothing is spotlit, falling to the theme's `dimOpacity` for every category but
225
+ * the chosen one as the reveal climbs.
226
+ */
227
+ function categoryDims(s: BarState): number[] {
228
+ const focus = clampUnit(s.spotlightReveal)
229
+ const dim = s.theme.spotlight.dimOpacity
230
+ const chosen = s.spotlight
231
+ return s.data.map((_, i) => (focus <= 0 || chosen === i ? 1 : 1 - (1 - dim) * focus))
232
+ }
233
+
234
+ type AnyTimeline = Timeline<any, any>
235
+
236
+ /** The parts a bar chart's commands drive, found through its children. */
237
+ function partsOf(children: readonly ChildView[]) {
238
+ const frame = cartesianViews(children)
239
+ if (!frame) return null
240
+ const cAxis = frame.below.find(CategoryAxis.is)
241
+ if (!VerticalAxis.is(frame.axis) || !cAxis) return null
242
+ return {
243
+ vAxis: frame.axis,
244
+ cAxis,
245
+ bars: frame.plot.filter(ChartBars.is),
246
+ legend: frame.below.find(ChartLegend.is) ?? null,
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Move series `index`'s slot share to `target` with its legend entry, the group
252
+ * reflowing. Its columns are drawn for every frame the move covers, and switch
253
+ * off only once a hide has landed, so arriving at a time backwards shows what
254
+ * arriving forwards does.
255
+ */
256
+ function toggling(timeline: AnyTimeline, state: BarState & { readonly showing: boolean[] }, children: readonly ChildView[], index: number, target: number) {
257
+ const parts = partsOf(children)
258
+ if (!parts || !parts.bars[index]) return timeline.wait(timeline.duration)
259
+ // Read through `weightAt`, so a chart whose stored weights are short still
260
+ // tweens from the 1 it is drawing at.
261
+ const from = state.series.map((_, i) => weightAt(state, i))
262
+ const start = from[index] ?? 1
263
+ const showing = state.series.map((s, i) => state.showing[i] ?? (s.enabled ?? true))
264
+ return timeline.together([
265
+ timeline.animate((t) => {
266
+ const weights = [...from]
267
+ weights[index] = start + (target - start) * timeline.ease(t)
268
+ const shown = [...showing]
269
+ shown[index] = target > 0 || t < 1
270
+ return { weights, showing: shown }
271
+ }, { eased: false }),
272
+ ...(parts.legend ? [parts.legend.run(target > 0 ? "showSeries" : "hideSeries", { index })] : []),
273
+ ])
274
+ }
275
+
276
+ /**
277
+ * A grouped or stacked bar chart, the sibling of the line chart and built the
278
+ * same way, out of several of the same pieces:
279
+ *
280
+ * - `ChartCanvas` — the plot panel with a horizontal grid, under everything.
281
+ * - `VerticalAxis` — the numeric value markers, staggering in bottom-to-top.
282
+ * - {@link CategoryAxis} — the row of names beneath the baseline, one per row.
283
+ * - {@link ChartBars} (one per series) — that series' column in every category,
284
+ * plus the figures printed on them.
285
+ * - `ChartLegend` — a row of entries below the chart, one per series.
286
+ *
287
+ * Every part reads the chart's entries through bindings, and the columns map
288
+ * across the plot panel's own laid-out box, so a column's end lands exactly on
289
+ * its marker. **Zero is always on the scale**, and the columns grow about it, so
290
+ * a negative value draws downward out of the same `growth` signal.
291
+ *
292
+ * **Resting state is the finished chart**; `enter` arms every part on its first
293
+ * frame. `showSeries`/`hideSeries`/`spotlightSeries` pick out a *series* (hiding
294
+ * one reflows the group), `spotlightCategory`/`clearCategory` a *column of the
295
+ * table*. A `to` of the value axis's `range` or `ticks` tweens from the domain
296
+ * as drawn, so an auto axis rescales the columns continuously.
297
+ */
298
+ export const BarChart = component2d({
299
+ key: "barChart",
300
+ state: {
301
+ data: fresh<DataRecord[]>(() => []),
302
+ categoryField: "",
303
+ series: fresh<BarSeries[]>(() => []),
304
+ stacked: false,
305
+ valueAxis: Types.custom<AxisDomainConfig>({}, { resolve: resolveAxisDomain, lerp: lerpAxisEntry }),
306
+ categoryAxis: Types.custom<AxisDomainConfig>({}, { resolve: resolveAxisDomain, lerp: lerpAxisDomain }),
307
+ theme: Types.custom<BarChartTheme, BarChartConfig>(DEFAULT_BAR_CHART_THEME, { resolve: resolveBarChartTheme, lerp: lerpBarChartTheme }),
308
+ /**
309
+ * Global rise of every column in `[0, 1]`, measured about the baseline: 0
310
+ * collapses them all onto it, 1 draws them at full length.
311
+ */
312
+ growth: 1,
313
+ /**
314
+ * How much of the slot each series claims, one entry per series: a weight
315
+ * rather than a switch, so hiding one is the others widening into the space.
316
+ * Seeded from each series' `enabled`.
317
+ */
318
+ weights: fresh<number[]>(() => []),
319
+ /** The category spotlit, or `null` for none. The choice snaps; `spotlightReveal` is the animation. */
320
+ spotlight: Types.custom<number | null>(null),
321
+ /** How far the category spotlight is drawn in, `[0, 1]`. */
322
+ spotlightReveal: 0,
323
+ /** Read as the chart is built: the legend is a part the chart builds or doesn't. */
324
+ showLegend: Types.boolean(true, { animatable: false }),
325
+ /** Read as the chart is built: whether each column prints the figure it plots. */
326
+ showValues: Types.boolean(false, { animatable: false }),
327
+ /** Whether each series' columns are drawn: on for every frame a show or hide covers, off once a hide lands. */
328
+ showing: Types.custom<boolean[]>([], { private: true }),
329
+ },
330
+ defaults: {
331
+ // Its parts fill it; a node made of them would hug them.
332
+ width: "fill",
333
+ height: "fill",
334
+ weights: (state) => state.series.map((s) => ((s.enabled ?? true) ? 1 : 0)),
335
+ showing: (state) => state.series.map((s) => s.enabled ?? true),
336
+ },
337
+ children: (state) => {
338
+ const theme = () => state.theme
339
+ const domain = () => barChartDomain(state)
340
+ let plot: Node2D | undefined
341
+ // Before the panel is built or laid out it has no size, and the columns map onto nothing.
342
+ const plotSize = () => laidOutSize(plot)
343
+ const captioned = state.showValues === true
344
+
345
+ const vAxis = new VerticalAxis({
346
+ range: () => domain().range,
347
+ markers: () => domain().ticks,
348
+ captions: () => {
349
+ const d = domain()
350
+ return d.ticks.map((value) => valueLabel(state, d, value))
351
+ },
352
+ axis: () => theme().yAxis,
353
+ label: state.valueAxis.label ?? "",
354
+ width: "hug",
355
+ height: "fill",
356
+ })
357
+
358
+ const cAxis = new CategoryAxis({
359
+ categories: barCategories(state.data, state.categoryField),
360
+ axis: () => theme().xAxis,
361
+ label: state.categoryAxis.label ?? "",
362
+ dims: () => categoryDims(state),
363
+ width: "fill",
364
+ height: "hug",
365
+ }) as unknown as Node2D
366
+
367
+ const barSets = state.series.map(
368
+ (s, i) =>
369
+ new ChartBars({
370
+ bars: () => seriesBars(state, i, plotSize(), captioned),
371
+ baseline: () => baselinePx(domain(), plotSize()),
372
+ fill: () => resolveBarFill(theme().seriesFills, s, i),
373
+ barStroke: () => theme().bar.stroke,
374
+ barShadow: () => theme().bar.shadow,
375
+ cornerRadius: () => theme().bar.cornerRadius,
376
+ growth: () => state.growth,
377
+ dims: () => categoryDims(state),
378
+ showValues: captioned,
379
+ valueStyle: state.theme.valueStyle,
380
+ enabled: () => state.showing[i] ?? (s.enabled ?? true),
381
+ }) as unknown as Node2D
382
+ )
383
+
384
+ const below: Node2D[] = [cAxis]
385
+ if (state.showLegend !== false) {
386
+ below.push(
387
+ new ChartLegend({
388
+ series: state.series,
389
+ swatches: () => state.series.map((s, i) => resolveBarFill(theme().seriesFills, s, i)),
390
+ legend: () => theme().legend,
391
+ // The row's spacing is the theme's as the chart was built, like the
392
+ // entries' type and chips: a theme tween re-paints the swatches only.
393
+ gap: state.theme.legend.itemGap,
394
+ padding: state.theme.legend.padding,
395
+ }) as unknown as Node2D
396
+ )
397
+ }
398
+
399
+ plot = new Rect({
400
+ clip: true,
401
+ children: [
402
+ new ChartCanvas({
403
+ fill: () => theme().plotArea.fill,
404
+ shadow: () => theme().plotArea.shadow,
405
+ xGridStroke: () => theme().xAxis.lineStyle,
406
+ yGridStroke: () => theme().yAxis.lineStyle,
407
+ // No vertical rules: the horizontal axis is categorical, so there is no
408
+ // numeric position along it for a grid line to mark.
409
+ xMarkers: [],
410
+ yMarkers: () => domain().ticks,
411
+ xExtent: () => [0, 1] as Range,
412
+ yExtent: () => domain().range,
413
+ }),
414
+ ...barSets,
415
+ new ChartBorder({ stroke: () => theme().plotArea.stroke }),
416
+ ],
417
+ }) as unknown as Node2D
418
+
419
+ const gutter = new VerticalAxis({
420
+ opacity: 0,
421
+ range: () => domain().range,
422
+ markers: () => domain().ticks,
423
+ axis: () => theme().yAxis,
424
+ label: state.valueAxis.label ?? "",
425
+ width: "hug",
426
+ height: 0,
427
+ }) as unknown as Node2D
428
+
429
+ return asParts([
430
+ ...(state.children as unknown as Node2D[]),
431
+ cartesianFrame({ axis: vAxis as unknown as Node2D, plot, gutter, below }),
432
+ ])
433
+ },
434
+ commands: {
435
+ /**
436
+ * Animate the whole chart in: the two axes stagger their markers and
437
+ * captions in, the columns rise from the baseline, and the legend fades up
438
+ * last. Its first frame arms every part: markers and captions shifted and
439
+ * transparent, columns collapsed, the legend dropped and transparent.
440
+ * `duration` is the **whole** entrance; the beats are shares of it.
441
+ */
442
+ enter: {
443
+ args: {},
444
+ easing: easeOut(),
445
+ run: (timeline, _state, children) => {
446
+ const parts = partsOf(children)
447
+ if (!parts) return timeline.wait(timeline.duration)
448
+ const duration = timeline.duration
449
+ const axes = duration * AXES_SHARE
450
+ const rise = duration * BARS_SHARE
451
+ const { legend } = parts
452
+ const at0 = (piece: Beat["piece"]): Beat => ({ at: 0, duration: 0, piece })
453
+ // Without a legend the beat is still its share of the whole.
454
+ return beats(timeline, [
455
+ at0(timeline.animate(() => ({ growth: 0 }))),
456
+ ...(legend ? [at0(legend.to({ opacity: 0, y: -LEGEND_SLIDE }))] : []),
457
+ { at: 0, duration: axes, piece: parts.vAxis.run("enter", { slide: 24 }) },
458
+ { at: 0, duration: axes, piece: parts.cAxis.run("enter", { slide: 24 }) },
459
+ // No priming to 0 first: the value at `t` is a function of `t`.
460
+ { at: axes, duration: rise, piece: timeline.animate((t) => ({ growth: t })) },
461
+ ...(legend ? [{ at: axes + rise, duration: duration * LEGEND_SHARE, piece: legend.to({ opacity: 1, y: 0 }) }] : []),
462
+ ])
463
+ },
464
+ },
465
+ /** Show series `index`: its columns come back, the group reflowing to make room, with its legend entry. */
466
+ showSeries: {
467
+ args: { seriesIndex: SERIES_ARG },
468
+ easing: easeOut(),
469
+ run: (timeline, state, children) => toggling(timeline, state, children, timeline.args.seriesIndex, 1),
470
+ },
471
+ /**
472
+ * Hide series `index`: its columns narrow away (or, stacked, sink out of the
473
+ * stack) while the rest of the group widens into the space — the mirror of
474
+ * `showSeries`.
475
+ */
476
+ hideSeries: {
477
+ args: { seriesIndex: SERIES_ARG },
478
+ easing: easeOut(),
479
+ run: (timeline, state, children) => toggling(timeline, state, children, timeline.args.seriesIndex, 0),
480
+ },
481
+ /**
482
+ * Fade every other series — its columns **and its legend entry** — to focus
483
+ * on `index`, which comes back to full. Nothing moves, so the group doesn't
484
+ * reflow.
485
+ */
486
+ spotlightSeries: {
487
+ args: { seriesIndex: SERIES_ARG },
488
+ easing: easeOut(),
489
+ run: (timeline, state, children) => {
490
+ const parts = partsOf(children)
491
+ if (!parts) return timeline.wait(timeline.duration)
492
+ const index = timeline.args.seriesIndex
493
+ const dim = state.theme.spotlight.dimOpacity
494
+ return timeline.together([
495
+ ...parts.bars.map((bars, i) => bars.to({ opacity: i === index ? 1 : dim })),
496
+ ...(parts.legend ? [parts.legend.run("spotlightSeries", { index })] : []),
497
+ ])
498
+ },
499
+ },
500
+ /**
501
+ * Spotlight one **category**: every other category's columns and caption
502
+ * fade to the theme's `dimOpacity`. Called while another is lit, the focus
503
+ * moves directly: only the dimming changes, so nothing retracts first. A
504
+ * category that is not there takes its slot and changes nothing.
505
+ */
506
+ spotlightCategory: {
507
+ args: { categoryIndex: Types.number(0, { min: 0, step: 1 }) },
508
+ easing: easeOut(),
509
+ run: (timeline, state) => {
510
+ const index = timeline.args.categoryIndex
511
+ if (index < 0 || index >= state.data.length) return timeline.wait(timeline.duration)
512
+ const from = state.spotlightReveal
513
+ return timeline.animate((t) => ({ spotlight: index, spotlightReveal: from + (1 - from) * t }))
514
+ },
515
+ },
516
+ /**
517
+ * Drop the category spotlight, every category back to full. The lit
518
+ * category is held until the fade lands; a no-op when nothing is lit, which
519
+ * still takes its slot.
520
+ */
521
+ clearCategory: {
522
+ args: {},
523
+ easing: easeOut(),
524
+ run: (timeline, state) => {
525
+ const from = state.spotlightReveal
526
+ if (from === 0) return timeline.wait(timeline.duration)
527
+ const lit = state.spotlight
528
+ return timeline.animate((t) => (t >= 1 ? { spotlight: null, spotlightReveal: 0 } : { spotlight: lit, spotlightReveal: from * (1 - t) }))
529
+ },
530
+ },
531
+ },
532
+ })
533
+
534
+ export type BarChart = NodeOf<typeof BarChart>