@motionscript/charts 0.0.0-stage → 0.1.0-alpha.0

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 (137) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +201 -0
  3. package/dist/bar-chart/bar-chart.d.ts +286 -0
  4. package/dist/bar-chart/bar-chart.d.ts.map +1 -0
  5. package/dist/bar-chart/bar-chart.js +610 -0
  6. package/dist/bar-chart/bar-chart.js.map +1 -0
  7. package/dist/bar-chart/category-axis.d.ts +77 -0
  8. package/dist/bar-chart/category-axis.d.ts.map +1 -0
  9. package/dist/bar-chart/category-axis.js +141 -0
  10. package/dist/bar-chart/category-axis.js.map +1 -0
  11. package/dist/bar-chart/chart-bars.d.ts +149 -0
  12. package/dist/bar-chart/chart-bars.d.ts.map +1 -0
  13. package/dist/bar-chart/chart-bars.js +236 -0
  14. package/dist/bar-chart/chart-bars.js.map +1 -0
  15. package/dist/bar-chart/index.d.ts +16 -0
  16. package/dist/bar-chart/index.d.ts.map +1 -0
  17. package/dist/bar-chart/index.js +12 -0
  18. package/dist/bar-chart/index.js.map +1 -0
  19. package/dist/bar-chart/shared.d.ts +146 -0
  20. package/dist/bar-chart/shared.d.ts.map +1 -0
  21. package/dist/bar-chart/shared.js +182 -0
  22. package/dist/bar-chart/shared.js.map +1 -0
  23. package/dist/browser/chunks/chunk-ZMBOBHYL.js +2 -0
  24. package/dist/browser/chunks/chunk-ZMBOBHYL.js.map +7 -0
  25. package/dist/browser/index.js +2 -0
  26. package/dist/browser/index.js.map +7 -0
  27. package/dist/browser/kit.js +2 -0
  28. package/dist/browser/kit.js.map +7 -0
  29. package/dist/browser/manifest.json +12 -0
  30. package/dist/engine.d.ts +27 -0
  31. package/dist/engine.d.ts.map +1 -0
  32. package/dist/engine.js +27 -0
  33. package/dist/engine.js.map +1 -0
  34. package/dist/index.d.ts +6 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +6 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/kit/chart-border.d.ts +28 -0
  39. package/dist/kit/chart-border.d.ts.map +1 -0
  40. package/dist/kit/chart-border.js +45 -0
  41. package/dist/kit/chart-border.js.map +1 -0
  42. package/dist/kit/chart-canvas.d.ts +56 -0
  43. package/dist/kit/chart-canvas.d.ts.map +1 -0
  44. package/dist/kit/chart-canvas.js +125 -0
  45. package/dist/kit/chart-canvas.js.map +1 -0
  46. package/dist/kit/chart-legend.d.ts +126 -0
  47. package/dist/kit/chart-legend.d.ts.map +1 -0
  48. package/dist/kit/chart-legend.js +212 -0
  49. package/dist/kit/chart-legend.js.map +1 -0
  50. package/dist/kit/shared.d.ts +251 -0
  51. package/dist/kit/shared.d.ts.map +1 -0
  52. package/dist/kit/shared.js +401 -0
  53. package/dist/kit/shared.js.map +1 -0
  54. package/dist/kit/vertical-axis.d.ts +99 -0
  55. package/dist/kit/vertical-axis.d.ts.map +1 -0
  56. package/dist/kit/vertical-axis.js +176 -0
  57. package/dist/kit/vertical-axis.js.map +1 -0
  58. package/dist/line-chart/chart-line.d.ts +91 -0
  59. package/dist/line-chart/chart-line.d.ts.map +1 -0
  60. package/dist/line-chart/chart-line.js +156 -0
  61. package/dist/line-chart/chart-line.js.map +1 -0
  62. package/dist/line-chart/chart-region.d.ts +47 -0
  63. package/dist/line-chart/chart-region.d.ts.map +1 -0
  64. package/dist/line-chart/chart-region.js +101 -0
  65. package/dist/line-chart/chart-region.js.map +1 -0
  66. package/dist/line-chart/horizontal-axis.d.ts +85 -0
  67. package/dist/line-chart/horizontal-axis.d.ts.map +1 -0
  68. package/dist/line-chart/horizontal-axis.js +158 -0
  69. package/dist/line-chart/horizontal-axis.js.map +1 -0
  70. package/dist/line-chart/index.d.ts +22 -0
  71. package/dist/line-chart/index.d.ts.map +1 -0
  72. package/dist/line-chart/index.js +19 -0
  73. package/dist/line-chart/index.js.map +1 -0
  74. package/dist/line-chart/line-chart.d.ts +347 -0
  75. package/dist/line-chart/line-chart.d.ts.map +1 -0
  76. package/dist/line-chart/line-chart.js +701 -0
  77. package/dist/line-chart/line-chart.js.map +1 -0
  78. package/dist/line-chart/shared.d.ts +171 -0
  79. package/dist/line-chart/shared.d.ts.map +1 -0
  80. package/dist/line-chart/shared.js +270 -0
  81. package/dist/line-chart/shared.js.map +1 -0
  82. package/dist/line-chart/x-scale.d.ts +84 -0
  83. package/dist/line-chart/x-scale.d.ts.map +1 -0
  84. package/dist/line-chart/x-scale.js +302 -0
  85. package/dist/line-chart/x-scale.js.map +1 -0
  86. package/dist/nodes.d.ts +20 -0
  87. package/dist/nodes.d.ts.map +1 -0
  88. package/dist/nodes.js +20 -0
  89. package/dist/nodes.js.map +1 -0
  90. package/dist/pie-chart/index.d.ts +18 -0
  91. package/dist/pie-chart/index.d.ts.map +1 -0
  92. package/dist/pie-chart/index.js +14 -0
  93. package/dist/pie-chart/index.js.map +1 -0
  94. package/dist/pie-chart/pie-chart.d.ts +170 -0
  95. package/dist/pie-chart/pie-chart.d.ts.map +1 -0
  96. package/dist/pie-chart/pie-chart.js +291 -0
  97. package/dist/pie-chart/pie-chart.js.map +1 -0
  98. package/dist/pie-chart/pie-legend.d.ts +60 -0
  99. package/dist/pie-chart/pie-legend.d.ts.map +1 -0
  100. package/dist/pie-chart/pie-legend.js +131 -0
  101. package/dist/pie-chart/pie-legend.js.map +1 -0
  102. package/dist/pie-chart/pie-ring.d.ts +266 -0
  103. package/dist/pie-chart/pie-ring.d.ts.map +1 -0
  104. package/dist/pie-chart/pie-ring.js +708 -0
  105. package/dist/pie-chart/pie-ring.js.map +1 -0
  106. package/dist/pie-chart/shared.d.ts +210 -0
  107. package/dist/pie-chart/shared.d.ts.map +1 -0
  108. package/dist/pie-chart/shared.js +240 -0
  109. package/dist/pie-chart/shared.js.map +1 -0
  110. package/package.json +69 -3
  111. package/registry.json +23 -0
  112. package/src/bar-chart/bar-chart.ts +804 -0
  113. package/src/bar-chart/category-axis.ts +177 -0
  114. package/src/bar-chart/chart-bars.ts +310 -0
  115. package/src/bar-chart/index.ts +31 -0
  116. package/src/bar-chart/shared.ts +354 -0
  117. package/src/engine.ts +26 -0
  118. package/src/index.ts +5 -0
  119. package/src/kit/chart-border.ts +61 -0
  120. package/src/kit/chart-canvas.ts +157 -0
  121. package/src/kit/chart-legend.ts +250 -0
  122. package/src/kit/shared.ts +675 -0
  123. package/src/kit/vertical-axis.ts +224 -0
  124. package/src/line-chart/chart-line.ts +208 -0
  125. package/src/line-chart/chart-region.ts +135 -0
  126. package/src/line-chart/horizontal-axis.ts +202 -0
  127. package/src/line-chart/index.ts +39 -0
  128. package/src/line-chart/line-chart.ts +894 -0
  129. package/src/line-chart/shared.ts +459 -0
  130. package/src/line-chart/x-scale.ts +367 -0
  131. package/src/nodes.ts +20 -0
  132. package/src/pie-chart/index.ts +37 -0
  133. package/src/pie-chart/pie-chart.ts +374 -0
  134. package/src/pie-chart/pie-legend.ts +159 -0
  135. package/src/pie-chart/pie-ring.ts +903 -0
  136. package/src/pie-chart/shared.ts +490 -0
  137. package/README.md +0 -4
