@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,929 +1,585 @@
1
- import {
2
- command,
3
- node,
4
- Node2D,
5
- Rect,
6
- easeOut,
7
- property,
8
- type Command,
9
- type CommandArgs,
10
- type DataRecord,
11
- type EasingFunction,
12
- type NodeConfig,
13
- type Node2DProps,
14
- type Vector2,
15
- } from "@motionscript/sdk"
16
-
17
- import { ChartBorder } from "../kit/chart-border"
18
- import { ChartCanvas } from "../kit/chart-canvas"
19
- import { ChartLegend } from "../kit/chart-legend"
20
- import { VerticalAxis } from "../kit/vertical-axis"
21
- import {
22
- SPOTLIGHT_DIM,
23
- formatMarker,
24
- lerpAxisDomain,
25
- markerValues,
26
- resolveAxisDomain,
27
- resolveSeriesFill,
28
- resolveSeriesStroke,
29
- type AxisDomainConfig,
30
- type Range,
31
- } from "../kit/shared"
32
- import { ChartLine } from "./chart-line"
33
- import { ChartRegion } from "./chart-region"
34
- import { HorizontalAxis } from "./horizontal-axis"
35
- import {
36
- DEFAULT_CHART_THEME,
37
- lerpChartTheme,
38
- resolveChartTheme,
39
- resolveRegionBox,
40
- resolveYScale,
41
- seriesPoints,
42
- type ChartConfig,
43
- type ChartTheme,
44
- type LineSeries,
45
- type PlotRegion,
46
- type RegionBox,
47
- } from "./shared"
48
- import { resolveXScale, type XScale } from "./x-scale"
49
- import { asCommand, formatNumber, hold, sequence as sequenceOf, together } from "@motionscript/sdk/component"
50
-
51
- export interface LineChartProps extends Node2DProps {
52
- /** One row per sample — a plain record of field name to value. */
53
- data: DataRecord[]
54
- /**
55
- * Key into each row for its x value, shared by every series. Named `xField`
56
- * rather than `x` because every node already has an `x` — its position.
57
- */
58
- xField: string
59
- /** One polyline per entry: which field it plots, its legend `label`, its `fill`. */
60
- series: LineSeries[]
61
- /** X-axis data domain: caption, scale range, and tick placement. */
62
- xAxis?: AxisDomainConfig
63
- /** Y-axis data domain: caption, scale range, and tick placement. */
64
- yAxis?: AxisDomainConfig
65
- /**
66
- * A slice of the plot to spotlight, in **data units**. Dashed rules mark the
67
- * bounded edges and every series fades outside the box — see
68
- * {@link LineChart.spotlightRegion}, which animates the same thing. `null`
69
- * (the default) is no region.
70
- */
71
- region?: PlotRegion | null
72
- /**
73
- * The chart's visual theme — series palette, axis text/grid/gutters, plot
74
- * panel paint, and legend styling. Every branch is optional and deep-merged
75
- * onto {@link DEFAULT_CHART_THEME}, so pass only what you want to override.
76
- */
77
- theme?: ChartTheme
78
- /** Whether the legend row below the plot is drawn at all. */
79
- showLegend?: boolean
80
- }
81
-
82
- /**
83
- * Headroom above the plot, in px.
84
- *
85
- * Two jobs, and the second is why it is real padding on the composition rather
86
- * than a number the point-mapping math imagines: a series peaking at `yMax`
87
- * isn't flush to the top edge, **and** the top y-marker — which is centred on
88
- * that top grid line — has somewhere to be. Without it the marker's upper half
89
- * is drawn above the chart's own box, outside the rectangle the editor draws
90
- * around the node.
91
- */
92
- const TOP_HEADROOM = 24
93
-
94
- /**
95
- * The argument every per-series command takes: an index into `series`. Its own
96
- * kind rather than `number` so a host can offer the series by name.
97
- */
98
- const SERIES_ARG = { key: "seriesIndex", kind: "series", default: 0, min: 0, step: 1 }
99
-
100
- /** How far the legend starts below its slot when it enters, in px. */
101
- const LEGEND_SLIDE = 20
102
-
103
- /**
104
- * The two signals the region call-out is made of, as a props type for the
105
- * commands that move them.
106
- *
107
- * Written out rather than reusing `LineChartProps` because the pair is what
108
- * those commands actually touch, and because `regionReveal` is a signal of the
109
- * chart's own rather than part of its authored props.
110
- */
111
- type RegionState = { region: PlotRegion | null; regionReveal: number }
112
-
113
- /** The axis domains {@link LineChart.zoomTo} and {@link LineChart.resetZoom} move. */
114
- type AxisState = { xAxis: AxisDomainConfig; yAxis: AxisDomainConfig }
115
-
116
- /** Both axes' domains with their ranges and ticks resolved. */
117
- type Domains = { x: AxisDomainConfig; y: AxisDomainConfig }
118
-
119
- /**
120
- * How {@link LineChart.enter} divides its duration between its three beats: the
121
- * axes arriving, the lines tracing, and the legend coming up. Shares of the
122
- * whole, so they must sum to 1 — the entrance takes exactly the time it was
123
- * given (see the note on `enter`).
124
- */
125
- const AXES_SHARE = 0.35
126
- const LINES_SHARE = 0.5
127
- const LEGEND_SHARE = 0.15
128
-
129
- /**
130
- * A multi-series line chart, composed from five independent parts rather than
131
- * one monolithic draw:
132
- *
133
- * - {@link ChartCanvas} — the plot panel with a two-way grid, under everything.
134
- * - {@link VerticalAxis} / {@link HorizontalAxis} — columns/rows of real text
135
- * markers that stagger in, each carrying its own axis caption.
136
- * - {@link ChartRegion} — the optional call-out marking a spotlit slice of the
137
- * plot: dashed rules on its bounded edges, and every series faded outside it.
138
- * - {@link ChartLine} (one per series) — the traced polylines over the canvas.
139
- * - {@link ChartLegend} — a row of entries below the chart, one per series.
140
- *
141
- * The parts are laid out from this node's `layoutBounds`: a left gutter for the
142
- * vertical axis, a bottom gutter for the horizontal axis, the plot filling
143
- * what's left, and the legend row beneath the whole chart. Every child's
144
- * position/size is bound reactively, so the chart re-flows if its box changes,
145
- * and the series lines read the same resolved scales as the axes, so points land
146
- * exactly on their markers.
147
- *
148
- * **Resting state is the finished chart.** Unlike the standalone component this
149
- * was ported from, nothing is built hidden: the studio paints a node's Initial
150
- * state on a paused canvas, and a chart that only appeared once a command had
151
- * run would be edited blind. {@link enter} arms every part back to its
152
- * pre-entrance state before animating, so the entrance itself is unchanged.
153
- *
154
- * Past the entrance, three things move the chart around:
155
- * {@link showSeries}/{@link hideSeries}/{@link spotlightSeries} pick out a
156
- * *series*, {@link spotlightRegion} marks a *slice of the plot* without changing
157
- * the scale, and {@link zoomTo} rescales the axes so a slice fills the plot. The
158
- * last two take the same {@link PlotRegion} and compose — a spotlit region
159
- * resolves against the live scales, so it travels with a zoom.
160
- */
161
- @node({
162
- key: "lineChart",
163
- parentKey: "node",
164
- forkable: true,
165
- layout: {
166
- children: "freeform",
167
- defaultWidthMode: "fixed",
168
- defaultHeightMode: "fixed",
169
- acceptsChildren: true,
170
- },
171
- seed: {
172
- width: 760,
173
- height: 460,
174
- },
175
- })
176
- export class LineChart extends Node2D<LineChartProps> {
177
- @property({ default: () => [] as DataRecord[], kind: "dataset" }) declare data: DataRecord[]
178
- @property({ default: "" }) declare xField: string
179
- @property({ default: () => [] as LineSeries[], kind: "series" }) declare series: LineSeries[]
180
- /**
181
- * X/Y-axis data domain (label/range/ticks), tweenable and mappable like
182
- * `theme`: the mapper merges a partial input onto the previous resolved
183
- * domain (leaving `range`/`ticks` `undefined` — the auto-derive signal — on
184
- * first resolution), and the tween interpolates them numerically, so
185
- * `chart.to({ yAxis: { range: [0, 10] } }, 1)` smoothly rescales the plotted
186
- * lines. Like `theme`, the axis *label* text is captured once at construction.
187
- */
188
- @property({
189
- default: {},
190
- mapper: resolveAxisDomain,
191
- tween: lerpAxisDomain,
192
- })
193
- declare xAxis: AxisDomainConfig
194
- @property({
195
- default: {},
196
- mapper: resolveAxisDomain,
197
- tween: lerpAxisDomain,
198
- })
199
- declare yAxis: AxisDomainConfig
200
- /**
201
- * The chart's visual theme, tweenable and mappable like a `stroke`/`fill`
202
- * prop: the mapper merges the author's partial input onto the previous
203
- * resolved theme (or {@link DEFAULT_CHART_THEME} the first time) and resolves
204
- * every leaf; the tween interpolates two resolved themes leaf-by-leaf, so
205
- * `chart.to({ theme: next }, 1)` animates smoothly.
206
- */
207
- @property({
208
- default: DEFAULT_CHART_THEME,
209
- mapper: resolveChartTheme,
210
- tween: lerpChartTheme,
211
- })
212
- declare theme: ChartTheme
213
- /**
214
- * The spotlit slice of the plot in data units, or `null` for none. Held as a
215
- * plain reactive value rather than a tweened one: the box itself snaps, and
216
- * the *animation* is {@link regionReveal} drawing the rules on and the lines
217
- * dimming outside it.
218
- */
219
- @property({ default: null }) declare region: PlotRegion | null
220
- /**
221
- * How far the {@link region} call-out is drawn in, `[0, 1]` — the single
222
- * signal behind both halves of the effect: the rules grow out and the wash
223
- * fades up as it climbs, while every line's out-of-region stretch fades from
224
- * full down to the theme's `region.dimOpacity`. At 0 a chart with a `region`
225
- * set looks exactly like one without.
226
- */
227
- @property({ default: 0 }) declare regionReveal: number
228
- /**
229
- * Read once, in the constructor, like `series`: the legend is a part the
230
- * chart builds or doesn't, so a change reaches it by rebuilding the node.
231
- */
232
- @property({ default: true, animatable: false }) declare showLegend: boolean
233
-
234
- // ---- Part handles (built in the constructor) --------------------------
235
- private vAxis: VerticalAxis
236
- private hAxis: HorizontalAxis
237
- /** The plot panel — the box the grid, the lines and the region all share. */
238
- private plotRect: Rect
239
- private legend: ChartLegend | null = null
240
- private lines: ChartLine[] = []
241
-
242
- /**
243
- * `this.theme` read back through its *resolved* shape: the property's declared
244
- * type is the loose author-facing {@link ChartTheme} (so a partial theme is
245
- * accepted), but the mapper always stores the fully-resolved
246
- * {@link ChartConfig} at runtime — the same loose-declared/resolved-stored
247
- * idiom as a shape's `fill`/`stroke`.
248
- */
249
- private get resolvedTheme(): ChartConfig {
250
- return this.theme as unknown as ChartConfig
251
- }
252
-
253
- // ---- Derived scales ---------------------------------------------------
254
-
255
- /** Fallback marker count when neither axis's ticks are given. */
256
- private static readonly DEFAULT_MARKERS = 5
257
-
258
- /**
259
- * What the x column *is* — a number, an instant, or a place in the file — and
260
- * with it how each row is positioned, ticked and captioned. See `x-scale.ts`.
261
- */
262
- private get xColumn(): XScale {
263
- return resolveXScale(this.data, this.xField, this.xAxis.format)
264
- }
265
-
266
- private get xScale(): Range {
267
- return this.xAxis.range ?? this.xColumn.extent
268
- }
269
-
270
- private get yScale(): Range {
271
- // Auto-ranging steps into one fewer segment than the intended marker count
272
- // — the explicit ticks' count when given, else the default — so the tidy
273
- // bounds still frame the ticks the axis draws.
274
- const divisions =
275
- (this.yAxis.ticks?.length ?? LineChart.DEFAULT_MARKERS) - 1
276
- return resolveYScale(this.data, this.series, this.yAxis.range, divisions)
277
- }
278
-
279
- /** The vertical axis ticks: the explicit ones, else five across the scale. */
280
- private get resolvedYMarkers(): number[] {
281
- return (
282
- this.yAxis.ticks ??
283
- markerValues(this.yScale, LineChart.DEFAULT_MARKERS - 1)
284
- )
285
- }
286
-
287
- /**
288
- * The horizontal axis ticks: the explicit ones, else five across the scale.
289
- *
290
- * Asked of the column rather than spaced evenly, because only a numeric column
291
- * has round numbers between its samples. On a month column, five evenly spaced
292
- * values land two-thirds of the way through four different months; the ticks
293
- * a reader wants are Jan/Apr/Jul/Oct/Dec, which are rows.
294
- */
295
- private get resolvedXMarkers(): number[] {
296
- return (
297
- this.xAxis.ticks ??
298
- this.xColumn.ticks(this.xScale, LineChart.DEFAULT_MARKERS - 1)
299
- )
300
- }
301
-
302
- // ---- Plot geometry ------------------------------------------------------
303
-
304
- /**
305
- * The plot panel's size, **as laid out**.
306
- *
307
- * This used to be computed: six constants estimating what the axis gutters and
308
- * the legend row would take, subtracted from the node's box. The estimate was
309
- * never the layout — the vertical axis is `width: "hug"`, so its real width is
310
- * whatever its widest marker needs — and everything downstream inherited the
311
- * gap. The grid is drawn by {@link ChartCanvas} across its *own* allocation,
312
- * while the lines were mapped across the estimate, so a series sat a few
313
- * percent off the grid line it was supposed to touch, silently and by an
314
- * amount that changed with the theme.
315
- *
316
- * Asking the panel is exact by construction and cannot drift: the lines, the
317
- * region rules and the grid all resolve against one box, and it is the box
318
- * they are drawn in. Zero until the first layout pass, like any other
319
- * `layoutBounds` read — the bindings that call this re-run on the next frame.
320
- */
321
- private plotSize(): { width: number; height: number } {
322
- const { width, height } = this.plotRect.layoutBounds
323
- return { width, height }
324
- }
325
-
326
- /**
327
- * Map one series' data points into the plot's **centred** pixel space (origin
328
- * at the plot centre, y-up) — the local frame of the clip/line box that fills
329
- * the plot. x runs `[-w/2, +w/2]`, y runs `[-h/2, +h/2]`.
330
- */
331
- private seriesPixels(index: number): Vector2[] {
332
- const s = this.series[index]
333
- if (!s) return []
334
- const points = seriesPoints(this.data, this.xColumn, s)
335
- if (points.length === 0) return []
336
- const { width: w, height: h } = this.plotSize()
337
- const [xMin, xMax] = this.xScale
338
- const [yMin, yMax] = this.yScale
339
- // Plot centre is the origin; map the data fraction to [-half, +half].
340
- const xToPx = (x: number) =>
341
- xMax <= xMin ? 0 : ((x - xMin) / (xMax - xMin) - 0.5) * w
342
- const yToPx = (y: number) =>
343
- yMax <= yMin ? 0 : ((y - yMin) / (yMax - yMin) - 0.5) * h
344
- // `seriesPoints` already sorted them along x.
345
- return points.map(([x, y]) => ({ x: xToPx(x), y: yToPx(y) }))
346
- }
347
-
348
- /**
349
- * {@link region} mapped into the plot's **centred** pixel space — the same
350
- * frame {@link seriesPixels} returns, so the region's rules and each line's
351
- * clip resolve against one box from one place. Reads the live scales, so it
352
- * re-maps when `xAxis`/`yAxis` tween.
353
- */
354
- /**
355
- * Whether a call-out is authored at all — the question {@link enter} and
356
- * {@link spotlightRegion} branch on.
357
- *
358
- * Deliberately **not** `hasRegion(this.regionBox())`, which they used to ask.
359
- * That resolves the region into pixels, so it answers "and has the chart been
360
- * laid out yet" as well, and comes back false for a perfectly real region on a
361
- * chart that has not been measured. A generator never noticed, because it only
362
- * ever ran mid-playback; a command is *built* before the first layout pass, and
363
- * would have quietly dropped the region beat every time.
364
- *
365
- * What is left once the pixels are taken out is the same test
366
- * {@link resolveRegionBox} applies before it maps anything: a region bounding
367
- * *neither* axis is not a call-out, so `{}` counts as none exactly as `null`
368
- * does.
369
- */
370
- private hasCallout(): boolean {
371
- const region = this.region
372
- return region != null && (region.x !== undefined || region.y !== undefined)
373
- }
374
-
375
- private regionBox(): RegionBox {
376
- const { width: w, height: h } = this.plotSize()
377
- // The region lives in the plot's own centred frame, the same one
378
- // seriesPixels maps its points into.
379
- return resolveRegionBox(
380
- this.region,
381
- { left: -w / 2, right: w / 2, bottom: -h / 2, top: h / 2 },
382
- this.xScale,
383
- this.yScale
384
- )
385
- }
386
-
387
- // ---- Build ------------------------------------------------------------
388
-
389
- constructor(props?: NodeConfig<LineChart, LineChartProps>) {
390
- super(props)
391
-
392
- // The whole chart is composed from plain props/`data` — no context needed,
393
- // so the parts are built here (super() applied the props above).
394
- //
395
- // Every theme/axis-derived prop below that a *leaf* drawing part reads live
396
- // in `renderSelf` every frame — the canvas's fill/grid/extent, the border's
397
- // stroke, each line's stroke/points — is passed as a closure, not a one-time
398
- // snapshot, so `chart.to({ theme })` and `chart.to({ yAxis: { range } })`
399
- // genuinely animate the panel, grid, border, and plotted lines. The two axes
400
- // compose their child text nodes *once* (the marker count is fixed at
401
- // construction) but bind each marker's caption and position to the live
402
- // range/ticks, so a rescale re-labels and re-places the row as it tweens.
403
- const enabled = this.series.map((s) => s.enabled ?? true)
404
- const showLegend = this.showLegend !== false
405
-
406
- this.vAxis = new VerticalAxis({
407
- // Bound, not snapshotted — this is the half of a rescale the axis owns.
408
- // The marker *count* is still read once (it fixes how many text nodes get
409
- // built), which is why `zoomTo` keeps the count constant.
410
- range: () => this.yScale,
411
- markers: () => this.resolvedYMarkers,
412
- axis: () => this.resolvedTheme.yAxis,
413
- label: this.yAxis.label ?? "",
414
- width: "hug",
415
- height: "fill",
416
- })
417
- // The y axis is always numbers, so its format is simply the pattern.
418
- this.vAxis.labelFor = (value) =>
419
- this.yAxis.format === undefined
420
- ? formatMarker(value)
421
- : formatNumber(value, this.yAxis.format)
422
-
423
- this.hAxis = new HorizontalAxis({
424
- range: () => this.xScale,
425
- markers: () => this.resolvedXMarkers,
426
- axis: () => this.resolvedTheme.xAxis,
427
- label: this.xAxis.label ?? "",
428
- width: "fill",
429
- height: "hug",
430
- })
431
- // A tick on a month or category column is captioned with the cell it came
432
- // out of — `Jan`, not the instant it parsed to. Assigned rather than passed:
433
- // see the note on the field.
434
- this.hAxis.labelFor = (value) => this.xColumn.label(value)
435
-
436
- this.lines = this.series.map(
437
- (s, i) =>
438
- new ChartLine({
439
- points: () => this.seriesPixels(i),
440
- stroke: () => resolveSeriesStroke(this.resolvedTheme.seriesStyles, s, i),
441
- enabled: enabled[i],
442
- // Each line clips itself against the same box the rules are drawn
443
- // from, so the dim/bright boundary can't drift from the dashes.
444
- spotlight: () => this.regionBox(),
445
- // Ramped by the same reveal that draws the rules, so at reveal 0 the
446
- // line is uniform and the region invisible — one signal, both halves.
447
- dimOpacity: () =>
448
- 1 - (1 - this.resolvedTheme.region.dimOpacity) * this.regionReveal,
449
- })
450
- )
451
-
452
- if (showLegend) {
453
- this.legend = new ChartLegend({
454
- series: this.series,
455
- // The kit's legend paints a swatch, not a line, so the chart hands it
456
- // the *colour* each stroke resolves to rather than the stroke itself —
457
- // which is also what lets a bar chart's fill palette drive the same row.
458
- swatches: () =>
459
- this.series.map((s, i) =>
460
- resolveSeriesFill(this.resolvedTheme.seriesStyles, s, i)
461
- ),
462
- legend: () => this.resolvedTheme.legend,
463
- })
464
- }
465
-
466
- this.plotRect = new Rect({
467
- clip: true,
468
- children: [
469
- new ChartCanvas({
470
- fill: () => this.resolvedTheme.plotArea.fill,
471
- shadow: () => this.resolvedTheme.plotArea.shadow,
472
- xGridStroke: () => this.resolvedTheme.xAxis.lineStyle,
473
- yGridStroke: () => this.resolvedTheme.yAxis.lineStyle,
474
- // A grid line under every axis marker; the canvas maps the marker
475
- // values through the extents and skips the edges.
476
- xMarkers: () => this.resolvedXMarkers,
477
- yMarkers: () => this.resolvedYMarkers,
478
- xExtent: () => this.xScale,
479
- yExtent: () => this.yScale,
480
- }),
481
- // Region wash + dashed rules: over the grid, under the lines, so a
482
- // spotlit stretch of a series isn't tinted by the highlight meant to
483
- // pick it out.
484
- new ChartRegion({
485
- box: () => this.regionBox(),
486
- stroke: () => this.resolvedTheme.region.stroke,
487
- fill: () => this.resolvedTheme.region.fill,
488
- reveal: () => this.regionReveal,
489
- }),
490
- ...this.lines,
491
- new ChartBorder({
492
- stroke: () => this.resolvedTheme.plotArea.stroke,
493
- }),
494
- ],
495
- })
496
-
497
- // Invisible twin of the vertical axis, reserving the same left gutter under
498
- // the plot so the horizontal axis starts at the plot's left edge rather than
499
- // the chart's.
500
- const gutterSpacer = new VerticalAxis({
501
- opacity: 0,
502
- range: () => this.yScale,
503
- markers: () => this.resolvedYMarkers,
504
- axis: () => this.resolvedTheme.yAxis,
505
- label: this.yAxis.label ?? "",
506
- width: "hug",
507
- height: 0,
508
- })
509
-
510
- const below: Node2D[] = [this.hAxis]
511
- if (this.legend) below.push(this.legend)
512
-
513
- this.add(
514
- new Rect({ flow: "vertical",
515
- width: "fill",
516
- height: "fill",
517
- // See {@link TOP_HEADROOM}: the plot's top grid line is the one place a
518
- // marker would otherwise be drawn outside the chart's own box.
519
- padding: { top: TOP_HEADROOM },
520
- children: [
521
- new Rect({ flow: "horizontal",
522
- height: "fill",
523
- width: "fill",
524
- children: [this.vAxis, this.plotRect],
525
- }),
526
- new Rect({ flow: "horizontal",
527
- width: "fill",
528
- children: [
529
- gutterSpacer,
530
- new Rect({ flow: "vertical", width: "fill", gap: 20, children: below }),
531
- ],
532
- }),
533
- ],
534
- })
535
- )
536
- }
537
-
538
- // ---- Orchestrated entrance --------------------------------------------
539
-
540
- /**
541
- * Prime every part at its pre-entrance state — axis markers shifted and
542
- * transparent, lines untraced, legend dropped and transparent.
543
- *
544
- * Called by {@link enter} before its first frame so nothing flashes ahead of
545
- * its beat. Idempotent, and public so a scene can hide a chart ahead of time
546
- * without starting the entrance.
547
- */
548
- arm(): void {
549
- this.vAxis.arm()
550
- this.hAxis.arm()
551
- for (const line of this.lines) line.set({ progress: 0 })
552
- this.legend?.set({ opacity: 0, y: -LEGEND_SLIDE })
553
- }
554
-
555
- /**
556
- * Animate the whole chart in: the two axes stagger their markers in (vertical
557
- * bottom-to-top, horizontal left-to-right), the series lines trace
558
- * left-to-right, and the legend fades up last.
559
- *
560
- * `duration` is the **whole** entrance. The phases below are shares of it, not
561
- * multiples — a command that declares 1.4 seconds has to take 1.4 seconds,
562
- * because that is the slot the timeline lays out for it, the length its
563
- * parallel siblings are timed against, and its contribution to the scene's own
564
- * duration. (The component this was ported from scaled every phase *off* the
565
- * line trace and let the total fall where it may, which came out around 3×.)
566
- *
567
- * A chart authored with a `region` lands its call-out last, over lines that
568
- * have already traced — the same order a scene would get by calling
569
- * {@link spotlightRegion} right after this — and that beat comes out of the
570
- * same budget.
571
- */
572
- @command()
573
- enter(
574
- args: CommandArgs<Record<string, never>> & { duration: number }
575
- ): Command<Record<string, never>> {
576
- const duration = args.duration
577
- const easing = args.easing ?? easeOut()
578
- this.arm()
579
-
580
- const revealing = this.hasCallout() && this.regionReveal === 0
581
- // The region call-out, when there is one, takes the last quarter.
582
- const body = revealing ? duration * 0.75 : duration
583
-
584
- // The same three phases, in the same order and with the same shares — placed
585
- // at their offsets rather than sequenced by a generator, so the whole
586
- // entrance can be asked what it looks like at a time. Each part writes to its
587
- // own node (the axes, the lines, the legend), which is why these compose as
588
- // steppers rather than as merged props.
589
- const axes = together(
590
- this.vAxis.enter({ data: { slide: 24 }, duration: body * AXES_SHARE, easing }),
591
- this.hAxis.enter({ data: { slide: 24 }, duration: body * AXES_SHARE, easing })
592
- )
593
- const lines = together(
594
- ...this.lines.map((line) => line.enter({ duration: body * LINES_SHARE, easing }))
595
- )
596
- const legend = this.legend
597
- ? [this.legend.to({ data: { opacity: 1, y: 0 }, duration: body * LEGEND_SHARE, easing })]
598
- : []
599
-
600
- const phases = sequenceOf(axes, lines, ...legend)
601
-
602
- return asCommand(
603
- revealing
604
- ? sequenceOf(
605
- phases,
606
- // Typed to what it writes rather than to `LineChartProps`: `regionReveal`
607
- // is a signal of the chart's own, not part of its authored props.
608
- this.command<{ regionReveal: number }>(
609
- (t) => ({ regionReveal: t }),
610
- duration * 0.25,
611
- easing
612
- )
613
- )
614
- : phases,
615
- duration
616
- )
617
- }
618
-
619
- // ---- Region spotlight --------------------------------------------------
620
-
621
- /**
622
- * Spotlight a rectangular slice of the plot given in **data units**: dashed
623
- * rules draw themselves onto each bounded edge while every series fades
624
- * outside the box and stays full inside it.
625
- *
626
- * Either axis alone is a band — `{ x: [80, 100] }` picks out the last fifth
627
- * across all series, `{ y: [8, 10] }` a value band across the whole width —
628
- * and both together a box. The unbounded axis spans the plot and draws no
629
- * rule, since there's no data bound there to mark.
630
- *
631
- * Calling it while another region is already up cross-fades: the old call-out
632
- * retracts, then the new one draws in, each over half `duration`.
633
- *
634
- * Both the call-out's shape and its draw-on are plain signals — `region` and
635
- * {@link regionReveal} — so the whole thing is a function of `t`, including
636
- * the swap: which region is up is a step at the halfway point rather than an
637
- * effect that has to have happened.
638
- */
639
- @command({
640
- args: [
641
- // One argument, two controls: the method takes a `PlotRegion`, so the x
642
- // and y spans a host draws are declared inside it.
643
- {
644
- key: "region", kind: "region", properties: {
645
- x: { kind: "range", default: true, defaultMin: 0, defaultMax: 100 },
646
- y: { kind: "range", default: false, defaultMin: 0, defaultMax: 100 },
647
- },
648
- },
649
- ],
650
- })
651
- spotlightRegion(
652
- args: CommandArgs<{ region: PlotRegion }> & { duration?: number }
653
- ): Command<RegionState> {
654
- const region = LineChart.regionArg(args.data)
655
- const duration = args.duration ?? 0.5
656
- const easing = args.easing ?? easeOut()
657
- const from = this.regionReveal
658
- const previous = this.region
659
-
660
- // A region bounding neither axis is no call-out: spotlighting it is a clear.
661
- if (region.x === undefined && region.y === undefined) {
662
- return this.clearRegion({ duration, easing })
663
- }
664
-
665
- // Nothing up yet: the region is set from the first frame and just draws on.
666
- if (from <= 0 || !this.hasCallout()) {
667
- return this.command<RegionState>(
668
- (t) => ({ region, regionReveal: from + (1 - from) * t }),
669
- duration,
670
- easing
671
- )
672
- }
673
-
674
- // Something already up: retract it first so the rules don't jump across the
675
- // plot mid-draw. Each half eases on its own — which is why the easing is
676
- // applied here rather than handed to `animate`, whose easing would shape the
677
- // pair as one curve and leave both halves crawling past the seam.
678
- return this.command<RegionState>(
679
- (t) =>
680
- t < 0.5
681
- ? { region: previous, regionReveal: from * (1 - easing(t * 2)) }
682
- : { region, regionReveal: easing(t * 2 - 1) },
683
- duration
684
- )
685
- }
686
-
687
- /**
688
- * Drop the region call-out — the rules retract, the wash fades, and every
689
- * series comes back to full across its whole length. A no-op when nothing is
690
- * spotlit.
691
- */
692
- @command()
693
- clearRegion(
694
- args: CommandArgs<Record<string, never>> & { duration?: number } = {}
695
- ): Command<RegionState> {
696
- const duration = args.duration ?? 0.5
697
- const easing = args.easing ?? easeOut()
698
- const from = this.regionReveal
699
-
700
- if (from === 0) {
701
- // Nothing to retract, but the call still takes its slot: in the studio a
702
- // command's duration is what the timeline lays out and what parallel
703
- // siblings are timed against, so a no-op that took no frames would pull
704
- // everything after it forward. Same reason for `zoomTo`/`resetZoom` below.
705
- return this.command<RegionState>(
706
- () => ({ region: null, regionReveal: 0 }),
707
- duration
708
- )
709
- }
710
-
711
- // `region` is left alone until the retraction lands — cleared at `t === 1`
712
- // rather than up front, or there would be nothing left to retract.
713
- return this.command<RegionState>(
714
- (t) => (t >= 1 ? { region: null, regionReveal: 0 } : { regionReveal: from * (1 - t) }),
715
- duration,
716
- easing
717
- )
718
- }
719
-
720
- // ---- Zoom --------------------------------------------------------------
721
-
722
- /**
723
- * The domain to come back to, captured the first time {@link zoomTo} runs so a
724
- * later {@link resetZoom} restores the chart as authored — including ticks
725
- * that were auto-derived rather than given, which the props alone don't
726
- * record. Cleared by {@link resetZoom}, so a second zoom captures wherever the
727
- * chart genuinely rests then.
728
- */
729
- private home: Domains | null = null
730
-
731
- /**
732
- * The `region` a document handed a command, or `{}`. A command is added
733
- * before its arguments are filled in, so an unstated region is ordinary input
734
- * rather than a malformed one.
735
- */
736
- private static regionArg(data: { region?: PlotRegion | null } | undefined): PlotRegion {
737
- const region = data?.region
738
- return region != null && typeof region === "object" ? region : {}
739
- }
740
-
741
- /** A range read as a span, whichever way round the author wrote it. */
742
- private static span([a, b]: Range): Range {
743
- return a <= b ? [a, b] : [b, a]
744
- }
745
-
746
- /**
747
- * Rescale an axis to `range`, keeping the tick *count* it already has — the
748
- * axis tween interpolates ticks pairwise by index, so a constant count lets
749
- * each marker slide from its old value to its new one instead of the row
750
- * popping.
751
- */
752
- private static rescale(range: Range, ticks: number[]): AxisDomainConfig {
753
- const span = LineChart.span(range)
754
- const count = Math.max(2, ticks.length)
755
- return { range: span, ticks: markerValues(span, count - 1) }
756
- }
757
-
758
- /**
759
- * Zoom the plot to a slice of itself, given in **data units**: the named axes
760
- * rescale so that slice fills the plot, the grid and both marker rows
761
- * following the new scale, and every series re-tracing itself into the new
762
- * frame. All of it tweens, so the move reads as a camera push rather than a
763
- * cut.
764
- *
765
- * An **omitted axis is left as it is** rather than being fitted to what's
766
- * visible — so a zoom is exactly what was asked for, and two calls compose
767
- * predictably. A spotlit region, if one is up, follows the zoom: it resolves
768
- * against the same live scales, so its rules stay on their data bounds.
769
- */
770
- @command({
771
- args: [
772
- // One argument, two controls: the method takes a `PlotRegion`, so the x
773
- // and y spans a host draws are declared inside it.
774
- {
775
- key: "region", kind: "region", properties: {
776
- x: { kind: "range", default: true, defaultMin: 0, defaultMax: 100 },
777
- y: { kind: "range", default: false, defaultMin: 0, defaultMax: 100 },
778
- },
779
- },
780
- ],
781
- })
782
- zoomTo(
783
- args: CommandArgs<{ region: PlotRegion }> & { duration?: number }
784
- ): Command<AxisState> {
785
- const region = LineChart.regionArg(args.data)
786
- const duration = args.duration ?? 0.8
787
- const easing = args.easing ?? easeOut()
788
- if (!region.x && !region.y) return this.command<AxisState>(() => ({}), duration)
789
-
790
- // Captured *before* the first zoom moves it.
791
- const from = this._domains()
792
- this.home ??= from
793
-
794
- return this._tweenAxes(
795
- from,
796
- {
797
- ...(region.x && { x: { ...from.x, ...LineChart.rescale(region.x, from.x.ticks!) } }),
798
- ...(region.y && { y: { ...from.y, ...LineChart.rescale(region.y, from.y.ticks!) } }),
799
- },
800
- duration,
801
- easing
802
- )
803
- }
804
-
805
- /**
806
- * Pull back out to the domain the chart was authored with — the mirror of
807
- * {@link zoomTo}, and a no-op if it was never zoomed.
808
- */
809
- @command()
810
- resetZoom(
811
- args: CommandArgs<Record<string, never>> & { duration?: number } = {}
812
- ): Command<AxisState> {
813
- const duration = args.duration ?? 0.8
814
- const easing = args.easing ?? easeOut()
815
- const home = this.home
816
- if (!home) return this.command<AxisState>(() => ({}), duration)
817
-
818
- // Cleared here rather than once the move lands. Nothing reads `home` while
819
- // it runs, and a value has no "after" to clear it in — what matters is that
820
- // the *next* `zoomTo` captures wherever the chart genuinely rests by then,
821
- // and both this and its capture happen as the command list is walked.
822
- this.home = null
823
- return this._tweenAxes(this._domains(), home, duration, easing)
824
- }
825
-
826
- // ---- Per-series -------------------------------------------------------
827
-
828
- /**
829
- * Show series `index`: **trace** its line in left-to-right — the same draw as
830
- * {@link enter}, not an opacity fade — in lockstep with its legend entry
831
- * growing in.
832
- *
833
- * `enabled` is set as part of the command's own value rather than before it,
834
- * so the line is drawable for every `t` the trace covers and undrawn outside
835
- * it — which is what makes arriving here backwards show the same thing as
836
- * arriving forwards.
837
- */
838
- @command({ args: [SERIES_ARG] })
839
- showSeries(
840
- args: CommandArgs<{ seriesIndex: number }> & { duration?: number }
841
- ): Command<Record<string, never>> {
842
- const index = args.data?.seriesIndex ?? 0
843
- const duration = args.duration ?? 0.35
844
- const easing = args.easing ?? easeOut()
845
- const line = this.lines[index]
846
- if (!line) return asCommand(hold(duration))
847
-
848
- return asCommand(
849
- together(
850
- line.enterFrom(0, duration, easing),
851
- ...(this.legend ? [this.legend.showSeries({ data: { index }, duration, easing })] : [])
852
- ),
853
- duration
854
- )
855
- }
856
-
857
- /**
858
- * Hide series `index`: **retrace** its line back out (`progress` 1 → 0) as its
859
- * legend entry shrinks away — the mirror of {@link showSeries}.
860
- */
861
- @command({ args: [SERIES_ARG] })
862
- hideSeries(
863
- args: CommandArgs<{ seriesIndex: number }> & { duration?: number }
864
- ): Command<Record<string, never>> {
865
- const index = args.data?.seriesIndex ?? 0
866
- const duration = args.duration ?? 0.35
867
- const easing = args.easing ?? easeOut()
868
- const line = this.lines[index]
869
- if (!line) return asCommand(hold(duration))
870
-
871
- return asCommand(
872
- together(
873
- line.enterFrom(1, duration, easing, 0),
874
- ...(this.legend ? [this.legend.hideSeries({ data: { index }, duration, easing })] : [])
875
- ),
876
- duration
877
- )
878
- }
879
-
880
- /**
881
- * Fade out all other series — each line **and its legend entry** — to focus
882
- * attention on `index`, which comes back to full. The legend dims in place
883
- * (opacity only), so no entry moves and the row doesn't reflow.
884
- */
885
- @command({ args: [SERIES_ARG] })
886
- spotlightSeries(
887
- args: CommandArgs<{ seriesIndex: number }> & { duration?: number }
888
- ): Command<Record<string, never>> {
889
- const index = args.data?.seriesIndex ?? 0
890
- const duration = args.duration ?? 0.35
891
- const easing = args.easing ?? easeOut()
892
- return asCommand(
893
- together(
894
- ...this.lines.map((line, i) =>
895
- line.to({ data: { opacity: i === index ? 1 : SPOTLIGHT_DIM }, duration, easing })
896
- ),
897
- ...(this.legend
898
- ? [this.legend.spotlightSeries({ data: { index }, duration, easing })]
899
- : [])
900
- ),
901
- duration
902
- )
903
- }
904
-
905
- /** Both axes as drawn, so an auto range or tick row is read back as itself. */
906
- private _domains(): Domains {
907
- return {
908
- x: { ...this.xAxis, range: this.xScale, ticks: this.resolvedXMarkers },
909
- y: { ...this.yAxis, range: this.yScale, ticks: this.resolvedYMarkers },
910
- }
911
- }
912
-
913
- /** From a resolved `from`: the axis tween steps an auto side at the midpoint, which is a cut. */
914
- private _tweenAxes(
915
- from: Domains,
916
- to: Partial<Domains>,
917
- duration: number,
918
- easing: EasingFunction
919
- ): Command<AxisState> {
920
- return this.command<AxisState>(
921
- (t) => ({
922
- ...(to.x && { xAxis: lerpAxisDomain(from.x, to.x, t) }),
923
- ...(to.y && { yAxis: lerpAxisDomain(from.y, to.y, t) }),
924
- }),
925
- duration,
926
- easing
927
- )
928
- }
929
- }
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
+ type Vector2,
16
+ } from "@motionscript/sdk"
17
+ import { formatNumber } from "@motionscript/sdk/component"
18
+
19
+ import { cartesianFrame, cartesianViews, laidOutSize } from "../kit/cartesian"
20
+ import { ChartBorder } from "../kit/chart-border"
21
+ import { ChartCanvas } from "../kit/chart-canvas"
22
+ import { ChartLegend } from "../kit/chart-legend"
23
+ import { asParts, fresh } from "../kit/entries"
24
+ import { beats, type Beat } from "../kit/motion"
25
+ import { VerticalAxis } from "../kit/vertical-axis"
26
+ import {
27
+ SPOTLIGHT_DIM,
28
+ formatMarker,
29
+ lerpAxisDomain,
30
+ lerpAxisEntry,
31
+ markerStep,
32
+ markerValues,
33
+ resolveAxisDomain,
34
+ resolveSeriesFill,
35
+ resolveSeriesStroke,
36
+ settleAxisDomain,
37
+ type AxisDomainConfig,
38
+ type Range,
39
+ } from "../kit/shared"
40
+ import { ChartLine } from "./chart-line"
41
+ import { ChartRegion } from "./chart-region"
42
+ import { HorizontalAxis } from "./horizontal-axis"
43
+ import {
44
+ DEFAULT_CHART_THEME,
45
+ lerpChartTheme,
46
+ resolveChartTheme,
47
+ resolveRegionBox,
48
+ resolveYScale,
49
+ seriesPoints,
50
+ type ChartConfig,
51
+ type ChartTheme,
52
+ type LineSeries,
53
+ type PlotRegion,
54
+ type RegionBox,
55
+ } from "./shared"
56
+ import { resolveXScale, type XScale } from "./x-scale"
57
+
58
+ export interface LineChartProps extends Node2DProps {
59
+ /** One row per sample — a plain record of field name to value. */
60
+ data: DataRecord[]
61
+ /**
62
+ * Key into each row for its x value, shared by every series. Named `xField`
63
+ * rather than `x` because every node already has an `x` — its position.
64
+ */
65
+ xField: string
66
+ /** One polyline per entry: which field it plots, its legend `label`, its `fill`. */
67
+ series: LineSeries[]
68
+ /** X-axis data domain: caption, scale range, and tick placement. */
69
+ xAxis?: AxisDomainConfig
70
+ /** Y-axis data domain: caption, scale range, and tick placement. */
71
+ yAxis?: AxisDomainConfig
72
+ /**
73
+ * A slice of the plot to spotlight, in **data units**. Dashed rules mark the
74
+ * bounded edges and every series fades outside the box — see
75
+ * `spotlightRegion`, which animates the same thing. `null` (the default) is no
76
+ * region.
77
+ */
78
+ region?: PlotRegion | null
79
+ /**
80
+ * The chart's visual theme — series palette, axis text/grid/gutters, plot
81
+ * panel paint, and legend styling. Every branch is optional and deep-merged
82
+ * onto {@link DEFAULT_CHART_THEME}, so pass only what you want to override.
83
+ */
84
+ theme?: ChartTheme
85
+ /** Whether the legend row below the plot is drawn at all. */
86
+ showLegend?: boolean
87
+ }
88
+
89
+ /** Both axes' domains with their ranges and ticks resolved. */
90
+ export interface LineChartDomains {
91
+ readonly x: AxisDomainConfig & { readonly range: Range; readonly ticks: number[] }
92
+ readonly y: AxisDomainConfig & { readonly range: Range; readonly ticks: number[] }
93
+ }
94
+
95
+ /** What a line chart plots, as its entries hold it. */
96
+ export interface LineChartValues {
97
+ readonly data: DataRecord[]
98
+ readonly xField: string
99
+ readonly series: LineSeries[]
100
+ readonly xAxis: AxisDomainConfig
101
+ readonly yAxis: AxisDomainConfig
102
+ }
103
+
104
+ /**
105
+ * The argument every per-series command takes: an index into `series`. Its own
106
+ * kind rather than `number` so a host can offer the series by name.
107
+ */
108
+ const SERIES_ARG = Types.custom<number, number, EntryOptions & { readonly min: number; readonly step: number }>(0, { kind: "series", min: 0, step: 1 })
109
+
110
+ /** One argument, two controls: the commands take a `PlotRegion`, so the x and y spans a host draws are declared inside it. */
111
+ const REGION_ARG = Types.custom<PlotRegion | undefined>(undefined, {
112
+ kind: "region",
113
+ properties: {
114
+ x: { kind: "range", default: true, defaultMin: 0, defaultMax: 100 },
115
+ y: { kind: "range", default: false, defaultMin: 0, defaultMax: 100 },
116
+ },
117
+ })
118
+
119
+ /** How far the legend starts below its slot when it enters, in px. */
120
+ const LEGEND_SLIDE = 20
121
+
122
+ /** Fallback marker count when neither axis's ticks are given. */
123
+ const DEFAULT_MARKERS = 5
124
+
125
+ /**
126
+ * How `enter` divides its duration between its three beats: the axes arriving,
127
+ * the lines tracing, and the legend coming up. Shares of the whole, so they must
128
+ * sum to 1 — the entrance takes exactly the time it was given.
129
+ */
130
+ const AXES_SHARE = 0.35
131
+ const LINES_SHARE = 0.5
132
+ const LEGEND_SHARE = 0.15
133
+
134
+ /** What the chart's own commands read: its entries, and the private `home` a zoom remembers. */
135
+ interface LineState extends LineChartValues {
136
+ readonly theme: ChartConfig
137
+ readonly region: PlotRegion | null
138
+ readonly regionReveal: number
139
+ readonly home: LineChartDomains | null
140
+ }
141
+
142
+ /**
143
+ * What the x column *is* — a number, an instant, or a place in the file — and
144
+ * with it how each row is positioned, ticked and captioned. See `x-scale.ts`.
145
+ */
146
+ function columnOf(s: LineChartValues, format = s.xAxis.format): XScale {
147
+ return resolveXScale(s.data, s.xField, format)
148
+ }
149
+
150
+ /**
151
+ * The horizontal axis with its range and ticks resolved: the explicit ones, else
152
+ * the column's extent and five ticks across it, asked of the column because only
153
+ * a numeric one has round numbers between its samples.
154
+ */
155
+ function drawnX(s: LineChartValues, domain: AxisDomainConfig): AxisDomainConfig {
156
+ const column = columnOf(s, domain.format)
157
+ const range = domain.range ?? column.extent
158
+ return { ...domain, range, ticks: domain.ticks ?? column.ticks(range, DEFAULT_MARKERS - 1) }
159
+ }
160
+
161
+ /**
162
+ * The vertical axis with its range and ticks resolved. Auto-ranging steps into
163
+ * one fewer segment than the intended marker count, so the tidy bounds frame the
164
+ * ticks the axis draws.
165
+ */
166
+ function drawnY(s: LineChartValues, domain: AxisDomainConfig): AxisDomainConfig {
167
+ const divisions = (domain.ticks?.length ?? DEFAULT_MARKERS) - 1
168
+ const range = resolveYScale(s.data, s.series, domain.range, divisions)
169
+ return { ...domain, range, ticks: domain.ticks ?? markerValues(range, DEFAULT_MARKERS - 1) }
170
+ }
171
+
172
+ /** Both axes as a line chart draws them now, an auto range or tick row read back as itself. */
173
+ export function lineChartDomains(s: LineChartValues): LineChartDomains {
174
+ return {
175
+ x: settleAxisDomain(s.xAxis, (d) => drawnX(s, d)) as LineChartDomains["x"],
176
+ y: settleAxisDomain(s.yAxis, (d) => drawnY(s, d)) as LineChartDomains["y"],
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Map one series' data points into the plot's **centred** pixel space (origin at
182
+ * the plot centre, y-up): x runs `[-w/2, +w/2]`, y runs `[-h/2, +h/2]`.
183
+ */
184
+ function seriesPixels(s: LineChartValues, domains: LineChartDomains, index: number, plot: Size2D): Vector2[] {
185
+ const series = s.series[index]
186
+ if (!series) return []
187
+ const points = seriesPoints(s.data, columnOf(s), series)
188
+ if (points.length === 0) return []
189
+ const { width: w, height: h } = plot
190
+ const [xMin, xMax] = domains.x.range
191
+ const [yMin, yMax] = domains.y.range
192
+ const xToPx = (x: number) => (xMax <= xMin ? 0 : ((x - xMin) / (xMax - xMin) - 0.5) * w)
193
+ const yToPx = (y: number) => (yMax <= yMin ? 0 : ((y - yMin) / (yMax - yMin) - 0.5) * h)
194
+ // `seriesPoints` already sorted them along x.
195
+ return points.map(([x, y]) => ({ x: xToPx(x), y: yToPx(y) }))
196
+ }
197
+
198
+ /** `region` mapped into the plot's centred pixel space, against the live scales, so it travels with a zoom. */
199
+ function regionBox(s: LineChartValues & { readonly region: PlotRegion | null }, domains: LineChartDomains, plot: Size2D): RegionBox {
200
+ const { width: w, height: h } = plot
201
+ return resolveRegionBox(s.region, { left: -w / 2, right: w / 2, bottom: -h / 2, top: h / 2 }, domains.x.range, domains.y.range)
202
+ }
203
+
204
+ /**
205
+ * Whether a call-out is authored at all. Not whether it resolves to pixels: a
206
+ * command is built before the first layout, and a region on a chart not yet
207
+ * measured is a real one. A region bounding neither axis is none, as `null` is.
208
+ */
209
+ function hasCallout(s: { readonly region: PlotRegion | null }): boolean {
210
+ const region = s.region
211
+ return region != null && (region.x !== undefined || region.y !== undefined)
212
+ }
213
+
214
+ /** The `region` a document handed a command, or `{}`: a command is added before its arguments are filled in. */
215
+ function regionArg(region: PlotRegion | null | undefined): PlotRegion {
216
+ return region != null && typeof region === "object" ? region : {}
217
+ }
218
+
219
+ /** A range read as a span, whichever way round the author wrote it. */
220
+ function span([a, b]: Range): Range {
221
+ return a <= b ? [a, b] : [b, a]
222
+ }
223
+
224
+ /**
225
+ * Rescale an axis to `range`, keeping the tick *count* it already has, so each
226
+ * marker slides from its old value to its new one instead of the row popping.
227
+ */
228
+ function rescale(range: Range, ticks: readonly number[]): AxisDomainConfig {
229
+ const to = span(range)
230
+ return { range: to, ticks: markerValues(to, Math.max(2, ticks.length) - 1) }
231
+ }
232
+
233
+ /** The axis writes of a move from `from` toward `to` at `t`. */
234
+ function axesAt(from: LineChartDomains, to: Partial<Record<"x" | "y", AxisDomainConfig>>, t: number) {
235
+ return {
236
+ ...(to.x && { xAxis: lerpAxisDomain(from.x, to.x, t) }),
237
+ ...(to.y && { yAxis: lerpAxisDomain(from.y, to.y, t) }),
238
+ }
239
+ }
240
+
241
+ type AnyTimeline = Timeline<any, any>
242
+
243
+ /** The parts a line chart's commands drive, found through its children. */
244
+ function partsOf(children: readonly ChildView[]) {
245
+ const frame = cartesianViews(children)
246
+ if (!frame) return null
247
+ const hAxis = frame.below.find(HorizontalAxis.is)
248
+ if (!VerticalAxis.is(frame.axis) || !hAxis) return null
249
+ return {
250
+ vAxis: frame.axis,
251
+ hAxis,
252
+ lines: frame.plot.filter(ChartLine.is),
253
+ legend: frame.below.find(ChartLegend.is) ?? null,
254
+ }
255
+ }
256
+
257
+ /** Drop the call-out: the rules retract, the wash fades, and every series comes back to full. */
258
+ function clearing(timeline: AnyTimeline, state: LineState) {
259
+ const from = state.regionReveal
260
+ const region = state.region
261
+ // Nothing to retract, but the call still takes its slot on the timeline.
262
+ if (from === 0) return timeline.animate(() => ({ region: null, regionReveal: 0 }), { eased: false })
263
+ // `region` is held until the retraction lands, or there would be nothing left to retract.
264
+ return timeline.animate((t) => (t >= 1 ? { region: null, regionReveal: 0 } : { region, regionReveal: from * (1 - t) }))
265
+ }
266
+
267
+ /** Trace series `index`'s line in (`show`) or back out, in lockstep with its legend entry. */
268
+ function toggling(timeline: AnyTimeline, children: readonly ChildView[], index: number, show: boolean) {
269
+ const parts = partsOf(children)
270
+ const line = parts?.lines[index]
271
+ if (!parts || !line) return timeline.wait(timeline.duration)
272
+ return timeline.together([
273
+ line.run("enter", show ? { from: 0, to: 1 } : { from: 1, to: 0 }),
274
+ ...(parts.legend ? [parts.legend.run(show ? "showSeries" : "hideSeries", { index })] : []),
275
+ ])
276
+ }
277
+
278
+ /**
279
+ * A multi-series line chart, composed from five independent parts rather than
280
+ * one monolithic draw:
281
+ *
282
+ * - {@link ChartCanvas} — the plot panel with a two-way grid, under everything.
283
+ * - {@link VerticalAxis} / {@link HorizontalAxis} — columns/rows of real text
284
+ * markers that stagger in, each carrying its own axis caption.
285
+ * - {@link ChartRegion} — the optional call-out marking a spotlit slice of the
286
+ * plot: dashed rules on its bounded edges, and every series faded outside it.
287
+ * - {@link ChartLine} (one per series) — the traced polylines over the canvas.
288
+ * - {@link ChartLegend} — a row of entries below the chart, one per series.
289
+ *
290
+ * Every part reads the chart's entries through bindings, and the lines, the
291
+ * region and the grid all map against the plot panel's own laid-out box, so
292
+ * points land exactly on their markers and the chart re-flows if its box
293
+ * changes.
294
+ *
295
+ * **Resting state is the finished chart**: an editor paints a node's Initial
296
+ * state on a paused canvas. `enter` arms every part on its first frame.
297
+ *
298
+ * Past the entrance, `showSeries`/`hideSeries`/`spotlightSeries` pick out a
299
+ * *series*, `spotlightRegion` marks a *slice of the plot* without changing the
300
+ * scale, and `zoomTo` rescales the axes so a slice fills the plot. A spotlit
301
+ * region resolves against the live scales, so it travels with a zoom. A `to` of
302
+ * an axis `range` or `ticks` tweens from the domain as drawn (see
303
+ * {@link lerpAxisEntry}), so an auto axis rescales continuously.
304
+ */
305
+ export const LineChart = component2d({
306
+ key: "lineChart",
307
+ state: {
308
+ data: fresh<DataRecord[]>(() => [], { kind: "dataset" }),
309
+ xField: "",
310
+ series: fresh<LineSeries[]>(() => [], { kind: "series" }),
311
+ xAxis: Types.custom<AxisDomainConfig>({}, { resolve: resolveAxisDomain, lerp: lerpAxisEntry }),
312
+ yAxis: Types.custom<AxisDomainConfig>({}, { resolve: resolveAxisDomain, lerp: lerpAxisEntry }),
313
+ theme: Types.custom<ChartTheme, ChartConfig>(DEFAULT_CHART_THEME, { resolve: resolveChartTheme, lerp: lerpChartTheme }),
314
+ /**
315
+ * The spotlit slice of the plot in data units, or `null` for none. The box
316
+ * snaps; the animation is {@link regionReveal} drawing the rules on.
317
+ */
318
+ region: Types.custom<PlotRegion | null>(null),
319
+ /**
320
+ * How far the `region` call-out is drawn in, `[0, 1]`: the rules grow out and
321
+ * the wash fades up as it climbs, while every line's out-of-region stretch
322
+ * fades to the theme's `region.dimOpacity`.
323
+ */
324
+ regionReveal: 0,
325
+ /** Read as the chart is built: the legend is a part the chart builds or doesn't. */
326
+ showLegend: Types.boolean(true, { animatable: false }),
327
+ /**
328
+ * The domain `zoomTo` first left, so `resetZoom` restores the chart as it
329
+ * stood, auto-derived ticks included. Cleared by `resetZoom`, so the next zoom
330
+ * remembers wherever the chart rests then.
331
+ */
332
+ home: Types.custom<LineChartDomains | null>(null, { private: true }),
333
+ },
334
+ // Its parts fill it; a node made of them would hug them.
335
+ defaults: { width: "fill", height: "fill" },
336
+ children: (state) => {
337
+ const theme = () => state.theme
338
+ const domains = () => lineChartDomains(state)
339
+ let plot: Node2D | undefined
340
+ const plotSize = () => laidOutSize(plot)
341
+ const enabled = state.series.map((s) => s.enabled ?? true)
342
+
343
+ // Bound, not snapshotted, so a rescale re-labels and re-places the row as it
344
+ // tweens. The marker *count* is read once, which is why `zoomTo` keeps it.
345
+ const vAxis = new VerticalAxis({
346
+ range: () => domains().y.range,
347
+ markers: () => domains().y.ticks,
348
+ // The y axis is always numbers, so its format is simply the pattern.
349
+ captions: () => {
350
+ const markers = domains().y.ticks
351
+ const format = state.yAxis.format
352
+ return markers.map((value) => (format === undefined ? formatMarker(value, markerStep(markers)) : formatNumber(value, format)))
353
+ },
354
+ axis: () => theme().yAxis,
355
+ label: state.yAxis.label ?? "",
356
+ width: "hug",
357
+ height: "fill",
358
+ })
359
+
360
+ const hAxis = new HorizontalAxis({
361
+ range: () => domains().x.range,
362
+ markers: () => domains().x.ticks,
363
+ // A tick on a month or category column is captioned with the cell it came
364
+ // out of — `Jan`, not the instant it parsed to.
365
+ captions: () => {
366
+ const column = columnOf(state)
367
+ return domains().x.ticks.map((value) => column.label(value))
368
+ },
369
+ axis: () => theme().xAxis,
370
+ label: state.xAxis.label ?? "",
371
+ width: "fill",
372
+ height: "hug",
373
+ })
374
+
375
+ const lines = state.series.map(
376
+ (s, i) =>
377
+ new ChartLine({
378
+ points: () => seriesPixels(state, domains(), i, plotSize()),
379
+ stroke: () => resolveSeriesStroke(theme().seriesStyles, s, i),
380
+ enabled: enabled[i],
381
+ // Each line clips itself against the box the rules are drawn from, so
382
+ // the dim/bright boundary can't drift from the dashes.
383
+ spotlight: () => regionBox(state, domains(), plotSize()),
384
+ // Ramped by the reveal that draws the rules: one signal, both halves.
385
+ dimOpacity: () => 1 - (1 - theme().region.dimOpacity) * state.regionReveal,
386
+ }) as unknown as Node2D
387
+ )
388
+
389
+ const below: Node2D[] = [hAxis as unknown as Node2D]
390
+ if (state.showLegend !== false) {
391
+ below.push(
392
+ new ChartLegend({
393
+ series: state.series,
394
+ // The legend paints a swatch, not a line, so it is handed the colour each
395
+ // stroke resolves to rather than the stroke itself.
396
+ swatches: () => state.series.map((s, i) => resolveSeriesFill(theme().seriesStyles, s, i)),
397
+ legend: () => theme().legend,
398
+ // The row's spacing is the theme's as the chart was built, like the
399
+ // entries' type and chips: a theme tween re-paints the swatches only.
400
+ gap: state.theme.legend.itemGap,
401
+ padding: state.theme.legend.padding,
402
+ }) as unknown as Node2D
403
+ )
404
+ }
405
+
406
+ plot = new Rect({
407
+ clip: true,
408
+ children: [
409
+ new ChartCanvas({
410
+ fill: () => theme().plotArea.fill,
411
+ shadow: () => theme().plotArea.shadow,
412
+ xGridStroke: () => theme().xAxis.lineStyle,
413
+ yGridStroke: () => theme().yAxis.lineStyle,
414
+ // A grid line under every axis marker; the canvas skips the edges.
415
+ xMarkers: () => domains().x.ticks,
416
+ yMarkers: () => domains().y.ticks,
417
+ xExtent: () => domains().x.range,
418
+ yExtent: () => domains().y.range,
419
+ }),
420
+ // Over the grid, under the lines, so a spotlit stretch of a series isn't
421
+ // tinted by the highlight meant to pick it out.
422
+ new ChartRegion({
423
+ box: () => regionBox(state, domains(), plotSize()),
424
+ stroke: () => theme().region.stroke,
425
+ fill: () => theme().region.fill,
426
+ reveal: () => state.regionReveal,
427
+ }),
428
+ ...lines,
429
+ new ChartBorder({ stroke: () => theme().plotArea.stroke }),
430
+ ],
431
+ }) as unknown as Node2D
432
+
433
+ const gutter = new VerticalAxis({
434
+ opacity: 0,
435
+ range: () => domains().y.range,
436
+ markers: () => domains().y.ticks,
437
+ axis: () => theme().yAxis,
438
+ label: state.yAxis.label ?? "",
439
+ width: "hug",
440
+ height: 0,
441
+ }) as unknown as Node2D
442
+
443
+ return asParts([
444
+ ...(state.children as unknown as Node2D[]),
445
+ cartesianFrame({ axis: vAxis as unknown as Node2D, plot, gutter, below }),
446
+ ])
447
+ },
448
+ commands: {
449
+ /**
450
+ * Animate the whole chart in: the two axes stagger their markers in, the
451
+ * series lines trace left to right, and the legend fades up last. Its first
452
+ * frame arms every part: markers shifted and transparent, lines untraced,
453
+ * the legend dropped and transparent.
454
+ *
455
+ * `duration` is the **whole** entrance; the beats are shares of it. A chart
456
+ * authored with a `region` lands its call-out last, in the final quarter.
457
+ */
458
+ enter: {
459
+ args: {},
460
+ easing: easeOut(),
461
+ run: (timeline, state, children) => {
462
+ const parts = partsOf(children)
463
+ if (!parts) return timeline.wait(timeline.duration)
464
+ const duration = timeline.duration
465
+ const revealing = hasCallout(state) && state.regionReveal === 0
466
+ const body = revealing ? duration * 0.75 : duration
467
+ const axes = body * AXES_SHARE
468
+ const traced = body * LINES_SHARE
469
+ const { legend } = parts
470
+ const at0 = (piece: Beat["piece"]): Beat => ({ at: 0, duration: 0, piece })
471
+ // The first frame arms what every later beat moves: a beat ahead of the
472
+ // playhead writes nothing. A beat with nothing to do still takes its share.
473
+ return beats(timeline, [
474
+ ...(revealing ? [at0(timeline.animate(() => ({ regionReveal: 0 })))] : []),
475
+ ...parts.lines.map((line) => at0(line.to({ progress: 0 }))),
476
+ ...(legend ? [at0(legend.to({ opacity: 0, y: -LEGEND_SLIDE }))] : []),
477
+ { at: 0, duration: axes, piece: parts.vAxis.run("enter", { slide: 24 }) },
478
+ { at: 0, duration: axes, piece: parts.hAxis.run("enter", { slide: 24 }) },
479
+ ...parts.lines.map((line) => ({ at: axes, duration: traced, piece: line.run("enter") })),
480
+ ...(legend ? [{ at: axes + traced, duration: body * LEGEND_SHARE, piece: legend.to({ opacity: 1, y: 0 }) }] : []),
481
+ ...(revealing ? [{ at: body, duration: duration * 0.25, piece: timeline.animate((t) => ({ regionReveal: t })) }] : []),
482
+ ])
483
+ },
484
+ },
485
+ /**
486
+ * Spotlight a rectangular slice of the plot given in **data units**: dashed
487
+ * rules draw onto each bounded edge while every series fades outside the box.
488
+ * Either axis alone is a band; both are a box. Called while another region is
489
+ * up, the old call-out retracts over the first half and the new one draws in
490
+ * over the second, each half eased on its own.
491
+ */
492
+ spotlightRegion: {
493
+ args: { region: REGION_ARG },
494
+ easing: easeOut(),
495
+ run: (timeline, state) => {
496
+ const region = regionArg(timeline.args.region)
497
+ const from = state.regionReveal
498
+ const previous = state.region
499
+ // A region bounding neither axis is no call-out: spotlighting it is a clear.
500
+ if (region.x === undefined && region.y === undefined) return clearing(timeline, state)
501
+ // Nothing up yet: the region is set from the first frame and just draws on.
502
+ if (from <= 0 || !hasCallout(state)) return timeline.animate((t) => ({ region, regionReveal: from + (1 - from) * t }))
503
+ return timeline.animate(
504
+ (t) => (t < 0.5
505
+ ? { region: previous, regionReveal: from * (1 - timeline.ease(t * 2)) }
506
+ : { region, regionReveal: timeline.ease(t * 2 - 1) }),
507
+ { eased: false }
508
+ )
509
+ },
510
+ },
511
+ /** Drop the region call-out. A no-op when nothing is spotlit, which still takes its slot. */
512
+ clearRegion: {
513
+ args: {},
514
+ easing: easeOut(),
515
+ run: (timeline, state) => clearing(timeline, state),
516
+ },
517
+ /**
518
+ * Zoom the plot to a slice of itself, given in **data units**: the named axes
519
+ * rescale so that slice fills the plot, the grid, both marker rows and every
520
+ * series following. An omitted axis is left as it is. The first zoom
521
+ * remembers the domain it left, for `resetZoom`.
522
+ */
523
+ zoomTo: {
524
+ args: { region: REGION_ARG },
525
+ easing: easeOut(),
526
+ run: (timeline, state) => {
527
+ const region = regionArg(timeline.args.region)
528
+ if (!region.x && !region.y) return timeline.wait(timeline.duration)
529
+ const from = lineChartDomains(state)
530
+ const home = state.home ?? from
531
+ const to = {
532
+ ...(region.x && { x: { ...from.x, ...rescale(region.x, from.x.ticks) } }),
533
+ ...(region.y && { y: { ...from.y, ...rescale(region.y, from.y.ticks) } }),
534
+ }
535
+ return timeline.animate((t) => ({ home, ...axesAt(from, to, t) }))
536
+ },
537
+ },
538
+ /** Pull back out to the domain the first zoom left — the mirror of `zoomTo`, and a hold if it never zoomed. */
539
+ resetZoom: {
540
+ args: {},
541
+ easing: easeOut(),
542
+ run: (timeline, state) => {
543
+ const home = state.home
544
+ if (!home) return timeline.wait(timeline.duration)
545
+ const from = lineChartDomains(state)
546
+ return timeline.animate((t) => ({ home: null, ...axesAt(from, home, t) }))
547
+ },
548
+ },
549
+ /**
550
+ * Show series `index`: **trace** its line in left to right, in lockstep with
551
+ * its legend entry growing in.
552
+ */
553
+ showSeries: {
554
+ args: { seriesIndex: SERIES_ARG },
555
+ easing: easeOut(),
556
+ run: (timeline, _state, children) => toggling(timeline, children, timeline.args.seriesIndex, true),
557
+ },
558
+ /** Hide series `index`: **retrace** its line back out as its legend entry shrinks away. */
559
+ hideSeries: {
560
+ args: { seriesIndex: SERIES_ARG },
561
+ easing: easeOut(),
562
+ run: (timeline, _state, children) => toggling(timeline, children, timeline.args.seriesIndex, false),
563
+ },
564
+ /**
565
+ * Fade every other series — each line **and its legend entry** — to focus on
566
+ * `index`, which comes back to full. The legend dims in place, so the row
567
+ * doesn't reflow.
568
+ */
569
+ spotlightSeries: {
570
+ args: { seriesIndex: SERIES_ARG },
571
+ easing: easeOut(),
572
+ run: (timeline, _state, children) => {
573
+ const parts = partsOf(children)
574
+ if (!parts) return timeline.wait(timeline.duration)
575
+ const index = timeline.args.seriesIndex
576
+ return timeline.together([
577
+ ...parts.lines.map((line, i) => line.to({ opacity: i === index ? 1 : SPOTLIGHT_DIM })),
578
+ ...(parts.legend ? [parts.legend.run("spotlightSeries", { index })] : []),
579
+ ])
580
+ },
581
+ },
582
+ },
583
+ })
584
+
585
+ export type LineChart = NodeOf<typeof LineChart>