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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +49 -0
  4. package/README.md +98 -3
  5. package/dist/bar-chart/bar-chart.d.ts +191 -0
  6. package/dist/bar-chart/bar-chart.d.ts.map +1 -0
  7. package/dist/bar-chart/bar-chart.js +431 -0
  8. package/dist/bar-chart/bar-chart.js.map +1 -0
  9. package/dist/bar-chart/category-axis.d.ts +71 -0
  10. package/dist/bar-chart/category-axis.d.ts.map +1 -0
  11. package/dist/bar-chart/category-axis.js +119 -0
  12. package/dist/bar-chart/category-axis.js.map +1 -0
  13. package/dist/bar-chart/chart-bars.d.ts +129 -0
  14. package/dist/bar-chart/chart-bars.d.ts.map +1 -0
  15. package/dist/bar-chart/chart-bars.js +181 -0
  16. package/dist/bar-chart/chart-bars.js.map +1 -0
  17. package/dist/bar-chart/index.d.ts +16 -0
  18. package/dist/bar-chart/index.d.ts.map +1 -0
  19. package/dist/bar-chart/index.js +12 -0
  20. package/dist/bar-chart/index.js.map +1 -0
  21. package/dist/bar-chart/shared.d.ts +146 -0
  22. package/dist/bar-chart/shared.d.ts.map +1 -0
  23. package/dist/bar-chart/shared.js +182 -0
  24. package/dist/bar-chart/shared.js.map +1 -0
  25. package/dist/browser/chunks/chunk-TJNHLQGV.js +2 -0
  26. package/dist/browser/chunks/chunk-TJNHLQGV.js.map +7 -0
  27. package/dist/browser/index.js +2 -0
  28. package/dist/browser/index.js.map +7 -0
  29. package/dist/browser/kit.js +2 -0
  30. package/dist/browser/kit.js.map +7 -0
  31. package/dist/browser/manifest.json +13 -0
  32. package/dist/engine.d.ts +29 -0
  33. package/dist/engine.d.ts.map +1 -0
  34. package/dist/engine.js +29 -0
  35. package/dist/engine.js.map +1 -0
  36. package/dist/index.d.ts +6 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +6 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/kit/cartesian.d.ts +44 -0
  41. package/dist/kit/cartesian.d.ts.map +1 -0
  42. package/dist/kit/cartesian.js +59 -0
  43. package/dist/kit/cartesian.js.map +1 -0
  44. package/dist/kit/chart-border.d.ts +27 -0
  45. package/dist/kit/chart-border.d.ts.map +1 -0
  46. package/dist/kit/chart-border.js +28 -0
  47. package/dist/kit/chart-border.js.map +1 -0
  48. package/dist/kit/chart-canvas.d.ts +67 -0
  49. package/dist/kit/chart-canvas.d.ts.map +1 -0
  50. package/dist/kit/chart-canvas.js +68 -0
  51. package/dist/kit/chart-canvas.js.map +1 -0
  52. package/dist/kit/chart-legend.d.ts +164 -0
  53. package/dist/kit/chart-legend.d.ts.map +1 -0
  54. package/dist/kit/chart-legend.js +163 -0
  55. package/dist/kit/chart-legend.js.map +1 -0
  56. package/dist/kit/entries.d.ts +17 -0
  57. package/dist/kit/entries.d.ts.map +1 -0
  58. package/dist/kit/entries.js +19 -0
  59. package/dist/kit/entries.js.map +1 -0
  60. package/dist/kit/motion.d.ts +48 -0
  61. package/dist/kit/motion.d.ts.map +1 -0
  62. package/dist/kit/motion.js +63 -0
  63. package/dist/kit/motion.js.map +1 -0
  64. package/dist/kit/paints.d.ts +10 -0
  65. package/dist/kit/paints.d.ts.map +1 -0
  66. package/dist/kit/paints.js +12 -0
  67. package/dist/kit/paints.js.map +1 -0
  68. package/dist/kit/shared.d.ts +302 -0
  69. package/dist/kit/shared.d.ts.map +1 -0
  70. package/dist/kit/shared.js +496 -0
  71. package/dist/kit/shared.js.map +1 -0
  72. package/dist/kit/vertical-axis.d.ts +86 -0
  73. package/dist/kit/vertical-axis.d.ts.map +1 -0
  74. package/dist/kit/vertical-axis.js +141 -0
  75. package/dist/kit/vertical-axis.js.map +1 -0
  76. package/dist/line-chart/chart-line.d.ts +74 -0
  77. package/dist/line-chart/chart-line.d.ts.map +1 -0
  78. package/dist/line-chart/chart-line.js +135 -0
  79. package/dist/line-chart/chart-line.js.map +1 -0
  80. package/dist/line-chart/chart-region.d.ts +46 -0
  81. package/dist/line-chart/chart-region.d.ts.map +1 -0
  82. package/dist/line-chart/chart-region.js +67 -0
  83. package/dist/line-chart/chart-region.js.map +1 -0
  84. package/dist/line-chart/horizontal-axis.d.ts +79 -0
  85. package/dist/line-chart/horizontal-axis.d.ts.map +1 -0
  86. package/dist/line-chart/horizontal-axis.js +129 -0
  87. package/dist/line-chart/horizontal-axis.js.map +1 -0
  88. package/dist/line-chart/index.d.ts +22 -0
  89. package/dist/line-chart/index.d.ts.map +1 -0
  90. package/dist/line-chart/index.js +19 -0
  91. package/dist/line-chart/index.js.map +1 -0
  92. package/dist/line-chart/line-chart.d.ts +200 -0
  93. package/dist/line-chart/line-chart.d.ts.map +1 -0
  94. package/dist/line-chart/line-chart.js +473 -0
  95. package/dist/line-chart/line-chart.js.map +1 -0
  96. package/dist/line-chart/shared.d.ts +171 -0
  97. package/dist/line-chart/shared.d.ts.map +1 -0
  98. package/dist/line-chart/shared.js +285 -0
  99. package/dist/line-chart/shared.js.map +1 -0
  100. package/dist/line-chart/x-scale.d.ts +77 -0
  101. package/dist/line-chart/x-scale.d.ts.map +1 -0
  102. package/dist/line-chart/x-scale.js +313 -0
  103. package/dist/line-chart/x-scale.js.map +1 -0
  104. package/dist/nodes.d.ts +17 -0
  105. package/dist/nodes.d.ts.map +1 -0
  106. package/dist/nodes.js +18 -0
  107. package/dist/nodes.js.map +1 -0
  108. package/dist/pie-chart/index.d.ts +18 -0
  109. package/dist/pie-chart/index.d.ts.map +1 -0
  110. package/dist/pie-chart/index.js +14 -0
  111. package/dist/pie-chart/index.js.map +1 -0
  112. package/dist/pie-chart/pie-chart.d.ts +152 -0
  113. package/dist/pie-chart/pie-chart.d.ts.map +1 -0
  114. package/dist/pie-chart/pie-chart.js +222 -0
  115. package/dist/pie-chart/pie-chart.js.map +1 -0
  116. package/dist/pie-chart/pie-legend.d.ts +113 -0
  117. package/dist/pie-chart/pie-legend.d.ts.map +1 -0
  118. package/dist/pie-chart/pie-legend.js +117 -0
  119. package/dist/pie-chart/pie-legend.js.map +1 -0
  120. package/dist/pie-chart/pie-ring.d.ts +304 -0
  121. package/dist/pie-chart/pie-ring.d.ts.map +1 -0
  122. package/dist/pie-chart/pie-ring.js +680 -0
  123. package/dist/pie-chart/pie-ring.js.map +1 -0
  124. package/dist/pie-chart/shared.d.ts +216 -0
  125. package/dist/pie-chart/shared.d.ts.map +1 -0
  126. package/dist/pie-chart/shared.js +246 -0
  127. package/dist/pie-chart/shared.js.map +1 -0
  128. package/package.json +72 -3
  129. package/registry.json +23 -0
  130. package/src/bar-chart/bar-chart.ts +542 -0
  131. package/src/bar-chart/category-axis.ts +162 -0
  132. package/src/bar-chart/chart-bars.ts +287 -0
  133. package/src/bar-chart/index.ts +31 -0
  134. package/src/bar-chart/shared.ts +354 -0
  135. package/src/engine.ts +28 -0
  136. package/src/index.ts +5 -0
  137. package/src/kit/cartesian.ts +81 -0
  138. package/src/kit/chart-border.ts +50 -0
  139. package/src/kit/chart-canvas.ts +122 -0
  140. package/src/kit/chart-legend.ts +229 -0
  141. package/src/kit/entries.ts +20 -0
  142. package/src/kit/motion.ts +90 -0
  143. package/src/kit/paints.ts +15 -0
  144. package/src/kit/shared.ts +782 -0
  145. package/src/kit/vertical-axis.ts +194 -0
  146. package/src/line-chart/chart-line.ts +156 -0
  147. package/src/line-chart/chart-region.ts +90 -0
  148. package/src/line-chart/horizontal-axis.ts +151 -0
  149. package/src/line-chart/index.ts +39 -0
  150. package/src/line-chart/line-chart.ts +598 -0
  151. package/src/line-chart/shared.ts +473 -0
  152. package/src/line-chart/x-scale.ts +382 -0
  153. package/src/nodes.ts +18 -0
  154. package/src/pie-chart/index.ts +37 -0
  155. package/src/pie-chart/pie-chart.ts +296 -0
  156. package/src/pie-chart/pie-legend.ts +169 -0
  157. package/src/pie-chart/pie-ring.ts +848 -0
  158. package/src/pie-chart/shared.ts +496 -0
