docxkeun 0.1.3 → 0.3.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 (199) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +166 -16
  3. package/dist/api/editor.d.ts +231 -7
  4. package/dist/api/editor.js +1125 -26
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +6 -1
  8. package/dist/api/index.js +4 -1
  9. package/dist/api/lists.d.ts +37 -0
  10. package/dist/api/lists.js +132 -0
  11. package/dist/api/parts.js +1 -0
  12. package/dist/api/positions.js +1 -0
  13. package/dist/api/revisions.d.ts +61 -0
  14. package/dist/api/revisions.js +401 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/api/tables.d.ts +60 -0
  18. package/dist/api/tables.js +138 -0
  19. package/dist/charts/color.d.ts +45 -0
  20. package/dist/charts/color.js +322 -0
  21. package/dist/charts/format.d.ts +12 -0
  22. package/dist/charts/format.js +459 -0
  23. package/dist/charts/index.d.ts +11 -0
  24. package/dist/charts/index.js +8 -0
  25. package/dist/charts/model.d.ts +225 -0
  26. package/dist/charts/model.js +758 -0
  27. package/dist/charts/outline.d.ts +17 -0
  28. package/dist/charts/outline.js +214 -0
  29. package/dist/charts/render.d.ts +20 -0
  30. package/dist/charts/render.js +1772 -0
  31. package/dist/drawing/arrows.d.ts +37 -0
  32. package/dist/drawing/arrows.js +99 -0
  33. package/dist/drawing/formula.d.ts +40 -0
  34. package/dist/drawing/formula.js +159 -0
  35. package/dist/drawing/geometry.d.ts +61 -0
  36. package/dist/drawing/geometry.js +286 -0
  37. package/dist/drawing/index.d.ts +12 -0
  38. package/dist/drawing/index.js +8 -0
  39. package/dist/drawing/presets.d.ts +72 -0
  40. package/dist/drawing/presets.js +2874 -0
  41. package/dist/fonts/shaping/apply.d.ts +94 -0
  42. package/dist/fonts/shaping/apply.js +349 -0
  43. package/dist/fonts/shaping/arabic.d.ts +28 -0
  44. package/dist/fonts/shaping/arabic.js +235 -0
  45. package/dist/fonts/shaping/buffer.d.ts +53 -0
  46. package/dist/fonts/shaping/buffer.js +95 -0
  47. package/dist/fonts/shaping/gdef.d.ts +30 -0
  48. package/dist/fonts/shaping/gdef.js +66 -0
  49. package/dist/fonts/shaping/gpos.d.ts +86 -0
  50. package/dist/fonts/shaping/gpos.js +428 -0
  51. package/dist/fonts/shaping/gsub.d.ts +65 -0
  52. package/dist/fonts/shaping/gsub.js +313 -0
  53. package/dist/fonts/shaping/index.d.ts +32 -0
  54. package/dist/fonts/shaping/index.js +402 -0
  55. package/dist/fonts/shaping/indic.d.ts +6 -0
  56. package/dist/fonts/shaping/indic.js +805 -0
  57. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  58. package/dist/fonts/shaping/layout-common.js +349 -0
  59. package/dist/fonts/shaping/plan.d.ts +87 -0
  60. package/dist/fonts/shaping/plan.js +152 -0
  61. package/dist/fonts/shaping/scripts.d.ts +26 -0
  62. package/dist/fonts/shaping/scripts.js +160 -0
  63. package/dist/fonts/shaping/shaper.d.ts +23 -0
  64. package/dist/fonts/shaping/shaper.js +5 -0
  65. package/dist/fonts/shaping/unicode.d.ts +34 -0
  66. package/dist/fonts/shaping/unicode.js +138 -0
  67. package/dist/images/bmp.d.ts +9 -0
  68. package/dist/images/bmp.js +234 -0
  69. package/dist/images/gif.d.ts +9 -0
  70. package/dist/images/gif.js +215 -0
  71. package/dist/images/index.d.ts +18 -0
  72. package/dist/images/index.js +63 -0
  73. package/dist/images/png-encode.d.ts +4 -0
  74. package/dist/images/png-encode.js +73 -0
  75. package/dist/images/size.d.ts +10 -0
  76. package/dist/images/size.js +83 -0
  77. package/dist/images/tiff.d.ts +14 -0
  78. package/dist/images/tiff.js +407 -0
  79. package/dist/index.d.ts +7 -2
  80. package/dist/index.js +5 -0
  81. package/dist/layout/bidi.d.ts +18 -0
  82. package/dist/layout/bidi.js +71 -0
  83. package/dist/layout/blocks.d.ts +20 -3
  84. package/dist/layout/blocks.js +88 -58
  85. package/dist/layout/cache.d.ts +31 -0
  86. package/dist/layout/cache.js +38 -0
  87. package/dist/layout/drawing.d.ts +30 -0
  88. package/dist/layout/drawing.js +120 -0
  89. package/dist/layout/engine.d.ts +3 -0
  90. package/dist/layout/engine.js +218 -11
  91. package/dist/layout/index.d.ts +1 -0
  92. package/dist/layout/index.js +1 -0
  93. package/dist/layout/lines.d.ts +63 -5
  94. package/dist/layout/lines.js +245 -20
  95. package/dist/layout/paint.d.ts +25 -3
  96. package/dist/layout/paint.js +26 -10
  97. package/dist/layout/shapes.d.ts +7 -0
  98. package/dist/layout/shapes.js +338 -0
  99. package/dist/layout/style.d.ts +4 -0
  100. package/dist/layout/style.js +2 -0
  101. package/dist/layout/types.d.ts +89 -2
  102. package/dist/math/boxes.d.ts +88 -0
  103. package/dist/math/boxes.js +166 -0
  104. package/dist/math/index.d.ts +29 -0
  105. package/dist/math/index.js +44 -0
  106. package/dist/math/layout.d.ts +13 -0
  107. package/dist/math/layout.js +771 -0
  108. package/dist/math/linear.d.ts +3 -0
  109. package/dist/math/linear.js +152 -0
  110. package/dist/math/omml.d.ts +15 -0
  111. package/dist/math/omml.js +57 -0
  112. package/dist/math/paths.d.ts +61 -0
  113. package/dist/math/paths.js +450 -0
  114. package/dist/math/symbols.d.ts +49 -0
  115. package/dist/math/symbols.js +269 -0
  116. package/dist/math/text.d.ts +53 -0
  117. package/dist/math/text.js +316 -0
  118. package/dist/metafile/canvas.d.ts +80 -0
  119. package/dist/metafile/canvas.js +515 -0
  120. package/dist/metafile/dib.d.ts +27 -0
  121. package/dist/metafile/dib.js +300 -0
  122. package/dist/metafile/emf.d.ts +31 -0
  123. package/dist/metafile/emf.js +591 -0
  124. package/dist/metafile/geometry.d.ts +49 -0
  125. package/dist/metafile/geometry.js +85 -0
  126. package/dist/metafile/index.d.ts +27 -0
  127. package/dist/metafile/index.js +34 -0
  128. package/dist/metafile/reader.d.ts +28 -0
  129. package/dist/metafile/reader.js +59 -0
  130. package/dist/metafile/state.d.ts +118 -0
  131. package/dist/metafile/state.js +172 -0
  132. package/dist/metafile/text.d.ts +17 -0
  133. package/dist/metafile/text.js +130 -0
  134. package/dist/metafile/wmf.d.ts +33 -0
  135. package/dist/metafile/wmf.js +395 -0
  136. package/dist/model/content.d.ts +92 -7
  137. package/dist/model/content.js +251 -17
  138. package/dist/model/document.d.ts +34 -1
  139. package/dist/model/document.js +80 -1
  140. package/dist/model/fields.d.ts +4 -0
  141. package/dist/model/fields.js +10 -0
  142. package/dist/model/numbering.d.ts +2 -0
  143. package/dist/model/numbering.js +22 -0
  144. package/dist/model/props.d.ts +2 -0
  145. package/dist/model/props.js +3 -0
  146. package/dist/opc/index.d.ts +1 -1
  147. package/dist/opc/package.d.ts +34 -0
  148. package/dist/opc/package.js +58 -4
  149. package/dist/pdf/export.js +97 -6
  150. package/dist/pdf/images.d.ts +7 -0
  151. package/dist/pdf/images.js +39 -2
  152. package/dist/render/activity.d.ts +179 -0
  153. package/dist/render/activity.js +1003 -0
  154. package/dist/render/clipboard.d.ts +29 -0
  155. package/dist/render/clipboard.js +401 -0
  156. package/dist/render/comments.d.ts +166 -0
  157. package/dist/render/comments.js +779 -0
  158. package/dist/render/context-menu.d.ts +124 -0
  159. package/dist/render/context-menu.js +525 -0
  160. package/dist/render/editing.d.ts +146 -5
  161. package/dist/render/editing.js +678 -53
  162. package/dist/render/index.d.ts +12 -0
  163. package/dist/render/index.js +11 -0
  164. package/dist/render/navigation-panel.d.ts +76 -0
  165. package/dist/render/navigation-panel.js +431 -0
  166. package/dist/render/selection.js +5 -0
  167. package/dist/render/svg.d.ts +4 -6
  168. package/dist/render/svg.js +69 -7
  169. package/dist/render/toolbar.d.ts +83 -0
  170. package/dist/render/toolbar.js +505 -0
  171. package/dist/render/ui/comment-layout.d.ts +39 -0
  172. package/dist/render/ui/comment-layout.js +79 -0
  173. package/dist/render/ui/icons.d.ts +6 -0
  174. package/dist/render/ui/icons.js +38 -0
  175. package/dist/render/ui/menu.d.ts +38 -0
  176. package/dist/render/ui/menu.js +274 -0
  177. package/dist/render/ui/nav-model.d.ts +11 -0
  178. package/dist/render/ui/nav-model.js +34 -0
  179. package/dist/render/ui/overflow.d.ts +5 -0
  180. package/dist/render/ui/overflow.js +18 -0
  181. package/dist/render/ui/popover.d.ts +18 -0
  182. package/dist/render/ui/popover.js +109 -0
  183. package/dist/render/ui/theme.d.ts +2 -0
  184. package/dist/render/ui/theme.js +29 -0
  185. package/dist/render/undo.d.ts +76 -0
  186. package/dist/render/undo.js +144 -0
  187. package/dist/render/viewer.d.ts +100 -7
  188. package/dist/render/viewer.js +304 -92
  189. package/dist/security/policy.d.ts +3 -0
  190. package/dist/security/policy.js +6 -2
  191. package/dist/security/protection.d.ts +1 -0
  192. package/dist/security/protection.js +1 -1
  193. package/dist/text/bidi-data.d.ts +53 -0
  194. package/dist/text/bidi-data.js +318 -0
  195. package/dist/text/bidi.d.ts +37 -0
  196. package/dist/text/bidi.js +508 -0
  197. package/dist/xml/ns.d.ts +5 -0
  198. package/dist/xml/ns.js +7 -0
  199. package/package.json +9 -2
