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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/LICENSE +201 -201
  3. package/NOTICE +48 -0
  4. package/README.md +85 -0
  5. package/dist/bar-chart/bar-chart.d.ts +33 -19
  6. package/dist/bar-chart/bar-chart.d.ts.map +1 -1
  7. package/dist/bar-chart/bar-chart.js +68 -64
  8. package/dist/bar-chart/bar-chart.js.map +1 -1
  9. package/dist/bar-chart/category-axis.d.ts +2 -2
  10. package/dist/bar-chart/category-axis.d.ts.map +1 -1
  11. package/dist/bar-chart/category-axis.js +2 -2
  12. package/dist/bar-chart/category-axis.js.map +1 -1
  13. package/dist/bar-chart/chart-bars.d.ts +1 -1
  14. package/dist/bar-chart/chart-bars.d.ts.map +1 -1
  15. package/dist/bar-chart/chart-bars.js +2 -2
  16. package/dist/bar-chart/chart-bars.js.map +1 -1
  17. package/dist/bar-chart/index.js.map +1 -1
  18. package/dist/bar-chart/shared.d.ts +4 -4
  19. package/dist/bar-chart/shared.d.ts.map +1 -1
  20. package/dist/bar-chart/shared.js +4 -4
  21. package/dist/bar-chart/shared.js.map +1 -1
  22. package/dist/browser/chunks/chunk-5ZPBV6BU.js +2 -0
  23. package/dist/browser/chunks/chunk-5ZPBV6BU.js.map +7 -0
  24. package/dist/browser/index.js +1 -1
  25. package/dist/browser/index.js.map +3 -3
  26. package/dist/browser/kit.js +1 -1
  27. package/dist/browser/manifest.json +4 -3
  28. package/dist/engine.d.ts +1 -1
  29. package/dist/engine.d.ts.map +1 -1
  30. package/dist/engine.js +1 -1
  31. package/dist/engine.js.map +1 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/kit/chart-border.d.ts +1 -1
  34. package/dist/kit/chart-border.d.ts.map +1 -1
  35. package/dist/kit/chart-border.js +2 -2
  36. package/dist/kit/chart-border.js.map +1 -1
  37. package/dist/kit/chart-canvas.d.ts +1 -1
  38. package/dist/kit/chart-canvas.d.ts.map +1 -1
  39. package/dist/kit/chart-canvas.js +2 -2
  40. package/dist/kit/chart-canvas.js.map +1 -1
  41. package/dist/kit/chart-legend.d.ts +6 -27
  42. package/dist/kit/chart-legend.d.ts.map +1 -1
  43. package/dist/kit/chart-legend.js +33 -57
  44. package/dist/kit/chart-legend.js.map +1 -1
  45. package/dist/kit/shared.d.ts +31 -8
  46. package/dist/kit/shared.d.ts.map +1 -1
  47. package/dist/kit/shared.js +67 -11
  48. package/dist/kit/shared.js.map +1 -1
  49. package/dist/kit/vertical-axis.d.ts +2 -2
  50. package/dist/kit/vertical-axis.d.ts.map +1 -1
  51. package/dist/kit/vertical-axis.js +2 -2
  52. package/dist/kit/vertical-axis.js.map +1 -1
  53. package/dist/line-chart/chart-line.d.ts +3 -3
  54. package/dist/line-chart/chart-line.d.ts.map +1 -1
  55. package/dist/line-chart/chart-line.js +2 -2
  56. package/dist/line-chart/chart-line.js.map +1 -1
  57. package/dist/line-chart/chart-region.d.ts +1 -1
  58. package/dist/line-chart/chart-region.d.ts.map +1 -1
  59. package/dist/line-chart/chart-region.js +2 -2
  60. package/dist/line-chart/chart-region.js.map +1 -1
  61. package/dist/line-chart/horizontal-axis.d.ts +2 -2
  62. package/dist/line-chart/horizontal-axis.d.ts.map +1 -1
  63. package/dist/line-chart/horizontal-axis.js +2 -2
  64. package/dist/line-chart/horizontal-axis.js.map +1 -1
  65. package/dist/line-chart/index.js.map +1 -1
  66. package/dist/line-chart/line-chart.d.ts +25 -9
  67. package/dist/line-chart/line-chart.d.ts.map +1 -1
  68. package/dist/line-chart/line-chart.js +66 -43
  69. package/dist/line-chart/line-chart.js.map +1 -1
  70. package/dist/line-chart/shared.d.ts +4 -4
  71. package/dist/line-chart/shared.d.ts.map +1 -1
  72. package/dist/line-chart/shared.js +20 -5
  73. package/dist/line-chart/shared.js.map +1 -1
  74. package/dist/line-chart/x-scale.d.ts +2 -2
  75. package/dist/line-chart/x-scale.d.ts.map +1 -1
  76. package/dist/line-chart/x-scale.js +2 -2
  77. package/dist/line-chart/x-scale.js.map +1 -1
  78. package/dist/nodes.js.map +1 -1
  79. package/dist/pie-chart/index.js.map +1 -1
  80. package/dist/pie-chart/pie-chart.d.ts +16 -10
  81. package/dist/pie-chart/pie-chart.d.ts.map +1 -1
  82. package/dist/pie-chart/pie-chart.js +15 -16
  83. package/dist/pie-chart/pie-chart.js.map +1 -1
  84. package/dist/pie-chart/pie-legend.d.ts +2 -2
  85. package/dist/pie-chart/pie-legend.d.ts.map +1 -1
  86. package/dist/pie-chart/pie-legend.js +6 -6
  87. package/dist/pie-chart/pie-legend.js.map +1 -1
  88. package/dist/pie-chart/pie-ring.d.ts +14 -5
  89. package/dist/pie-chart/pie-ring.d.ts.map +1 -1
  90. package/dist/pie-chart/pie-ring.js +45 -15
  91. package/dist/pie-chart/pie-ring.js.map +1 -1
  92. package/dist/pie-chart/shared.d.ts +4 -4
  93. package/dist/pie-chart/shared.d.ts.map +1 -1
  94. package/dist/pie-chart/shared.js +4 -4
  95. package/dist/pie-chart/shared.js.map +1 -1
  96. package/package.json +6 -4
  97. package/registry.json +23 -23
  98. package/src/bar-chart/bar-chart.ts +820 -804
  99. package/src/bar-chart/category-axis.ts +177 -177
  100. package/src/bar-chart/chart-bars.ts +310 -310
  101. package/src/bar-chart/index.ts +31 -31
  102. package/src/bar-chart/shared.ts +354 -354
  103. package/src/engine.ts +26 -26
  104. package/src/index.ts +5 -5
  105. package/src/kit/chart-border.ts +61 -61
  106. package/src/kit/chart-canvas.ts +157 -157
  107. package/src/kit/chart-legend.ts +245 -250
  108. package/src/kit/shared.ts +733 -675
  109. package/src/kit/vertical-axis.ts +224 -224
  110. package/src/line-chart/chart-line.ts +208 -208
  111. package/src/line-chart/chart-region.ts +135 -135
  112. package/src/line-chart/horizontal-axis.ts +202 -202
  113. package/src/line-chart/index.ts +39 -39
  114. package/src/line-chart/line-chart.ts +961 -894
  115. package/src/line-chart/shared.ts +473 -459
  116. package/src/line-chart/x-scale.ts +367 -367
  117. package/src/nodes.ts +20 -20
  118. package/src/pie-chart/index.ts +37 -37
  119. package/src/pie-chart/pie-chart.ts +383 -374
  120. package/src/pie-chart/pie-legend.ts +159 -159
  121. package/src/pie-chart/pie-ring.ts +935 -903
  122. package/src/pie-chart/shared.ts +490 -490
  123. package/dist/browser/chunks/chunk-ZMBOBHYL.js +0 -2
  124. package/dist/browser/chunks/chunk-ZMBOBHYL.js.map +0 -7