@@ -0,0 +1,903 @@
1
+ import {
2
+ Rect,
3
+ command,
4
+ type AssetScope,
5
+ Graphics2D,
6
+ Node2D,
7
+ PathBuilder,
8
+ Text,
9
+ easeOut,
10
+ fillOps,
11
+ property,
12
+ strokeOps,
13
+ textOps,
14
+ type Command,
15
+ type CommandArgs,
16
+ type FillResolved,
17
+ type NodeConfig,
18
+ type Node2DProps,
19
+ type RenderContext2D,
20
+ type TextStyle,
21
+ type Vector2,
22
+ } from "@motionscript/core"
23
+
24
+ import { clampUnit, formatPercent } from "../kit/shared"
25
+ import {
26
+ DEFAULT_PIE_CHART_THEME,
27
+ pieArcs,
28
+ relaxLabels,
29
+ ringPoint,
30
+ type CenterConfig,
31
+ type LabelConfig,
32
+ type PieArc,
33
+ type PieLabelMode,
34
+ type PieLabelPlacement,
35
+ type PieSlice,
36
+ type RingConfig,
37
+ } from "./shared"
38
+ import { declarePaints } from "@motionscript/core/component"
39
+
40
+ export interface PieRingProps extends Node2DProps {
41
+ /** One entry per slice: its `category`, `value` and `fill`. */
42
+ slices: PieSlice[]
43
+ /** Ring geometry and paint — gap, hole, start angle, selection growth. */
44
+ ring: RingConfig
45
+ /** How the labels are set, and the leader lines that point at them. */
46
+ label: LabelConfig
47
+ /**
48
+ * How the hole's summary is set.
49
+ *
50
+ * Named `centerStyle` rather than `center` because every node already has a
51
+ * `center` — the anchor its position is measured from.
52
+ */
53
+ centerStyle: CenterConfig
54
+ /** What the labels say, or `"none"` to drop them entirely. */
55
+ labelMode: PieLabelMode
56
+ /** Where the labels sit: inside their wedge, outside on a leader, or nowhere. */
57
+ labelPlacement: PieLabelPlacement
58
+ /**
59
+ * Sweep of the ring in `[0, 1]`: 0 draws nothing, 1 the full circle. The
60
+ * wedges grow around clockwise from the ring's `startAngle` as this rises.
61
+ */
62
+ growth: number
63
+ /**
64
+ * Fade of the leader lines and labels in `[0, 1]`, held separate from
65
+ * {@link growth} so they arrive *after* the ring has swept in.
66
+ */
67
+ labelReveal: number
68
+ /**
69
+ * How far each slice is currently pushed out of the ring, `0`–`1` per index.
70
+ * Owned by the chart, so the ring and the legend read one signal.
71
+ */
72
+ pops: number[]
73
+ /** Opacity everything *unselected* falls back to while any slice is selected. */
74
+ dimOpacity: number
75
+ /**
76
+ * Text set in the middle of the ring's hole — the largest uninterrupted area
77
+ * the chart owns, and on a donut otherwise empty. A one-line summary there
78
+ * routinely does more work than the whole ring around it. Empty (the default)
79
+ * leaves the hole clear; ignored when there is no hole.
80
+ */
81
+ centerLabel: string
82
+ /** Smaller second line under {@link centerLabel}. Empty (the default) drops it. */
83
+ centerCaption: string
84
+ /**
85
+ * Fade of the hole's summary in `[0, 1]`. Its own signal, untouched by the
86
+ * ring's entrance — a hole label is usually a *conclusion*, so a scene that
87
+ * wants it to land on a later beat sets this to 0 and calls
88
+ * `PieChart.revealCenter` when it gets there.
89
+ */
90
+ centerReveal: number
91
+ }
92
+
93
+ /** Vertical breathing room between one label block and the next, in px. */
94
+ const LABEL_GAP = 12
95
+ /** Breathing room past the outermost label, so it never touches the node's edge, in px. */
96
+ const LABEL_PAD = 14
97
+ /** Rough width of one glyph as a fraction of the font size, for gutter sizing. */
98
+ const GLYPH_RATIO = 0.62
99
+ /** Gap between a wedge's outer edge and where its leader lifts off, in px. */
100
+ const LEADER_LIFTOFF = 6
101
+ /** How far past the ring's outer edge a leader runs before it elbows, in px. */
102
+ const LEADER_LENGTH = 34
103
+ /** Horizontal run from the elbow to the label, in px. */
104
+ const LABEL_STUB = 26
105
+ /** Gap between a leader's end and the label text it points at, in px. */
106
+ const TEXT_INSET = 8
107
+ /**
108
+ * Floor on the elbow's horizontal distance from the ring's axis, as a fraction
109
+ * of the leader radius — so a label pushed clear above (or below) the ring still
110
+ * elbows out sideways rather than running straight down the 12 o'clock line.
111
+ */
112
+ const MIN_ELBOW = 0.18
113
+ /** Segments used to tessellate a full turn of arc; a wedge takes its share. */
114
+ const ARC_STEPS = 240
115
+ /** Rounding applied to the leader's elbow, in px. */
116
+ const ELBOW_RADIUS = 8
117
+ /** Side padding used when nothing is leadered out — no gutter to reserve. */
118
+ const BARE_PAD = 2
119
+ /** An inside label's caption size, as a fraction of its leading line. */
120
+ const INSIDE_CAPTION_RATIO = 0.44
121
+ /**
122
+ * Where an inside label sits on a **solid pie** (no hole to split the band
123
+ * with), as a fraction of the wedge's radius — far enough out that the label
124
+ * clears the point every wedge converges on.
125
+ */
126
+ const PIE_LABEL_RADIUS = 0.62
127
+ /** Fraction of the hole's diameter its summary is allowed to run to. */
128
+ const CENTER_LABEL_FIT = 0.78
129
+ /** Fraction of the room inside a wedge that its label is allowed to run to. */
130
+ const INSIDE_LABEL_FIT = 0.9
131
+ /** Below this, a wedge's bisector counts as axis-aligned and that term stops binding. */
132
+ const AXIS_EPSILON = 1e-3
133
+ /** Fallback type size when a theme style leaves it unset or on autofit. */
134
+ const FALLBACK_SIZE = 26
135
+
136
+ /** A style's numeric size, guarding the autofit and unset cases. */
137
+ function sizeOf(style: TextStyle, fallback = FALLBACK_SIZE): number {
138
+ const size = style.fontSize
139
+ return typeof size === "number" ? size : fallback
140
+ }
141
+
142
+ /** Where one slice's label sits and the polyline that points at it. */
143
+ interface LabelPlacement {
144
+ /** Index of the slice. */
145
+ index: number
146
+ /** Which side of the ring the label sits on: +1 right, −1 left. */
147
+ side: 1 | -1
148
+ /** Leader polyline: wedge edge → elbow → label. */
149
+ leader: Vector2[]
150
+ /** Point the label's inner edge is pinned to. */
151
+ text: Vector2
152
+ }
153
+
154
+ /**
155
+ * A ring-band wedge over `a0`→`a1` (radians, clockwise from 12 o'clock) spanning
156
+ * `rInner`→`rOuter`, centred on `cx`. Ring wedges trace the outer arc, step in,
157
+ * and trace the inner arc back; full pie wedges (`rInner <= 0`) close through the
158
+ * centre.
159
+ *
160
+ * `halfGap` is **half the gap to the neighbouring slice, in px**, shaved off both
161
+ * ends of the wedge. It's converted to an angle *per radius* (`halfGap / r` — a
162
+ * wider angle near the hole than out at the rim), which is what keeps the channel
163
+ * between two slices the same width all the way across the band. A fixed angular
164
+ * gap instead reads as a thin pizza slice: right at the rim, pinched shut at the
165
+ * hole. The inset is capped at the wedge's own half-span so a sliver of a slice
166
+ * narrows to nothing rather than turning inside out.
167
+ */
168
+ function wedgePath(
169
+ a0: number,
170
+ a1: number,
171
+ rInner: number,
172
+ rOuter: number,
173
+ halfGap: number,
174
+ cx: number
175
+ ): PathBuilder {
176
+ const path = new PathBuilder()
177
+ const span = a1 - a0
178
+ const steps = Math.max(
179
+ 2,
180
+ Math.ceil((Math.abs(span) / (Math.PI * 2)) * ARC_STEPS)
181
+ )
182
+ /** Angular inset at radius `r` that puts the wedge's edge `halfGap` px off the divide. */
183
+ const insetAt = (r: number): number =>
184
+ r <= 0 ? 0 : Math.min(halfGap / r, span / 2.2)
185
+ const arcTo = (r: number, i: number): Vector2 => {
186
+ const inset = insetAt(r)
187
+ const from = a0 + inset
188
+ const to = a1 - inset
189
+ const point = ringPoint(r, from + ((to - from) * i) / steps)
190
+ return { x: point.x + cx, y: point.y }
191
+ }
192
+
193
+ if (rInner <= 0) {
194
+ // Solid pie wedge: the sides converge on the centre, so only the outer rim
195
+ // carries the gap.
196
+ path.moveTo(cx, 0)
197
+ for (let i = 0; i <= steps; i++) {
198
+ const p = arcTo(rOuter, i)
199
+ path.lineTo(p.x, p.y)
200
+ }
201
+ path.close()
202
+ return path
203
+ }
204
+
205
+ for (let i = 0; i <= steps; i++) {
206
+ const p = arcTo(rOuter, i)
207
+ if (i === 0) path.moveTo(p.x, p.y)
208
+ else path.lineTo(p.x, p.y)
209
+ }
210
+ // Back along the inner arc — its own (wider) inset makes each side edge a
211
+ // straight chord sitting `halfGap` px off the divide at both ends.
212
+ for (let i = steps; i >= 0; i--) {
213
+ const p = arcTo(rInner, i)
214
+ path.lineTo(p.x, p.y)
215
+ }
216
+ path.close()
217
+ return path
218
+ }
219
+
220
+ /**
221
+ * The ring itself: one wedge per {@link PieSlice}, sized by its share of the
222
+ * total, swept clockwise from the theme's `startAngle` with a `gap` of clear
223
+ * space between neighbours — a *constant-width* channel, the same at the hole as
224
+ * at the rim (see {@link wedgePath}). A **selected** slice reaches further out
225
+ * while its hole edge stays put — so it reads as that band swelling out of the
226
+ * ring rather than breaking off it — and the rest of the ring dims behind it,
227
+ * leaders and labels included.
228
+ *
229
+ * This is the only part of the chart family that draws a path: the wedges are
230
+ * filled {@link PathBuilder} polygons approximating each arc, and the leaders are
231
+ * stroked polylines — both in the node's centred, y-up space, so neither depends
232
+ * on SVG arc-sweep conventions. The **labels are real {@link Text} nodes**
233
+ * (stacked in a hug vertical flow and pinned by their inner edge), so no
234
+ * glyph-width guesswork decides where a caption starts.
235
+ *
236
+ * ### Label placement
237
+ * Each label sits either **inside** its wedge or **outside** on a leader.
238
+ *
239
+ * An inside label is centred on its slice's band and leads with the number, the
240
+ * caption set small underneath — inside a wedge the reader already knows which
241
+ * slice they're on, so the magnitude is the thing being read. It costs no gutter
242
+ * and no eye round-trip, so a ring labelled that way draws considerably bigger in
243
+ * the same box.
244
+ *
245
+ * A leader label sits outside on the end of a polyline that lifts off its wedge,
246
+ * elbows, and runs horizontally into the text. Labels are split into a left and a
247
+ * right column by which way their slice's bisector points, and each column is
248
+ * de-conflicted independently (see {@link relaxLabels}): a label takes the spot
249
+ * nearest its wedge that still clears its neighbour, and the column is squeezed
250
+ * to fit the node's height rather than spilling out of it. The elbow then rides on
251
+ * a circle just outside the ring **at the label's settled y**, so the run into the
252
+ * text is always horizontal and a nudged label never drags its leader back across
253
+ * the ring.
254
+ *
255
+ * Only the sides that actually carry a leader reserve a gutter, and the ring's
256
+ * centre slides into whatever the other side left over ({@link centerX}) — so a
257
+ * ring whose slices all leader one way doesn't leave a bald patch on the other.
258
+ */
259
+ export class PieRing extends Node2D<PieRingProps> {
260
+ @property({ default: () => [] as PieSlice[] }) declare slices: PieSlice[]
261
+ @property({ default: DEFAULT_PIE_CHART_THEME.ring }) declare ring: RingConfig
262
+ @property({ default: DEFAULT_PIE_CHART_THEME.label })
263
+ declare label: LabelConfig
264
+ @property({ default: DEFAULT_PIE_CHART_THEME.center })
265
+ declare centerStyle: CenterConfig
266
+ @property({ default: "percent" }) declare labelMode: PieLabelMode
267
+ @property({ default: "leader" }) declare labelPlacement: PieLabelPlacement
268
+ @property({ default: 1 }) declare growth: number
269
+ @property({ default: 1 }) declare labelReveal: number
270
+ @property({ default: () => [] as number[] }) declare pops: number[]
271
+ @property({ default: DEFAULT_PIE_CHART_THEME.spotlight.dimOpacity })
272
+ declare dimOpacity: number
273
+ @property({ default: "" }) declare centerLabel: string
274
+ @property({ default: "" }) declare centerCaption: string
275
+ @property({ default: 1 }) declare centerReveal: number
276
+
277
+ /** Each slice's fill, resolved once so `renderSelf` doesn't re-resolve every frame. */
278
+ private fills: FillResolved[][] = []
279
+
280
+ constructor(props?: NodeConfig<PieRing, PieRingProps>) {
281
+ super(props)
282
+
283
+ this.fills = this.slices.map((slice) => fillOps.resolve(slice.fill))
284
+
285
+ // One label per *drawn* slice (a zero-valued slice gets no wedge, so no
286
+ // label either), in whichever of the two forms the chart asked for. Both are
287
+ // real Text stacked in a hug vertical flow — the difference is only what they are
288
+ // pinned to and which line leads.
289
+ //
290
+ // The *point* each label is pinned to stays reactive and follows the ring as
291
+ // the box resizes or its slice pops out; only the choice of form, which
292
+ // depends on props alone, is settled here.
293
+ if (this.labelPlacement !== "none" && this.labelMode !== "none") {
294
+ for (const arc of this.arcs) this.addLabel(arc)
295
+ }
296
+
297
+ // The hole's summary, pinned to the ring's centre so it tracks the sideways
298
+ // shift a one-sided label column puts on the ring.
299
+ if (this.hasCenterLabel) this.addCenterLabel()
300
+ }
301
+
302
+ /** Build slice `arc`'s label, in whichever form the chart's placement asks for. */
303
+ private addLabel(arc: PieArc): void {
304
+ const slice = this.slices[arc.index]
305
+ // Fades in with the ring's labels, then dims along with its own slice
306
+ // whenever another slice takes the focus.
307
+ const opacity = () =>
308
+ clampUnit(this.labelReveal) * this.sliceOpacity(arc.index)
309
+ const wantsCategory =
310
+ this.labelMode === "both" || this.labelMode === "category"
311
+ const wantsPercent =
312
+ this.labelMode === "both" || this.labelMode === "percent"
313
+
314
+ if (this.labelPlacement === "inside") {
315
+ // The number leads and the caption sits under it: inside a wedge the
316
+ // reader already knows *which* wedge they are looking at, so the magnitude
317
+ // is what the label is for. Both sizes are bound rather than read once —
318
+ // the fitted size derives from the ring's radius, which isn't known until
319
+ // the node has been laid out.
320
+ const inside: Node2D[] = []
321
+ if (wantsPercent) {
322
+ inside.push(
323
+ new Text({
324
+ ...textOps.styleProps(this.label.insideStyle),
325
+ text: formatPercent(arc.fraction),
326
+ fontSize: () => this.insideFont,
327
+ })
328
+ )
329
+ }
330
+ if (wantsCategory) {
331
+ inside.push(
332
+ new Text({
333
+ ...textOps.styleProps(this.label.insideStyle),
334
+ text: slice.category,
335
+ fontSize: () =>
336
+ this.labelMode === "category"
337
+ ? this.insideFont
338
+ : this.insideFont * INSIDE_CAPTION_RATIO,
339
+ })
340
+ )
341
+ }
342
+ this.add(
343
+ new Rect({ flow: "vertical",
344
+ width: "hug",
345
+ height: "hug",
346
+ gap: 0,
347
+ align: "center",
348
+ opacity,
349
+ center: () => this.insideAnchor(arc.index),
350
+ children: inside,
351
+ })
352
+ )
353
+ return
354
+ }
355
+
356
+ const side = this.sideOf(arc.mid)
357
+ const at = () => this.placementFor(arc.index)?.text ?? { x: 0, y: 0 }
358
+ const children: Node2D[] = []
359
+ if (wantsCategory) {
360
+ children.push(
361
+ new Text({
362
+ ...textOps.styleProps(this.label.textStyle),
363
+ text: slice.category,
364
+ textAlign: side > 0 ? "left" : "right",
365
+ })
366
+ )
367
+ }
368
+ if (wantsPercent) {
369
+ children.push(
370
+ new Text({
371
+ ...textOps.styleProps(this.label.percentStyle),
372
+ text: formatPercent(arc.fraction),
373
+ textAlign: side > 0 ? "left" : "right",
374
+ })
375
+ )
376
+ }
377
+ this.add(
378
+ new Rect({ flow: "vertical",
379
+ width: "hug",
380
+ height: "hug",
381
+ gap: 2,
382
+ align: side > 0 ? "centerLeft" : "centerRight",
383
+ opacity,
384
+ // Exactly one of these is set; `undefined` anchors are ignored.
385
+ centerLeft: side > 0 ? at : undefined,
386
+ centerRight: side > 0 ? undefined : at,
387
+ children,
388
+ })
389
+ )
390
+ }
391
+
392
+ /** Build the hole's summary block. */
393
+ private addCenterLabel(): void {
394
+ const children: Node2D[] = []
395
+ if (this.centerLabel !== "") {
396
+ children.push(
397
+ new Text({
398
+ ...textOps.styleProps(this.centerStyle.labelStyle),
399
+ text: this.centerLabel,
400
+ fontSize: () => this.centerFont,
401
+ })
402
+ )
403
+ }
404
+ if (this.centerCaption !== "") {
405
+ children.push(
406
+ new Text({
407
+ ...textOps.styleProps(this.centerStyle.captionStyle),
408
+ text: this.centerCaption,
409
+ fontSize: () =>
410
+ this.centerFont *
411
+ (sizeOf(this.centerStyle.captionStyle, 22) /
412
+ sizeOf(this.centerStyle.labelStyle, 46)),
413
+ })
414
+ )
415
+ }
416
+ this.add(
417
+ new Rect({ flow: "vertical",
418
+ width: "hug",
419
+ height: "hug",
420
+ gap: 2,
421
+ align: "center",
422
+ opacity: () => clampUnit(this.centerReveal),
423
+ center: () => ({ x: this.centerX, y: 0 }),
424
+ children,
425
+ })
426
+ )
427
+ }
428
+
429
+ // ---- Arcs --------------------------------------------------------------
430
+
431
+ /** The drawn slices' angular spans, re-read every frame so a value tween re-cuts them. */
432
+ private get arcs(): PieArc[] {
433
+ return pieArcs(this.slices, this.ring.startAngle)
434
+ }
435
+
436
+ /** Which side a leader off bisector `mid` runs to: +1 right, −1 left. */
437
+ private sideOf(mid: number): 1 | -1 {
438
+ return Math.sin(mid) >= 0 ? 1 : -1
439
+ }
440
+
441
+ /** Whether any slice is labelled on a leader — the only thing that costs a gutter. */
442
+ private get hasLeaderLabels(): boolean {
443
+ return (
444
+ this.labelPlacement === "leader" &&
445
+ this.labelMode !== "none" &&
446
+ this.arcs.length > 0
447
+ )
448
+ }
449
+
450
+ // ---- Label sizing ------------------------------------------------------
451
+
452
+ /**
453
+ * How wide a horizontal label centred in slice `arc`'s band can run before it
454
+ * leaves the wedge, in px.
455
+ *
456
+ * Two things bound it, and which one binds depends entirely on where the wedge
457
+ * sits. Stepping sideways from the label's centre moves you *radially* by
458
+ * `dx·sin(mid)` and *tangentially* by `dx·cos(mid)`, so a wedge at 3 o'clock is
459
+ * limited by the band's thickness (its label runs straight across the band)
460
+ * while a wedge at 12 o'clock is limited by its own arc (its label runs along
461
+ * the band, which is much roomier). Taking the smaller of the two is what stops
462
+ * a label overflowing the ring on one chart and being pointlessly shrunk on the
463
+ * next.
464
+ *
465
+ * Measured off the *unpopped* radius, so a slice growing out of the ring
466
+ * doesn't resize its own text mid-animation.
467
+ */
468
+ private insideRoom(arc: PieArc): number {
469
+ const outer = this.outerRadius
470
+ const hole = this.holeRadius
471
+ const band = hole > 0 ? outer - hole : outer * (1 - PIE_LABEL_RADIUS) * 2
472
+ const mid = hole > 0 ? (hole + outer) / 2 : outer * PIE_LABEL_RADIUS
473
+ const sin = Math.abs(Math.sin(arc.mid))
474
+ const cos = Math.abs(Math.cos(arc.mid))
475
+ const acrossBand = sin > AXIS_EPSILON ? band / sin : Infinity
476
+ const alongArc = cos > AXIS_EPSILON ? ((arc.a1 - arc.a0) * mid) / cos : Infinity
477
+ return Math.max(0, Math.min(acrossBand, alongArc))
478
+ }
479
+
480
+ /** Widest line, in glyphs at the leading line's size, an inside label runs to. */
481
+ private insideGlyphs(arc: PieArc): number {
482
+ const category = this.slices[arc.index]?.category.length ?? 0
483
+ const percent =
484
+ this.labelMode === "both" || this.labelMode === "percent"
485
+ ? formatPercent(arc.fraction).length
486
+ : 0
487
+ // The caption is set at a fraction of the leading line, except when it *is*
488
+ // the leading line.
489
+ const caption =
490
+ this.labelMode === "category"
491
+ ? category
492
+ : this.labelMode === "both"
493
+ ? category * INSIDE_CAPTION_RATIO
494
+ : 0
495
+ return Math.max(1, percent, caption)
496
+ }
497
+
498
+ /**
499
+ * Font size of an inside label's leading line: what the theme asked for,
500
+ * shrunk if that wouldn't fit inside its wedge. **One size across every inside
501
+ * label** — the smallest any of them needs — because labels at mismatched
502
+ * sizes read as a mistake rather than as emphasis.
503
+ *
504
+ * So the theme's `insideStyle.fontSize` is an upper bound, not a promise: ask
505
+ * for the size the chart wants and the ring keeps it legal.
506
+ */
507
+ private get insideFont(): number {
508
+ let size = sizeOf(this.label.insideStyle, FALLBACK_SIZE * 1.9)
509
+ for (const arc of this.arcs) {
510
+ const fits =
511
+ (this.insideRoom(arc) * INSIDE_LABEL_FIT) /
512
+ (this.insideGlyphs(arc) * GLYPH_RATIO)
513
+ size = Math.min(size, fits)
514
+ }
515
+ return Math.max(1, size)
516
+ }
517
+
518
+ /** Whether the hole carries a summary at all. */
519
+ private get hasCenterLabel(): boolean {
520
+ return this.centerLabel !== "" || this.centerCaption !== ""
521
+ }
522
+
523
+ /**
524
+ * Font size of the hole's summary: the configured size, capped so it still
525
+ * fits across the hole. The cap matters because the hole's radius derives from
526
+ * the box, so a chart that reflows smaller would otherwise push its summary out
527
+ * through the ring.
528
+ */
529
+ private get centerFont(): number {
530
+ const wanted = sizeOf(this.centerStyle.labelStyle, 46)
531
+ const hole = this.holeRadius
532
+ if (hole <= 0) return wanted
533
+ const captionRatio =
534
+ sizeOf(this.centerStyle.captionStyle, 22) / Math.max(1, wanted)
535
+ // Both lines have to clear the hole, and the caption is set at a fraction of
536
+ // this size — so what binds is whichever is wider once drawn, not whichever
537
+ // has more characters.
538
+ const glyphs = Math.max(
539
+ 1,
540
+ this.centerLabel.length,
541
+ this.centerCaption.length * captionRatio
542
+ )
543
+ return Math.min(wanted, (hole * 2 * CENTER_LABEL_FIT) / (glyphs * GLYPH_RATIO))
544
+ }
545
+
546
+ // ---- Ring geometry, all derived from layoutBounds ------------------------
547
+
548
+ /** Rim radius of a fully selected slice as a multiple of the ring's, clamped sane. */
549
+ private get growFactor(): number {
550
+ return Math.max(1, Math.min(1.6, this.ring.selectedGrow))
551
+ }
552
+
553
+ /** How far past the ring's rim a fully selected slice reaches, in px. */
554
+ private get maxPop(): number {
555
+ return this.outerRadius * (this.growFactor - 1)
556
+ }
557
+
558
+ /** Height of one **leader** label block, in px — the unit those columns are spaced by. */
559
+ private get labelRowHeight(): number {
560
+ // Inside labels are stacked in the band, not in a column beside the ring, so
561
+ // they cost no vertical reserve.
562
+ if (!this.hasLeaderLabels) return 0
563
+ const caption = sizeOf(this.label.textStyle) * 1.25
564
+ const percent = sizeOf(this.label.percentStyle) * 1.25
565
+ if (this.labelMode === "both") return caption + percent + 2
566
+ return this.labelMode === "category" ? caption : percent
567
+ }
568
+
569
+ /** Widest line, in glyphs, that a leader label for slice `index` can run to. */
570
+ private captionGlyphs(index: number): number {
571
+ // "100%" is the widest a percentage gets; captions are their own length.
572
+ const percent =
573
+ this.labelMode === "percent" || this.labelMode === "both" ? 4 : 0
574
+ const category =
575
+ this.labelMode === "category" || this.labelMode === "both"
576
+ ? (this.slices[index]?.category.length ?? 0)
577
+ : 0
578
+ return Math.max(percent, category)
579
+ }
580
+
581
+ /**
582
+ * Horizontal room reserved on each side for the leaders and their labels, in
583
+ * px — measured **per side**, from the slices that actually leader out that
584
+ * way. A ring whose labels are all inside reserves nothing and draws bigger.
585
+ *
586
+ * Excludes the ring's own selection-growth allowance, which scales with the
587
+ * radius and so is divided out in {@link outerRadius} instead.
588
+ */
589
+ private get labelGutters(): { left: number; right: number } {
590
+ const gutters = { left: BARE_PAD, right: BARE_PAD }
591
+ if (!this.hasLeaderLabels) return gutters
592
+ const glyph = sizeOf(this.label.textStyle) * GLYPH_RATIO
593
+ for (const arc of this.arcs) {
594
+ const room =
595
+ LEADER_LENGTH +
596
+ LABEL_STUB +
597
+ TEXT_INSET +
598
+ this.captionGlyphs(arc.index) * glyph +
599
+ LABEL_PAD
600
+ const key = this.sideOf(arc.mid) > 0 ? "right" : "left"
601
+ gutters[key] = Math.max(gutters[key], room)
602
+ }
603
+ return gutters
604
+ }
605
+
606
+ /**
607
+ * How far the ring's centre sits from the node's, in px. Zero while the
608
+ * gutters match; when the labels all fall one way it slides the ring into the
609
+ * empty half so the ring-plus-labels group stays centred in the box instead of
610
+ * the ring sitting dead centre with a bald patch beside it.
611
+ */
612
+ private get centerX(): number {
613
+ const { left, right } = this.labelGutters
614
+ return (left - right) / 2
615
+ }
616
+
617
+ /**
618
+ * Radius of the ring's outer edge, fitted to whatever the label gutters leave.
619
+ * A fully selected slice reaches `radius × growFactor`, so the room has to
620
+ * cover that — hence the divisor, which keeps even the grown slice inside the
621
+ * box (and holds the ring the same size whether or not anything is selected).
622
+ */
623
+ private get outerRadius(): number {
624
+ const { left, right } = this.labelGutters
625
+ const room = Math.min(
626
+ (this.layoutBounds.width - left - right) / 2,
627
+ this.layoutBounds.height / 2 - this.labelRowHeight - 4
628
+ )
629
+ return Math.max(0, room / this.growFactor)
630
+ }
631
+
632
+ /** Radius of the hole in the middle: a fraction of the outer radius, or explicit px. */
633
+ private get holeRadius(): number {
634
+ const configured = this.ring.holeRadius
635
+ if (configured <= 0) return 0
636
+ const px = configured < 1 ? configured * this.outerRadius : configured
637
+ return Math.min(px, this.outerRadius * 0.95)
638
+ }
639
+
640
+ /** Radius of the circle every leader elbows on, clear of even a popped-out slice. */
641
+ private get elbowRadius(): number {
642
+ return this.outerRadius + this.maxPop + LEADER_LENGTH
643
+ }
644
+
645
+ /** How far slice `index` is currently pushed out, in `[0, 1]`. */
646
+ private popOf(index: number): number {
647
+ return clampUnit(this.pops[index] ?? 0)
648
+ }
649
+
650
+ /** Radius of slice `index`'s outer edge, its selection growth included. */
651
+ private anchorRadius(index: number): number {
652
+ return this.outerRadius + this.maxPop * this.popOf(index)
653
+ }
654
+
655
+ /**
656
+ * Radius an inside label sits at on slice `index`: halfway across the band on a
657
+ * donut, and further out than halfway on a solid pie, where "halfway" would
658
+ * crowd the point every wedge converges on. Rides the slice's own pop, so an
659
+ * inside label travels out with the wedge it belongs to.
660
+ */
661
+ private bandMidRadius(index: number): number {
662
+ const rim = this.anchorRadius(index)
663
+ const hole = this.holeRadius
664
+ return hole > 0 ? (hole + rim) / 2 : rim * PIE_LABEL_RADIUS
665
+ }
666
+
667
+ /** Node2D-space point slice `index`'s inside label is centred on. */
668
+ private insideAnchor(index: number): Vector2 {
669
+ const arc = this.arcs.find((a) => a.index === index)
670
+ if (arc === undefined) return { x: this.centerX, y: 0 }
671
+ const point = ringPoint(this.bandMidRadius(index), arc.mid)
672
+ return { x: point.x + this.centerX, y: point.y }
673
+ }
674
+
675
+ /**
676
+ * How selected the ring is overall, in `[0, 1]` — the most-grown slice. Rides
677
+ * the same tween the pops do, so the dim below arrives with the growth rather
678
+ * than needing an animation of its own.
679
+ */
680
+ private get selectionStrength(): number {
681
+ let strongest = 0
682
+ for (let i = 0; i < this.slices.length; i++) {
683
+ strongest = Math.max(strongest, this.popOf(i))
684
+ }
685
+ return strongest
686
+ }
687
+
688
+ /**
689
+ * Opacity slice `index` (and its leader and label) is drawn at: full while
690
+ * nothing is selected, falling toward {@link dimOpacity} in proportion to how
691
+ * selected the *rest* of the ring is. A slice that's selected itself stays at
692
+ * full — the two factors cancel.
693
+ */
694
+ private sliceOpacity(index: number): number {
695
+ const focus = this.selectionStrength
696
+ if (focus <= 0) return 1
697
+ return 1 - (1 - clampUnit(this.dimOpacity)) * focus * (1 - this.popOf(index))
698
+ }
699
+
700
+ // ---- Label placement ---------------------------------------------------
701
+
702
+ /**
703
+ * Where every leader label sits and how its leader gets there. Labels are split
704
+ * into a right and a left column by their slice's bisector, each column is
705
+ * spread so nothing overlaps (and nothing leaves the box), and each leader is
706
+ * then built as wedge edge → elbow → label. The elbow rides the leader circle at
707
+ * the label's *settled* y, which keeps the final run horizontal and the whole
708
+ * polyline outside the ring however far the label was nudged.
709
+ */
710
+ private placements(): LabelPlacement[] {
711
+ if (!this.hasLeaderLabels) return []
712
+ const arcs = this.arcs
713
+ if (arcs.length === 0 || this.outerRadius <= 0) return []
714
+
715
+ const radius = this.elbowRadius
716
+ const rowHeight = this.labelRowHeight
717
+ const top = this.layoutBounds.height / 2 - rowHeight / 2
718
+ const bottom = -top
719
+ const cx = this.centerX
720
+
721
+ interface Slot {
722
+ index: number
723
+ side: 1 | -1
724
+ mid: number
725
+ ideal: number
726
+ y: number
727
+ }
728
+ const right: Slot[] = []
729
+ const left: Slot[] = []
730
+ for (const arc of arcs) {
731
+ const side = this.sideOf(arc.mid)
732
+ const ideal = ringPoint(radius, arc.mid).y
733
+ ;(side > 0 ? right : left).push({
734
+ index: arc.index,
735
+ side,
736
+ mid: arc.mid,
737
+ ideal,
738
+ y: ideal,
739
+ })
740
+ }
741
+ relaxLabels(right, rowHeight + LABEL_GAP, top, bottom)
742
+ relaxLabels(left, rowHeight + LABEL_GAP, top, bottom)
743
+
744
+ return [...right, ...left].map((slot) => {
745
+ const start = ringPoint(
746
+ this.anchorRadius(slot.index) + LEADER_LIFTOFF,
747
+ slot.mid
748
+ )
749
+ // The elbow sits where the label's y crosses the leader circle. Solving
750
+ // x² + y² = radius² for x keeps it *on* that circle (never inside the
751
+ // ring); a label pushed past the circle's top or bottom falls back to the
752
+ // sideways floor so its leader still reads as pointing outward.
753
+ const onCircle = Math.sqrt(
754
+ Math.max(0, radius * radius - slot.y * slot.y)
755
+ )
756
+ const elbowX = cx + slot.side * Math.max(onCircle, radius * MIN_ELBOW)
757
+ const endX = cx + slot.side * (radius + LABEL_STUB)
758
+
759
+ return {
760
+ index: slot.index,
761
+ side: slot.side,
762
+ leader: [
763
+ { x: start.x + cx, y: start.y },
764
+ { x: elbowX, y: slot.y },
765
+ { x: endX, y: slot.y },
766
+ ],
767
+ text: { x: endX + slot.side * TEXT_INSET, y: slot.y },
768
+ }
769
+ })
770
+ }
771
+
772
+ /** This frame's placement for slice `index`, or `undefined` if it isn't leadered. */
773
+ private placementFor(index: number): LabelPlacement | undefined {
774
+ return this.placements().find((placement) => placement.index === index)
775
+ }
776
+
777
+ // ---- Draw --------------------------------------------------------------
778
+
779
+ /**
780
+ * The ring's paints live nowhere `ShapeNode` would look: one fill per slice,
781
+ * resolved once into {@link fills}, plus the leader line's own stroke. Both are
782
+ * passed explicitly — see {@link declarePaints}.
783
+ */
784
+ override declareAssets(assets: AssetScope): void {
785
+ super.declareAssets(assets)
786
+ declarePaints(this, assets, {
787
+ fills: this.fills,
788
+ strokes: [strokeOps.resolve(this.label.leaderStroke)],
789
+ })
790
+ }
791
+
792
+ protected renderSelf(ctx: RenderContext2D): void {
793
+ const rOuter = this.outerRadius
794
+ if (rOuter <= 0) return
795
+
796
+ const arcs = this.arcs
797
+ if (arcs.length === 0) return
798
+
799
+ const sweep = clampUnit(this.growth)
800
+ const revealEnd = this.ring.startAngle * (Math.PI / 180) + Math.PI * 2 * sweep
801
+ const hole = this.holeRadius
802
+ const halfGap = Math.max(0, this.ring.gap) / 2
803
+
804
+ // One shared frame (the whole ring square, grown slices included) pinned onto
805
+ // every wedge path, so `Graphics2D.path()` doesn't re-centre each wedge on its
806
+ // own bbox and collapse them all onto the origin. It stays symmetric about the
807
+ // *node's* origin — so path coordinates land exactly in node space — and is
808
+ // grown by the ring's sideways offset rather than moved with it, which would
809
+ // undo the very shift it has to contain.
810
+ const cx = this.centerX
811
+ const half = rOuter + this.maxPop + 1 + Math.abs(cx)
812
+ const centerBounds: [number, number, number, number] = [
813
+ -half,
814
+ -half,
815
+ half,
816
+ half,
817
+ ]
818
+ // Explicit width/height alongside centerBounds: a wedge path's command list
819
+ // carries no implied extent, so a slice filled with an image or a video needs
820
+ // this to size its decode.
821
+ const span = half * 2
822
+
823
+ for (const arc of arcs) {
824
+ // Clip the wedge to the growth-revealed arc; skip it until the sweep
825
+ // reaches it, so the ring draws in as one clockwise wipe.
826
+ const a1 = Math.min(arc.a1, revealEnd)
827
+ if (a1 <= arc.a0) continue
828
+
829
+ const path = wedgePath(
830
+ arc.a0,
831
+ a1,
832
+ hole,
833
+ this.anchorRadius(arc.index),
834
+ halfGap,
835
+ cx
836
+ )
837
+ const g = new Graphics2D().path(
838
+ path.toPathState({ centerBounds, width: span, height: span })
839
+ )
840
+ g.shadow(this.ring.shadow)
841
+ g.fill(this.fills[arc.index] ?? [])
842
+ g.stroke(this.ring.stroke)
843
+ ctx.draw(g.opacity(this.sliceOpacity(arc.index)))
844
+ }
845
+
846
+ // Leaders. Each polyline gets its own `Graphics2D`: several open polylines
847
+ // chained into one command list are combined into a single surface before the
848
+ // stroke, which closes each contour back on itself and paints the leaders as
849
+ // thin triangles.
850
+ const reveal = clampUnit(this.labelReveal)
851
+ if (reveal <= 0.001) return
852
+ for (const placement of this.placements()) {
853
+ ctx.draw(
854
+ new Graphics2D()
855
+ .line({ points: placement.leader, radius: ELBOW_RADIUS })
856
+ .stroke(this.label.leaderStroke)
857
+ .opacity(reveal * this.sliceOpacity(placement.index))
858
+ )
859
+ }
860
+ }
861
+
862
+ // ---- Entrance ----------------------------------------------------------
863
+
864
+ /** Tween {@link growth} `0 → 1`, wiping the wedges in around the ring. */
865
+ @command()
866
+ sweep(
867
+ args: CommandArgs<Record<string, never>> & { duration: number }
868
+ ): Command<RingSweep> {
869
+ // No priming to 0 first — the value at `t` is a function of `t`, so a repeat
870
+ // call re-sweeps by definition rather than by having reset something.
871
+ return this.command<RingSweep>((t) => ({ growth: t }), args.duration, args.easing ?? easeOut())
872
+ }
873
+
874
+ /** Tween {@link labelReveal} `0 → 1`, fading the leaders and captions up. */
875
+ @command()
876
+ revealLabels(
877
+ args: CommandArgs<Record<string, never>> & { duration: number }
878
+ ): Command<RingLabels> {
879
+ return this.command<RingLabels>((t) => ({ labelReveal: t }), args.duration, args.easing ?? easeOut())
880
+ }
881
+
882
+ /**
883
+ * Fade the hole's summary up. Deliberately not part of the ring's entrance: a
884
+ * hole label is usually the chart's conclusion, so the scene decides when it
885
+ * lands.
886
+ */
887
+ @command()
888
+ revealCenter(
889
+ args: CommandArgs<Record<string, never>> & { duration?: number } = {}
890
+ ): Command<RingCenter> {
891
+ const from = clampUnit(this.centerReveal)
892
+ return this.command<RingCenter>(
893
+ (t) => ({ centerReveal: from + (1 - from) * t }),
894
+ args.duration ?? 0.6,
895
+ args.easing ?? easeOut()
896
+ )
897
+ }
898
+ }
899
+
900
+ /** The signals the ring's own commands move, as props types. */
901
+ type RingSweep = { growth: number }
902
+ type RingLabels = { labelReveal: number }
903
+ type RingCenter = { centerReveal: number }