@@ -0,0 +1,1772 @@
1
+ /**
2
+ * Draws a chart model into display items inside a frame (points, y down): chart and plot area,
3
+ * title, legend, axes with automatic "nice" scales, gridlines, bars, lines, areas, scatter and bubble
4
+ * points, pies and doughnuts, radar, and data labels. Layout follows Office's order: the title and
5
+ * legend take their space first, axis labels next, and the plot gets what is left (or the manual
6
+ * layout written in the file). Fonts keep their point sizes whatever the frame size, as in Office.
7
+ */
8
+ import { measureChars, textItem } from '../layout/paint.js';
9
+ import { dashPattern } from './color.js';
10
+ import { formatNumber, isDateCode } from './format.js';
11
+ import { readChart } from './model.js';
12
+ import { hasOutlines, textOutline } from './outline.js';
13
+ /** Read a c:chartSpace and draw it into `frame`. */
14
+ export function renderChart(chartSpace, frame, options) {
15
+ const model = readChart(chartSpace, { schemeColor: (name) => options.schemeColor(name) });
16
+ return drawChart(model, frame, options);
17
+ }
18
+ const TICK = 3.5;
19
+ const LABEL_GAP = 3;
20
+ // ---------------------------------------------------------------------------------------------
21
+ // Drawing primitives
22
+ class Draw {
23
+ fonts;
24
+ defaultFont;
25
+ items = [];
26
+ constructor(fonts, defaultFont) {
27
+ this.fonts = fonts;
28
+ this.defaultFont = defaultFont;
29
+ }
30
+ font(st) {
31
+ return this.fonts.get(st.font ?? this.defaultFont, st.bold, st.italic);
32
+ }
33
+ lineHeight(st) {
34
+ const f = this.font(st);
35
+ return (f.ascent + f.descent) * st.size;
36
+ }
37
+ ascent(st) {
38
+ return this.font(st).ascent * st.size;
39
+ }
40
+ /** Split text into runs that one font can draw (fallback fonts for missing glyphs). */
41
+ runs(text, st) {
42
+ const base = this.font(st);
43
+ const out = [];
44
+ for (const ch of text) {
45
+ const f = this.fonts.forChar(base, ch.codePointAt(0));
46
+ const last = out[out.length - 1];
47
+ if (last && last.font === f)
48
+ last.chars.push(ch);
49
+ else
50
+ out.push({ font: f, chars: [ch] });
51
+ }
52
+ return out;
53
+ }
54
+ width(text, st) {
55
+ let w = 0;
56
+ for (const run of this.runs(text, st))
57
+ for (const ch of run.chars)
58
+ w += run.font.advance(ch.codePointAt(0)) * st.size;
59
+ return w;
60
+ }
61
+ /** One line of text with its left end at x and its baseline at y. */
62
+ textLine(text, x, baseline, st) {
63
+ let cx = x;
64
+ for (const run of this.runs(text, st)) {
65
+ const m = measureChars(run.chars.join(''), run.font, st.size, cx);
66
+ this.items.push(textItem(cx, baseline, m.chars, m.xs, m.widths, run.font, st.size, st.color));
67
+ cx += m.width;
68
+ }
69
+ }
70
+ /**
71
+ * Lines of text around an anchor: `h` says which part of the block sits at x (left end, centre,
72
+ * right end), `v` which part sits at y.
73
+ */
74
+ textBlock(lines, x, y, st, h, v) {
75
+ const lh = this.lineHeight(st);
76
+ const total = lh * lines.length;
77
+ let top = v === 'top' ? y : v === 'middle' ? y - total / 2 : y - total;
78
+ const asc = this.ascent(st);
79
+ for (const line of lines) {
80
+ const w = this.width(line, st);
81
+ const left = h === 'left' ? x : h === 'center' ? x - w / 2 : x - w;
82
+ if (line)
83
+ this.textLine(line, left, top + asc, st);
84
+ top += lh;
85
+ }
86
+ }
87
+ /** Can text in this style be drawn rotated (as glyph outlines)? */
88
+ canRotate(st) {
89
+ return hasOutlines(this.font(st));
90
+ }
91
+ /**
92
+ * Rotated text as filled outlines. The point (x, y) is where the text's anchor sits: `along` 0, 0.5
93
+ * or 1 picks the start, middle or end of the line, vertically the line's middle. Degrees clockwise.
94
+ */
95
+ rotatedText(text, x, y, st, degrees, along) {
96
+ const font = this.font(st);
97
+ if (!hasOutlines(font))
98
+ return false;
99
+ const w = this.width(text, st);
100
+ const asc = font.ascent * st.size;
101
+ const desc = font.descent * st.size;
102
+ const rad = (degrees * Math.PI) / 180;
103
+ const cos = Math.cos(rad);
104
+ const sin = Math.sin(rad);
105
+ let pen = 0;
106
+ const commands = [];
107
+ for (const run of this.runs(text, st)) {
108
+ const start = pen;
109
+ const cmds = textOutline(run.chars, run.font, st.size, (u, v) => {
110
+ const lu = start + u - along * w;
111
+ const lv = v + (asc - desc) / 2;
112
+ return { x: x + lu * cos - lv * sin, y: y + lu * sin + lv * cos };
113
+ });
114
+ if (!cmds)
115
+ return false;
116
+ commands.push(...cmds);
117
+ for (const ch of run.chars)
118
+ pen += run.font.advance(ch.codePointAt(0)) * st.size;
119
+ }
120
+ const item = { type: 'path', commands, fill: st.color };
121
+ if (font.syntheticBold) {
122
+ item.stroke = st.color;
123
+ item.strokeWidth = st.size * 0.03;
124
+ }
125
+ this.items.push(item);
126
+ return true;
127
+ }
128
+ /** Greedy word wrap to `maxWidth`; words longer than the width stay whole. Honours "\n". */
129
+ wrap(text, maxWidth, st) {
130
+ const out = [];
131
+ for (const para of text.split('\n')) {
132
+ const words = para.split(/ +/);
133
+ let line = '';
134
+ for (const word of words) {
135
+ const candidate = line ? `${line} ${word}` : word;
136
+ if (line && this.width(candidate, st) > maxWidth) {
137
+ out.push(line);
138
+ line = word;
139
+ }
140
+ else
141
+ line = candidate;
142
+ }
143
+ out.push(line);
144
+ }
145
+ return out;
146
+ }
147
+ path(commands, fill, line, extra = {}) {
148
+ if (commands.length === 0)
149
+ return;
150
+ const item = { type: 'path', commands, ...extra };
151
+ if (fill) {
152
+ item.fill = fill.color;
153
+ if (fill.opacity < 1)
154
+ item.fillOpacity = fill.opacity;
155
+ }
156
+ if (line && line.paint && line.width > 0) {
157
+ item.stroke = line.paint.color;
158
+ if (line.paint.opacity < 1)
159
+ item.strokeOpacity = line.paint.opacity;
160
+ item.strokeWidth = line.width;
161
+ const dash = dashPattern(line.dash, line.width);
162
+ if (dash)
163
+ item.dash = dash;
164
+ if (line.cap)
165
+ item.lineCap = line.cap;
166
+ if (line.join)
167
+ item.lineJoin = line.join;
168
+ }
169
+ if (item.fill === undefined && item.stroke === undefined)
170
+ return;
171
+ this.items.push(item);
172
+ }
173
+ segment(x1, y1, x2, y2, line) {
174
+ if (!line?.paint)
175
+ return;
176
+ this.path([
177
+ { op: 'M', x: x1, y: y1 },
178
+ { op: 'L', x: x2, y: y2 },
179
+ ], null, line);
180
+ }
181
+ }
182
+ function rectPath(b, radius = 0) {
183
+ if (radius <= 0) {
184
+ return [{ op: 'M', x: b.x, y: b.y }, { op: 'L', x: b.x + b.w, y: b.y }, { op: 'L', x: b.x + b.w, y: b.y + b.h }, { op: 'L', x: b.x, y: b.y + b.h }, { op: 'Z' }];
185
+ }
186
+ const r = Math.min(radius, b.w / 2, b.h / 2);
187
+ const k = r * 0.5523;
188
+ const { x, y, w, h } = b;
189
+ return [
190
+ { op: 'M', x: x + r, y },
191
+ { op: 'L', x: x + w - r, y },
192
+ { op: 'C', x1: x + w - r + k, y1: y, x2: x + w, y2: y + r - k, x: x + w, y: y + r },
193
+ { op: 'L', x: x + w, y: y + h - r },
194
+ { op: 'C', x1: x + w, y1: y + h - r + k, x2: x + w - r + k, y2: y + h, x: x + w - r, y: y + h },
195
+ { op: 'L', x: x + r, y: y + h },
196
+ { op: 'C', x1: x + r - k, y1: y + h, x2: x, y2: y + h - r + k, x, y: y + h - r },
197
+ { op: 'L', x, y: y + r },
198
+ { op: 'C', x1: x, y1: y + r - k, x2: x + r - k, y2: y, x: x + r, y },
199
+ { op: 'Z' },
200
+ ];
201
+ }
202
+ /** Point on a circle at `deg` clockwise from 12 o'clock. */
203
+ function polar(cx, cy, r, deg) {
204
+ const a = (deg * Math.PI) / 180;
205
+ return { x: cx + r * Math.sin(a), y: cy - r * Math.cos(a) };
206
+ }
207
+ /** Arc from a1 to a2 (degrees clockwise from 12 o'clock; a2 < a1 runs counter-clockwise) as Béziers. */
208
+ function arcTo(cmds, cx, cy, r, a1, a2) {
209
+ const sweep = a2 - a1;
210
+ const n = Math.max(1, Math.ceil(Math.abs(sweep) / 90 - 1e-9));
211
+ const step = sweep / n;
212
+ for (let i = 0; i < n; i++) {
213
+ const s = a1 + i * step;
214
+ const e = s + step;
215
+ const k = (4 / 3) * Math.tan(((step * Math.PI) / 180) / 4) * r;
216
+ const sr = (s * Math.PI) / 180;
217
+ const er = (e * Math.PI) / 180;
218
+ const p1 = polar(cx, cy, r, s);
219
+ const p2 = polar(cx, cy, r, e);
220
+ // Tangent of (sin a, -cos a) is (cos a, sin a).
221
+ cmds.push({ op: 'C', x1: p1.x + k * Math.cos(sr), y1: p1.y + k * Math.sin(sr), x2: p2.x - k * Math.cos(er), y2: p2.y - k * Math.sin(er), x: p2.x, y: p2.y });
222
+ }
223
+ }
224
+ function circlePath(cx, cy, r) {
225
+ const p = polar(cx, cy, r, 0);
226
+ const cmds = [{ op: 'M', x: p.x, y: p.y }];
227
+ arcTo(cmds, cx, cy, r, 0, 360);
228
+ cmds.push({ op: 'Z' });
229
+ return cmds;
230
+ }
231
+ /** Smooth curve through points (Catmull-Rom as cubic Béziers), as Office's "smoothed line". */
232
+ function smoothPath(pts) {
233
+ const cmds = [];
234
+ if (pts.length === 0)
235
+ return cmds;
236
+ cmds.push({ op: 'M', x: pts[0].x, y: pts[0].y });
237
+ for (let i = 0; i < pts.length - 1; i++) {
238
+ const p0 = pts[i - 1] ?? pts[i];
239
+ const p1 = pts[i];
240
+ const p2 = pts[i + 1];
241
+ const p3 = pts[i + 2] ?? p2;
242
+ cmds.push({ op: 'C', x1: p1.x + (p2.x - p0.x) / 6, y1: p1.y + (p2.y - p0.y) / 6, x2: p2.x - (p3.x - p1.x) / 6, y2: p2.y - (p3.y - p1.y) / 6, x: p2.x, y: p2.y });
243
+ }
244
+ return cmds;
245
+ }
246
+ function polyline(pts) {
247
+ return pts.map((p, i) => ({ op: i === 0 ? 'M' : 'L', x: p.x, y: p.y }));
248
+ }
249
+ function drawMarker(d, m, x, y) {
250
+ if (m.symbol === 'none')
251
+ return;
252
+ const s = m.size;
253
+ const h = s / 2;
254
+ const line = m.line ? { paint: m.line, width: m.lineWidth, join: 'miter' } : null;
255
+ let cmds;
256
+ let strokeOnly = false;
257
+ switch (m.symbol) {
258
+ case 'circle':
259
+ cmds = circlePath(x, y, h);
260
+ break;
261
+ case 'diamond':
262
+ cmds = [{ op: 'M', x, y: y - h }, { op: 'L', x: x + h, y }, { op: 'L', x, y: y + h }, { op: 'L', x: x - h, y }, { op: 'Z' }];
263
+ break;
264
+ case 'triangle':
265
+ cmds = [{ op: 'M', x, y: y - h }, { op: 'L', x: x + h, y: y + h }, { op: 'L', x: x - h, y: y + h }, { op: 'Z' }];
266
+ break;
267
+ case 'x':
268
+ cmds = [{ op: 'M', x: x - h, y: y - h }, { op: 'L', x: x + h, y: y + h }, { op: 'M', x: x + h, y: y - h }, { op: 'L', x: x - h, y: y + h }];
269
+ strokeOnly = true;
270
+ break;
271
+ case 'plus':
272
+ cmds = [{ op: 'M', x, y: y - h }, { op: 'L', x, y: y + h }, { op: 'M', x: x - h, y }, { op: 'L', x: x + h, y }];
273
+ strokeOnly = true;
274
+ break;
275
+ case 'star':
276
+ cmds = [
277
+ { op: 'M', x: x - h, y: y - h },
278
+ { op: 'L', x: x + h, y: y + h },
279
+ { op: 'M', x: x + h, y: y - h },
280
+ { op: 'L', x: x - h, y: y + h },
281
+ { op: 'M', x, y: y - h },
282
+ { op: 'L', x, y: y + h },
283
+ ];
284
+ strokeOnly = true;
285
+ break;
286
+ case 'dash':
287
+ cmds = rectPath({ x: x - h, y: y - s / 8, w: s, h: s / 4 });
288
+ break;
289
+ case 'dot':
290
+ cmds = rectPath({ x: x - s / 4, y: y - s / 8, w: s / 2, h: s / 4 });
291
+ break;
292
+ default:
293
+ cmds = rectPath({ x: x - h, y: y - h, w: s, h: s });
294
+ }
295
+ if (strokeOnly)
296
+ d.path(cmds, null, { paint: m.line ?? m.fill, width: Math.max(m.lineWidth, 0.75) });
297
+ else
298
+ d.path(cmds, m.fill, line);
299
+ }
300
+ function roundNice(v) {
301
+ return Number(v.toPrecision(12));
302
+ }
303
+ /** Tick values of a scale. */
304
+ function ticks(s) {
305
+ const out = [];
306
+ if (s.log) {
307
+ for (let v = s.min, i = 0; v <= s.max * (1 + 1e-9) && i < 100; v *= s.log, i++)
308
+ out.push(roundNice(v));
309
+ return out;
310
+ }
311
+ const n = Math.round((s.max - s.min) / s.major);
312
+ for (let i = 0; i <= Math.min(n, 1000); i++)
313
+ out.push(roundNice(s.min + i * s.major));
314
+ return out;
315
+ }
316
+ /**
317
+ * Office-like automatic axis scale: zero-based unless the data sits in a narrow band far from zero,
318
+ * about 5% headroom beyond the data, and the smallest 1-2-5 major unit whose ticks are not crowded
319
+ * (`minSpacing` says how far apart ticks must be, in points, for a candidate).
320
+ */
321
+ function niceScale(lo, hi, axis, length, percent, minSpacing) {
322
+ if (axis.logBase) {
323
+ const b = axis.logBase;
324
+ const pos = (v) => (v > 0 ? v : 1);
325
+ const min = axis.min && axis.min > 0 ? axis.min : b ** Math.floor(Math.log(pos(Number.isFinite(lo) ? lo : 1)) / Math.log(b) + 1e-9);
326
+ let max = axis.max && axis.max > min ? axis.max : b ** Math.ceil(Math.log(pos(Number.isFinite(hi) ? hi : b)) / Math.log(b) - 1e-9);
327
+ if (max <= min)
328
+ max = min * b;
329
+ return { min, max, major: b, minor: b, log: b };
330
+ }
331
+ if (!Number.isFinite(lo) || !Number.isFinite(hi)) {
332
+ lo = 0;
333
+ hi = percent ? 1 : 1;
334
+ }
335
+ if (percent) {
336
+ hi = hi > 0 ? 1 : 0;
337
+ lo = lo < 0 ? -1 : 0;
338
+ }
339
+ if (lo === hi) {
340
+ if (lo === 0)
341
+ hi = 1;
342
+ else if (lo > 0)
343
+ lo = 0;
344
+ else
345
+ hi = 0;
346
+ }
347
+ const fixedMin = axis.min;
348
+ const fixedMax = axis.max !== undefined && (fixedMin === undefined || axis.max > fixedMin) ? axis.max : undefined;
349
+ const headroom = percent ? 0 : 0.05;
350
+ const build = (unit) => {
351
+ let min;
352
+ if (fixedMin !== undefined)
353
+ min = fixedMin;
354
+ else if (lo >= 0) {
355
+ // A narrow band of positive values gets a non-zero minimum, as Office does.
356
+ min = hi > 0 && (hi - lo) / hi < 1 / 6 ? Math.max(0, Math.floor((lo - (hi - lo) / 2) / unit) * unit) : 0;
357
+ }
358
+ else
359
+ min = Math.floor((lo - headroom * (Math.max(hi, 0) - lo)) / unit + 1e-9) * unit;
360
+ let max;
361
+ if (fixedMax !== undefined)
362
+ max = fixedMax;
363
+ else if (hi <= 0)
364
+ max = lo < 0 && (hi - lo) / -lo < 1 / 6 ? Math.min(0, Math.ceil((hi + (hi - lo) / 2) / unit) * unit) : 0;
365
+ else
366
+ max = Math.ceil((hi + headroom * (hi - min)) / unit - 1e-9) * unit;
367
+ if (percent) {
368
+ if (fixedMax === undefined)
369
+ max = hi > 0 ? 1 : 0;
370
+ if (fixedMin === undefined)
371
+ min = lo < 0 ? -1 : 0;
372
+ }
373
+ if (max <= min)
374
+ max = min + unit;
375
+ return { min: roundNice(min), max: roundNice(max), major: unit, minor: unit / 5 };
376
+ };
377
+ if (axis.majorUnit) {
378
+ const s = build(axis.majorUnit);
379
+ s.minor = axis.minorUnit ?? axis.majorUnit / 5;
380
+ return s;
381
+ }
382
+ const span = Math.max((fixedMax ?? hi) - (fixedMin ?? Math.min(lo, 0)), Math.abs(hi) * 1e-9, 1e-12);
383
+ let exp = Math.floor(Math.log10(span / 50));
384
+ for (let guard = 0; guard < 40; guard++, exp++) {
385
+ for (const m of [1, 2, 5]) {
386
+ const unit = roundNice(m * 10 ** exp);
387
+ const s = build(unit);
388
+ const intervals = (s.max - s.min) / unit;
389
+ if (intervals > 200)
390
+ continue;
391
+ if (intervals < 1 || length / intervals >= minSpacing(s)) {
392
+ if (axis.minorUnit)
393
+ s.minor = axis.minorUnit;
394
+ return s;
395
+ }
396
+ }
397
+ }
398
+ return build(span);
399
+ }
400
+ function pointFill(series, i) {
401
+ const pt = series.points.find((p) => p.index === i);
402
+ if (pt?.fill !== undefined)
403
+ return pt.fill;
404
+ const auto = series.pointColors?.[i];
405
+ if (auto)
406
+ return { color: auto, opacity: 1 };
407
+ return series.fill;
408
+ }
409
+ function pointLine(series, i) {
410
+ return series.points.find((p) => p.index === i)?.line ?? series.line;
411
+ }
412
+ function isVaried(plot) {
413
+ return plot.varyColors && (plot.type === 'pie' || plot.type === 'doughnut' || (plot.series.length === 1 && (plot.type === 'bar' || plot.type === 'bubble')));
414
+ }
415
+ function legendEntries(model) {
416
+ const entries = [];
417
+ const first = model.plots[0];
418
+ if (model.plots.length === 1 && first && isVaried(first) && first.series[0]) {
419
+ const s = first.series[0];
420
+ const n = Math.max(s.categories.length, s.values.length);
421
+ for (let i = 0; i < n; i++)
422
+ entries.push({ label: s.categories[i] ?? String(i + 1), kind: 'fill', fill: pointFill(s, i), line: pointLine(s, i) });
423
+ }
424
+ else {
425
+ for (const plot of model.plots) {
426
+ const plotEntries = [];
427
+ for (const s of plot.series) {
428
+ const lineKind = plot.type === 'line' || plot.type === 'scatter' || (plot.type === 'radar' && plot.radarStyle !== 'filled');
429
+ if (lineKind) {
430
+ const e = { label: s.name, kind: 'line', fill: null, line: s.line };
431
+ if (s.marker.symbol !== 'none')
432
+ e.marker = s.marker;
433
+ plotEntries.push(e);
434
+ }
435
+ else
436
+ plotEntries.push({ label: s.name, kind: 'fill', fill: s.fill, line: s.line });
437
+ }
438
+ // Stacked columns and areas list the top series first in a vertical legend, matching the stack.
439
+ const vertical = model.legend && ['r', 'l', 'tr'].includes(model.legend.position);
440
+ if (vertical && (plot.grouping === 'stacked' || plot.grouping === 'percentStacked') && ((plot.type === 'bar' && plot.barDir === 'col') || plot.type === 'area'))
441
+ plotEntries.reverse();
442
+ entries.push(...plotEntries);
443
+ }
444
+ }
445
+ const deleted = new Set(model.legend?.deletedEntries ?? []);
446
+ return entries.filter((_, i) => !deleted.has(i));
447
+ }
448
+ function planLegend(d, model, frame, area) {
449
+ const legend = model.legend;
450
+ const entries = legendEntries(model);
451
+ if (entries.length === 0)
452
+ return undefined;
453
+ const st = legend.style;
454
+ const lh = d.lineHeight(st);
455
+ const pad = st.size * 0.35;
456
+ const keyGap = st.size * 0.4;
457
+ const keyW = (e) => (e.kind === 'line' ? st.size * 2.2 : st.size * 0.75);
458
+ const vertical = legend.position === 'r' || legend.position === 'l' || legend.position === 'tr';
459
+ const manual = legend.layout;
460
+ const maxW = manual?.w !== undefined && manual.wMode !== 'edge' ? manual.w * frame.w : vertical ? area.w * 0.35 : area.w;
461
+ const rows = [];
462
+ let boxW;
463
+ let boxH;
464
+ if (vertical) {
465
+ let y = pad;
466
+ let widest = 0;
467
+ const col = [];
468
+ for (const e of entries) {
469
+ const kw = keyW(e);
470
+ const lines = d.wrap(e.label, Math.max(maxW - kw - keyGap - 2 * pad, st.size * 3), st);
471
+ const h = lines.length * lh;
472
+ if (y + h > area.h && col.length > 0)
473
+ break; // entries that do not fit are left out
474
+ col.push({ entry: e, x: pad, y, lines, keyW: kw });
475
+ widest = Math.max(widest, kw + keyGap + Math.max(...lines.map((l) => d.width(l, st))));
476
+ y += h;
477
+ }
478
+ rows.push(col);
479
+ boxW = widest + 2 * pad;
480
+ boxH = y + pad;
481
+ }
482
+ else {
483
+ const spacing = st.size * 1.1;
484
+ let x = pad;
485
+ let y = pad;
486
+ let row = [];
487
+ let widest = 0;
488
+ for (const e of entries) {
489
+ const kw = keyW(e);
490
+ const w = kw + keyGap + d.width(e.label, st);
491
+ if (row.length > 0 && x + w + pad > maxW) {
492
+ rows.push(row);
493
+ widest = Math.max(widest, x - spacing);
494
+ row = [];
495
+ x = pad;
496
+ y += lh;
497
+ }
498
+ row.push({ entry: e, x, y, lines: [e.label], keyW: kw });
499
+ x += w + spacing;
500
+ }
501
+ rows.push(row);
502
+ widest = Math.max(widest, x - spacing);
503
+ boxW = Math.min(widest + pad, area.w);
504
+ boxH = y + lh + pad;
505
+ // Centre each row within the legend box.
506
+ for (const r of rows) {
507
+ const last = r[r.length - 1];
508
+ if (!last)
509
+ continue;
510
+ const rowW = last.x + last.keyW + keyGap + d.width(last.lines[0] ?? '', st) + pad;
511
+ const shift = (boxW - rowW) / 2;
512
+ for (const item of r)
513
+ item.x += Math.max(0, shift);
514
+ }
515
+ }
516
+ let box;
517
+ const remaining = { ...area };
518
+ const gap = Math.max(4, st.size * 0.5);
519
+ if (manual && (manual.x !== undefined || manual.y !== undefined)) {
520
+ const x = manual.x !== undefined ? (manual.xMode === 'edge' ? frame.x + manual.x * frame.w : area.x + manual.x * frame.w) : area.x + area.w - boxW;
521
+ const y = manual.y !== undefined ? (manual.yMode === 'edge' ? frame.y + manual.y * frame.h : area.y + manual.y * frame.h) : area.y;
522
+ const w = manual.w !== undefined ? (manual.wMode === 'edge' ? frame.x + manual.w * frame.w - x : manual.w * frame.w) : boxW;
523
+ const h = manual.h !== undefined ? (manual.hMode === 'edge' ? frame.y + manual.h * frame.h - y : manual.h * frame.h) : boxH;
524
+ box = { x, y, w, h };
525
+ return { box, rows, remaining };
526
+ }
527
+ switch (legend.position) {
528
+ case 'l':
529
+ box = { x: area.x, y: area.y + (area.h - boxH) / 2, w: boxW, h: boxH };
530
+ if (!legend.overlay) {
531
+ remaining.x += boxW + gap;
532
+ remaining.w -= boxW + gap;
533
+ }
534
+ break;
535
+ case 't':
536
+ box = { x: area.x + (area.w - boxW) / 2, y: area.y, w: boxW, h: boxH };
537
+ if (!legend.overlay) {
538
+ remaining.y += boxH + gap;
539
+ remaining.h -= boxH + gap;
540
+ }
541
+ break;
542
+ case 'b':
543
+ box = { x: area.x + (area.w - boxW) / 2, y: area.y + area.h - boxH, w: boxW, h: boxH };
544
+ if (!legend.overlay)
545
+ remaining.h -= boxH + gap;
546
+ break;
547
+ case 'tr':
548
+ box = { x: area.x + area.w - boxW, y: area.y, w: boxW, h: boxH };
549
+ if (!legend.overlay)
550
+ remaining.w -= boxW + gap;
551
+ break;
552
+ default:
553
+ box = { x: area.x + area.w - boxW, y: area.y + (area.h - boxH) / 2, w: boxW, h: boxH };
554
+ if (!legend.overlay)
555
+ remaining.w -= boxW + gap;
556
+ }
557
+ return { box, rows, remaining };
558
+ }
559
+ function drawLegend(d, model, plan) {
560
+ const legend = model.legend;
561
+ const st = legend.style;
562
+ const lh = d.lineHeight(st);
563
+ const keyGap = st.size * 0.4;
564
+ d.path(rectPath(plan.box), legend.fill ?? null, legend.line ?? null);
565
+ for (const row of plan.rows) {
566
+ for (const item of row) {
567
+ const x = plan.box.x + item.x;
568
+ const top = plan.box.y + item.y;
569
+ const cy = top + lh / 2;
570
+ const e = item.entry;
571
+ if (e.kind === 'fill') {
572
+ const s = st.size * 0.75;
573
+ // Swatches keep a visible edge only when the series has an outline.
574
+ d.path(rectPath({ x: x + (item.keyW - s) / 2, y: cy - s / 2, w: s, h: s }), e.fill, e.line?.paint ? { ...e.line, width: Math.min(e.line.width, 1), dash: undefined } : null);
575
+ }
576
+ else {
577
+ if (e.line?.paint)
578
+ d.segment(x, cy, x + item.keyW, cy, { ...e.line, width: Math.min(e.line.width, 3) });
579
+ if (e.marker)
580
+ drawMarker(d, e.marker, x + item.keyW / 2, cy);
581
+ }
582
+ d.textBlock(item.lines, x + item.keyW + keyGap, top, st, 'left', 'top');
583
+ }
584
+ }
585
+ }
586
+ function planTitle(d, model, frame, area) {
587
+ const title = model.title;
588
+ const st = title.style;
589
+ const lines = title.lines.flatMap((l) => d.wrap(l, area.w * 0.8, st));
590
+ const lh = d.lineHeight(st);
591
+ const h = lines.length * lh;
592
+ const w = Math.max(...lines.map((l) => d.width(l, st)), 0);
593
+ const remaining = { ...area };
594
+ let cx = area.x + area.w / 2;
595
+ let top = area.y;
596
+ const layout = title.layout;
597
+ if (layout && (layout.x !== undefined || layout.y !== undefined)) {
598
+ // Manual position: x/y are the top-left corner of the title box.
599
+ if (layout.x !== undefined)
600
+ cx = (layout.xMode === 'edge' ? frame.x + layout.x * frame.w : cx - w / 2 + layout.x * frame.w) + w / 2;
601
+ if (layout.y !== undefined)
602
+ top = layout.yMode === 'edge' ? frame.y + layout.y * frame.h : top + layout.y * frame.h;
603
+ if (!title.overlay && top < area.y + h) {
604
+ const used = Math.max(0, top + h - area.y) + 4;
605
+ remaining.y += used;
606
+ remaining.h -= used;
607
+ }
608
+ }
609
+ else if (!title.overlay) {
610
+ const used = h + Math.max(4, st.size * 0.4);
611
+ remaining.y += used;
612
+ remaining.h -= used;
613
+ }
614
+ return {
615
+ remaining,
616
+ draw: () => {
617
+ if (title.fill || title.line)
618
+ d.path(rectPath({ x: cx - w / 2 - 3, y: top - 1, w: w + 6, h: h + 2 }), title.fill ?? null, title.line ?? null);
619
+ d.textBlock(lines, cx, top, st, 'center', 'top');
620
+ },
621
+ };
622
+ }
623
+ function labelFlags(series, i) {
624
+ const dl = series.dataLabels;
625
+ if (!dl)
626
+ return undefined;
627
+ const flags = dl.points.get(i) ?? dl;
628
+ if (flags.deleted)
629
+ return undefined;
630
+ if (!flags.showVal && !flags.showPercent && !flags.showCatName && !flags.showSerName && !flags.showBubbleSize)
631
+ return undefined;
632
+ return flags;
633
+ }
634
+ function labelText(flags, series, i, value, percent, xValue) {
635
+ const parts = [];
636
+ const code = flags.numFmt && !flags.numFmt.sourceLinked ? flags.numFmt.code : series.formatCode;
637
+ if (flags.showSerName)
638
+ parts.push(series.name);
639
+ if (flags.showCatName)
640
+ parts.push(xValue !== undefined ? formatNumber(xValue, series.categoryFormat) : (series.categories[i] ?? String(i + 1)));
641
+ if (flags.showVal)
642
+ parts.push(formatNumber(value, code));
643
+ if (flags.showPercent && percent !== undefined)
644
+ parts.push(formatNumber(percent, flags.numFmt && !flags.numFmt.sourceLinked && flags.numFmt.code.includes('%') ? flags.numFmt.code : '0%'));
645
+ if (flags.showBubbleSize) {
646
+ const b = series.bubbleSizes?.[i];
647
+ if (b !== null && b !== undefined)
648
+ parts.push(formatNumber(b, 'General'));
649
+ }
650
+ return parts.join(flags.separator ?? ', ');
651
+ }
652
+ function drawLabels(d, jobs) {
653
+ for (const job of jobs) {
654
+ const lines = job.text.split('\n');
655
+ if (job.fill) {
656
+ const lh = d.lineHeight(job.style);
657
+ const w = Math.max(...lines.map((l) => d.width(l, job.style)));
658
+ const h = lh * lines.length;
659
+ const left = job.h === 'left' ? job.x : job.h === 'center' ? job.x - w / 2 : job.x - w;
660
+ const top = job.v === 'top' ? job.y : job.v === 'middle' ? job.y - h / 2 : job.y - h;
661
+ d.path(rectPath({ x: left - 2, y: top, w: w + 4, h }), job.fill, null);
662
+ }
663
+ d.textBlock(lines, job.x, job.y, job.style, job.h, job.v);
664
+ }
665
+ }
666
+ const AXIS_TYPES = new Set(['bar', 'line', 'area', 'scatter', 'bubble']);
667
+ function syntheticAxis(id, kind, position, text) {
668
+ return {
669
+ id,
670
+ kind,
671
+ position,
672
+ deleted: true,
673
+ orientation: 'minMax',
674
+ majorTickMark: 'none',
675
+ minorTickMark: 'none',
676
+ tickLblPos: 'none',
677
+ crosses: 'autoZero',
678
+ line: { paint: null, width: 0.75 },
679
+ textStyle: text,
680
+ };
681
+ }
682
+ /** Values of a series as plotted (blanks per dispBlanksAs). */
683
+ function plotted(v, blanks) {
684
+ if (v === null || v === undefined)
685
+ return blanks === 'zero' ? 0 : null;
686
+ return v;
687
+ }
688
+ function stackRange(plot, model) {
689
+ let lo = Number.POSITIVE_INFINITY;
690
+ let hi = Number.NEGATIVE_INFINITY;
691
+ const n = Math.max(0, ...plot.series.map((s) => s.values.length));
692
+ const stacked = plot.grouping === 'stacked' || plot.grouping === 'percentStacked';
693
+ const splitSigns = plot.type === 'bar';
694
+ for (let i = 0; i < n; i++) {
695
+ if (!stacked) {
696
+ for (const s of plot.series) {
697
+ const v = plotted(s.values[i], model.dispBlanksAs);
698
+ if (v === null)
699
+ continue;
700
+ lo = Math.min(lo, v);
701
+ hi = Math.max(hi, v);
702
+ }
703
+ continue;
704
+ }
705
+ const total = plot.series.reduce((a, s) => a + Math.abs(s.values[i] ?? 0), 0);
706
+ let pos = 0;
707
+ let neg = 0;
708
+ let cum = 0;
709
+ for (const s of plot.series) {
710
+ let v = s.values[i] ?? 0;
711
+ if (plot.grouping === 'percentStacked')
712
+ v = total ? v / total : 0;
713
+ if (splitSigns) {
714
+ if (v >= 0)
715
+ pos += v;
716
+ else
717
+ neg += v;
718
+ lo = Math.min(lo, neg);
719
+ hi = Math.max(hi, pos);
720
+ }
721
+ else {
722
+ cum += v;
723
+ lo = Math.min(lo, cum);
724
+ hi = Math.max(hi, cum);
725
+ }
726
+ }
727
+ }
728
+ return { lo, hi };
729
+ }
730
+ function catFrac(info, i) {
731
+ if (info.between)
732
+ return (i + 0.5) / Math.max(info.count, 1);
733
+ return info.count > 1 ? i / (info.count - 1) : 0.5;
734
+ }
735
+ function valFrac(info, v) {
736
+ const s = info.scale;
737
+ if (s.log) {
738
+ const lv = Math.log(Math.max(v, s.min * 1e-6));
739
+ return (lv - Math.log(s.min)) / (Math.log(s.max) - Math.log(s.min));
740
+ }
741
+ return (v - s.min) / (s.max - s.min || 1);
742
+ }
743
+ class AxisLayout {
744
+ inner = { x: 0, y: 0, w: 0, h: 0 };
745
+ coord(info, f) {
746
+ const g = info.reverse ? 1 - f : f;
747
+ return info.horizontal ? this.inner.x + g * this.inner.w : this.inner.y + this.inner.h - g * this.inner.h;
748
+ }
749
+ /** Coordinate of a value on an axis, clamped to the plot. */
750
+ at(info, v) {
751
+ const f = info.role === 'cat' ? catFrac(info, v) : valFrac(info, v);
752
+ return this.coord(info, Math.max(0, Math.min(1, f)));
753
+ }
754
+ /**
755
+ * Where `info`'s axis line sits across the plot, as a fraction of its partner's length from the
756
+ * bottom/left edge (reversal applied): 0 and 1 are the plot edges.
757
+ */
758
+ crossFrac(info) {
759
+ const other = info.partner;
760
+ if (!other)
761
+ return 0;
762
+ const a = info.axis;
763
+ let f;
764
+ if (other.role === 'val') {
765
+ const s = other.scale;
766
+ const v = a.crossesAt ?? (a.crosses === 'max' ? s.max : a.crosses === 'min' ? s.min : s.log ? s.min : 0);
767
+ f = valFrac(other, Math.max(s.min, Math.min(s.max, v)));
768
+ }
769
+ else if (a.crossesAt !== undefined) {
770
+ const k = a.crossesAt - 1;
771
+ f = other.between ? k / Math.max(other.count, 1) : other.count > 1 ? k / (other.count - 1) : 0;
772
+ }
773
+ else
774
+ f = a.crosses === 'max' ? 1 : 0;
775
+ f = Math.max(0, Math.min(1, f));
776
+ return other.reverse ? 1 - f : f;
777
+ }
778
+ /** Page coordinate of `info`'s axis line (y for a horizontal axis, x for a vertical one). */
779
+ cross(info) {
780
+ const g = this.crossFrac(info);
781
+ return info.horizontal ? this.inner.y + this.inner.h - g * this.inner.h : this.inner.x + g * this.inner.w;
782
+ }
783
+ /** Value (on the partner value axis) where `info` crosses: the base of bars and areas. */
784
+ crossValue(info) {
785
+ const other = info.partner;
786
+ if (!other || other.role !== 'val')
787
+ return 0;
788
+ const s = other.scale;
789
+ const a = info.axis;
790
+ const v = a.crossesAt ?? (a.crosses === 'max' ? s.max : a.crosses === 'min' ? s.min : s.log ? s.min : 0);
791
+ return Math.max(s.min, Math.min(s.max, v));
792
+ }
793
+ }
794
+ function axisFormat(info, firstSeries, xRole) {
795
+ const nf = info.axis.numFmt;
796
+ let code;
797
+ if (nf && !nf.sourceLinked)
798
+ code = nf.code;
799
+ else
800
+ code = (xRole ? firstSeries?.categoryFormat : firstSeries?.formatCode) ?? 'General';
801
+ if (info.percent && (code === 'General' || (nf?.sourceLinked ?? true)))
802
+ code = '0%';
803
+ return code;
804
+ }
805
+ function valueLabels(info) {
806
+ const div = info.axis.dispUnits ?? 1;
807
+ return ticks(info.scale).map((v) => formatNumber(v / div, info.format));
808
+ }
809
+ function layoutCategoryLabels(d, info, length, maxOther) {
810
+ const st = info.axis.textStyle;
811
+ const lh = d.lineHeight(st);
812
+ const n = Math.max(info.count, 1);
813
+ const slots = info.between ? n : Math.max(n - 1, 1);
814
+ const band = length / slots;
815
+ let skip = info.axis.tickLblSkip ?? 1;
816
+ const explicitRot = st.rotation !== undefined && Math.abs(st.rotation) <= 90 ? st.rotation : undefined;
817
+ if (info.horizontal) {
818
+ if (explicitRot && explicitRot !== 0 && d.canRotate(st)) {
819
+ const rad = (Math.abs(explicitRot) * Math.PI) / 180;
820
+ const widths = info.labels.map((l) => d.width(l, st));
821
+ const thick = Math.max(0, ...widths.map((w) => w * Math.sin(rad) + lh * Math.cos(rad)));
822
+ if (info.axis.tickLblSkip === undefined && Math.abs(Math.sin(rad)) > 0.1)
823
+ skip = Math.max(1, Math.ceil((lh / Math.sin(rad)) / band));
824
+ return { lines: info.labels.map((l) => [l]), skip, rotation: explicitRot, thickness: thick };
825
+ }
826
+ const maxW = Math.max(band * skip - st.size * 0.4, st.size * 1.5);
827
+ const lines = info.labels.map((l) => d.wrap(l, maxW, st).slice(0, 3));
828
+ const fits = lines.every((ls) => ls.every((l) => d.width(l, st) <= band * skip));
829
+ if (fits)
830
+ return { lines, skip, rotation: 0, thickness: Math.max(1, ...lines.map((l) => l.length)) * lh };
831
+ if (info.axis.tickLblSkip === undefined && d.canRotate(st) && explicitRot === undefined) {
832
+ // Office turns crowded category labels 45° before it starts skipping them.
833
+ const widths = info.labels.map((l) => Math.min(d.width(l, st), maxOther));
834
+ const rotSkip = Math.max(1, Math.ceil((lh * Math.SQRT2) / band));
835
+ return { lines: info.labels.map((l) => [l]), skip: rotSkip, rotation: -45, thickness: Math.max(0, ...widths.map((w) => (w + lh) * Math.SQRT1_2)) };
836
+ }
837
+ const widest = Math.max(0, ...info.labels.map((l) => d.width(l, st)));
838
+ if (info.axis.tickLblSkip === undefined)
839
+ skip = Math.max(1, Math.ceil((widest + st.size * 0.5) / band));
840
+ return { lines: info.labels.map((l) => [l]), skip, rotation: 0, thickness: lh };
841
+ }
842
+ // Vertical category axis (bar charts): labels wrap to a share of the width, then skip if crowded.
843
+ const maxW = Math.max(maxOther * 0.4, st.size * 3);
844
+ const lines = info.labels.map((l) => d.wrap(l, maxW, st).slice(0, 3));
845
+ const tallest = Math.max(1, ...lines.map((l) => l.length)) * lh;
846
+ if (info.axis.tickLblSkip === undefined)
847
+ skip = Math.max(1, Math.ceil(tallest / band - 1e-6));
848
+ const thickness = Math.max(0, ...lines.map((ls) => Math.max(0, ...ls.map((l) => d.width(l, st)))));
849
+ return { lines, skip, rotation: 0, thickness };
850
+ }
851
+ function tickOut(axis) {
852
+ return axis.majorTickMark === 'out' || axis.majorTickMark === 'cross' ? TICK : 0;
853
+ }
854
+ /** Space an axis needs beside the plot: its labels (with ticks) and its title, in points. */
855
+ function axisThickness(d, info, inner, outer) {
856
+ if (!info.visible)
857
+ return { labels: 0, title: 0 };
858
+ const a = info.axis;
859
+ const st = a.textStyle;
860
+ let t = tickOut(a);
861
+ if (a.tickLblPos !== 'none') {
862
+ t += LABEL_GAP;
863
+ const length = info.horizontal ? inner.w : inner.h;
864
+ if (info.role === 'cat') {
865
+ info.catLayout = layoutCategoryLabels(d, info, length, info.horizontal ? outer.h * 0.4 : outer.w);
866
+ t += info.catLayout.thickness;
867
+ if (info.horizontal && info.groups)
868
+ t += info.groups.length * (d.lineHeight(st) + LABEL_GAP);
869
+ }
870
+ else if (info.horizontal)
871
+ t += d.lineHeight(st);
872
+ else
873
+ t += Math.max(0, ...valueLabels(info).map((l) => d.width(l, st)));
874
+ }
875
+ const title = a.title ? a.title.lines.length * d.lineHeight(a.title.style) + LABEL_GAP * 2 : 0;
876
+ return { labels: t, title };
877
+ }
878
+ /**
879
+ * Which side of its line an axis' labels go: "low"/"high" follow the partner's minimum/maximum end;
880
+ * "nextTo" labels go outside the plot when the line sits on an edge (a reversed partner moves it to
881
+ * the far edge), and on the axPos side when the line crosses inside the plot.
882
+ */
883
+ function labelSide(info, layout) {
884
+ const far = info.horizontal ? 't' : 'r';
885
+ const near = info.horizontal ? 'b' : 'l';
886
+ const minAtFar = info.partner?.reverse ?? false;
887
+ if (info.axis.tickLblPos === 'low')
888
+ return minAtFar ? far : near;
889
+ if (info.axis.tickLblPos === 'high')
890
+ return minAtFar ? near : far;
891
+ const g = layout.crossFrac(info);
892
+ if (g >= 1 - 1e-9)
893
+ return far;
894
+ if (g <= 1e-9)
895
+ return near;
896
+ return info.horizontal ? (info.axis.position === 't' ? 't' : 'b') : info.axis.position === 'r' ? 'r' : 'l';
897
+ }
898
+ /** The plot edge on an axis' label side. */
899
+ function edgeOf(inner, side) {
900
+ return side === 'b' ? inner.y + inner.h : side === 't' ? inner.y : side === 'l' ? inner.x : inner.x + inner.w;
901
+ }
902
+ function drawAxisChart(d, model, outer, manualInner, labels) {
903
+ const plots = model.plots.filter((p) => AXIS_TYPES.has(p.type));
904
+ const axesById = new Map(model.axes.map((a) => [a.id, a]));
905
+ const infos = new Map();
906
+ const pairs = [];
907
+ plots.forEach((plot, pi) => {
908
+ const xy = plot.type === 'scatter' || plot.type === 'bubble';
909
+ const horizontalCats = !(plot.type === 'bar' && plot.barDir === 'bar');
910
+ const ids = [plot.axisIds[0] ?? `#x${pi}`, plot.axisIds[1] ?? `#y${pi}`];
911
+ const make = (id, isX) => {
912
+ let info = infos.get(id);
913
+ if (info)
914
+ return info;
915
+ const horizontal = isX ? horizontalCats : !horizontalCats;
916
+ const axis = axesById.get(id) ?? syntheticAxis(id, isX && !xy ? 'cat' : 'val', horizontal ? 'b' : 'l', model.textStyle);
917
+ const role = isX && !xy ? 'cat' : 'val';
918
+ const side = horizontal ? (axis.position === 't' ? 't' : 'b') : axis.position === 'r' ? 'r' : 'l';
919
+ info = {
920
+ axis,
921
+ role,
922
+ horizontal,
923
+ count: 0,
924
+ between: true,
925
+ labels: [],
926
+ lo: Number.POSITIVE_INFINITY,
927
+ hi: Number.NEGATIVE_INFINITY,
928
+ percent: false,
929
+ format: 'General',
930
+ reverse: axis.orientation === 'maxMin',
931
+ side,
932
+ visible: !axis.deleted,
933
+ };
934
+ infos.set(id, info);
935
+ return info;
936
+ };
937
+ const x = make(ids[0], true);
938
+ const y = make(ids[1], false);
939
+ x.partner ??= y;
940
+ y.partner ??= x;
941
+ pairs.push({ plot, x, y });
942
+ });
943
+ // Data extents and category counts.
944
+ for (const { plot, x, y } of pairs) {
945
+ const first = plot.series[0];
946
+ if (x.role === 'cat') {
947
+ const n = Math.max(0, ...plot.series.map((s) => Math.max(s.values.length, s.categories.length)));
948
+ if (n > x.count) {
949
+ x.count = n;
950
+ const src = plot.series.find((s) => s.categories.length > 0) ?? first;
951
+ const nf = x.axis.numFmt;
952
+ x.labels = Array.from({ length: n }, (_, i) => {
953
+ const num = src?.categoryNumbers?.[i];
954
+ if (num !== null && num !== undefined && nf && !nf.sourceLinked)
955
+ return formatNumber(num, nf.code);
956
+ if (num !== null && num !== undefined && src?.categoryFormat && isDateCode(src.categoryFormat))
957
+ return formatNumber(num, src.categoryFormat);
958
+ return src?.categories[i] ?? String(i + 1);
959
+ });
960
+ if (src?.categoryGroups)
961
+ x.groups = src.categoryGroups;
962
+ }
963
+ // Bars sit between tick marks; lines too unless the value axis says midCat (areas default to it).
964
+ const cb = y.axis.crossBetween ?? (plot.type === 'area' ? 'midCat' : 'between');
965
+ if (plot.type === 'bar')
966
+ x.between = true;
967
+ else if (!pairs.some((p) => p.x === x && p.plot.type === 'bar'))
968
+ x.between = cb === 'between';
969
+ }
970
+ else {
971
+ for (const s of plot.series) {
972
+ s.values.forEach((_, i) => {
973
+ const xv = s.categoryNumbers?.[i] ?? (s.categoryNumbers ? null : i + 1);
974
+ if (xv === null)
975
+ return;
976
+ x.lo = Math.min(x.lo, xv);
977
+ x.hi = Math.max(x.hi, xv);
978
+ });
979
+ }
980
+ x.format = axisFormat(x, first, true);
981
+ }
982
+ const r = stackRange(plot, model);
983
+ y.lo = Math.min(y.lo, r.lo);
984
+ y.hi = Math.max(y.hi, r.hi);
985
+ if (plot.grouping === 'percentStacked')
986
+ y.percent = true;
987
+ y.format = axisFormat(y, first, false);
988
+ }
989
+ const all = [...infos.values()];
990
+ const layout = new AxisLayout();
991
+ const computeScales = (inner) => {
992
+ for (const info of all) {
993
+ if (info.role !== 'val')
994
+ continue;
995
+ const st = info.axis.textStyle;
996
+ const lh = d.lineHeight(st);
997
+ const length = info.horizontal ? inner.w : inner.h;
998
+ info.scale = niceScale(info.lo, info.hi, info.axis, length, info.percent, (s) => {
999
+ if (!info.horizontal)
1000
+ return lh * 1.4;
1001
+ const div = info.axis.dispUnits ?? 1;
1002
+ const widest = Math.max(...ticks(s).map((v) => d.width(formatNumber(v / div, info.format), st)));
1003
+ return widest * 1.5 + st.size * 1.5;
1004
+ });
1005
+ }
1006
+ };
1007
+ let inner = manualInner ?? { ...outer };
1008
+ for (let pass = 0; pass < 3; pass++) {
1009
+ computeScales(inner);
1010
+ if (manualInner) {
1011
+ layout.inner = inner;
1012
+ for (const info of all)
1013
+ info.side = labelSide(info, layout);
1014
+ for (const info of all)
1015
+ axisThickness(d, info, inner, outer);
1016
+ break;
1017
+ }
1018
+ const t = { b: 0, t: 0, l: 0, r: 0 };
1019
+ layout.inner = inner;
1020
+ for (const info of all)
1021
+ info.side = labelSide(info, layout);
1022
+ for (const info of all) {
1023
+ const th = axisThickness(d, info, inner, outer);
1024
+ // Labels "next to" an axis line inside the plot (negative values) hang inside it, as in Office.
1025
+ const inside = info.axis.tickLblPos === 'nextTo' && info.partner ? Math.abs(edgeOf(inner, info.side) - layout.cross(info)) : 0;
1026
+ t[info.side] += Math.max(0, th.labels - inside) + th.title;
1027
+ }
1028
+ // Value labels centred on the end ticks stick out past the plot edges.
1029
+ for (const info of all) {
1030
+ if (!info.visible || info.axis.tickLblPos === 'none')
1031
+ continue;
1032
+ const st = info.axis.textStyle;
1033
+ if (info.role === 'val' && !info.horizontal) {
1034
+ const half = d.lineHeight(st) / 2;
1035
+ t.t = Math.max(t.t, half);
1036
+ t.b = Math.max(t.b, half);
1037
+ }
1038
+ else if (info.role === 'val') {
1039
+ const labs = valueLabels(info);
1040
+ t.l = Math.max(t.l, d.width(labs[0] ?? '', st) / 2);
1041
+ t.r = Math.max(t.r, d.width(labs[labs.length - 1] ?? '', st) / 2);
1042
+ }
1043
+ }
1044
+ inner = { x: outer.x + t.l, y: outer.y + t.t, w: Math.max(outer.w - t.l - t.r, 10), h: Math.max(outer.h - t.t - t.b, 10) };
1045
+ }
1046
+ layout.inner = inner;
1047
+ // Plot area, then gridlines.
1048
+ d.path(rectPath(inner), model.plotArea.fill, null);
1049
+ for (const info of all)
1050
+ drawGridlines(d, layout, info, 'minor');
1051
+ for (const info of all)
1052
+ drawGridlines(d, layout, info, 'major');
1053
+ // Plots: areas at the back, then bars, then lines and points.
1054
+ const rank = { area: 0, bar: 1, line: 2, scatter: 3, bubble: 3 };
1055
+ const ordered = [...pairs].sort((a, b) => (rank[a.plot.type] ?? 9) - (rank[b.plot.type] ?? 9));
1056
+ for (const pair of ordered) {
1057
+ switch (pair.plot.type) {
1058
+ case 'bar':
1059
+ drawBars(d, model, layout, pair.plot, pair.x, pair.y, labels);
1060
+ break;
1061
+ case 'area':
1062
+ drawAreas(d, model, layout, pair.plot, pair.x, pair.y, labels);
1063
+ break;
1064
+ case 'line':
1065
+ drawLines(d, model, layout, pair.plot, pair.x, pair.y, labels);
1066
+ break;
1067
+ default:
1068
+ drawScatter(d, model, layout, pair.plot, pair.x, pair.y, labels);
1069
+ }
1070
+ }
1071
+ d.path(rectPath(inner), null, model.plotArea.line);
1072
+ for (const info of all)
1073
+ drawAxis(d, layout, info, outer);
1074
+ }
1075
+ function drawGridlines(d, layout, info, which) {
1076
+ const style = which === 'major' ? info.axis.majorGridlines : info.axis.minorGridlines;
1077
+ if (!style?.paint)
1078
+ return;
1079
+ const { inner } = layout;
1080
+ const positions = [];
1081
+ if (info.role === 'val') {
1082
+ const s = info.scale;
1083
+ if (which === 'major')
1084
+ for (const v of ticks(s))
1085
+ positions.push(layout.coord(info, valFrac(info, v)));
1086
+ else if (!s.log) {
1087
+ const n = Math.round((s.max - s.min) / s.minor);
1088
+ for (let i = 0; i <= Math.min(n, 500); i++)
1089
+ positions.push(layout.coord(info, valFrac(info, s.min + i * s.minor)));
1090
+ }
1091
+ }
1092
+ else {
1093
+ const n = info.count;
1094
+ if (info.between)
1095
+ for (let i = 0; i <= n; i++)
1096
+ positions.push(layout.coord(info, i / Math.max(n, 1)));
1097
+ else
1098
+ for (let i = 0; i < n; i++)
1099
+ positions.push(layout.coord(info, catFrac(info, i)));
1100
+ }
1101
+ for (const p of positions) {
1102
+ if (info.horizontal)
1103
+ d.segment(p, inner.y, p, inner.y + inner.h, style);
1104
+ else
1105
+ d.segment(inner.x, p, inner.x + inner.w, p, style);
1106
+ }
1107
+ }
1108
+ function drawAxis(d, layout, info, outer) {
1109
+ if (!info.visible)
1110
+ return;
1111
+ const a = info.axis;
1112
+ const { inner } = layout;
1113
+ const st = a.textStyle;
1114
+ const lh = d.lineHeight(st);
1115
+ const line = layout.cross(info);
1116
+ const outward = info.side === 'b' || info.side === 'r' ? 1 : -1;
1117
+ // Axis line.
1118
+ if (info.horizontal)
1119
+ d.segment(inner.x, line, inner.x + inner.w, line, a.line);
1120
+ else
1121
+ d.segment(line, inner.y, line, inner.y + inner.h, a.line);
1122
+ // Tick positions along the axis.
1123
+ const tickPos = [];
1124
+ if (info.role === 'val')
1125
+ for (const v of ticks(info.scale))
1126
+ tickPos.push(layout.coord(info, valFrac(info, v)));
1127
+ else if (info.between)
1128
+ for (let i = 0; i <= info.count; i++)
1129
+ tickPos.push(layout.coord(info, i / Math.max(info.count, 1)));
1130
+ else
1131
+ for (let i = 0; i < info.count; i++)
1132
+ tickPos.push(layout.coord(info, catFrac(info, i)));
1133
+ const mark = a.majorTickMark;
1134
+ if (mark !== 'none' && a.line.paint) {
1135
+ const from = mark === 'in' ? -TICK : mark === 'cross' ? -TICK : 0;
1136
+ const to = mark === 'in' ? 0 : TICK;
1137
+ for (const p of tickPos) {
1138
+ if (info.horizontal)
1139
+ d.segment(p, line + outward * from, p, line + outward * to, a.line);
1140
+ else
1141
+ d.segment(line + outward * from, p, line + outward * to, p, a.line);
1142
+ }
1143
+ }
1144
+ // Labels sit next to the axis line, or at the plot edge for low/high.
1145
+ let base = line;
1146
+ if (a.tickLblPos === 'low' || a.tickLblPos === 'high')
1147
+ base = info.horizontal ? (info.side === 'b' ? inner.y + inner.h : inner.y) : info.side === 'l' ? inner.x : inner.x + inner.w;
1148
+ const labelStart = base + outward * (tickOut(a) + LABEL_GAP);
1149
+ let extent = 0;
1150
+ if (a.tickLblPos !== 'none') {
1151
+ if (info.role === 'val') {
1152
+ const values = ticks(info.scale);
1153
+ const labs = valueLabels(info);
1154
+ values.forEach((v, k) => {
1155
+ const p = layout.coord(info, valFrac(info, v));
1156
+ const text = labs[k] ?? '';
1157
+ if (info.horizontal)
1158
+ d.textBlock([text], p, labelStart, st, 'center', outward > 0 ? 'top' : 'bottom');
1159
+ else
1160
+ d.textBlock([text], labelStart, p, st, outward > 0 ? 'left' : 'right', 'middle');
1161
+ });
1162
+ extent = info.horizontal ? lh : Math.max(0, ...labs.map((l) => d.width(l, st)));
1163
+ }
1164
+ else {
1165
+ const cl = info.catLayout ?? layoutCategoryLabels(d, info, info.horizontal ? inner.w : inner.h, outer.w);
1166
+ for (let i = 0; i < info.count; i += cl.skip) {
1167
+ const p = layout.coord(info, catFrac(info, i));
1168
+ const lines = cl.lines[i] ?? [];
1169
+ if (cl.rotation !== 0 && info.horizontal) {
1170
+ // Rotated labels end at the tick (Office's -45° labels read up towards it).
1171
+ const text = lines.join(' ');
1172
+ const rad = (cl.rotation * Math.PI) / 180;
1173
+ const along = cl.rotation < 0 ? 1 : 0;
1174
+ const cy = labelStart + outward * (lh / 2) * Math.abs(Math.cos(rad));
1175
+ if (!d.rotatedText(text, p, cy, st, cl.rotation, along))
1176
+ d.textBlock([text], p, labelStart, st, 'center', outward > 0 ? 'top' : 'bottom');
1177
+ }
1178
+ else if (info.horizontal)
1179
+ d.textBlock(lines, p, labelStart, st, 'center', outward > 0 ? 'top' : 'bottom');
1180
+ else
1181
+ d.textBlock(lines, labelStart, p, st, outward > 0 ? 'left' : 'right', 'middle');
1182
+ }
1183
+ extent = cl.thickness;
1184
+ // Outer levels of multi-level categories: one row per level, labels centred over their groups.
1185
+ if (info.horizontal && info.groups) {
1186
+ let rowStart = labelStart + outward * (extent + LABEL_GAP);
1187
+ for (const level of info.groups) {
1188
+ const starts = [];
1189
+ level.forEach((v, i) => {
1190
+ if (v !== undefined)
1191
+ starts.push(i);
1192
+ });
1193
+ starts.forEach((s, k) => {
1194
+ const e = (starts[k + 1] ?? info.count) - 1;
1195
+ const p1 = layout.coord(info, s / Math.max(info.count, 1));
1196
+ const p2 = layout.coord(info, (e + 1) / Math.max(info.count, 1));
1197
+ d.textBlock([level[s] ?? ''], (p1 + p2) / 2, rowStart, st, 'center', outward > 0 ? 'top' : 'bottom');
1198
+ // Dividers between groups, and closing the last one.
1199
+ d.segment(p1, rowStart - outward * LABEL_GAP, p1, rowStart + outward * lh, a.line);
1200
+ if (k === starts.length - 1)
1201
+ d.segment(p2, rowStart - outward * LABEL_GAP, p2, rowStart + outward * lh, a.line);
1202
+ });
1203
+ rowStart += outward * (lh + LABEL_GAP);
1204
+ extent += lh + LABEL_GAP;
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ // Axis title beyond the labels; vertical axes turn it to read bottom to top.
1210
+ if (a.title) {
1211
+ const t = a.title;
1212
+ const tlh = d.lineHeight(t.style);
1213
+ const labelsEnd = labelStart + outward * extent;
1214
+ const edge = edgeOf(inner, info.side);
1215
+ const pos = (outward > 0 ? Math.max(labelsEnd, edge) : Math.min(labelsEnd, edge)) + outward * LABEL_GAP;
1216
+ if (info.horizontal)
1217
+ d.textBlock(t.lines, inner.x + inner.w / 2, pos, t.style, 'center', outward > 0 ? 'top' : 'bottom');
1218
+ else {
1219
+ const rot = t.style.rotation !== undefined && Math.abs(t.style.rotation) <= 90 ? t.style.rotation : -90;
1220
+ const cx = pos + (outward * (t.lines.length * tlh)) / 2;
1221
+ const cy = inner.y + inner.h / 2;
1222
+ const text = t.lines.join(' ');
1223
+ if (rot === 0 || !d.rotatedText(text, cx, cy, t.style, rot, 0.5)) {
1224
+ // Without outlines the title stays horizontal, above the plot on the axis' side.
1225
+ if (outward > 0)
1226
+ d.textBlock(t.lines, outer.x + outer.w, inner.y - LABEL_GAP, t.style, 'right', 'bottom');
1227
+ else
1228
+ d.textBlock(t.lines, outer.x, inner.y - LABEL_GAP, t.style, 'left', 'bottom');
1229
+ }
1230
+ }
1231
+ }
1232
+ }
1233
+ function barRect(layout, x, y, f0, f1, from, to) {
1234
+ const a = layout.coord(x, f0);
1235
+ const b = layout.coord(x, f1);
1236
+ const c = layout.coord(y, Math.max(0, Math.min(1, valFrac(y, from))));
1237
+ const e = layout.coord(y, Math.max(0, Math.min(1, valFrac(y, to))));
1238
+ if (x.horizontal)
1239
+ return { x: Math.min(a, b), y: Math.min(c, e), w: Math.abs(b - a), h: Math.abs(e - c) };
1240
+ return { x: Math.min(c, e), y: Math.min(a, b), w: Math.abs(e - c), h: Math.abs(b - a) };
1241
+ }
1242
+ function drawBars(d, model, layout, plot, x, y, labels) {
1243
+ const n = Math.max(x.count, 1);
1244
+ const stacked = plot.grouping === 'stacked' || plot.grouping === 'percentStacked';
1245
+ const slots = stacked ? 1 : Math.max(plot.series.length, 1);
1246
+ const ov = Math.max(-100, Math.min(100, plot.overlap)) / 100;
1247
+ const gap = Math.max(0, Math.min(500, plot.gapWidth)) / 100;
1248
+ const band = 1 / n;
1249
+ const barW = band / (slots - (slots - 1) * ov + gap);
1250
+ const groupW = barW * (slots - (slots - 1) * ov);
1251
+ const base = layout.crossValue(x);
1252
+ const pos = new Array(n).fill(0);
1253
+ const neg = new Array(n).fill(0);
1254
+ const totals = Array.from({ length: n }, (_, i) => plot.series.reduce((a, s) => a + Math.abs(s.values[i] ?? 0), 0));
1255
+ const varied = isVaried(plot);
1256
+ plot.series.forEach((s, si) => {
1257
+ for (let i = 0; i < n; i++) {
1258
+ const raw = plotted(s.values[i], model.dispBlanksAs);
1259
+ if (raw === null)
1260
+ continue;
1261
+ const v = plot.grouping === 'percentStacked' ? (totals[i] ? raw / totals[i] : 0) : raw;
1262
+ let from;
1263
+ let to;
1264
+ if (stacked) {
1265
+ if (v >= 0) {
1266
+ from = pos[i];
1267
+ to = from + v;
1268
+ pos[i] = to;
1269
+ }
1270
+ else {
1271
+ from = neg[i];
1272
+ to = from + v;
1273
+ neg[i] = to;
1274
+ }
1275
+ }
1276
+ else {
1277
+ from = y.scale.log ? y.scale.min : base;
1278
+ to = v;
1279
+ }
1280
+ const f0 = i * band + (band - groupW) / 2 + (stacked ? 0 : si) * barW * (1 - ov);
1281
+ const box = barRect(layout, x, y, f0, f0 + barW, from, to);
1282
+ const pt = s.points.find((p) => p.index === i);
1283
+ let fill = pt?.fill !== undefined ? pt.fill : varied && s.pointColors?.[i] ? { color: s.pointColors[i], opacity: 1 } : s.fill;
1284
+ const line = pt?.line ?? s.line;
1285
+ if ((pt?.invertIfNegative ?? s.invertIfNegative) && v < 0)
1286
+ fill = { color: 'FFFFFF', opacity: 1 };
1287
+ d.path(rectPath(box), fill, line, { lineJoin: 'miter' });
1288
+ const flags = labelFlags(s, i);
1289
+ if (flags) {
1290
+ const text = labelText(flags, s, i, raw, undefined);
1291
+ const position = flags.position ?? (stacked ? 'ctr' : 'outEnd');
1292
+ const up = to >= from !== y.reverse;
1293
+ labels.push(barLabel(text, box, x.horizontal, up, position, flags));
1294
+ }
1295
+ }
1296
+ });
1297
+ }
1298
+ function barLabel(text, box, vertical, positive, position, flags) {
1299
+ const job = (xx, yy, h, v) => {
1300
+ const j = { text, x: xx, y: yy, h, v, style: flags.style };
1301
+ if (flags.fill)
1302
+ j.fill = flags.fill;
1303
+ return j;
1304
+ };
1305
+ const g = 2;
1306
+ if (vertical) {
1307
+ const cx = box.x + box.w / 2;
1308
+ const endY = positive ? box.y : box.y + box.h;
1309
+ const baseY = positive ? box.y + box.h : box.y;
1310
+ switch (position) {
1311
+ case 'ctr':
1312
+ return job(cx, box.y + box.h / 2, 'center', 'middle');
1313
+ case 'inEnd':
1314
+ return job(cx, endY + (positive ? g : -g), 'center', positive ? 'top' : 'bottom');
1315
+ case 'inBase':
1316
+ return job(cx, baseY + (positive ? -g : g), 'center', positive ? 'bottom' : 'top');
1317
+ default:
1318
+ return job(cx, endY + (positive ? -g : g), 'center', positive ? 'bottom' : 'top');
1319
+ }
1320
+ }
1321
+ const cy = box.y + box.h / 2;
1322
+ const endX = positive ? box.x + box.w : box.x;
1323
+ const baseX = positive ? box.x : box.x + box.w;
1324
+ switch (position) {
1325
+ case 'ctr':
1326
+ return job(box.x + box.w / 2, cy, 'center', 'middle');
1327
+ case 'inEnd':
1328
+ return job(endX + (positive ? -g : g), cy, positive ? 'right' : 'left', 'middle');
1329
+ case 'inBase':
1330
+ return job(baseX + (positive ? g : -g), cy, positive ? 'left' : 'right', 'middle');
1331
+ default:
1332
+ return job(endX + (positive ? g : -g), cy, positive ? 'left' : 'right', 'middle');
1333
+ }
1334
+ }
1335
+ /** Plotted points of each series of a line or area plot (stacked and percent-stacked applied). */
1336
+ function seriesPoints(model, layout, plot, x, y, area) {
1337
+ const n = x.count;
1338
+ const cum = new Array(n).fill(0);
1339
+ const stacked = plot.grouping === 'stacked' || plot.grouping === 'percentStacked';
1340
+ const totals = Array.from({ length: n }, (_, i) => plot.series.reduce((a, s) => a + Math.abs(s.values[i] ?? 0), 0));
1341
+ return plot.series.map((s) => {
1342
+ const pts = [];
1343
+ for (let i = 0; i < n; i++) {
1344
+ // Stacked and area series treat blanks as zero so the stack stays closed.
1345
+ const raw = stacked || area ? (s.values[i] ?? 0) : plotted(s.values[i], model.dispBlanksAs);
1346
+ if (raw === null || i >= s.values.length) {
1347
+ pts.push(null);
1348
+ continue;
1349
+ }
1350
+ let v = plot.grouping === 'percentStacked' ? (totals[i] ? raw / totals[i] : 0) : raw;
1351
+ const lower = stacked ? cum[i] : 0;
1352
+ if (stacked) {
1353
+ v += cum[i];
1354
+ cum[i] = v;
1355
+ }
1356
+ pts.push({ x: 0, y: 0, v, raw, i, lower });
1357
+ }
1358
+ for (const p of pts) {
1359
+ if (!p)
1360
+ continue;
1361
+ const a = layout.coord(x, catFrac(x, p.i));
1362
+ const b = layout.at(y, p.v);
1363
+ if (x.horizontal) {
1364
+ p.x = a;
1365
+ p.y = b;
1366
+ }
1367
+ else {
1368
+ p.x = b;
1369
+ p.y = a;
1370
+ }
1371
+ }
1372
+ return pts;
1373
+ });
1374
+ }
1375
+ /** Split a point list at gaps (or join across them for "span"). */
1376
+ function runsOf(pts, span) {
1377
+ const runs = [];
1378
+ let cur = [];
1379
+ for (const p of pts) {
1380
+ if (p === null) {
1381
+ if (!span && cur.length) {
1382
+ runs.push(cur);
1383
+ cur = [];
1384
+ }
1385
+ continue;
1386
+ }
1387
+ cur.push(p);
1388
+ }
1389
+ if (cur.length)
1390
+ runs.push(cur);
1391
+ return runs;
1392
+ }
1393
+ function pointLabel(text, px, py, position, flags) {
1394
+ const g = 3;
1395
+ const job = { text, x: px + g, y: py, h: 'left', v: 'middle', style: flags.style };
1396
+ switch (position) {
1397
+ case 't':
1398
+ Object.assign(job, { x: px, y: py - g, h: 'center', v: 'bottom' });
1399
+ break;
1400
+ case 'b':
1401
+ Object.assign(job, { x: px, y: py + g, h: 'center', v: 'top' });
1402
+ break;
1403
+ case 'l':
1404
+ Object.assign(job, { x: px - g, h: 'right' });
1405
+ break;
1406
+ case 'ctr':
1407
+ Object.assign(job, { x: px, h: 'center' });
1408
+ break;
1409
+ default:
1410
+ break;
1411
+ }
1412
+ if (flags.fill)
1413
+ job.fill = flags.fill;
1414
+ return job;
1415
+ }
1416
+ function drawLines(d, model, layout, plot, x, y, labels) {
1417
+ const all = seriesPoints(model, layout, plot, x, y, false);
1418
+ plot.series.forEach((s, si) => {
1419
+ const pts = all[si];
1420
+ if (s.line.paint) {
1421
+ for (const run of runsOf(pts, model.dispBlanksAs === 'span')) {
1422
+ if (run.length < 2)
1423
+ continue;
1424
+ d.path(s.smooth ? smoothPath(run) : polyline(run), null, s.line);
1425
+ }
1426
+ }
1427
+ for (const p of pts) {
1428
+ if (!p)
1429
+ continue;
1430
+ const pt = s.points.find((q) => q.index === p.i);
1431
+ drawMarker(d, pt?.marker ?? s.marker, p.x, p.y);
1432
+ const flags = labelFlags(s, p.i);
1433
+ if (flags)
1434
+ labels.push(pointLabel(labelText(flags, s, p.i, p.raw, undefined), p.x, p.y, flags.position ?? 'r', flags));
1435
+ }
1436
+ });
1437
+ }
1438
+ function drawAreas(d, model, layout, plot, x, y, labels) {
1439
+ const all = seriesPoints(model, layout, plot, x, y, true);
1440
+ const stacked = plot.grouping === 'stacked' || plot.grouping === 'percentStacked';
1441
+ const baseValue = layout.crossValue(x);
1442
+ plot.series.forEach((s, si) => {
1443
+ const pts = all[si].filter((p) => p !== null);
1444
+ if (pts.length === 0)
1445
+ return;
1446
+ const cmds = polyline(pts);
1447
+ // Down the lower edge: the previous stack level, or the axis crossing.
1448
+ for (let k = pts.length - 1; k >= 0; k--) {
1449
+ const p = pts[k];
1450
+ const lowerV = stacked ? p.lower : baseValue;
1451
+ const c = layout.at(y, lowerV);
1452
+ cmds.push(x.horizontal ? { op: 'L', x: p.x, y: c } : { op: 'L', x: c, y: p.y });
1453
+ }
1454
+ cmds.push({ op: 'Z' });
1455
+ d.path(cmds, s.fill, s.line.paint ? s.line : null, { lineJoin: 'round' });
1456
+ for (const p of pts) {
1457
+ const flags = labelFlags(s, p.i);
1458
+ if (!flags)
1459
+ continue;
1460
+ const lowerC = layout.at(y, stacked ? p.lower : baseValue);
1461
+ const mx = x.horizontal ? p.x : (p.x + lowerC) / 2;
1462
+ const my = x.horizontal ? (p.y + lowerC) / 2 : p.y;
1463
+ labels.push(pointLabel(labelText(flags, s, p.i, p.raw, undefined), mx, my, 'ctr', flags));
1464
+ }
1465
+ });
1466
+ }
1467
+ function drawScatter(d, model, layout, plot, x, y, labels) {
1468
+ const bubble = plot.type === 'bubble';
1469
+ const maxSize = bubble ? Math.max(0, ...plot.series.flatMap((s) => (s.bubbleSizes ?? []).map((b) => Math.abs(b ?? 0)))) : 0;
1470
+ // The largest bubble's diameter is a quarter of the plot's smaller side at 100% scale.
1471
+ const maxR = (Math.min(layout.inner.w, layout.inner.h) / 8) * (plot.bubbleScale / 100);
1472
+ for (const s of plot.series) {
1473
+ const pts = s.values.map((v, i) => {
1474
+ const yv = plotted(v, model.dispBlanksAs);
1475
+ const xv = s.categoryNumbers ? s.categoryNumbers[i] : i + 1;
1476
+ if (yv === null || xv === null || xv === undefined)
1477
+ return null;
1478
+ const px = layout.at(x, xv);
1479
+ const py = layout.at(y, yv);
1480
+ return x.horizontal ? { x: px, y: py, i, xv, v: yv } : { x: py, y: px, i, xv, v: yv };
1481
+ });
1482
+ if (bubble) {
1483
+ for (const p of pts) {
1484
+ if (!p)
1485
+ continue;
1486
+ const size = Math.abs(s.bubbleSizes?.[p.i] ?? 0);
1487
+ const r = maxSize > 0 ? Math.sqrt(size / maxSize) * maxR : 0;
1488
+ if (r > 0)
1489
+ d.path(circlePath(p.x, p.y, r), pointFill(s, p.i), pointLine(s, p.i));
1490
+ }
1491
+ }
1492
+ else {
1493
+ if (s.line.paint) {
1494
+ for (const run of runsOf(pts, model.dispBlanksAs === 'span')) {
1495
+ if (run.length < 2)
1496
+ continue;
1497
+ d.path(s.smooth ? smoothPath(run) : polyline(run), null, s.line);
1498
+ }
1499
+ }
1500
+ for (const p of pts)
1501
+ if (p)
1502
+ drawMarker(d, s.points.find((q) => q.index === p.i)?.marker ?? s.marker, p.x, p.y);
1503
+ }
1504
+ for (const p of pts) {
1505
+ if (!p)
1506
+ continue;
1507
+ const flags = labelFlags(s, p.i);
1508
+ if (flags)
1509
+ labels.push(pointLabel(labelText(flags, s, p.i, p.v, undefined, p.xv), p.x, p.y, flags.position ?? (bubble ? 'ctr' : 'r'), flags));
1510
+ }
1511
+ }
1512
+ }
1513
+ // ---------------------------------------------------------------------------------------------
1514
+ // Pie and doughnut
1515
+ function drawPie(d, model, outer, labels) {
1516
+ const plot = model.plots.find((p) => p.type === 'pie' || p.type === 'doughnut');
1517
+ const doughnut = plot.type === 'doughnut';
1518
+ const series = doughnut ? plot.series : plot.series.slice(0, 1);
1519
+ if (series.length === 0)
1520
+ return;
1521
+ const cx = outer.x + outer.w / 2;
1522
+ const cy = outer.y + outer.h / 2;
1523
+ // Slices of each ring: angles in degrees clockwise from 12 o'clock.
1524
+ const rings = series.map((s) => {
1525
+ const total = s.values.reduce((a, v) => a + Math.abs(v ?? 0), 0);
1526
+ let angle = plot.firstSliceAng;
1527
+ return s.values.map((v, i) => {
1528
+ const value = Math.abs(v ?? 0);
1529
+ const sweep = total > 0 ? (value / total) * 360 : 0;
1530
+ const slice = { i, start: angle, sweep, value: v ?? 0, percent: total > 0 ? value / total : 0 };
1531
+ angle += sweep;
1532
+ return slice;
1533
+ });
1534
+ });
1535
+ const maxExplosion = Math.max(0, ...series.flatMap((s) => [s.explosion, ...s.points.map((p) => p.explosion ?? 0)]));
1536
+ // Labels decide how much room the pie leaves around itself.
1537
+ const first = series[series.length - 1];
1538
+ const ringSlices = rings[series.length - 1];
1539
+ const texts = ringSlices.map((sl) => {
1540
+ const flags = labelFlags(first, sl.i);
1541
+ return flags ? { flags, text: labelText(flags, first, sl.i, sl.value, sl.percent) } : undefined;
1542
+ });
1543
+ const lhOf = (st) => d.lineHeight(st);
1544
+ let radius = Math.max(4, Math.min(outer.w, outer.h) / 2) / (1 + maxExplosion / 100);
1545
+ const outside = new Set();
1546
+ if (!doughnut) {
1547
+ const r0 = radius * 0.95;
1548
+ texts.forEach((t, k) => {
1549
+ if (!t)
1550
+ return;
1551
+ const pos = t.flags.position ?? 'bestFit';
1552
+ if (pos === 'outEnd')
1553
+ outside.add(k);
1554
+ else if (pos === 'bestFit') {
1555
+ const sl = ringSlices[k];
1556
+ const lines = t.text.split('\n');
1557
+ const w = Math.max(...lines.map((l) => d.width(l, t.flags.style)));
1558
+ const h = lines.length * lhOf(t.flags.style);
1559
+ const rho = r0 * 0.62;
1560
+ const arc = (Math.min(sl.sweep, 180) * Math.PI) / 180 * rho;
1561
+ if (arc < w * 0.9 || r0 - rho < h * 0.6)
1562
+ outside.add(k);
1563
+ }
1564
+ });
1565
+ if (outside.size) {
1566
+ let mx = 0;
1567
+ let my = 0;
1568
+ for (const k of outside) {
1569
+ const t = texts[k];
1570
+ const lines = t.text.split('\n');
1571
+ mx = Math.max(mx, ...lines.map((l) => d.width(l, t.flags.style)));
1572
+ my = Math.max(my, lines.length * lhOf(t.flags.style));
1573
+ }
1574
+ radius = Math.max(4, Math.min((outer.w - 2 * (mx + 6)) / 2, (outer.h - 2 * (my + 6)) / 2)) / (1 + maxExplosion / 100);
1575
+ }
1576
+ else
1577
+ radius *= 0.95;
1578
+ }
1579
+ else
1580
+ radius *= 0.95;
1581
+ const hole = doughnut ? (Math.max(10, Math.min(90, plot.holeSize)) / 100) * radius : 0;
1582
+ const ringW = (radius - hole) / series.length;
1583
+ const varied = plot.varyColors;
1584
+ series.forEach((s, si) => {
1585
+ const r1 = doughnut ? hole + si * ringW : 0;
1586
+ const r2 = doughnut ? hole + (si + 1) * ringW : radius;
1587
+ for (const sl of rings[si]) {
1588
+ if (sl.sweep <= 0)
1589
+ continue;
1590
+ const pt = s.points.find((p) => p.index === sl.i);
1591
+ const ex = ((pt?.explosion ?? s.explosion) / 100) * radius;
1592
+ const mid = sl.start + sl.sweep / 2;
1593
+ const off = ex > 0 ? polar(0, 0, ex, mid) : { x: 0, y: 0 };
1594
+ const ox = cx + off.x;
1595
+ const oy = cy + off.y;
1596
+ const cmds = [];
1597
+ if (sl.sweep >= 359.999) {
1598
+ cmds.push(...circlePath(ox, oy, r2));
1599
+ if (r1 > 0)
1600
+ cmds.push(...circlePath(ox, oy, r1));
1601
+ }
1602
+ else if (r1 > 0) {
1603
+ const a = polar(ox, oy, r2, sl.start);
1604
+ cmds.push({ op: 'M', x: a.x, y: a.y });
1605
+ arcTo(cmds, ox, oy, r2, sl.start, sl.start + sl.sweep);
1606
+ const b = polar(ox, oy, r1, sl.start + sl.sweep);
1607
+ cmds.push({ op: 'L', x: b.x, y: b.y });
1608
+ arcTo(cmds, ox, oy, r1, sl.start + sl.sweep, sl.start);
1609
+ cmds.push({ op: 'Z' });
1610
+ }
1611
+ else {
1612
+ const a = polar(ox, oy, r2, sl.start);
1613
+ cmds.push({ op: 'M', x: ox, y: oy }, { op: 'L', x: a.x, y: a.y });
1614
+ arcTo(cmds, ox, oy, r2, sl.start, sl.start + sl.sweep);
1615
+ cmds.push({ op: 'Z' });
1616
+ }
1617
+ const fill = pt?.fill !== undefined ? pt.fill : varied && s.pointColors?.[sl.i] ? { color: s.pointColors[sl.i], opacity: 1 } : s.fill;
1618
+ d.path(cmds, fill, pt?.line ?? s.line, { evenOdd: sl.sweep >= 359.999 && r1 > 0, lineJoin: 'round' });
1619
+ const flags = labelFlags(s, sl.i);
1620
+ if (!flags)
1621
+ continue;
1622
+ const text = labelText(flags, s, sl.i, sl.value, sl.percent);
1623
+ if (!text)
1624
+ continue;
1625
+ const pos = flags.position ?? 'bestFit';
1626
+ const job = { text, x: 0, y: 0, h: 'center', v: 'middle', style: flags.style };
1627
+ if (flags.fill)
1628
+ job.fill = flags.fill;
1629
+ if (doughnut || !outside.has(sl.i) || pos === 'ctr' || pos === 'inEnd' || pos === 'inBase') {
1630
+ const rho = doughnut ? (r1 + r2) / 2 : pos === 'inEnd' ? r2 * 0.78 : pos === 'ctr' ? r2 * 0.5 : r2 * 0.62;
1631
+ const p = polar(ox, oy, rho, mid);
1632
+ job.x = p.x;
1633
+ job.y = p.y;
1634
+ }
1635
+ else {
1636
+ const p = polar(ox, oy, r2 + 5, mid);
1637
+ job.x = p.x;
1638
+ job.y = p.y;
1639
+ const sin = Math.sin((mid * Math.PI) / 180);
1640
+ job.h = sin > 0.15 ? 'left' : sin < -0.15 ? 'right' : 'center';
1641
+ const cos = Math.cos((mid * Math.PI) / 180);
1642
+ job.v = job.h === 'center' ? (cos > 0 ? 'bottom' : 'top') : 'middle';
1643
+ }
1644
+ labels.push(job);
1645
+ }
1646
+ });
1647
+ }
1648
+ // ---------------------------------------------------------------------------------------------
1649
+ // Radar
1650
+ function drawRadar(d, model, outer, labels) {
1651
+ const plot = model.plots.find((p) => p.type === 'radar');
1652
+ const axes = new Map(model.axes.map((a) => [a.id, a]));
1653
+ const catAxis = axes.get(plot.axisIds[0] ?? '') ?? syntheticAxis('#rc', 'cat', 'b', model.textStyle);
1654
+ const valAxis = axes.get(plot.axisIds[1] ?? '') ?? syntheticAxis('#rv', 'val', 'l', model.textStyle);
1655
+ const first = plot.series[0];
1656
+ const n = Math.max(0, ...plot.series.map((s) => Math.max(s.values.length, s.categories.length)));
1657
+ if (n === 0)
1658
+ return;
1659
+ const cats = Array.from({ length: n }, (_, i) => first?.categories[i] ?? String(i + 1));
1660
+ const st = catAxis.textStyle;
1661
+ const lh = d.lineHeight(st);
1662
+ const showCats = !catAxis.deleted && catAxis.tickLblPos !== 'none';
1663
+ const labelW = showCats ? Math.max(0, ...cats.map((c) => d.width(c, st))) : 0;
1664
+ const radius = Math.max(4, Math.min(outer.w / 2 - labelW - 6, outer.h / 2 - (showCats ? lh * 1.5 : 0) - 6));
1665
+ const cx = outer.x + outer.w / 2;
1666
+ const cy = outer.y + outer.h / 2;
1667
+ let lo = Number.POSITIVE_INFINITY;
1668
+ let hi = Number.NEGATIVE_INFINITY;
1669
+ for (const s of plot.series)
1670
+ for (const v of s.values)
1671
+ if (v !== null && v !== undefined) {
1672
+ lo = Math.min(lo, v);
1673
+ hi = Math.max(hi, v);
1674
+ }
1675
+ const vst = valAxis.textStyle;
1676
+ const scale = niceScale(lo, hi, valAxis, radius, false, () => d.lineHeight(vst) * 1.6);
1677
+ const rOf = (v) => (Math.max(scale.min, Math.min(scale.max, v)) - scale.min) / (scale.max - scale.min || 1) * radius;
1678
+ const angle = (i) => (i * 360) / n;
1679
+ // Web: rings at each major tick, spokes per category.
1680
+ const ring = valAxis.majorGridlines ?? { paint: { color: 'D9D9D9', opacity: 1 }, width: 0.75 };
1681
+ for (const v of ticks(scale)) {
1682
+ const r = rOf(v);
1683
+ if (r <= 0)
1684
+ continue;
1685
+ const pts = Array.from({ length: n }, (_, i) => polar(cx, cy, r, angle(i)));
1686
+ d.path([...polyline(pts), { op: 'Z' }], null, ring);
1687
+ }
1688
+ const spoke = catAxis.majorGridlines ?? ring;
1689
+ for (let i = 0; i < n; i++) {
1690
+ const p = polar(cx, cy, radius, angle(i));
1691
+ d.segment(cx, cy, p.x, p.y, spoke);
1692
+ }
1693
+ if (!valAxis.deleted) {
1694
+ d.segment(cx, cy, cx, cy - radius, valAxis.line);
1695
+ if (valAxis.tickLblPos !== 'none') {
1696
+ const fmt = valAxis.numFmt && !valAxis.numFmt.sourceLinked ? valAxis.numFmt.code : (first?.formatCode ?? 'General');
1697
+ for (const v of ticks(scale))
1698
+ d.textBlock([formatNumber(v, fmt)], cx - LABEL_GAP, cy - rOf(v), vst, 'right', 'middle');
1699
+ }
1700
+ }
1701
+ if (showCats) {
1702
+ cats.forEach((c, i) => {
1703
+ const a = angle(i);
1704
+ const sin = Math.sin((a * Math.PI) / 180);
1705
+ const cos = Math.cos((a * Math.PI) / 180);
1706
+ const p = polar(cx, cy, radius + 4 + (Math.abs(cos) * d.lineHeight(vst)) / 2, a);
1707
+ const h = sin > 0.1 ? 'left' : sin < -0.1 ? 'right' : 'center';
1708
+ const v = h !== 'center' ? 'middle' : cos > 0 ? 'bottom' : 'top';
1709
+ d.textBlock([c], p.x, p.y, st, h, v);
1710
+ });
1711
+ }
1712
+ const filled = plot.radarStyle === 'filled';
1713
+ for (const s of plot.series) {
1714
+ const pts = Array.from({ length: n }, (_, i) => polar(cx, cy, rOf(s.values[i] ?? 0), angle(i)));
1715
+ d.path([...polyline(pts), { op: 'Z' }], filled ? s.fill : null, filled ? (s.line.paint ? s.line : null) : s.line, { lineJoin: 'round' });
1716
+ if (!filled)
1717
+ pts.forEach((p) => drawMarker(d, s.marker, p.x, p.y));
1718
+ pts.forEach((p, i) => {
1719
+ const flags = labelFlags(s, i);
1720
+ const v = s.values[i];
1721
+ if (flags && v !== null && v !== undefined)
1722
+ labels.push(pointLabel(labelText(flags, s, i, v, undefined), p.x, p.y, flags.position ?? 't', flags));
1723
+ });
1724
+ }
1725
+ }
1726
+ // ---------------------------------------------------------------------------------------------
1727
+ // The chart
1728
+ function manualBox(layout, frame, dflt) {
1729
+ const x = layout.x === undefined ? dflt.x : layout.xMode === 'edge' ? frame.x + layout.x * frame.w : dflt.x + layout.x * frame.w;
1730
+ const y = layout.y === undefined ? dflt.y : layout.yMode === 'edge' ? frame.y + layout.y * frame.h : dflt.y + layout.y * frame.h;
1731
+ const w = layout.w === undefined ? dflt.x + dflt.w - x : layout.wMode === 'edge' ? frame.x + layout.w * frame.w - x : layout.w * frame.w;
1732
+ const h = layout.h === undefined ? dflt.y + dflt.h - y : layout.hMode === 'edge' ? frame.y + layout.h * frame.h - y : layout.h * frame.h;
1733
+ return { x, y, w: Math.max(w, 1), h: Math.max(h, 1) };
1734
+ }
1735
+ /** Draw an already-read chart model into `frame`. */
1736
+ export function drawChart(model, frame, options) {
1737
+ const d = new Draw(options.fonts, options.defaultFont ?? 'Calibri');
1738
+ if (!(frame.w > 0 && frame.h > 0))
1739
+ return d.items;
1740
+ const ca = model.chartArea;
1741
+ d.path(rectPath(frame, ca.roundedCorners ? Math.min(frame.w, frame.h) * 0.06 : 0), ca.fill, ca.line);
1742
+ const pad = Math.max(2, Math.min(7, Math.min(frame.w, frame.h) * 0.03));
1743
+ let area = { x: frame.x + pad, y: frame.y + pad, w: frame.w - 2 * pad, h: frame.h - 2 * pad };
1744
+ let title;
1745
+ if (model.title && model.title.text.trim()) {
1746
+ title = planTitle(d, model, frame, area);
1747
+ area = title.remaining;
1748
+ }
1749
+ const legend = model.legend ? planLegend(d, model, frame, area) : undefined;
1750
+ if (legend)
1751
+ area = legend.remaining;
1752
+ const layout = model.plotArea.layout;
1753
+ const placed = layout ? manualBox(layout, frame, area) : area;
1754
+ const outer = layout && layout.target === 'outer' ? placed : area;
1755
+ const manualInner = layout && layout.target === 'inner' ? placed : undefined;
1756
+ const labels = [];
1757
+ if (model.plots.some((p) => AXIS_TYPES.has(p.type)))
1758
+ drawAxisChart(d, model, outer, manualInner, labels);
1759
+ else {
1760
+ const box = manualInner ?? outer;
1761
+ d.path(rectPath(box), model.plotArea.fill, model.plotArea.line);
1762
+ if (model.plots.some((p) => p.type === 'pie' || p.type === 'doughnut'))
1763
+ drawPie(d, model, box, labels);
1764
+ else if (model.plots.some((p) => p.type === 'radar'))
1765
+ drawRadar(d, model, box, labels);
1766
+ }
1767
+ drawLabels(d, labels);
1768
+ title?.draw();
1769
+ if (legend)
1770
+ drawLegend(d, model, legend);
1771
+ return d.items;
1772
+ }