@@ -0,0 +1,680 @@
1
+ import { Graphics2D, PathBuilder, Rect, Text, Types, component2d, fillOps, shadowOps, strokeOps, textOps, } from "@motionscript/sdk";
2
+ import { asParts, fresh } from "../kit/entries.js";
3
+ import { frameEase } from "../kit/motion.js";
4
+ import { loadPaints } from "../kit/paints.js";
5
+ import { clampUnit, formatPercent } from "../kit/shared.js";
6
+ import { DEFAULT_PIE_CHART_THEME, pieArcs, relaxLabels, ringPoint, } from "./shared.js";
7
+ /** Vertical breathing room between one label block and the next, in px. */
8
+ const LABEL_GAP = 12;
9
+ /** Breathing room past the outermost label, so it never touches the node's edge, in px. */
10
+ const LABEL_PAD = 14;
11
+ /** Rough width of one glyph as a fraction of the font size, for gutter sizing. */
12
+ const GLYPH_RATIO = 0.62;
13
+ /** Gap between a wedge's outer edge and where its leader lifts off, in px. */
14
+ const LEADER_LIFTOFF = 6;
15
+ /** How far past the ring's outer edge a leader runs before it elbows, in px. */
16
+ const LEADER_LENGTH = 34;
17
+ /** Horizontal run from the elbow to the label, in px. */
18
+ const LABEL_STUB = 26;
19
+ /** Gap between a leader's end and the label text it points at, in px. */
20
+ const TEXT_INSET = 8;
21
+ /**
22
+ * Floor on the elbow's horizontal distance from the ring's axis, as a fraction
23
+ * of the leader radius — so a label pushed clear above (or below) the ring still
24
+ * elbows out sideways rather than running straight down the 12 o'clock line.
25
+ */
26
+ const MIN_ELBOW = 0.18;
27
+ /** Segments used to tessellate a full turn of arc; a wedge takes its share. */
28
+ const ARC_STEPS = 240;
29
+ /** Rounding applied to the leader's elbow, in px. */
30
+ const ELBOW_RADIUS = 8;
31
+ /** Side padding used when nothing is leadered out — no gutter to reserve. */
32
+ const BARE_PAD = 2;
33
+ /** An inside label's caption size, as a fraction of its leading line. */
34
+ const INSIDE_CAPTION_RATIO = 0.44;
35
+ /**
36
+ * Where an inside label sits on a **solid pie** (no hole to split the band
37
+ * with), as a fraction of the wedge's radius — far enough out that the label
38
+ * clears the point every wedge converges on.
39
+ */
40
+ const PIE_LABEL_RADIUS = 0.62;
41
+ /** Fraction of the hole's diameter its summary is allowed to run to. */
42
+ const CENTER_LABEL_FIT = 0.78;
43
+ /** Fraction of the room inside a wedge that its label is allowed to run to. */
44
+ const INSIDE_LABEL_FIT = 0.9;
45
+ /** Below this, a wedge's bisector counts as axis-aligned and that term stops binding. */
46
+ const AXIS_EPSILON = 1e-3;
47
+ /** Fallback type size when a theme style leaves it unset or on autofit. */
48
+ const FALLBACK_SIZE = 26;
49
+ /** A style's numeric size, guarding the autofit and unset cases. */
50
+ function sizeOf(style, fallback = FALLBACK_SIZE) {
51
+ const size = style.fontSize;
52
+ return typeof size === "number" ? size : fallback;
53
+ }
54
+ /**
55
+ * A ring-band wedge over `a0`→`a1` (radians, clockwise from 12 o'clock) spanning
56
+ * `rInner`→`rOuter`, centred on `cx`. Ring wedges trace the outer arc, step in,
57
+ * and trace the inner arc back; full pie wedges (`rInner <= 0`) close through the
58
+ * centre.
59
+ *
60
+ * `halfGap` is **half the gap to the neighbouring slice, in px**, shaved off both
61
+ * ends of the wedge. It's converted to an angle *per radius* (`halfGap / r` — a
62
+ * wider angle near the hole than out at the rim), which is what keeps the channel
63
+ * between two slices the same width all the way across the band. A fixed angular
64
+ * gap instead reads as a thin pizza slice: right at the rim, pinched shut at the
65
+ * hole. The inset is capped at the wedge's own half-span so a sliver of a slice
66
+ * narrows to nothing rather than turning inside out.
67
+ */
68
+ function wedgePath(a0, a1, rInner, rOuter, halfGap, cx) {
69
+ const path = new PathBuilder();
70
+ const span = a1 - a0;
71
+ const steps = Math.max(2, Math.ceil((Math.abs(span) / (Math.PI * 2)) * ARC_STEPS));
72
+ /** Angular inset at radius `r` that puts the wedge's edge `halfGap` px off the divide. */
73
+ const insetAt = (r) => r <= 0 ? 0 : Math.min(halfGap / r, span / 2.2);
74
+ const arcTo = (r, i) => {
75
+ const inset = insetAt(r);
76
+ const from = a0 + inset;
77
+ const to = a1 - inset;
78
+ const point = ringPoint(r, from + ((to - from) * i) / steps);
79
+ return { x: point.x + cx, y: point.y };
80
+ };
81
+ if (rInner <= 0) {
82
+ // Solid pie wedge: the sides converge on the centre, so only the outer rim
83
+ // carries the gap.
84
+ path.moveTo(cx, 0);
85
+ for (let i = 0; i <= steps; i++) {
86
+ const p = arcTo(rOuter, i);
87
+ path.lineTo(p.x, p.y);
88
+ }
89
+ path.close();
90
+ return path;
91
+ }
92
+ for (let i = 0; i <= steps; i++) {
93
+ const p = arcTo(rOuter, i);
94
+ if (i === 0)
95
+ path.moveTo(p.x, p.y);
96
+ else
97
+ path.lineTo(p.x, p.y);
98
+ }
99
+ // Back along the inner arc — its own (wider) inset makes each side edge a
100
+ // straight chord sitting `halfGap` px off the divide at both ends.
101
+ for (let i = steps; i >= 0; i--) {
102
+ const p = arcTo(rInner, i);
103
+ path.lineTo(p.x, p.y);
104
+ }
105
+ path.close();
106
+ return path;
107
+ }
108
+ /**
109
+ * The ring's geometry for one box: every radius, gutter and label position,
110
+ * derived from the entries and the size the ring was laid out at, and asked
111
+ * afresh wherever it is read — the drawing, and the labels' bound positions
112
+ * and sizes alike, so the two cannot disagree.
113
+ */
114
+ export class RingGeometry {
115
+ s;
116
+ box;
117
+ constructor(s, box) {
118
+ this.s = s;
119
+ this.box = box;
120
+ }
121
+ /** The drawn slices' angular spans, re-read every frame so a value tween re-cuts them. */
122
+ get arcs() {
123
+ return pieArcs(this.s.slices, this.s.ring.startAngle);
124
+ }
125
+ /** Whether any slice is labelled on a leader — the only thing that costs a gutter. */
126
+ get hasLeaderLabels() {
127
+ return this.s.labelPlacement === "leader" && this.s.labelMode !== "none" && this.arcs.length > 0;
128
+ }
129
+ // ---- Label sizing ------------------------------------------------------
130
+ /**
131
+ * How wide a horizontal label centred in slice `arc`'s band can run before it
132
+ * leaves the wedge, in px.
133
+ *
134
+ * Two things bound it, and which one binds depends entirely on where the wedge
135
+ * sits. Stepping sideways from the label's centre moves you *radially* by
136
+ * `dx·sin(mid)` and *tangentially* by `dx·cos(mid)`, so a wedge at 3 o'clock is
137
+ * limited by the band's thickness (its label runs straight across the band)
138
+ * while a wedge at 12 o'clock is limited by its own arc (its label runs along
139
+ * the band, which is much roomier). Taking the smaller of the two is what stops
140
+ * a label overflowing the ring on one chart and being pointlessly shrunk on the
141
+ * next.
142
+ *
143
+ * Measured off the *unpopped* radius, so a slice growing out of the ring
144
+ * doesn't resize its own text mid-animation.
145
+ */
146
+ insideRoom(arc) {
147
+ const outer = this.outerRadius;
148
+ const hole = this.holeRadius;
149
+ const band = hole > 0 ? outer - hole : outer * (1 - PIE_LABEL_RADIUS) * 2;
150
+ const mid = hole > 0 ? (hole + outer) / 2 : outer * PIE_LABEL_RADIUS;
151
+ const sin = Math.abs(Math.sin(arc.mid));
152
+ const cos = Math.abs(Math.cos(arc.mid));
153
+ const acrossBand = sin > AXIS_EPSILON ? band / sin : Infinity;
154
+ const alongArc = cos > AXIS_EPSILON ? ((arc.a1 - arc.a0) * mid) / cos : Infinity;
155
+ return Math.max(0, Math.min(acrossBand, alongArc));
156
+ }
157
+ /** Widest line, in glyphs at the leading line's size, an inside label runs to. */
158
+ insideGlyphs(arc) {
159
+ const mode = this.s.labelMode;
160
+ const category = this.s.slices[arc.index]?.category.length ?? 0;
161
+ const percent = mode === "both" || mode === "percent" ? formatPercent(arc.fraction).length : 0;
162
+ // The caption is set at a fraction of the leading line, except when it *is*
163
+ // the leading line.
164
+ const caption = mode === "category" ? category : mode === "both" ? category * INSIDE_CAPTION_RATIO : 0;
165
+ return Math.max(1, percent, caption);
166
+ }
167
+ /**
168
+ * Font size of an inside label's leading line: what the theme asked for,
169
+ * shrunk if that wouldn't fit inside its wedge. **One size across every inside
170
+ * label** — the smallest any of them needs — because labels at mismatched
171
+ * sizes read as a mistake rather than as emphasis.
172
+ *
173
+ * So the theme's `insideStyle.fontSize` is an upper bound, not a promise: ask
174
+ * for the size the chart wants and the ring keeps it legal.
175
+ */
176
+ get insideFont() {
177
+ let size = sizeOf(this.s.label.insideStyle, FALLBACK_SIZE * 1.9);
178
+ for (const arc of this.arcs) {
179
+ const fits = (this.insideRoom(arc) * INSIDE_LABEL_FIT) / (this.insideGlyphs(arc) * GLYPH_RATIO);
180
+ size = Math.min(size, fits);
181
+ }
182
+ return Math.max(1, size);
183
+ }
184
+ /**
185
+ * Font size of the hole's summary: the configured size, capped so it still
186
+ * fits across the hole. The cap matters because the hole's radius derives from
187
+ * the box, so a chart that reflows smaller would otherwise push its summary out
188
+ * through the ring.
189
+ */
190
+ get centerFont() {
191
+ const { centerStyle, centerLabel, centerCaption } = this.s;
192
+ const wanted = sizeOf(centerStyle.labelStyle, 46);
193
+ const hole = this.holeRadius;
194
+ if (hole <= 0)
195
+ return wanted;
196
+ const captionRatio = sizeOf(centerStyle.captionStyle, 22) / Math.max(1, wanted);
197
+ // Both lines have to clear the hole, and the caption is set at a fraction of
198
+ // this size — so what binds is whichever is wider once drawn, not whichever
199
+ // has more characters.
200
+ const glyphs = Math.max(1, centerLabel.length, centerCaption.length * captionRatio);
201
+ return Math.min(wanted, (hole * 2 * CENTER_LABEL_FIT) / (glyphs * GLYPH_RATIO));
202
+ }
203
+ // ---- Ring geometry, all derived from the box ---------------------------
204
+ /** Rim radius of a fully selected slice as a multiple of the ring's, clamped sane. */
205
+ get growFactor() {
206
+ return Math.max(1, Math.min(1.6, this.s.ring.selectedGrow));
207
+ }
208
+ /** How far past the ring's rim a fully selected slice reaches, in px. */
209
+ get maxPop() {
210
+ return this.outerRadius * (this.growFactor - 1);
211
+ }
212
+ /** Height of one **leader** label block, in px — the unit those columns are spaced by. */
213
+ get labelRowHeight() {
214
+ // Inside labels are stacked in the band, not in a column beside the ring, so
215
+ // they cost no vertical reserve.
216
+ if (!this.hasLeaderLabels)
217
+ return 0;
218
+ const caption = sizeOf(this.s.label.textStyle) * 1.25;
219
+ const percent = sizeOf(this.s.label.percentStyle) * 1.25;
220
+ if (this.s.labelMode === "both")
221
+ return caption + percent + 2;
222
+ return this.s.labelMode === "category" ? caption : percent;
223
+ }
224
+ /** Widest line, in glyphs, that a leader label for slice `index` can run to. */
225
+ captionGlyphs(index) {
226
+ const mode = this.s.labelMode;
227
+ // "100%" is the widest a percentage gets; captions are their own length.
228
+ const percent = mode === "percent" || mode === "both" ? 4 : 0;
229
+ const category = mode === "category" || mode === "both" ? (this.s.slices[index]?.category.length ?? 0) : 0;
230
+ return Math.max(percent, category);
231
+ }
232
+ /**
233
+ * Horizontal room reserved on each side for the leaders and their labels, in
234
+ * px — measured **per side**, from the slices that actually leader out that
235
+ * way. A ring whose labels are all inside reserves nothing and draws bigger.
236
+ *
237
+ * Excludes the ring's own selection-growth allowance, which scales with the
238
+ * radius and so is divided out in {@link outerRadius} instead.
239
+ */
240
+ get labelGutters() {
241
+ const gutters = { left: BARE_PAD, right: BARE_PAD };
242
+ if (!this.hasLeaderLabels)
243
+ return gutters;
244
+ const glyph = sizeOf(this.s.label.textStyle) * GLYPH_RATIO;
245
+ for (const arc of this.arcs) {
246
+ const room = LEADER_LENGTH + LABEL_STUB + TEXT_INSET + this.captionGlyphs(arc.index) * glyph + LABEL_PAD;
247
+ const key = sideOf(arc.mid) > 0 ? "right" : "left";
248
+ gutters[key] = Math.max(gutters[key], room);
249
+ }
250
+ return gutters;
251
+ }
252
+ /**
253
+ * How far the ring's centre sits from the node's, in px. Zero while the
254
+ * gutters match; when the labels all fall one way it slides the ring into the
255
+ * empty half so the ring-plus-labels group stays centred in the box instead of
256
+ * the ring sitting dead centre with a bald patch beside it.
257
+ */
258
+ get centerX() {
259
+ const { left, right } = this.labelGutters;
260
+ return (left - right) / 2;
261
+ }
262
+ /**
263
+ * Radius of the ring's outer edge, fitted to whatever the label gutters leave.
264
+ * A fully selected slice reaches `radius × growFactor`, so the room has to
265
+ * cover that — hence the divisor, which keeps even the grown slice inside the
266
+ * box (and holds the ring the same size whether or not anything is selected).
267
+ */
268
+ get outerRadius() {
269
+ const { left, right } = this.labelGutters;
270
+ const room = Math.min((this.box.width - left - right) / 2, this.box.height / 2 - this.labelRowHeight - 4);
271
+ return Math.max(0, room / this.growFactor);
272
+ }
273
+ /** Radius of the hole in the middle: a fraction of the outer radius, or explicit px. */
274
+ get holeRadius() {
275
+ const configured = this.s.ring.holeRadius;
276
+ if (configured <= 0)
277
+ return 0;
278
+ const px = configured < 1 ? configured * this.outerRadius : configured;
279
+ return Math.min(px, this.outerRadius * 0.95);
280
+ }
281
+ /** Radius of the circle every leader elbows on, clear of even a popped-out slice. */
282
+ get elbowRadius() {
283
+ return this.outerRadius + this.maxPop + LEADER_LENGTH;
284
+ }
285
+ /** How far slice `index` is currently pushed out, in `[0, 1]`. */
286
+ popOf(index) {
287
+ return clampUnit(this.s.pops[index] ?? 0);
288
+ }
289
+ /** Radius of slice `index`'s outer edge, its selection growth included. */
290
+ anchorRadius(index) {
291
+ return this.outerRadius + this.maxPop * this.popOf(index);
292
+ }
293
+ /**
294
+ * Radius an inside label sits at on slice `index`: halfway across the band on a
295
+ * donut, and further out than halfway on a solid pie, where "halfway" would
296
+ * crowd the point every wedge converges on. Rides the slice's own pop, so an
297
+ * inside label travels out with the wedge it belongs to.
298
+ */
299
+ bandMidRadius(index) {
300
+ const rim = this.anchorRadius(index);
301
+ const hole = this.holeRadius;
302
+ return hole > 0 ? (hole + rim) / 2 : rim * PIE_LABEL_RADIUS;
303
+ }
304
+ /** The point slice `index`'s inside label is centred on. */
305
+ insideAnchor(index) {
306
+ const arc = this.arcs.find((a) => a.index === index);
307
+ if (arc === undefined)
308
+ return { x: this.centerX, y: 0 };
309
+ const point = ringPoint(this.bandMidRadius(index), arc.mid);
310
+ return { x: point.x + this.centerX, y: point.y };
311
+ }
312
+ /**
313
+ * How selected the ring is overall, in `[0, 1]` — the most-grown slice. Rides
314
+ * the same tween the pops do, so the dim below arrives with the growth rather
315
+ * than needing an animation of its own.
316
+ */
317
+ get selectionStrength() {
318
+ let strongest = 0;
319
+ for (let i = 0; i < this.s.slices.length; i++)
320
+ strongest = Math.max(strongest, this.popOf(i));
321
+ return strongest;
322
+ }
323
+ /**
324
+ * Opacity slice `index` (and its leader and label) is drawn at: full while
325
+ * nothing is selected, falling toward `dimOpacity` in proportion to how
326
+ * selected the *rest* of the ring is. A slice that's selected itself stays at
327
+ * full — the two factors cancel.
328
+ */
329
+ sliceOpacity(index) {
330
+ const focus = this.selectionStrength;
331
+ if (focus <= 0)
332
+ return 1;
333
+ return 1 - (1 - clampUnit(this.s.dimOpacity)) * focus * (1 - this.popOf(index));
334
+ }
335
+ /** Slice `index`'s share of the ring as its label reads it, off the live values. */
336
+ percentText(index) {
337
+ const arc = this.arcs.find((a) => a.index === index);
338
+ return formatPercent(arc?.fraction ?? 0);
339
+ }
340
+ // ---- Label placement ---------------------------------------------------
341
+ /**
342
+ * Where every leader label sits and how its leader gets there. Labels are split
343
+ * into a right and a left column by their slice's bisector, each column is
344
+ * spread so nothing overlaps (and nothing leaves the box), and each leader is
345
+ * then built as wedge edge → elbow → label. The elbow rides the leader circle at
346
+ * the label's *settled* y, which keeps the final run horizontal and the whole
347
+ * polyline outside the ring however far the label was nudged.
348
+ */
349
+ placements() {
350
+ if (!this.hasLeaderLabels)
351
+ return [];
352
+ const arcs = this.arcs;
353
+ if (arcs.length === 0 || this.outerRadius <= 0)
354
+ return [];
355
+ const radius = this.elbowRadius;
356
+ const rowHeight = this.labelRowHeight;
357
+ const top = this.box.height / 2 - rowHeight / 2;
358
+ const bottom = -top;
359
+ const cx = this.centerX;
360
+ const right = [];
361
+ const left = [];
362
+ for (const arc of arcs) {
363
+ const side = sideOf(arc.mid);
364
+ const ideal = ringPoint(radius, arc.mid).y;
365
+ (side > 0 ? right : left).push({ index: arc.index, side, mid: arc.mid, ideal, y: ideal });
366
+ }
367
+ relaxLabels(right, rowHeight + LABEL_GAP, top, bottom);
368
+ relaxLabels(left, rowHeight + LABEL_GAP, top, bottom);
369
+ return [...right, ...left].map((slot) => {
370
+ const start = ringPoint(this.anchorRadius(slot.index) + LEADER_LIFTOFF, slot.mid);
371
+ // The elbow sits where the label's y crosses the leader circle. Solving
372
+ // x² + y² = radius² for x keeps it *on* that circle (never inside the
373
+ // ring); a label pushed past the circle's top or bottom falls back to the
374
+ // sideways floor so its leader still reads as pointing outward.
375
+ const onCircle = Math.sqrt(Math.max(0, radius * radius - slot.y * slot.y));
376
+ const elbowX = cx + slot.side * Math.max(onCircle, radius * MIN_ELBOW);
377
+ const endX = cx + slot.side * (radius + LABEL_STUB);
378
+ return {
379
+ index: slot.index,
380
+ side: slot.side,
381
+ leader: [
382
+ { x: start.x + cx, y: start.y },
383
+ { x: elbowX, y: slot.y },
384
+ { x: endX, y: slot.y },
385
+ ],
386
+ text: { x: endX + slot.side * TEXT_INSET, y: slot.y },
387
+ };
388
+ });
389
+ }
390
+ /** This frame's placement for slice `index`, or `undefined` if it isn't leadered. */
391
+ placementFor(index) {
392
+ return this.placements().find((placement) => placement.index === index);
393
+ }
394
+ }
395
+ /** Which side a leader off bisector `mid` runs to: +1 right, −1 left. */
396
+ function sideOf(mid) {
397
+ return Math.sin(mid) >= 0 ? 1 : -1;
398
+ }
399
+ const NO_BOX = { width: 0, height: 0 };
400
+ /**
401
+ * Each slice's fill, resolved once per paint rather than every frame: the slices
402
+ * are bound to the chart's rows and palette, so a theme tween hands over new
403
+ * paint and the drawing must see it, but a frame that moves nothing must not
404
+ * re-resolve. Keyed by the paint itself, so it is shared and needs no node.
405
+ */
406
+ const resolvedFills = new WeakMap();
407
+ function resolvedFill(fill) {
408
+ if (typeof fill !== "object" || fill === null)
409
+ return fillOps.resolve(fill);
410
+ let resolved = resolvedFills.get(fill);
411
+ if (resolved === undefined)
412
+ resolvedFills.set(fill, resolved = fillOps.resolve(fill));
413
+ return resolved;
414
+ }
415
+ /** Each slice's fill, resolved. */
416
+ export function ringFills(slices) {
417
+ return slices.map((slice) => resolvedFill(slice.fill));
418
+ }
419
+ /**
420
+ * The labels a ring was built with: one per *drawn* slice (a zero-valued slice
421
+ * gets no wedge, so no label either), in whichever of the two forms the chart
422
+ * asked for, then the hole's summary. Both are real Text stacked in a hug
423
+ * vertical flow — the difference is only what they are pinned to and which line
424
+ * leads. The point each is pinned to stays reactive and follows the ring as the
425
+ * box resizes or its slice pops out; only the choice of form, which depends on
426
+ * entries alone, is settled here.
427
+ */
428
+ function ringLabels(s) {
429
+ const blocks = [];
430
+ // A label block's parent is the ring: its box is what the ring was laid out at.
431
+ const geometry = () => new RingGeometry(s, blocks[0]?.parent?.layoutBounds ?? NO_BOX);
432
+ const label = (arc) => {
433
+ // Fades in with the ring's labels, then dims along with its own slice
434
+ // whenever another slice takes the focus.
435
+ const opacity = () => clampUnit(s.labelReveal) * geometry().sliceOpacity(arc.index);
436
+ const wantsCategory = s.labelMode === "both" || s.labelMode === "category";
437
+ const wantsPercent = s.labelMode === "both" || s.labelMode === "percent";
438
+ if (s.labelPlacement === "inside") {
439
+ // The number leads and the caption sits under it: inside a wedge the
440
+ // reader already knows *which* wedge they are looking at, so the magnitude
441
+ // is what the label is for. Both sizes are bound rather than read once —
442
+ // the fitted size derives from the ring's radius, which isn't known until
443
+ // the node has been laid out.
444
+ const inside = [];
445
+ if (wantsPercent) {
446
+ inside.push(new Text({
447
+ ...textOps.styleProps(s.label.insideStyle),
448
+ text: () => geometry().percentText(arc.index),
449
+ fontSize: () => geometry().insideFont,
450
+ }));
451
+ }
452
+ if (wantsCategory) {
453
+ inside.push(new Text({
454
+ ...textOps.styleProps(s.label.insideStyle),
455
+ text: () => s.slices[arc.index]?.category ?? "",
456
+ fontSize: () => (s.labelMode === "category" ? geometry().insideFont : geometry().insideFont * INSIDE_CAPTION_RATIO),
457
+ }));
458
+ }
459
+ return new Rect({
460
+ flow: "vertical",
461
+ width: "hug",
462
+ height: "hug",
463
+ gap: 0,
464
+ align: "center",
465
+ opacity,
466
+ center: () => geometry().insideAnchor(arc.index),
467
+ children: inside,
468
+ });
469
+ }
470
+ const side = sideOf(arc.mid);
471
+ const at = () => geometry().placementFor(arc.index)?.text ?? { x: 0, y: 0 };
472
+ const children = [];
473
+ if (wantsCategory) {
474
+ children.push(new Text({
475
+ ...textOps.styleProps(s.label.textStyle),
476
+ text: () => s.slices[arc.index]?.category ?? "",
477
+ textAlign: side > 0 ? "left" : "right",
478
+ }));
479
+ }
480
+ if (wantsPercent) {
481
+ children.push(new Text({
482
+ ...textOps.styleProps(s.label.percentStyle),
483
+ text: () => geometry().percentText(arc.index),
484
+ textAlign: side > 0 ? "left" : "right",
485
+ }));
486
+ }
487
+ return new Rect({
488
+ flow: "vertical",
489
+ width: "hug",
490
+ height: "hug",
491
+ gap: 2,
492
+ align: side > 0 ? "centerLeft" : "centerRight",
493
+ opacity,
494
+ // Exactly one of these is set; `undefined` anchors are ignored.
495
+ centerLeft: side > 0 ? at : undefined,
496
+ centerRight: side > 0 ? undefined : at,
497
+ children,
498
+ });
499
+ };
500
+ if (s.labelPlacement !== "none" && s.labelMode !== "none") {
501
+ for (const arc of pieArcs(s.slices, s.ring.startAngle))
502
+ blocks.push(label(arc));
503
+ }
504
+ // The hole's summary, pinned to the ring's centre so it tracks the sideways
505
+ // shift a one-sided label column puts on the ring.
506
+ if (s.centerLabel !== "" || s.centerCaption !== "") {
507
+ const children = [];
508
+ if (s.centerLabel !== "") {
509
+ children.push(new Text({
510
+ ...textOps.styleProps(s.centerStyle.labelStyle),
511
+ text: s.centerLabel,
512
+ fontSize: () => geometry().centerFont,
513
+ }));
514
+ }
515
+ if (s.centerCaption !== "") {
516
+ children.push(new Text({
517
+ ...textOps.styleProps(s.centerStyle.captionStyle),
518
+ text: s.centerCaption,
519
+ fontSize: () => geometry().centerFont * (sizeOf(s.centerStyle.captionStyle, 22) / sizeOf(s.centerStyle.labelStyle, 46)),
520
+ }));
521
+ }
522
+ blocks.push(new Rect({
523
+ flow: "vertical",
524
+ width: "hug",
525
+ height: "hug",
526
+ gap: 2,
527
+ align: "center",
528
+ opacity: () => clampUnit(s.centerReveal),
529
+ center: () => ({ x: geometry().centerX, y: 0 }),
530
+ children,
531
+ }));
532
+ }
533
+ return asParts(blocks);
534
+ }
535
+ /**
536
+ * The ring itself: one wedge per {@link PieSlice}, sized by its share of the
537
+ * total, swept clockwise from the theme's `startAngle` with a `gap` of clear
538
+ * space between neighbours — a *constant-width* channel, the same at the hole as
539
+ * at the rim (see {@link wedgePath}). A **selected** slice reaches further out
540
+ * while its hole edge stays put — so it reads as that band swelling out of the
541
+ * ring rather than breaking off it — and the rest of the ring dims behind it,
542
+ * leaders and labels included.
543
+ *
544
+ * This is the only part of the chart family that draws a path: the wedges are
545
+ * filled {@link PathBuilder} polygons approximating each arc, and the leaders are
546
+ * stroked polylines — both in the node's centred, y-up space, so neither depends
547
+ * on SVG arc-sweep conventions. The **labels are real {@link Text} nodes**
548
+ * (stacked in a hug vertical flow and pinned by their inner edge), so no
549
+ * glyph-width guesswork decides where a caption starts.
550
+ *
551
+ * ### Label placement
552
+ * Each label sits either **inside** its wedge or **outside** on a leader.
553
+ *
554
+ * An inside label is centred on its slice's band and leads with the number, the
555
+ * caption set small underneath — inside a wedge the reader already knows which
556
+ * slice they're on, so the magnitude is the thing being read. It costs no gutter
557
+ * and no eye round-trip, so a ring labelled that way draws considerably bigger in
558
+ * the same box.
559
+ *
560
+ * A leader label sits outside on the end of a polyline that lifts off its wedge,
561
+ * elbows, and runs horizontally into the text. Labels are split into a left and a
562
+ * right column by which way their slice's bisector points, and each column is
563
+ * de-conflicted independently (see {@link relaxLabels}): a label takes the spot
564
+ * nearest its wedge that still clears its neighbour, and the column is squeezed
565
+ * to fit the node's height rather than spilling out of it. The elbow then rides on
566
+ * a circle just outside the ring **at the label's settled y**, so the run into the
567
+ * text is always horizontal and a nudged label never drags its leader back across
568
+ * the ring.
569
+ *
570
+ * Only the sides that actually carry a leader reserve a gutter, and the ring's
571
+ * centre slides into whatever the other side left over — so a ring whose slices
572
+ * all leader one way doesn't leave a bald patch on the other.
573
+ */
574
+ export const PieRing = component2d({
575
+ key: "pieRing",
576
+ state: {
577
+ slices: fresh(() => []),
578
+ ring: Types.custom(DEFAULT_PIE_CHART_THEME.ring),
579
+ label: Types.custom(DEFAULT_PIE_CHART_THEME.label),
580
+ centerStyle: Types.custom(DEFAULT_PIE_CHART_THEME.center),
581
+ labelMode: Types.custom("percent"),
582
+ labelPlacement: Types.custom("leader"),
583
+ growth: 1,
584
+ labelReveal: 1,
585
+ pops: fresh(() => []),
586
+ dimOpacity: DEFAULT_PIE_CHART_THEME.spotlight.dimOpacity,
587
+ centerLabel: "",
588
+ centerCaption: "",
589
+ centerReveal: 1,
590
+ },
591
+ // A plain node filled its parent; one made of its labels would hug them.
592
+ defaults: { width: "fill", height: "fill" },
593
+ children: (state) => ringLabels(state),
594
+ // The ring's paints live nowhere a paint entry would look: one fill per slice,
595
+ // the wedge outline and drop shadow of `ring`, and the leader line's own stroke.
596
+ load: (loader, state) => loadPaints(loader, {
597
+ fills: ringFills(state.slices),
598
+ shadows: [shadowOps.resolve(state.ring.shadow)],
599
+ strokes: [strokeOps.resolve(state.ring.stroke), strokeOps.resolve(state.label.leaderStroke)],
600
+ }),
601
+ commands: {
602
+ /**
603
+ * Tween `growth` `0 → 1`, wiping the wedges in around the ring. No priming
604
+ * to 0 first — the value at `t` is a function of `t`, so a repeat call
605
+ * re-sweeps by definition rather than by having reset something.
606
+ */
607
+ sweep: (timeline) => {
608
+ const ease = frameEase(timeline);
609
+ return timeline.animate((t) => ({ growth: ease(t) }));
610
+ },
611
+ /** Tween `labelReveal` `0 → 1`, fading the leaders and captions up. */
612
+ revealLabels: (timeline) => {
613
+ const ease = frameEase(timeline);
614
+ return timeline.animate((t) => ({ labelReveal: ease(t) }));
615
+ },
616
+ /**
617
+ * Fade the hole's summary up. Deliberately not part of the ring's entrance: a
618
+ * hole label is usually the chart's conclusion, so the scene decides when it
619
+ * lands.
620
+ */
621
+ revealCenter: (timeline, state) => {
622
+ const ease = frameEase(timeline);
623
+ const from = clampUnit(state.centerReveal);
624
+ return timeline.animate((t) => ({ centerReveal: from + (1 - from) * ease(t) }));
625
+ },
626
+ },
627
+ render: (ctx, state) => {
628
+ const g = new RingGeometry(state, ctx.size);
629
+ const rOuter = g.outerRadius;
630
+ const arcs = rOuter > 0 ? g.arcs : [];
631
+ if (arcs.length > 0) {
632
+ const sweep = clampUnit(state.growth);
633
+ const revealEnd = state.ring.startAngle * (Math.PI / 180) + Math.PI * 2 * sweep;
634
+ const hole = g.holeRadius;
635
+ const halfGap = Math.max(0, state.ring.gap) / 2;
636
+ // One shared frame (the whole ring square, grown slices included) pinned onto
637
+ // every wedge path, so `Graphics2D.path()` doesn't re-centre each wedge on its
638
+ // own bbox and collapse them all onto the origin. It stays symmetric about the
639
+ // *node's* origin — so path coordinates land exactly in node space — and is
640
+ // grown by the ring's sideways offset rather than moved with it, which would
641
+ // undo the very shift it has to contain.
642
+ const cx = g.centerX;
643
+ const half = rOuter + g.maxPop + 1 + Math.abs(cx);
644
+ const centerBounds = [-half, -half, half, half];
645
+ // Explicit width/height alongside centerBounds: a wedge path's command list
646
+ // carries no implied extent, so a slice filled with an image or a video needs
647
+ // this to size its decode.
648
+ const span = half * 2;
649
+ const fills = ringFills(state.slices);
650
+ for (const arc of arcs) {
651
+ // Clip the wedge to the growth-revealed arc; skip it until the sweep
652
+ // reaches it, so the ring draws in as one clockwise wipe.
653
+ const a1 = Math.min(arc.a1, revealEnd);
654
+ if (a1 <= arc.a0)
655
+ continue;
656
+ const path = wedgePath(arc.a0, a1, hole, g.anchorRadius(arc.index), halfGap, cx);
657
+ const wedge = new Graphics2D().path(path.toPathState({ centerBounds, width: span, height: span }));
658
+ wedge.shadow(state.ring.shadow);
659
+ wedge.fill(fills[arc.index] ?? []);
660
+ wedge.stroke(state.ring.stroke);
661
+ ctx.draw(wedge.opacity(g.sliceOpacity(arc.index)));
662
+ }
663
+ // Leaders. Each polyline gets its own `Graphics2D`: several open polylines
664
+ // chained into one command list are combined into a single surface before the
665
+ // stroke, which closes each contour back on itself and paints the leaders as
666
+ // thin triangles.
667
+ const reveal = clampUnit(state.labelReveal);
668
+ if (reveal > 0.001) {
669
+ for (const placement of g.placements()) {
670
+ ctx.draw(new Graphics2D()
671
+ .line({ points: placement.leader, radius: ELBOW_RADIUS })
672
+ .stroke(state.label.leaderStroke)
673
+ .opacity(reveal * g.sliceOpacity(placement.index)));
674
+ }
675
+ }
676
+ }
677
+ ctx.children();
678
+ },
679
+ });
680
+ //# sourceMappingURL=pie-ring.js.map