@motionscript/charts 0.1.0-alpha.0 → 0.1.0-alpha.10

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