package/src/kit/shared.ts CHANGED
@@ -1,675 +1,733 @@
1
- /**
2
- * The vocabulary every chart node shares: what a *series* is, how an axis is
3
- * scaled and formatted, and the theme leaves each chart's own theme is assembled
4
- * from.
5
- *
6
- * This module exists because the three chart types are three ways of drawing the
7
- * same table. A line chart, a bar chart and a pie chart disagree about almost
8
- * everything visible — polylines against columns against wedges — and agree
9
- * about almost everything underneath: a series is a column with a caption and a
10
- * paint, a marker is a number formatted one way, a legend is a swatch beside a
11
- * label, and a theme is a tree of paints with one mapper and one tween. Writing
12
- * that three times would mean three answers to "how does a chart round its axis"
13
- * within one app.
14
- *
15
- * Kept renderer-agnostic (no `Node` imports) so the studio's own inspector
16
- * mappings can build a partial theme without pulling the node classes in, the
17
- * same way `line-chart-props.ts` always has.
18
- *
19
- * **Two conventions run through every resolver and lerp below**, inherited from
20
- * the shape system's `resolveStroke`/`resolveShadow`:
21
- *
22
- * - A **mapper** merges the author's loose, partial input onto a `previous`
23
- * resolved value and resolves every leaf, so the tween always has resolved
24
- * data to interpolate. It is idempotent.
25
- * - A **tween** interpolates two resolved values leaf by leaf. Categorical
26
- * fields (`fontFamily`, `textAlign`) and fields that are `undefined` on either
27
- * side **step at the midpoint**, because there is no meaningful in-between and
28
- * defaulting the missing side to 0 would animate a font weight down to nothing
29
- * on the way to "unset".
30
- */
31
-
32
- import {
33
- fillOps,
34
- lerpNumber,
35
- shadowOps,
36
- strokeOps,
37
- insetsOps,
38
- textOps,
39
- type DataRecord,
40
- type Fill,
41
- type FillResolved,
42
- type Insets,
43
- type InsetsResolved,
44
- type Shadow,
45
- type ShadowResolved,
46
- type Stroke,
47
- type StrokeResolved,
48
- type TextStyle,
49
- } from "@motionscript/core"
50
-
51
- /**
52
- * One series of a chart: a column of the table, captioned and painted.
53
- *
54
- * `field` names the column carrying this series' values. What that becomes is
55
- * the chart's business — a traced polyline, a column of bars, a wedge — but the
56
- * three questions asked of it are the same everywhere: which column, what to
57
- * call it, what to paint it, and whether it is currently drawn.
58
- *
59
- * `fill` is an **override**: omit it and the series takes the theme palette's
60
- * entry for its own index, which is what makes a chart nobody has themed come
61
- * out in five distinct colours rather than five identical ones.
62
- */
63
- export interface ChartSeries {
64
- /** Key into each data row for this series' value. */
65
- field: string
66
- /** Legend caption for this series. */
67
- label: string
68
- /**
69
- * Paint override for this series' mark and its legend swatch. Omit to take
70
- * the theme palette's entry for this series' index.
71
- */
72
- fill?: Fill
73
- /** Whether the series shows by default. Defaults to `true`. */
74
- enabled?: boolean
75
- }
76
-
77
- /** A `[min, max]` numeric range in data units. */
78
- export type Range = [min: number, max: number]
79
-
80
- /**
81
- * One axis's *data* domain — what it shows — as opposed to {@link AxisConfig},
82
- * which is how it's *styled*. Every field is optional: `range`/`ticks` derive
83
- * from the plotted data when omitted, and `label` defaults to `""`.
84
- */
85
- export interface AxisDomainConfig {
86
- /** Caption drawn alongside the axis. Pass `""` (the default) to hide it. */
87
- label?: string
88
- /** `[min, max]` of the scale. Derived from the data bounds when omitted. */
89
- range?: Range
90
- /** Tick values (in data units). Derived (five evenly-spaced) when omitted. */
91
- ticks?: number[]
92
- /**
93
- * How a tick value is written down — a `number-format` pattern such as
94
- * `#,##0.00` or `$#,##0`.
95
- *
96
- * Here rather than in {@link AxisConfig} because it is a statement about the
97
- * *numbers*, not about the ink they are set in: `$` on a revenue axis says
98
- * what the column holds, and it has to survive a re-theme. It sits beside
99
- * `range` and `ticks` for the same reason those do.
100
- */
101
- format?: string
102
- }
103
-
104
- /**
105
- * An axis domain's @property mapper: merges the author's partial input onto
106
- * `previous`, so a later partial `.set({ yAxis: {...} })` patches
107
- * `label`/`range`/`ticks` independently. `range`/`ticks` staying `undefined`
108
- * after the merge is the auto-derive signal the scale getters read.
109
- */
110
- export function resolveAxisDomain(
111
- domain: AxisDomainConfig | undefined,
112
- previous?: AxisDomainConfig
113
- ): AxisDomainConfig {
114
- return {
115
- label: domain?.label ?? previous?.label ?? "",
116
- range: domain?.range ?? previous?.range,
117
- ticks: domain?.ticks ?? previous?.ticks,
118
- format: domain?.format ?? previous?.format,
119
- }
120
- }
121
-
122
- /**
123
- * An axis domain's @property tween: interpolates `range`/`ticks` numerically
124
- * (pairwise by index for `ticks`), so a `to` command that restates a range
125
- * rescales the plot smoothly. `label`, and either field when one side is in
126
- * auto-derive mode, step at the midpoint.
127
- */
128
- export function lerpAxisDomain(
129
- from: AxisDomainConfig,
130
- to: AxisDomainConfig,
131
- t: number
132
- ): AxisDomainConfig {
133
- return {
134
- label: t < 0.5 ? from.label : to.label,
135
- range: lerpOptionalRange(from.range, to.range, t),
136
- ticks: lerpOptionalTicks(from.ticks, to.ticks, t),
137
- // Steps at the midpoint with the caption, for the same reason: there is no
138
- // halfway between `$#,##0` and `0.0%`.
139
- format: t < 0.5 ? from.format : to.format,
140
- }
141
- }
142
-
143
- function lerpOptionalRange(
144
- from: Range | undefined,
145
- to: Range | undefined,
146
- t: number
147
- ): Range | undefined {
148
- if (!from || !to) return t < 0.5 ? from : to
149
- return [lerpNumber(from[0], to[0], t), lerpNumber(from[1], to[1], t)]
150
- }
151
-
152
- function lerpOptionalTicks(
153
- from: number[] | undefined,
154
- to: number[] | undefined,
155
- t: number
156
- ): number[] | undefined {
157
- if (!from || !to) return t < 0.5 ? from : to
158
- const n = Math.max(from.length, to.length)
159
- const out: number[] = []
160
- for (let i = 0; i < n; i++) {
161
- out.push(lerpNumber(from[i] ?? to[i], to[i] ?? from[i], t))
162
- }
163
- return out
164
- }
165
-
166
- /**
167
- * The low-level colour tokens the default themes are built from — a dark plot
168
- * panel with warm-grey axis furniture.
169
- */
170
- export const CHART_PALETTE = {
171
- /** Fill of the plot panel behind the marks. */
172
- plotFill: "#15130e",
173
- /** Colour of the plot's thick border. */
174
- borderColor: "#4a4036",
175
- /** Colour of the faint grid lines spanning the plot. */
176
- gridColor: "#2c2820",
177
- /** Colour of the numeric axis markers, axis captions, and legend labels. */
178
- markerColor: "#8a7f70",
179
- /** Colour of a spotlit region's dashed rules and its wash. */
180
- regionColor: "#d99a3a",
181
- } as const
182
-
183
- /** The out-of-the-box series palette, cycled by series index. */
184
- export const DEFAULT_SERIES_COLORS = [
185
- "#d9603b",
186
- "#8194ad",
187
- "#e0a93b",
188
- "#5e9d6b",
189
- "#9ec85a",
190
- ] as const
191
-
192
- /**
193
- * Opacity an *un*-spotlighted series fades to — its mark and its legend entry
194
- * alike, so the two dim together.
195
- */
196
- export const SPOTLIGHT_DIM = 0.2
197
-
198
- /** Clamp a number into `[0, 1]` — the range every reveal signal here runs in. */
199
- export function clampUnit(value: number): number {
200
- return value < 0 ? 0 : value > 1 ? 1 : value
201
- }
202
-
203
- // ---- Row readers ---------------------------------------------------------
204
-
205
- /**
206
- * Read a numeric field off a row, defaulting missing/non-numeric values to 0.
207
- *
208
- * A column left as strings silently plots as 0, which is why the CSV parser's
209
- * numeric auto-coercion matters — a quoted or unit-suffixed column won't plot
210
- * until it's coerced.
211
- */
212
- export function num(row: DataRecord, field: string | undefined): number {
213
- if (field === undefined) return 0
214
- const v = row[field]
215
- return typeof v === "number" ? v : 0
216
- }
217
-
218
- /**
219
- * Read a field off a row as its caption — the counterpart to {@link num} for
220
- * the columns a chart *names* things by rather than measures them by (a bar's
221
- * category, a wedge's slice). A missing cell reads as empty rather than as the
222
- * string `"undefined"`.
223
- */
224
- export function text(row: DataRecord, field: string | undefined): string {
225
- if (field === undefined || field === "") return ""
226
- const v = row[field]
227
- return v === undefined || v === null ? "" : String(v)
228
- }
229
-
230
- /**
231
- * Every column that holds numbers across `data`, in header order, skipping the
232
- * names in `exclude` (typically the category column).
233
- *
234
- * A column counts as numeric only if every non-empty cell in it is a number, so
235
- * a stray text cell leaves the column out rather than plotting zeros. This is
236
- * what lets a chart plot "every other column" without the author naming twenty
237
- * fields.
238
- */
239
- export function numericFields(
240
- data: DataRecord[],
241
- exclude: string[] = []
242
- ): string[] {
243
- if (data.length === 0) return []
244
- const skip = new Set(exclude)
245
- const seen = new Set<string>()
246
- const order: string[] = []
247
- for (const row of data)
248
- for (const key of Object.keys(row))
249
- if (!skip.has(key) && !seen.has(key)) {
250
- seen.add(key)
251
- order.push(key)
252
- }
253
-
254
- return order.filter((key) => {
255
- let sawValue = false
256
- for (const row of data) {
257
- const v = row[key]
258
- if (v === undefined || v === "") continue
259
- if (typeof v !== "number") return false
260
- sawValue = true
261
- }
262
- return sawValue
263
- })
264
- }
265
-
266
- // ---- Theme branches ------------------------------------------------------
267
-
268
- /** One axis's (x or y) style vocabulary. */
269
- export interface AxisConfig {
270
- /** Style of each marker along the axis. */
271
- labelStyle: TextStyle
272
- /** Style of the axis caption. */
273
- titleStyle: TextStyle
274
- /**
275
- * This axis's direction of the plot's internal grid — weight+fill honoured,
276
- * dash/cap/join ignored (grid lines are drawn as filled rects).
277
- */
278
- lineStyle: Stroke
279
- /**
280
- * Gap between the plot and the marker row. Only the side facing the plot is
281
- * read — `.top` for a horizontal axis, `.right` for a vertical one.
282
- */
283
- tickPadding: Insets
284
- /** Gap between the marker row and the caption, read the same side. */
285
- titlePadding: Insets
286
- }
287
-
288
- /** A legend's per-series colour swatch — a rounded chip, not the caption. */
289
- export interface LegendMarkerConfig {
290
- width: number
291
- height: number
292
- borderRadius: number
293
- stroke: Stroke
294
- shadow: Shadow
295
- }
296
-
297
- /** A legend's visual theme. */
298
- export interface LegendConfig {
299
- padding: Insets
300
- /** Caption style — only the swatch carries the series colour. */
301
- textStyle: TextStyle
302
- /** Gap between legend entries. */
303
- itemGap: number
304
- markerStyle: LegendMarkerConfig
305
- }
306
-
307
- /** The plot panel a cartesian chart draws its marks over. */
308
- export interface PlotAreaConfig {
309
- stroke: Stroke
310
- fill: Fill
311
- shadow: Shadow
312
- }
313
-
314
- const AXIS_LABEL_STYLE: TextStyle = {
315
- fontSize: 24,
316
- fontWeight: 700,
317
- textAlign: "center",
318
- fill: CHART_PALETTE.markerColor,
319
- }
320
- const AXIS_TITLE_STYLE: TextStyle = {
321
- fontSize: 30,
322
- fontWeight: 600,
323
- textAlign: "center",
324
- fill: CHART_PALETTE.markerColor,
325
- }
326
- const AXIS_LINE_STYLE: Stroke = { weight: 2, fill: CHART_PALETTE.gridColor }
327
-
328
- /** The default styling of a horizontal (marker row beneath the plot) axis. */
329
- export const DEFAULT_X_AXIS: AxisConfig = {
330
- labelStyle: AXIS_LABEL_STYLE,
331
- titleStyle: AXIS_TITLE_STYLE,
332
- lineStyle: AXIS_LINE_STYLE,
333
- tickPadding: 20,
334
- titlePadding: 4,
335
- }
336
-
337
- /** The default styling of a vertical (marker column beside the plot) axis. */
338
- export const DEFAULT_Y_AXIS: AxisConfig = {
339
- labelStyle: { ...AXIS_LABEL_STYLE, fontWeight: 500, textAlign: "right" },
340
- titleStyle: AXIS_TITLE_STYLE,
341
- lineStyle: AXIS_LINE_STYLE,
342
- tickPadding: 40,
343
- titlePadding: 24,
344
- }
345
-
346
- /**
347
- * The default plot panel: **unpainted**, framed. A chart reads against the
348
- * stage rather than punching a panel into it, which is the look the family was
349
- * designed at.
350
- */
351
- export const DEFAULT_PLOT_AREA: PlotAreaConfig = {
352
- fill: [],
353
- stroke: { weight: 6, fill: CHART_PALETTE.borderColor },
354
- shadow: [],
355
- }
356
-
357
- /** The default legend styling, shared by every chart that draws one. */
358
- export const DEFAULT_LEGEND: LegendConfig = {
359
- padding: 0,
360
- textStyle: {
361
- fontSize: 30,
362
- fontWeight: 600,
363
- textAlign: "left",
364
- fill: CHART_PALETTE.markerColor,
365
- },
366
- itemGap: 44,
367
- markerStyle: {
368
- width: 60,
369
- height: 24,
370
- borderRadius: 6,
371
- stroke: [],
372
- shadow: [],
373
- },
374
- }
375
-
376
- /** The default per-series stroke palette — {@link DEFAULT_SERIES_COLORS}, drawn 4px. */
377
- export const DEFAULT_SERIES_STROKES: Stroke[] = DEFAULT_SERIES_COLORS.map(
378
- (fill) => ({ weight: 4, fill })
379
- )
380
-
381
- /** The default per-series fill palette — the same colours, as solid paint. */
382
- export const DEFAULT_SERIES_FILLS: Fill[] = DEFAULT_SERIES_COLORS.map(
383
- (fill) => fill
384
- )
385
-
386
- // ---- Theme branch resolvers ----------------------------------------------
387
- // Each chart type assembles its own theme out of these, so "the axis furniture"
388
- // means one thing across the family and each chart still declares only the
389
- // branches it actually draws.
390
-
391
- export function resolveAxisConfig(
392
- axis: Partial<AxisConfig> | undefined,
393
- previous: AxisConfig
394
- ): AxisConfig {
395
- return {
396
- labelStyle: textOps.resolveStyle(axis?.labelStyle, previous.labelStyle),
397
- titleStyle: textOps.resolveStyle(axis?.titleStyle, previous.titleStyle),
398
- lineStyle: strokeOps.resolve(axis?.lineStyle ?? previous.lineStyle),
399
- tickPadding: insetsOps.resolve(
400
- axis?.tickPadding ?? previous.tickPadding,
401
- previous.tickPadding as InsetsResolved
402
- ),
403
- titlePadding: insetsOps.resolve(
404
- axis?.titlePadding ?? previous.titlePadding,
405
- previous.titlePadding as InsetsResolved
406
- ),
407
- }
408
- }
409
-
410
- export function lerpAxisConfig(
411
- from: AxisConfig,
412
- to: AxisConfig,
413
- t: number
414
- ): AxisConfig {
415
- return {
416
- labelStyle: textOps.lerpStyle(from.labelStyle, to.labelStyle, t),
417
- titleStyle: textOps.lerpStyle(from.titleStyle, to.titleStyle, t),
418
- lineStyle: strokeOps.lerp(
419
- from.lineStyle as StrokeResolved[],
420
- to.lineStyle as StrokeResolved[],
421
- t
422
- ),
423
- tickPadding: insetsOps.lerp(
424
- from.tickPadding as InsetsResolved,
425
- to.tickPadding as InsetsResolved,
426
- t
427
- ),
428
- titlePadding: insetsOps.lerp(
429
- from.titlePadding as InsetsResolved,
430
- to.titlePadding as InsetsResolved,
431
- t
432
- ),
433
- }
434
- }
435
-
436
- export function resolvePlotArea(
437
- plotArea: Partial<PlotAreaConfig> | undefined,
438
- previous: PlotAreaConfig
439
- ): PlotAreaConfig {
440
- return {
441
- fill: fillOps.resolve(plotArea?.fill ?? previous.fill),
442
- stroke: strokeOps.resolve(plotArea?.stroke ?? previous.stroke),
443
- shadow: shadowOps.resolve(plotArea?.shadow ?? previous.shadow),
444
- }
445
- }
446
-
447
- export function lerpPlotArea(
448
- from: PlotAreaConfig,
449
- to: PlotAreaConfig,
450
- t: number
451
- ): PlotAreaConfig {
452
- return {
453
- fill: fillOps.lerp(
454
- from.fill as FillResolved[],
455
- to.fill as FillResolved[],
456
- t
457
- ),
458
- stroke: strokeOps.lerp(
459
- from.stroke as StrokeResolved[],
460
- to.stroke as StrokeResolved[],
461
- t
462
- ),
463
- shadow: shadowOps.lerp(
464
- from.shadow as ShadowResolved[],
465
- to.shadow as ShadowResolved[],
466
- t
467
- ),
468
- }
469
- }
470
-
471
- function resolveLegendMarkerConfig(
472
- marker: Partial<LegendMarkerConfig> | undefined,
473
- previous: LegendMarkerConfig
474
- ): LegendMarkerConfig {
475
- return {
476
- width: marker?.width ?? previous.width,
477
- height: marker?.height ?? previous.height,
478
- borderRadius: marker?.borderRadius ?? previous.borderRadius,
479
- stroke: strokeOps.resolve(marker?.stroke ?? previous.stroke),
480
- shadow: shadowOps.resolve(marker?.shadow ?? previous.shadow),
481
- }
482
- }
483
-
484
- function lerpLegendMarkerConfig(
485
- from: LegendMarkerConfig,
486
- to: LegendMarkerConfig,
487
- t: number
488
- ): LegendMarkerConfig {
489
- return {
490
- width: lerpNumber(from.width, to.width, t),
491
- height: lerpNumber(from.height, to.height, t),
492
- borderRadius: lerpNumber(from.borderRadius, to.borderRadius, t),
493
- stroke: strokeOps.lerp(
494
- from.stroke as StrokeResolved[],
495
- to.stroke as StrokeResolved[],
496
- t
497
- ),
498
- shadow: shadowOps.lerp(
499
- from.shadow as ShadowResolved[],
500
- to.shadow as ShadowResolved[],
501
- t
502
- ),
503
- }
504
- }
505
-
506
- /** A legend theme as the author may state it — every branch optional. */
507
- export type LegendTheme = Partial<Omit<LegendConfig, "markerStyle">> & {
508
- markerStyle?: Partial<LegendMarkerConfig>
509
- }
510
-
511
- export function resolveLegendConfig(
512
- legend: LegendTheme | undefined,
513
- previous: LegendConfig
514
- ): LegendConfig {
515
- return {
516
- padding: insetsOps.resolve(
517
- legend?.padding ?? previous.padding,
518
- previous.padding as InsetsResolved
519
- ),
520
- textStyle: textOps.resolveStyle(legend?.textStyle, previous.textStyle),
521
- itemGap: legend?.itemGap ?? previous.itemGap,
522
- markerStyle: resolveLegendMarkerConfig(
523
- legend?.markerStyle,
524
- previous.markerStyle
525
- ),
526
- }
527
- }
528
-
529
- export function lerpLegendConfig(
530
- from: LegendConfig,
531
- to: LegendConfig,
532
- t: number
533
- ): LegendConfig {
534
- return {
535
- padding: insetsOps.lerp(
536
- from.padding as InsetsResolved,
537
- to.padding as InsetsResolved,
538
- t
539
- ),
540
- textStyle: textOps.lerpStyle(from.textStyle, to.textStyle, t),
541
- itemGap: lerpNumber(from.itemGap, to.itemGap, t),
542
- markerStyle: lerpLegendMarkerConfig(from.markerStyle, to.markerStyle, t),
543
- }
544
- }
545
-
546
- /** A whole-palette override replaces the previous palette outright. */
547
- export function resolveSeriesStrokes(
548
- styles: Stroke[] | undefined,
549
- previous: Stroke[]
550
- ): Stroke[] {
551
- return (styles ?? previous).map((s) => strokeOps.resolve(s))
552
- }
553
-
554
- /** Pairwise by index; a palette that grows/shrinks holds the longer side's tail. */
555
- export function lerpSeriesStrokes(
556
- from: Stroke[],
557
- to: Stroke[],
558
- t: number
559
- ): Stroke[] {
560
- const n = Math.max(from.length, to.length)
561
- const out: Stroke[] = []
562
- for (let i = 0; i < n; i++) {
563
- const a = (from[i] ?? to[i]) as StrokeResolved[]
564
- const b = (to[i] ?? from[i]) as StrokeResolved[]
565
- out.push(strokeOps.lerp(a, b, t))
566
- }
567
- return out
568
- }
569
-
570
- /** The fill-palette twin of {@link resolveSeriesStrokes}, for filled marks. */
571
- export function resolveSeriesFills(
572
- fills: Fill[] | undefined,
573
- previous: Fill[]
574
- ): Fill[] {
575
- return (fills ?? previous).map((f) => fillOps.resolve(f))
576
- }
577
-
578
- /** The fill-palette twin of {@link lerpSeriesStrokes}. */
579
- export function lerpSeriesFills(from: Fill[], to: Fill[], t: number): Fill[] {
580
- const n = Math.max(from.length, to.length)
581
- const out: Fill[] = []
582
- for (let i = 0; i < n; i++) {
583
- const a = (from[i] ?? to[i]) as FillResolved[]
584
- const b = (to[i] ?? from[i]) as FillResolved[]
585
- out.push(fillOps.lerp(a, b, t))
586
- }
587
- return out
588
- }
589
-
590
- // ---- Per-series paint ----------------------------------------------------
591
-
592
- /**
593
- * The effective stroke for series `index`: the palette's entry at
594
- * `index % palette.length`, with the series' own `fill`, if set, overriding just
595
- * the last (topmost) layer's colour.
596
- */
597
- export function resolveSeriesStroke(
598
- palette: Stroke[],
599
- series: ChartSeries,
600
- index: number
601
- ): Stroke {
602
- const entry: Stroke =
603
- palette.length > 0
604
- ? palette[index % palette.length]
605
- : { weight: 4, fill: "white" }
606
- if (series.fill == null) return entry
607
- const layers = strokeOps.resolve(entry)
608
- if (layers.length === 0) return { weight: 4, fill: series.fill }
609
- const next = [...layers]
610
- next[next.length - 1] = {
611
- ...next[next.length - 1],
612
- fill: fillOps.resolve(series.fill),
613
- }
614
- return next
615
- }
616
-
617
- /**
618
- * The effective *colour* for series `index` — the same colour
619
- * {@link resolveSeriesStroke} draws its line in — for contexts (a legend
620
- * swatch) that only need the fill.
621
- */
622
- export function resolveSeriesFill(
623
- palette: Stroke[],
624
- series: ChartSeries,
625
- index: number
626
- ): Fill {
627
- const layers = strokeOps.resolve(resolveSeriesStroke(palette, series, index))
628
- return layers[layers.length - 1]?.fill ?? "white"
629
- }
630
-
631
- /**
632
- * The effective paint for mark `index` of a **filled** chart (a bar, a wedge):
633
- * the series' own `fill` when it carries one, else the palette's entry for its
634
- * index, cycled.
635
- *
636
- * The stroke twin above has to reach inside a stroke to swap one layer's colour;
637
- * a filled mark has no such geometry wrapped around its paint, so an override is
638
- * simply the whole answer.
639
- */
640
- export function resolvePalettePaint(
641
- palette: Fill[],
642
- override: Fill | undefined,
643
- index: number
644
- ): Fill {
645
- if (override != null) return override
646
- if (palette.length === 0) return "white"
647
- return palette[index % palette.length]
648
- }
649
-
650
- // ---- Scales and formatting -----------------------------------------------
651
-
652
-
653
- /** Format a marker value: integers plain, otherwise trimmed to one decimal. */
654
- export function formatMarker(value: number): string {
655
- if (Number.isInteger(value)) return String(value)
656
- return value.toFixed(1).replace(/\.0$/, "")
657
- }
658
-
659
- /** Format a fraction in `[0, 1]` as a percentage: integers plain, else one decimal. */
660
- export function formatPercent(fraction: number): string {
661
- const pct = fraction * 100
662
- if (Number.isInteger(pct)) return `${pct}%`
663
- return `${pct.toFixed(1).replace(/\.0$/, "")}%`
664
- }
665
-
666
- /** `markerCount` evenly-spaced tick values across `[min, max]`, ends inclusive. */
667
- export function markerValues([min, max]: Range, markerCount: number): number[] {
668
- const n = Math.max(2, Math.round(markerCount))
669
- return Array.from({ length: n + 1 }, (_, i) => min + ((max - min) / n) * i)
670
- }
671
-
672
- // Lifted into the engine, because a graph and a diagram want them too — see
673
- // `@motionscript/core/component`. Re-exported so a chart, and anything that
674
- // copied one, still reaches them where it always did.
675
- export { niceStep, enterBudget } from "@motionscript/core/component"
1
+ /**
2
+ * The vocabulary every chart node shares: what a *series* is, how an axis is
3
+ * scaled and formatted, and the theme leaves each chart's own theme is assembled
4
+ * from.
5
+ *
6
+ * This module exists because the three chart types are three ways of drawing the
7
+ * same table. A line chart, a bar chart and a pie chart disagree about almost
8
+ * everything visible — polylines against columns against wedges — and agree
9
+ * about almost everything underneath: a series is a column with a caption and a
10
+ * paint, a marker is a number formatted one way, a legend is a swatch beside a
11
+ * label, and a theme is a tree of paints with one mapper and one tween. Writing
12
+ * that three times would mean three answers to "how does a chart round its axis"
13
+ * within one app.
14
+ *
15
+ * Kept renderer-agnostic (no `Node` imports) so a host's own inspector
16
+ * mappings can build a partial theme without pulling the node classes in.
17
+ *
18
+ * **Two conventions run through every resolver and lerp below**, inherited from
19
+ * the shape system's `resolveStroke`/`resolveShadow`:
20
+ *
21
+ * - A **mapper** merges the author's loose, partial input onto a `previous`
22
+ * resolved value and resolves every leaf, so the tween always has resolved
23
+ * data to interpolate. It is idempotent.
24
+ * - A **tween** interpolates two resolved values leaf by leaf. Categorical
25
+ * fields (`fontFamily`, `textAlign`) and fields that are `undefined` on either
26
+ * side **step at the midpoint**, because there is no meaningful in-between and
27
+ * defaulting the missing side to 0 would animate a font weight down to nothing
28
+ * on the way to "unset".
29
+ */
30
+
31
+ import {
32
+ fillOps,
33
+ lerpNumber,
34
+ shadowOps,
35
+ strokeOps,
36
+ insetsOps,
37
+ textOps,
38
+ type DataRecord,
39
+ type Fill,
40
+ type FillResolved,
41
+ type Insets,
42
+ type InsetsResolved,
43
+ type Shadow,
44
+ type ShadowResolved,
45
+ type Stroke,
46
+ type StrokeResolved,
47
+ type TextStyle,
48
+ } from "@motionscript/sdk"
49
+
50
+ /**
51
+ * One series of a chart: a column of the table, captioned and painted.
52
+ *
53
+ * `field` names the column carrying this series' values. What that becomes is
54
+ * the chart's business — a traced polyline, a column of bars, a wedge — but the
55
+ * three questions asked of it are the same everywhere: which column, what to
56
+ * call it, what to paint it, and whether it is currently drawn.
57
+ *
58
+ * `fill` is an **override**: omit it and the series takes the theme palette's
59
+ * entry for its own index, which is what makes a chart nobody has themed come
60
+ * out in five distinct colours rather than five identical ones.
61
+ */
62
+ export interface ChartSeries {
63
+ /** Key into each data row for this series' value. */
64
+ field: string
65
+ /** Legend caption for this series. */
66
+ label: string
67
+ /**
68
+ * Paint override for this series' mark and its legend swatch. Omit to take
69
+ * the theme palette's entry for this series' index.
70
+ */
71
+ fill?: Fill
72
+ /** Whether the series shows by default. Defaults to `true`. */
73
+ enabled?: boolean
74
+ }
75
+
76
+ /** A `[min, max]` numeric range in data units. */
77
+ export type Range = [min: number, max: number]
78
+
79
+ /**
80
+ * One axis's *data* domain — what it shows — as opposed to {@link AxisConfig},
81
+ * which is how it's *styled*. Every field is optional: `range`/`ticks` derive
82
+ * from the plotted data when omitted, and `label` defaults to `""`.
83
+ */
84
+ export interface AxisDomainConfig {
85
+ /** Caption drawn alongside the axis. Pass `""` (the default) to hide it. */
86
+ label?: string
87
+ /** `[min, max]` of the scale. Derived from the data bounds when omitted. */
88
+ range?: Range
89
+ /** Tick values (in data units). Derived (five evenly-spaced) when omitted. */
90
+ ticks?: number[]
91
+ /**
92
+ * How a tick value is written down — a `number-format` pattern such as
93
+ * `#,##0.00` or `$#,##0`.
94
+ *
95
+ * Here rather than in {@link AxisConfig} because it is a statement about the
96
+ * *numbers*, not about the ink they are set in: `$` on a revenue axis says
97
+ * what the column holds, and it has to survive a re-theme. It sits beside
98
+ * `range` and `ticks` for the same reason those do.
99
+ */
100
+ format?: string
101
+ }
102
+
103
+ /**
104
+ * An axis domain's @property mapper: merges the author's partial input onto
105
+ * `previous`, so a later partial `.set({ yAxis: {...} })` patches
106
+ * `label`/`range`/`ticks` independently. `range`/`ticks` staying `undefined`
107
+ * after the merge is the auto-derive signal the scale getters read.
108
+ */
109
+ export function resolveAxisDomain(
110
+ domain: AxisDomainConfig | undefined,
111
+ previous?: AxisDomainConfig
112
+ ): AxisDomainConfig {
113
+ return {
114
+ label: domain?.label ?? previous?.label ?? "",
115
+ range: domain?.range ?? previous?.range,
116
+ ticks: domain?.ticks ?? previous?.ticks,
117
+ format: domain?.format ?? previous?.format,
118
+ }
119
+ }
120
+
121
+ /**
122
+ * An axis domain's @property tween: interpolates `range`/`ticks` numerically
123
+ * (pairwise by index for `ticks`), so a `to` command that restates a range
124
+ * rescales the plot smoothly. `label`, and either field when one side is in
125
+ * auto-derive mode, step at the midpoint.
126
+ */
127
+ export function lerpAxisDomain(
128
+ from: AxisDomainConfig,
129
+ to: AxisDomainConfig,
130
+ t: number
131
+ ): AxisDomainConfig {
132
+ return {
133
+ label: t < 0.5 ? from.label : to.label,
134
+ range: lerpOptionalRange(from.range, to.range, t),
135
+ ticks: lerpOptionalTicks(from.ticks, to.ticks, t),
136
+ // Steps at the midpoint with the caption, for the same reason: there is no
137
+ // halfway between `$#,##0` and `0.0%`.
138
+ format: t < 0.5 ? from.format : to.format,
139
+ }
140
+ }
141
+
142
+ function lerpOptionalRange(
143
+ from: Range | undefined,
144
+ to: Range | undefined,
145
+ t: number
146
+ ): Range | undefined {
147
+ if (!from || !to) return t < 0.5 ? from : to
148
+ return [lerpNumber(from[0], to[0], t), lerpNumber(from[1], to[1], t)]
149
+ }
150
+
151
+ function lerpOptionalTicks(
152
+ from: number[] | undefined,
153
+ to: number[] | undefined,
154
+ t: number
155
+ ): number[] | undefined {
156
+ if (!from || !to) return t < 0.5 ? from : to
157
+ const n = Math.max(from.length, to.length)
158
+ const out: number[] = []
159
+ for (let i = 0; i < n; i++) {
160
+ out.push(lerpNumber(from[i] ?? to[i], to[i] ?? from[i], t))
161
+ }
162
+ return out
163
+ }
164
+
165
+ /**
166
+ * Where a generic `to()` of an axis domain should land, given the domain as it
167
+ * is *drawn* (`drawn`, with `range` and `ticks` resolved off the data), or
168
+ * `undefined` when the request states neither a `range` nor `ticks` and the
169
+ * plain property tween will do.
170
+ *
171
+ * The stored domain of an auto axis has no `range` and no `ticks`, and
172
+ * {@link lerpAxisDomain} steps an unset side at the midpoint, so tweening the
173
+ * stored value from an auto axis is a cut. The charts therefore tween between
174
+ * resolved domains, as their zoom does; this builds the destination. A `range`
175
+ * given without `ticks` keeps the tick *count* the axis already draws, so each
176
+ * marker slides from its old value to its new one instead of the row popping.
177
+ */
178
+ export function axisTweenTarget(
179
+ drawn: AxisDomainConfig,
180
+ requested: AxisDomainConfig | undefined
181
+ ): AxisDomainConfig | undefined {
182
+ if (requested?.range === undefined && requested?.ticks === undefined) return undefined
183
+ const target = resolveAxisDomain(requested, drawn)
184
+ if (requested.ticks === undefined && requested.range !== undefined) {
185
+ const count = Math.max(2, drawn.ticks?.length ?? 2)
186
+ target.ticks = markerValues(requested.range, count - 1)
187
+ }
188
+ return target
189
+ }
190
+
191
+ /**
192
+ * The low-level colour tokens the default themes are built from — a dark plot
193
+ * panel with warm-grey axis furniture.
194
+ */
195
+ export const CHART_PALETTE = {
196
+ /** Fill of the plot panel behind the marks. */
197
+ plotFill: "#15130e",
198
+ /** Colour of the plot's thick border. */
199
+ borderColor: "#4a4036",
200
+ /** Colour of the faint grid lines spanning the plot. */
201
+ gridColor: "#2c2820",
202
+ /** Colour of the numeric axis markers, axis captions, and legend labels. */
203
+ markerColor: "#8a7f70",
204
+ /** Colour of a spotlit region's dashed rules and its wash. */
205
+ regionColor: "#d99a3a",
206
+ } as const
207
+
208
+ /** The out-of-the-box series palette, cycled by series index. */
209
+ export const DEFAULT_SERIES_COLORS = [
210
+ "#d9603b",
211
+ "#8194ad",
212
+ "#e0a93b",
213
+ "#5e9d6b",
214
+ "#9ec85a",
215
+ ] as const
216
+
217
+ /**
218
+ * Opacity an *un*-spotlighted series fades to — its mark and its legend entry
219
+ * alike, so the two dim together.
220
+ */
221
+ export const SPOTLIGHT_DIM = 0.2
222
+
223
+ /** Clamp a number into `[0, 1]` — the range every reveal signal here runs in. */
224
+ export function clampUnit(value: number): number {
225
+ return value < 0 ? 0 : value > 1 ? 1 : value
226
+ }
227
+
228
+ // ---- Row readers ---------------------------------------------------------
229
+
230
+ /**
231
+ * Read a numeric field off a row, defaulting missing, non-numeric and non-finite
232
+ * values to 0.
233
+ *
234
+ * A column left as strings silently plots as 0, which is why the CSV parser's
235
+ * numeric auto-coercion matters — a quoted or unit-suffixed column won't plot
236
+ * until it's coerced.
237
+ */
238
+ export function num(row: DataRecord, field: string | undefined): number {
239
+ if (field === undefined) return 0
240
+ const v = row[field]
241
+ // A `NaN` or infinite cell is no more a measurement than a missing one: read
242
+ // as 0, it cannot poison the scale and turn every point into `NaN`.
243
+ return typeof v === "number" && Number.isFinite(v) ? v : 0
244
+ }
245
+
246
+ /**
247
+ * Read a field off a row as its caption — the counterpart to {@link num} for
248
+ * the columns a chart *names* things by rather than measures them by (a bar's
249
+ * category, a wedge's slice). A missing cell reads as empty rather than as the
250
+ * string `"undefined"`.
251
+ */
252
+ export function text(row: DataRecord, field: string | undefined): string {
253
+ if (field === undefined || field === "") return ""
254
+ const v = row[field]
255
+ return v === undefined || v === null ? "" : String(v)
256
+ }
257
+
258
+ /**
259
+ * Every column that holds numbers across `data`, in header order, skipping the
260
+ * names in `exclude` (typically the category column).
261
+ *
262
+ * A column counts as numeric only if every non-empty cell in it is a number, so
263
+ * a stray text cell leaves the column out rather than plotting zeros. This is
264
+ * what lets a chart plot "every other column" without the author naming twenty
265
+ * fields.
266
+ */
267
+ export function numericFields(
268
+ data: DataRecord[],
269
+ exclude: string[] = []
270
+ ): string[] {
271
+ if (data.length === 0) return []
272
+ const skip = new Set(exclude)
273
+ const seen = new Set<string>()
274
+ const order: string[] = []
275
+ for (const row of data)
276
+ for (const key of Object.keys(row))
277
+ if (!skip.has(key) && !seen.has(key)) {
278
+ seen.add(key)
279
+ order.push(key)
280
+ }
281
+
282
+ return order.filter((key) => {
283
+ let sawValue = false
284
+ for (const row of data) {
285
+ const v = row[key]
286
+ if (v === undefined || v === "") continue
287
+ if (typeof v !== "number") return false
288
+ sawValue = true
289
+ }
290
+ return sawValue
291
+ })
292
+ }
293
+
294
+ // ---- Theme branches ------------------------------------------------------
295
+
296
+ /** One axis's (x or y) style vocabulary. */
297
+ export interface AxisConfig {
298
+ /** Style of each marker along the axis. */
299
+ labelStyle: TextStyle
300
+ /** Style of the axis caption. */
301
+ titleStyle: TextStyle
302
+ /**
303
+ * This axis's direction of the plot's internal grid — weight+fill honoured,
304
+ * dash/cap/join ignored (grid lines are drawn as filled rects).
305
+ */
306
+ lineStyle: Stroke
307
+ /**
308
+ * Gap between the plot and the marker row. Only the side facing the plot is
309
+ * read — `.top` for a horizontal axis, `.right` for a vertical one.
310
+ */
311
+ tickPadding: Insets
312
+ /** Gap between the marker row and the caption, read the same side. */
313
+ titlePadding: Insets
314
+ }
315
+
316
+ /** A legend's per-series colour swatch — a rounded chip, not the caption. */
317
+ export interface LegendMarkerConfig {
318
+ width: number
319
+ height: number
320
+ borderRadius: number
321
+ stroke: Stroke
322
+ shadow: Shadow
323
+ }
324
+
325
+ /** A legend's visual theme. */
326
+ export interface LegendConfig {
327
+ padding: Insets
328
+ /** Caption style — only the swatch carries the series colour. */
329
+ textStyle: TextStyle
330
+ /** Gap between legend entries. */
331
+ itemGap: number
332
+ markerStyle: LegendMarkerConfig
333
+ }
334
+
335
+ /** The plot panel a cartesian chart draws its marks over. */
336
+ export interface PlotAreaConfig {
337
+ stroke: Stroke
338
+ fill: Fill
339
+ shadow: Shadow
340
+ }
341
+
342
+ const AXIS_LABEL_STYLE: TextStyle = {
343
+ fontSize: 24,
344
+ fontWeight: 700,
345
+ textAlign: "center",
346
+ fill: CHART_PALETTE.markerColor,
347
+ }
348
+ const AXIS_TITLE_STYLE: TextStyle = {
349
+ fontSize: 30,
350
+ fontWeight: 600,
351
+ textAlign: "center",
352
+ fill: CHART_PALETTE.markerColor,
353
+ }
354
+ const AXIS_LINE_STYLE: Stroke = { weight: 2, fill: CHART_PALETTE.gridColor }
355
+
356
+ /** The default styling of a horizontal (marker row beneath the plot) axis. */
357
+ export const DEFAULT_X_AXIS: AxisConfig = {
358
+ labelStyle: AXIS_LABEL_STYLE,
359
+ titleStyle: AXIS_TITLE_STYLE,
360
+ lineStyle: AXIS_LINE_STYLE,
361
+ tickPadding: 20,
362
+ titlePadding: 4,
363
+ }
364
+
365
+ /** The default styling of a vertical (marker column beside the plot) axis. */
366
+ export const DEFAULT_Y_AXIS: AxisConfig = {
367
+ labelStyle: { ...AXIS_LABEL_STYLE, fontWeight: 500, textAlign: "right" },
368
+ titleStyle: AXIS_TITLE_STYLE,
369
+ lineStyle: AXIS_LINE_STYLE,
370
+ tickPadding: 40,
371
+ titlePadding: 24,
372
+ }
373
+
374
+ /**
375
+ * The default plot panel: **unpainted**, framed. A chart reads against the
376
+ * stage rather than punching a panel into it, which is the look the family was
377
+ * designed at.
378
+ */
379
+ export const DEFAULT_PLOT_AREA: PlotAreaConfig = {
380
+ fill: [],
381
+ stroke: { weight: 6, fill: CHART_PALETTE.borderColor },
382
+ shadow: [],
383
+ }
384
+
385
+ /** The default legend styling, shared by every chart that draws one. */
386
+ export const DEFAULT_LEGEND: LegendConfig = {
387
+ padding: 0,
388
+ textStyle: {
389
+ fontSize: 30,
390
+ fontWeight: 600,
391
+ textAlign: "left",
392
+ fill: CHART_PALETTE.markerColor,
393
+ },
394
+ itemGap: 44,
395
+ markerStyle: {
396
+ width: 60,
397
+ height: 24,
398
+ borderRadius: 6,
399
+ stroke: [],
400
+ shadow: [],
401
+ },
402
+ }
403
+
404
+ /** The default per-series stroke palette — {@link DEFAULT_SERIES_COLORS}, drawn 4px. */
405
+ export const DEFAULT_SERIES_STROKES: Stroke[] = DEFAULT_SERIES_COLORS.map(
406
+ (fill) => ({ weight: 4, fill })
407
+ )
408
+
409
+ /** The default per-series fill palette — the same colours, as solid paint. */
410
+ export const DEFAULT_SERIES_FILLS: Fill[] = DEFAULT_SERIES_COLORS.map(
411
+ (fill) => fill
412
+ )
413
+
414
+ // ---- Theme branch resolvers ----------------------------------------------
415
+ // Each chart type assembles its own theme out of these, so "the axis furniture"
416
+ // means one thing across the family and each chart still declares only the
417
+ // branches it actually draws.
418
+
419
+ export function resolveAxisConfig(
420
+ axis: Partial<AxisConfig> | undefined,
421
+ previous: AxisConfig
422
+ ): AxisConfig {
423
+ return {
424
+ labelStyle: textOps.resolveStyle(axis?.labelStyle, previous.labelStyle),
425
+ titleStyle: textOps.resolveStyle(axis?.titleStyle, previous.titleStyle),
426
+ lineStyle: strokeOps.resolve(axis?.lineStyle ?? previous.lineStyle),
427
+ tickPadding: insetsOps.resolve(
428
+ axis?.tickPadding ?? previous.tickPadding,
429
+ previous.tickPadding as InsetsResolved
430
+ ),
431
+ titlePadding: insetsOps.resolve(
432
+ axis?.titlePadding ?? previous.titlePadding,
433
+ previous.titlePadding as InsetsResolved
434
+ ),
435
+ }
436
+ }
437
+
438
+ export function lerpAxisConfig(
439
+ from: AxisConfig,
440
+ to: AxisConfig,
441
+ t: number
442
+ ): AxisConfig {
443
+ return {
444
+ labelStyle: textOps.lerpStyle(from.labelStyle, to.labelStyle, t),
445
+ titleStyle: textOps.lerpStyle(from.titleStyle, to.titleStyle, t),
446
+ lineStyle: strokeOps.lerp(
447
+ from.lineStyle as StrokeResolved[],
448
+ to.lineStyle as StrokeResolved[],
449
+ t
450
+ ),
451
+ tickPadding: insetsOps.lerp(
452
+ from.tickPadding as InsetsResolved,
453
+ to.tickPadding as InsetsResolved,
454
+ t
455
+ ),
456
+ titlePadding: insetsOps.lerp(
457
+ from.titlePadding as InsetsResolved,
458
+ to.titlePadding as InsetsResolved,
459
+ t
460
+ ),
461
+ }
462
+ }
463
+
464
+ export function resolvePlotArea(
465
+ plotArea: Partial<PlotAreaConfig> | undefined,
466
+ previous: PlotAreaConfig
467
+ ): PlotAreaConfig {
468
+ return {
469
+ fill: fillOps.resolve(plotArea?.fill ?? previous.fill),
470
+ stroke: strokeOps.resolve(plotArea?.stroke ?? previous.stroke),
471
+ shadow: shadowOps.resolve(plotArea?.shadow ?? previous.shadow),
472
+ }
473
+ }
474
+
475
+ export function lerpPlotArea(
476
+ from: PlotAreaConfig,
477
+ to: PlotAreaConfig,
478
+ t: number
479
+ ): PlotAreaConfig {
480
+ return {
481
+ fill: fillOps.lerp(
482
+ from.fill as FillResolved[],
483
+ to.fill as FillResolved[],
484
+ t
485
+ ),
486
+ stroke: strokeOps.lerp(
487
+ from.stroke as StrokeResolved[],
488
+ to.stroke as StrokeResolved[],
489
+ t
490
+ ),
491
+ shadow: shadowOps.lerp(
492
+ from.shadow as ShadowResolved[],
493
+ to.shadow as ShadowResolved[],
494
+ t
495
+ ),
496
+ }
497
+ }
498
+
499
+ function resolveLegendMarkerConfig(
500
+ marker: Partial<LegendMarkerConfig> | undefined,
501
+ previous: LegendMarkerConfig
502
+ ): LegendMarkerConfig {
503
+ return {
504
+ width: marker?.width ?? previous.width,
505
+ height: marker?.height ?? previous.height,
506
+ borderRadius: marker?.borderRadius ?? previous.borderRadius,
507
+ stroke: strokeOps.resolve(marker?.stroke ?? previous.stroke),
508
+ shadow: shadowOps.resolve(marker?.shadow ?? previous.shadow),
509
+ }
510
+ }
511
+
512
+ function lerpLegendMarkerConfig(
513
+ from: LegendMarkerConfig,
514
+ to: LegendMarkerConfig,
515
+ t: number
516
+ ): LegendMarkerConfig {
517
+ return {
518
+ width: lerpNumber(from.width, to.width, t),
519
+ height: lerpNumber(from.height, to.height, t),
520
+ borderRadius: lerpNumber(from.borderRadius, to.borderRadius, t),
521
+ stroke: strokeOps.lerp(
522
+ from.stroke as StrokeResolved[],
523
+ to.stroke as StrokeResolved[],
524
+ t
525
+ ),
526
+ shadow: shadowOps.lerp(
527
+ from.shadow as ShadowResolved[],
528
+ to.shadow as ShadowResolved[],
529
+ t
530
+ ),
531
+ }
532
+ }
533
+
534
+ /** A legend theme as the author may state it — every branch optional. */
535
+ export type LegendTheme = Partial<Omit<LegendConfig, "markerStyle">> & {
536
+ markerStyle?: Partial<LegendMarkerConfig>
537
+ }
538
+
539
+ export function resolveLegendConfig(
540
+ legend: LegendTheme | undefined,
541
+ previous: LegendConfig
542
+ ): LegendConfig {
543
+ return {
544
+ padding: insetsOps.resolve(
545
+ legend?.padding ?? previous.padding,
546
+ previous.padding as InsetsResolved
547
+ ),
548
+ textStyle: textOps.resolveStyle(legend?.textStyle, previous.textStyle),
549
+ itemGap: legend?.itemGap ?? previous.itemGap,
550
+ markerStyle: resolveLegendMarkerConfig(
551
+ legend?.markerStyle,
552
+ previous.markerStyle
553
+ ),
554
+ }
555
+ }
556
+
557
+ export function lerpLegendConfig(
558
+ from: LegendConfig,
559
+ to: LegendConfig,
560
+ t: number
561
+ ): LegendConfig {
562
+ return {
563
+ padding: insetsOps.lerp(
564
+ from.padding as InsetsResolved,
565
+ to.padding as InsetsResolved,
566
+ t
567
+ ),
568
+ textStyle: textOps.lerpStyle(from.textStyle, to.textStyle, t),
569
+ itemGap: lerpNumber(from.itemGap, to.itemGap, t),
570
+ markerStyle: lerpLegendMarkerConfig(from.markerStyle, to.markerStyle, t),
571
+ }
572
+ }
573
+
574
+ /** A whole-palette override replaces the previous palette outright. */
575
+ export function resolveSeriesStrokes(
576
+ styles: Stroke[] | undefined,
577
+ previous: Stroke[]
578
+ ): Stroke[] {
579
+ return (styles ?? previous).map((s) => strokeOps.resolve(s))
580
+ }
581
+
582
+ /** Pairwise by index; a palette that grows/shrinks holds the longer side's tail. */
583
+ export function lerpSeriesStrokes(
584
+ from: Stroke[],
585
+ to: Stroke[],
586
+ t: number
587
+ ): Stroke[] {
588
+ const n = Math.max(from.length, to.length)
589
+ const out: Stroke[] = []
590
+ for (let i = 0; i < n; i++) {
591
+ const a = (from[i] ?? to[i]) as StrokeResolved[]
592
+ const b = (to[i] ?? from[i]) as StrokeResolved[]
593
+ out.push(strokeOps.lerp(a, b, t))
594
+ }
595
+ return out
596
+ }
597
+
598
+ /** The fill-palette twin of {@link resolveSeriesStrokes}, for filled marks. */
599
+ export function resolveSeriesFills(
600
+ fills: Fill[] | undefined,
601
+ previous: Fill[]
602
+ ): Fill[] {
603
+ return (fills ?? previous).map((f) => fillOps.resolve(f))
604
+ }
605
+
606
+ /** The fill-palette twin of {@link lerpSeriesStrokes}. */
607
+ export function lerpSeriesFills(from: Fill[], to: Fill[], t: number): Fill[] {
608
+ const n = Math.max(from.length, to.length)
609
+ const out: Fill[] = []
610
+ for (let i = 0; i < n; i++) {
611
+ const a = (from[i] ?? to[i]) as FillResolved[]
612
+ const b = (to[i] ?? from[i]) as FillResolved[]
613
+ out.push(fillOps.lerp(a, b, t))
614
+ }
615
+ return out
616
+ }
617
+
618
+ // ---- Per-series paint ----------------------------------------------------
619
+
620
+ /**
621
+ * The effective stroke for series `index`: the palette's entry at
622
+ * `index % palette.length`, with the series' own `fill`, if set, overriding just
623
+ * the last (topmost) layer's colour.
624
+ */
625
+ export function resolveSeriesStroke(
626
+ palette: Stroke[],
627
+ series: ChartSeries,
628
+ index: number
629
+ ): Stroke {
630
+ const entry: Stroke =
631
+ palette.length > 0
632
+ ? palette[index % palette.length]
633
+ : { weight: 4, fill: "white" }
634
+ if (series.fill == null) return entry
635
+ const layers = strokeOps.resolve(entry)
636
+ if (layers.length === 0) return { weight: 4, fill: series.fill }
637
+ const next = [...layers]
638
+ next[next.length - 1] = {
639
+ ...next[next.length - 1],
640
+ fill: fillOps.resolve(series.fill),
641
+ }
642
+ return next
643
+ }
644
+
645
+ /**
646
+ * The effective *colour* for series `index` — the same colour
647
+ * {@link resolveSeriesStroke} draws its line in — for contexts (a legend
648
+ * swatch) that only need the fill.
649
+ */
650
+ export function resolveSeriesFill(
651
+ palette: Stroke[],
652
+ series: ChartSeries,
653
+ index: number
654
+ ): Fill {
655
+ const layers = strokeOps.resolve(resolveSeriesStroke(palette, series, index))
656
+ return layers[layers.length - 1]?.fill ?? "white"
657
+ }
658
+
659
+ /**
660
+ * The effective paint for mark `index` of a **filled** chart (a bar, a wedge):
661
+ * the series' own `fill` when it carries one, else the palette's entry for its
662
+ * index, cycled.
663
+ *
664
+ * The stroke twin above has to reach inside a stroke to swap one layer's colour;
665
+ * a filled mark has no such geometry wrapped around its paint, so an override is
666
+ * simply the whole answer.
667
+ */
668
+ export function resolvePalettePaint(
669
+ palette: Fill[],
670
+ override: Fill | undefined,
671
+ index: number
672
+ ): Fill {
673
+ if (override != null) return override
674
+ if (palette.length === 0) return "white"
675
+ return palette[index % palette.length]
676
+ }
677
+
678
+ // ---- Scales and formatting -----------------------------------------------
679
+
680
+
681
+ /**
682
+ * Format a marker value: integers plain, otherwise trimmed to one decimal, or to
683
+ * as many as the axis's tick `step` needs to tell neighbouring ticks apart.
684
+ *
685
+ * One decimal is the floor, so a step of 0.1 or more reads exactly as it always
686
+ * has; a finer step (a unit axis ticked every 0.05) gets two, instead of five
687
+ * ticks captioned `0.1 0.1 0.2 0.2 0.3`. Trailing zeros are dropped either way.
688
+ */
689
+ export function formatMarker(value: number, step?: number): string {
690
+ if (Number.isInteger(value)) return String(value)
691
+ const decimals = Math.max(1, step === undefined ? 1 : decimalsFor(step))
692
+ return value.toFixed(decimals).replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "")
693
+ }
694
+
695
+ /** Decimal places needed to write `step` exactly, capped at six. */
696
+ function decimalsFor(step: number): number {
697
+ if (!(step > 0) || !Number.isFinite(step)) return 1
698
+ for (let d = 0; d <= 6; d++) {
699
+ const scaled = step * 10 ** d
700
+ if (Math.abs(scaled - Math.round(scaled)) < 1e-6 * Math.max(1, scaled)) return d
701
+ }
702
+ // An irrational-looking step (a third): as many places as separate the ticks.
703
+ return Math.min(6, Math.max(1, Math.ceil(-Math.log10(step)) + 1))
704
+ }
705
+
706
+ /** The gap between neighbouring tick values, or `undefined` for fewer than two distinct ones. */
707
+ export function markerStep(markers: readonly number[]): number | undefined {
708
+ const sorted = [...markers].filter(Number.isFinite).sort((a, b) => a - b)
709
+ let step: number | undefined
710
+ for (let i = 1; i < sorted.length; i++) {
711
+ const gap = sorted[i] - sorted[i - 1]
712
+ if (gap > 1e-12 && (step === undefined || gap < step)) step = gap
713
+ }
714
+ return step
715
+ }
716
+
717
+ /** Format a fraction in `[0, 1]` as a percentage: integers plain, else one decimal. */
718
+ export function formatPercent(fraction: number): string {
719
+ const pct = fraction * 100
720
+ if (Number.isInteger(pct)) return `${pct}%`
721
+ return `${pct.toFixed(1).replace(/\.0$/, "")}%`
722
+ }
723
+
724
+ /** `markerCount` evenly-spaced tick values across `[min, max]`, ends inclusive. */
725
+ export function markerValues([min, max]: Range, markerCount: number): number[] {
726
+ const n = Math.max(2, Math.round(markerCount))
727
+ return Array.from({ length: n + 1 }, (_, i) => min + ((max - min) / n) * i)
728
+ }
729
+
730
+ // Lifted into the engine, because a graph and a diagram want them too — see
731
+ // `@motionscript/sdk/component`. Re-exported so a chart, and anything that
732
+ // copied one, still reaches them where it always did.
733
+ export { niceStep, enterBudget } from "@motionscript/sdk/component"