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