@formancy/report-render-pdf 0.2.0 → 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.
@@ -0,0 +1,1056 @@
1
+ import { a as chartOption, c as held$1, d as tooLarge, i as barWidth, l as named, n as AXIS, o as chartWords, r as GRID, s as pieCircle, u as points } from "./render-D4q7IZ7I.mjs";
2
+ import { RenderRefusal } from "@formancy/report-runtime";
3
+ import { BarChart, LineChart, PieChart } from "echarts/charts";
4
+ import { GridComponent, LegendComponent, TitleComponent } from "echarts/components";
5
+ import { init, setPlatformAPI, use } from "echarts/core";
6
+ import { SVGRenderer } from "echarts/renderers";
7
+ import { platformApi, setPlatformAPI as setPlatformAPI$1 } from "zrender/lib/core/platform.js";
8
+ // src/chart-measure.ts
9
+ /** zrender's platform, the one ECharts measures through, as `Platform` views it. */
10
+ const platform = platformApi;
11
+ /** `to`'s three functions set as zrender's. */
12
+ function set(to) {
13
+ platform.measureText = to.measureText;
14
+ platform.createCanvas = to.createCanvas;
15
+ platform.loadImage = to.loadImage;
16
+ }
17
+ /**
18
+ * What `lay` returns, run with the three functions `replace` makes of
19
+ * those that stand -- which it may call, as a wrapper does -- set as
20
+ * zrender's, and the three that stood put back after it, also when it
21
+ * throws: the one place zrender's platform is replaced, for a render's
22
+ * layout and for the tests that look on.
23
+ */
24
+ function withPlatform(replace, lay) {
25
+ const standing = {
26
+ measureText: platform.measureText,
27
+ createCanvas: platform.createCanvas,
28
+ loadImage: platform.loadImage
29
+ };
30
+ set(replace(standing));
31
+ try {
32
+ return lay();
33
+ } finally {
34
+ set(standing);
35
+ }
36
+ }
37
+ /** zrender's probe for a font's line: the width of this character, which it takes as a line's height. */
38
+ const LINE_PROBE = "国";
39
+ /** The font string zrender measures `face`'s words in: style, weight, size in pixels and family, joined as ECharts' `getFont` and zrender's `Text` join them. */
40
+ const fontOf = ({ font }) => `${font.fontStyle} ${font.fontWeight} ${String(font.fontSize)}px ${font.fontFamily}`;
41
+ /**
42
+ * What `lay` returns, run with zrender's `measureText` answering in
43
+ * `faces` by `widths` -- 国 with the face's line -- and `createCanvas` and
44
+ * `loadImage` refusing; the three put back as they were after it, also
45
+ * when it throws. `lay` is the whole of one synchronous layout: a measure
46
+ * it left for later would be answered by whatever stands then, so a
47
+ * promise it returns is refused, once the three are back, and its outcome
48
+ * left unread, so that a rejection of it is not left unhandled.
49
+ */
50
+ function withMeasurer(faces, widths, lay) {
51
+ const handed = new Map((faces.title === void 0 ? [faces.words] : [faces.words, faces.title]).map((face) => [fontOf(face), face]));
52
+ const measurer = {
53
+ measureText: (text, font) => {
54
+ const face = font === void 0 ? void 0 : handed.get(font);
55
+ if (face === void 0) throw new Error(`a chart's layout measured text in a font it was not handed: ${font === void 0 ? "none" : `'${font}'`}`);
56
+ return { width: text === LINE_PROBE ? face.line : widths.width(face.family, face.face, face.size, text) };
57
+ },
58
+ createCanvas: () => {
59
+ throw new Error("a chart's layout asked for a canvas");
60
+ },
61
+ loadImage: () => {
62
+ throw new Error("a chart's layout asked for an image");
63
+ }
64
+ };
65
+ const laid = withPlatform(() => measurer, lay);
66
+ if (isThenable(laid)) {
67
+ laid.then(void 0, () => void 0);
68
+ throw new Error("a chart's layout returned a promise, and would measure after its measurer was put back");
69
+ }
70
+ return laid;
71
+ }
72
+ /** Whether `value` is a promise, or anything else that settles later. */
73
+ function isThenable(value) {
74
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
75
+ }
76
+ // src/chart-svg.ts
77
+ /**
78
+ * The SVG ECharts writes of a chart, held to what ECharts 6.1.0 was seen to
79
+ * write and read back (0058). ECharts lays a chart out and draws its marks,
80
+ * and pdfmake prints each of its words where ECharts placed it: the drawing
81
+ * pdfmake's SVG converter is handed holds no word, no style sheet and no
82
+ * clip. Each `<text>` is taken out and read back as the box pdfmake prints
83
+ * its word in, and the one `<style>` ECharts writes, of hover rules that
84
+ * print nothing, is removed.
85
+ *
86
+ * So is every clip it writes, which ECharts 6.1.0 writes of a line series
87
+ * alone (`chart-svg.test.ts`): it clips a bar by working out each one, and
88
+ * a pie and a legend not at all. It clips every line series to its plot,
89
+ * whatever its `clip` says: to the plot widened by half the line's width,
90
+ * or, with `clip: false`, as the option sets it, by the plot's longer side
91
+ * (LineView.js `createLineClipPath`); and svg-to-pdfkit draws a clip path
92
+ * as a group the size of the page under a luminosity soft mask, which a
93
+ * reader composites for each series. It cuts nothing: every value stands
94
+ * inside the ticks (`check-chart.ts`), and what a clip holds is stroked
95
+ * with bevelled joins and butt ends, which stand no farther from a line's
96
+ * points than half its width, and is refused stroked otherwise. Each clip
97
+ * is still held as it is written, a path it defines once in zrender's
98
+ * black, before it is taken out with every `clip-path` that names it; the
99
+ * line is drawn as ECharts wrote it, inside the chart's box, which the
100
+ * converter clips it to.
101
+ *
102
+ * A pie's arcs alone are not as ECharts wrote them: the drawing writes them
103
+ * again before they are read (`chart-arcs.ts`). zrender writes a slice's
104
+ * arc between ends rounded to a tenth of a point, and the converter draws
105
+ * an arc on the circle through its ends: in the renders measured on
106
+ * 2026-11-13, up to 5 pt off the pie's near half a turn and 69 pt near a
107
+ * whole one, or no circle at all, and nothing drawn. Written again, each
108
+ * is arcs of at most a quarter turn on the pie's own circle, in the
109
+ * grammar ECharts writes an arc in, so that the reader holds them, and
110
+ * every number of them the converter is handed, as it holds ECharts' own.
111
+ *
112
+ * The drawing is ECharts', made of the runtime's words, and read as
113
+ * untrusted: it is held whole before anything of it is used, and refused
114
+ * as `unsupported`, naming the chart and quoting nothing of the drawing,
115
+ * where it holds
116
+ *
117
+ * - an element or an attribute `CHART_DRAWN` does not list, an element
118
+ * inside one ECharts does not write it in, a value ECharts does not
119
+ * write an attribute with, or a `<text>` or the `<svg>` without what
120
+ * reading it needs, or a shape without its fill, which zrender always
121
+ * writes and SVG paints black where it is left out;
122
+ * - a comment, a DOCTYPE or a processing instruction; or CDATA but in the
123
+ * one style sheet, a child of the `<svg>`, every selector of whose rules
124
+ * ends in `:hover`;
125
+ * - an entity or a character reference but the five zrender's `encodeHTML`
126
+ * writes, `&amp; &lt; &gt; &quot; &#39;`, or a character it escapes,
127
+ * unescaped;
128
+ * - a number that is not finite, or past the box by more than the box's
129
+ * longer side -- of a path, each point it reaches as the converter takes
130
+ * it, a relative step's from the point before it and never the step, and
131
+ * an arc's radius, every arc a circle's (`reached`): every number the
132
+ * converter writes of a chart is then far under what a PDF/A holds
133
+ * (`svg-pdfa.ts`'s `SVG_INTEGER_BOUND`);
134
+ * - groups nested deeper than a PDF/A nests the graphics state;
135
+ * - a `fill` or a `stroke` the option did not name -- the block's, the
136
+ * grid's, the axis's or the words' -- `none` and `transparent` aside, or
137
+ * in a clip path anything but zrender's black, a mask that paints
138
+ * nothing; or a clip by a path it does not define once;
139
+ * - a stroke inside a clip but with bevelled joins and butt ends, a
140
+ * join written or not, since SVG mitres one it is not told of: the
141
+ * condition on which the clip, taken out, cut nothing;
142
+ * - a `<text>` turned or scaled, which the option never asks for;
143
+ * - a `<text>` whose word, its entities read, is not one of the words the
144
+ * layout prints not yet placed, in its face; or a word the layout prints
145
+ * that no `<text>` holds. An empty `<text>` is no word.
146
+ *
147
+ * A word's box is where pdfmake prints it, which is where zrender laid it
148
+ * out: as wide as the word's advance in its face (`FaceWidths.width`), its
149
+ * left by its anchor -- its start, its middle or its end -- at its
150
+ * translation and its own x; `dominant-baseline: central`, as zrender lays
151
+ * it out and svg-to-pdfkit reads it, is the centre of the face's line at
152
+ * its translation and its own y, so that its top is half a line above, and
153
+ * its baseline the face's ascent below its top.
154
+ *
155
+ * Two words of one text in one face print alike, but are not one word: a
156
+ * tick's label and a value's stand apart, and the layout's rules read
157
+ * which is which. They are told apart by the order ECharts 6.1.0 writes a
158
+ * chart's words in (`WRITTEN`).
159
+ */
160
+ /** A number as zrender writes one: JavaScript's own spelling of a double -- a sign, digits, a point and digits, an exponent. */
161
+ const NUMBER = String.raw`-?\d+(?:\.\d+)?(?:e[+-]?\d+)?`;
162
+ /** A fill or a stroke as zrender writes one: a hex colour, or nothing. */
163
+ const PAINT = "#[0-9a-f]{3}|#[0-9a-f]{6}|none|transparent";
164
+ /** A translation as zrender writes one, to four places. */
165
+ const TRANSLATE = String.raw`translate\(${NUMBER} ${NUMBER}\)`;
166
+ /**
167
+ * Each element of the drawing as ECharts 6.1.0 writes it: its attributes,
168
+ * each with the values it is written with, those it is never written
169
+ * without that the drawing is read by, and what it is written inside, the
170
+ * `<svg>` inside nothing.
171
+ */
172
+ const VOCABULARY = {
173
+ svg: {
174
+ attributes: {
175
+ width: NUMBER,
176
+ height: NUMBER,
177
+ xmlns: String.raw`http://www\.w3\.org/2000/svg`,
178
+ "xmlns:xlink": String.raw`http://www\.w3\.org/1999/xlink`,
179
+ version: String.raw`1\.1`,
180
+ baseProfile: "full",
181
+ viewBox: `${NUMBER} ${NUMBER} ${NUMBER} ${NUMBER}`
182
+ },
183
+ required: [
184
+ "width",
185
+ "height",
186
+ "viewBox"
187
+ ],
188
+ inside: []
189
+ },
190
+ rect: {
191
+ attributes: {
192
+ width: NUMBER,
193
+ height: NUMBER,
194
+ x: NUMBER,
195
+ y: NUMBER,
196
+ fill: PAINT
197
+ },
198
+ required: ["fill"],
199
+ inside: ["svg", "g"]
200
+ },
201
+ path: {
202
+ attributes: {
203
+ d: String.raw`(?:M${NUMBER} ${NUMBER}(?:[MLl]${NUMBER} ${NUMBER}|C${NUMBER}(?: ${NUMBER}){5}|Q${NUMBER}(?: ${NUMBER}){3}|A(?<radius>${NUMBER}) \k<radius> 0 [01] [01] ${NUMBER} ${NUMBER}|Z)*)?`,
204
+ transform: String.raw`${TRANSLATE}|matrix\(${NUMBER}(?:,${NUMBER}){5}\)`,
205
+ fill: PAINT,
206
+ stroke: PAINT,
207
+ "stroke-width": NUMBER,
208
+ "stroke-linecap": "butt|round|square",
209
+ "stroke-linejoin": "miter|round|bevel",
210
+ "stroke-miterlimit": NUMBER,
211
+ "pointer-events": "visible",
212
+ class: String.raw`zr\d+-cls-\d+`,
213
+ ecmeta_series_index: String.raw`\d+`,
214
+ ecmeta_data_index: String.raw`\d+`,
215
+ ecmeta_ssr_type: "chart|legend",
216
+ ecmeta_silent: "true"
217
+ },
218
+ required: ["fill"],
219
+ inside: [
220
+ "svg",
221
+ "g",
222
+ "clipPath"
223
+ ]
224
+ },
225
+ text: {
226
+ attributes: {
227
+ "dominant-baseline": "central",
228
+ "text-anchor": "start|middle|end",
229
+ style: String.raw`font-size:${NUMBER}px;font-family:[\w-]+, f[0-9a-f]{64};(?:font-style:italic;)?(?:font-weight:bold;)?`,
230
+ "xml:space": "preserve",
231
+ x: NUMBER,
232
+ y: NUMBER,
233
+ transform: TRANSLATE,
234
+ fill: PAINT
235
+ },
236
+ required: [
237
+ "dominant-baseline",
238
+ "text-anchor",
239
+ "style"
240
+ ],
241
+ inside: ["svg", "g"]
242
+ },
243
+ g: {
244
+ attributes: { "clip-path": String.raw`url\(#[A-Za-z][\w-]*\)` },
245
+ inside: ["svg", "g"]
246
+ },
247
+ defs: {
248
+ attributes: {},
249
+ inside: ["svg"]
250
+ },
251
+ clipPath: {
252
+ attributes: { id: String.raw`[A-Za-z][\w-]*` },
253
+ inside: ["defs"]
254
+ },
255
+ style: {
256
+ attributes: {},
257
+ inside: ["svg"]
258
+ }
259
+ };
260
+ /** `VOCABULARY`, as the reader holds a drawing to it. */
261
+ const ELEMENTS = new Map(Object.entries(VOCABULARY).map(([element, { attributes, required = [], inside }]) => [element, {
262
+ values: new Map(Object.entries(attributes).map(([attribute, pattern]) => [attribute, new RegExp(`^(?:${pattern})$`)])),
263
+ required,
264
+ inside: new Set(inside)
265
+ }]));
266
+ new Map([...ELEMENTS].map(([element, { values }]) => [element, new Set(values.keys())]));
267
+ /** Whether `d` is a path as ECharts writes one, which the reader holds (`VOCABULARY`). */
268
+ const heldPath = (d) => ELEMENTS.get("path")?.values.get("d")?.test(d) === true;
269
+ /** The attributes whose numbers are coordinates or lengths in the drawing, each held to the box; a path's are the points it reaches (`reached`). */
270
+ const MEASURES = /* @__PURE__ */ new Set([
271
+ "width",
272
+ "height",
273
+ "x",
274
+ "y",
275
+ "stroke-width",
276
+ "stroke-miterlimit",
277
+ "viewBox",
278
+ "transform"
279
+ ]);
280
+ /** Every number in an attribute's value, each read by `matchAll`, which reads a copy. */
281
+ const NUMBERS = new RegExp(NUMBER, "g");
282
+ /**
283
+ * The order ECharts 6.1.0 writes a chart's words in, by the kind of word
284
+ * its key names: the value axis's title, the category axis's, the ticks',
285
+ * the categories', the values' series by series, the legend's and the
286
+ * chart's title, each kind in its own order (`chart-svg.test.ts`).
287
+ */
288
+ const WRITTEN = [
289
+ "valueTitle",
290
+ "categoryTitle",
291
+ "tick",
292
+ "category",
293
+ "value",
294
+ "legend",
295
+ "title"
296
+ ];
297
+ /**
298
+ * `svg` held to CHART_DRAWN and returned without its `<text>` elements and
299
+ * without the one `<style>` of hover rules ECharts writes (0058: no word
300
+ * and no stylesheet reaches the converter); its words read back where
301
+ * pdfmake will draw them; `printed` the words this layout prints, each
302
+ * placed once (none of them empty: an empty word prints nothing).
303
+ */
304
+ function readChartSvg(svg, chart, printed, faces, widths) {
305
+ const refuse = (what) => {
306
+ throw new RenderRefusal("unsupported", `ECharts' drawing of the chart ${chart.id} ${what}: the renderer hands pdfmake's SVG converter only what ECharts 6.1.0 was seen to write, and prints only the words the runtime resolved, each once`, chart.id);
307
+ };
308
+ const drawing = parse(svg, refuse);
309
+ hold(drawing, chart, faces, refuse);
310
+ return {
311
+ svg: serialised(drawing),
312
+ words: placed(drawing, printed, faces, widths, refuse)
313
+ };
314
+ }
315
+ /** `svg` read as markup into its one `<svg>`, each element held to `ELEMENTS`, its one style sheet read and left out: anything but elements, attributes, words and that sheet refused. */
316
+ function parse(svg, refuse) {
317
+ const open = [];
318
+ let root;
319
+ let sheets = 0;
320
+ let at = 0;
321
+ while (at < svg.length) {
322
+ const next = svg.indexOf("<", at);
323
+ held(open.at(-1), svg.slice(at, next < 0 ? svg.length : next), refuse);
324
+ if (next < 0) break;
325
+ at = next;
326
+ if (svg.startsWith("<!--", at)) refuse("holds a comment");
327
+ if (svg.startsWith("<![CDATA[", at)) refuse("holds CDATA outside its one style sheet");
328
+ if (svg.startsWith("<!", at)) refuse("holds a DOCTYPE or a declaration");
329
+ if (svg.startsWith("<?", at)) refuse("holds a processing instruction");
330
+ if (svg.startsWith("</", at)) {
331
+ const end = /<\/([A-Za-z][\w:.-]*)>/y;
332
+ end.lastIndex = at;
333
+ const [, name] = end.exec(svg) ?? refuse("holds markup that is no end tag");
334
+ if (open.pop()?.name !== name) refuse("holds an end tag that ends no element it opened");
335
+ at = end.lastIndex;
336
+ continue;
337
+ }
338
+ const start = /<([A-Za-z][\w:.-]*)((?:\s+[^\s=/>]+="[^"]*")*)\s*(\/?)>/y;
339
+ start.lastIndex = at;
340
+ const [, name = "", written = "", closed = ""] = start.exec(svg) ?? refuse("holds markup that is no element");
341
+ at = start.lastIndex;
342
+ const parent = open.at(-1);
343
+ const vocabulary = ELEMENTS.get(name) ?? refuse("holds an element ECharts writes none of");
344
+ const element = {
345
+ name,
346
+ attributes: attributesOf(vocabulary, name, written, refuse),
347
+ children: [],
348
+ written: ""
349
+ };
350
+ if (name === "svg" ? root !== void 0 : !vocabulary.inside.has(parent?.name ?? "")) refuse(parent === void 0 ? "holds an element outside its <svg>" : `holds an element inside its <${parent.name}>`);
351
+ if (closed !== "") refuse("holds an element closed as it opens");
352
+ if (name === "style") {
353
+ sheets += 1;
354
+ if (sheets > 1) refuse("holds a style sheet but its one of hover rules");
355
+ at = hoverRules(svg, at, refuse);
356
+ continue;
357
+ }
358
+ if (parent === void 0) root = element;
359
+ else parent.children.push(element);
360
+ open.push(element);
361
+ }
362
+ if (root === void 0 || open.length > 0) refuse("holds an element left open, or no <svg>");
363
+ return root;
364
+ }
365
+ /** What stands between two tags, as `parent` holds it: a word inside a `<text>`, and only whitespace anywhere else. */
366
+ function held(parent, between, refuse) {
367
+ if (parent?.name === "text") parent.written = between;
368
+ else if (!/^[ \t\r\n]*$/.test(between)) refuse("holds text outside a word");
369
+ }
370
+ /** The attributes written in `written`, each one `element`, a `name`, is written with, once, of a value it is written with, and none it is read by left out. */
371
+ function attributesOf(element, name, written, refuse) {
372
+ const attributes = /* @__PURE__ */ new Map();
373
+ for (const [, attribute = "", value = ""] of written.matchAll(/\s+([^\s=]+)="([^"]*)"/g)) {
374
+ const values = element.values.get(attribute) ?? refuse(`holds an attribute ECharts does not write its <${name}> with`);
375
+ if (attributes.has(attribute)) refuse(`holds an attribute written twice on its <${name}>`);
376
+ if (!values.test(value)) refuse(name === "text" && attribute === "transform" ? "holds a word turned or scaled" : `holds a value ECharts does not write an attribute of its <${name}> with`);
377
+ attributes.set(attribute, value);
378
+ }
379
+ if (element.required.some((attribute) => !attributes.has(attribute))) refuse(`holds its <${name}> without an attribute it is read by`);
380
+ return attributes;
381
+ }
382
+ /**
383
+ * Where the style sheet whose content starts at `at` ends: ECharts writes
384
+ * one, a CDATA section of rules every selector of which ends in `:hover`,
385
+ * which prints nothing and is left out. Any other is refused.
386
+ */
387
+ function hoverRules(svg, at, refuse) {
388
+ const end = svg.indexOf("</style>", at);
389
+ const sheet = /^\s*<!\[CDATA\[((?:\s*[^\s{}<>;@][^{}<>;@]*\{[^{}<>]*\})*)\s*\]\]>\s*$/.exec(svg.slice(at, end));
390
+ if (end < 0 || sheet === null) refuse("holds a style sheet but its one of hover rules");
391
+ const [, rules = ""] = sheet;
392
+ for (const [, selectors = ""] of rules.matchAll(/([^{}]+)\{/g)) if (!selectors.split(",").every((selector) => /\S:hover$/.test(selector.trim()))) refuse("holds a style sheet with a rule but of hovering");
393
+ return end + 8;
394
+ }
395
+ /** Whether `element` strokes: a `stroke` written that paints. */
396
+ const stroked = ({ attributes }) => ![
397
+ "none",
398
+ "transparent",
399
+ void 0
400
+ ].includes(attributes.get("stroke"));
401
+ /** `drawing` held, element by element, to its box, the nesting a PDF/A holds and the colours the option names, each clip to a path it defines once, and what a clip holds to the strokes it cuts nothing of. */
402
+ function hold(drawing, chart, faces, refuse) {
403
+ const reach = Math.max(chart.width, chart.height);
404
+ const painted = /* @__PURE__ */ new Set([
405
+ ...namedColours(chart, faces),
406
+ "none",
407
+ "transparent"
408
+ ]);
409
+ const masks = /* @__PURE__ */ new Set(["#000", "none"]);
410
+ const clips = [];
411
+ const clipped = [];
412
+ const walk = (element, depth, masked, inClip) => {
413
+ if (depth + 1 > 28) refuse(`holds groups nested deeper than the ${String(28)} graphics states a PDF/A holds`);
414
+ for (const [attribute, value] of element.attributes) {
415
+ const measures = attribute === "d" ? reached(value) : MEASURES.has(attribute) ? [...value.matchAll(NUMBERS)].map(([number]) => Number(number)) : [];
416
+ for (const measure of measures) {
417
+ if (!Number.isFinite(measure)) refuse("holds a number that is not finite");
418
+ if (measure < -reach || measure > 2 * reach) refuse(`holds a number past its box by more than its size, ${String(chart.width)} by ${String(chart.height)} points`);
419
+ }
420
+ if ((attribute === "fill" || attribute === "stroke") && !(masked ? masks : painted).has(value)) refuse(masked ? "paints a clip path" : "holds a colour the option did not name");
421
+ if (attribute === "clip-path") clipped.push(value.slice(5, -1));
422
+ if (attribute === "id") clips.push(value);
423
+ }
424
+ if (inClip && stroked(element) && !(element.attributes.get("stroke-linejoin") === "bevel" && (element.attributes.get("stroke-linecap") ?? "butt") === "butt")) refuse("strokes a path inside a clip otherwise than with bevelled joins and butt ends, and the clip is not drawn");
425
+ for (const child of element.children) walk(child, depth + 1, masked || element.name === "clipPath", inClip || element.attributes.has("clip-path"));
426
+ };
427
+ walk(drawing, 1, false, false);
428
+ const box = [
429
+ String(chart.width),
430
+ String(chart.height),
431
+ `0 0 ${String(chart.width)} ${String(chart.height)}`
432
+ ];
433
+ if ([
434
+ "width",
435
+ "height",
436
+ "viewBox"
437
+ ].some((attribute, index) => drawing.attributes.get(attribute) !== box[index])) refuse("is of another size than its box");
438
+ if (new Set(clips).size !== clips.length || clipped.some((id) => !clips.includes(id))) refuse("clips by a path it does not define once");
439
+ }
440
+ /**
441
+ * The measures of `d`, a path held to `VOCABULARY`, as the converter takes
442
+ * them (`pathParts`): each point it moves, draws or curves to -- a
443
+ * relative line's, and never its step, which ECharts takes back across the
444
+ * whole of a title's or a legend's background -- each curve's control
445
+ * points, and an arc's radius, its turn and its flags no measure. The
446
+ * converter draws an arc as curves on the circle through its ends, of its
447
+ * radius or of half the line between them where that is longer, so that
448
+ * every number it writes of one is within a few of the box's sizes when
449
+ * the radius and the ends are held to the box.
450
+ */
451
+ function reached(d) {
452
+ return pathParts(d).flatMap(({ command, numbers, to }) => command === "Z" ? [] : [...(command === "A" ? numbers.slice(0, 1) : numbers.slice(0, -2)).map(Number), ...to]);
453
+ }
454
+ /**
455
+ * The parts of `d`, a path in `VOCABULARY`'s grammar, each from the point
456
+ * the converter takes it from (svg-to-pdfkit's `SvgShape`, `source.js`) to
457
+ * the point it reaches: a relative line's the point before it moved by its
458
+ * step; a close's the one its path last moved to, which the part after it
459
+ * starts from.
460
+ */
461
+ function pathParts(d) {
462
+ const parts = [];
463
+ let at = [0, 0];
464
+ let start = at;
465
+ for (const { 0: written, 1: command = "", 2: given = "", index } of d.matchAll(/([MLlCQAZ])([^MLlCQAZ]*)/g)) {
466
+ const from = at;
467
+ const numbers = command === "Z" ? [] : given.split(" ");
468
+ const [x = 0, y = 0] = numbers.slice(-2).map(Number);
469
+ at = command === "Z" ? start : command === "l" ? [from[0] + x, from[1] + y] : [x, y];
470
+ if (command === "M") start = at;
471
+ parts.push({
472
+ index,
473
+ written,
474
+ command,
475
+ numbers,
476
+ from,
477
+ to: at
478
+ });
479
+ }
480
+ return parts;
481
+ }
482
+ /** The colours the option names for `chart` in `faces`: each series' or slice's and each legend entry's, the grid's, the axis's and the words'. */
483
+ function namedColours(chart, faces) {
484
+ const marks = chart.chart === "pie" ? chart.slices.map(({ color }) => color) : chart.series.map(({ color }) => color);
485
+ const words = faces.title === void 0 ? [faces.words] : [faces.words, faces.title];
486
+ return [
487
+ ...marks,
488
+ ...chart.legend.map(({ color }) => color),
489
+ GRID.color,
490
+ AXIS.color,
491
+ ...words.map(({ font }) => font.color)
492
+ ];
493
+ }
494
+ /** `drawing` as the converter is handed it: every element, attribute and value as read, but its words and every clip, which 6.1.0 writes of a line series alone. */
495
+ function serialised({ name, attributes, children }) {
496
+ return `<${name}${[...attributes].filter(([attribute]) => attribute !== "clip-path").map(([attribute, value]) => ` ${attribute}="${value}"`).join("")}>${children.filter((child) => child.name !== "text" && child.name !== "clipPath").map(serialised).join("")}</${name}>`;
497
+ }
498
+ /** Every `<text>` of `element`, in the order the drawing writes them. */
499
+ const textsOf = (element) => element.name === "text" ? [element] : element.children.flatMap(textsOf);
500
+ /** `word` as zrender's `encodeHTML` writes it (core/dom.js): its & < > " and ' as the five entities, an apostrophe as a numeric reference. */
501
+ const escaped = (word) => word.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
502
+ /** `written`, a word as zrender writes it, read: the five entities read, the ampersand's last, and refused where it is not what zrender writes of what they read as. */
503
+ function wordOf(written, refuse) {
504
+ if (/&(?!(?:amp|lt|gt|quot|#39);)/.test(written)) refuse("holds an entity or a character reference but the five zrender writes");
505
+ const word = written.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&#39;", "'").replaceAll("&amp;", "&");
506
+ if (escaped(word) !== written) refuse("holds a word with a character zrender escapes, unescaped");
507
+ return word;
508
+ }
509
+ /** Whether `text`, a `<text>` held to `ELEMENTS`, is written in `face`. */
510
+ function writtenIn(text, { font }) {
511
+ const italic = font.fontStyle === "italic" ? "font-style:italic;" : "";
512
+ const bold = font.fontWeight === "bold" ? "font-weight:bold;" : "";
513
+ return text.attributes.get("style") === `font-size:${String(font.fontSize)}px;font-family:${font.fontFamily};${italic}${bold}`;
514
+ }
515
+ /**
516
+ * Each of `printed` in the box its `<text>` places it in, in the order
517
+ * `printed` lists them: each `<text>` the first of the words of its text
518
+ * and in its face not yet placed, in the order ECharts writes them.
519
+ */
520
+ function placed(drawing, printed, faces, widths, refuse) {
521
+ const faceOf = (word) => {
522
+ const face = word.title ? faces.title : faces.words;
523
+ if (face === void 0) throw new Error("a chart's title was read with no face to print it in");
524
+ return face;
525
+ };
526
+ const rank = ({ key }) => WRITTEN.indexOf(key.replace(/\/.*$/, ""));
527
+ const waiting = /* @__PURE__ */ new Map();
528
+ for (const word of [...printed].sort((a, b) => rank(a) - rank(b))) {
529
+ const queue = waiting.get(word.text);
530
+ if (queue === void 0) waiting.set(word.text, [word]);
531
+ else queue.push(word);
532
+ }
533
+ const boxes = /* @__PURE__ */ new Map();
534
+ for (const text of textsOf(drawing)) {
535
+ const word = wordOf(text.written, refuse);
536
+ if (word === "") continue;
537
+ const queue = waiting.get(word) ?? [];
538
+ const index = queue.findIndex((each) => writtenIn(text, faceOf(each)));
539
+ const chosen = index < 0 ? void 0 : queue.splice(index, 1)[0];
540
+ if (chosen === void 0) refuse("holds a word the runtime did not resolve, one more often than it did, or one in another face than its own");
541
+ boxes.set(chosen, boxOf(chosen, faceOf(chosen), text, widths));
542
+ }
543
+ const words = printed.flatMap((word) => boxes.get(word) ?? []);
544
+ if (words.length < printed.length) refuse(`leaves out ${String(printed.length - words.length)} of the ${String(printed.length)} words its layout prints`);
545
+ return words;
546
+ }
547
+ /** `word`'s box in `face` as `text` places it: its left by its anchor at its translation and its own x, its top half its line above its line's centre. */
548
+ function boxOf(word, face, text, widths) {
549
+ const [, moveX = "0", moveY = "0"] = /^translate\((\S+) (\S+)\)$/.exec(text.attributes.get("transform") ?? "") ?? [];
550
+ const width = widths.width(face.family, face.face, face.size, word.text);
551
+ const anchor = text.attributes.get("text-anchor");
552
+ const left = Number(moveX) + Number(text.attributes.get("x") ?? 0) - (anchor === "middle" ? width / 2 : anchor === "end" ? width : 0);
553
+ const centre = Number(moveY) + Number(text.attributes.get("y") ?? 0);
554
+ return {
555
+ ...word,
556
+ face,
557
+ x: left,
558
+ top: centre - face.line / 2,
559
+ width,
560
+ height: face.line
561
+ };
562
+ }
563
+ // src/chart-arcs.ts
564
+ /**
565
+ * A pie's slices drawn on the pie's own circle (0058). zrender writes the
566
+ * arc of a slice as one SVG arc, its ends and its radius rounded to a
567
+ * tenth of a point (svg/SVGPathRebuilder.js), and svg-to-pdfkit draws an
568
+ * arc on the circle it works out again through those two ends (SVG 1.1
569
+ * F.6.5, `SvgShape.A` in pdfmake's copy). Through ends a tenth off, that
570
+ * circle stands off the pie's near half a turn, and turns about the ends
571
+ * near a whole one; where both ends round to one point it is no circle,
572
+ * and the arc is left out (F.6.2). Measured on 2026-11-13, as zrender
573
+ * writes them: a slice of 0.4938 of a pie 257.5 pt in radius printed 5 pt
574
+ * off its circle, the larger slice of 9998 and 2 on a circle 57 pt from
575
+ * the pie's, and a pie of 9999 and 1 at 160.23 pt nothing at all.
576
+ *
577
+ * So every arc of a slice is written again before the drawing is read
578
+ * (`chart-svg.ts`), in two pieces or more, each of at most a quarter turn
579
+ * about the pie's own centre and of its own radius -- the circle ECharts
580
+ * is handed (`pieCircle`) -- from and to the very points zrender wrote, so
581
+ * that two neighbours still meet where zrender put their common end; each
582
+ * point between is on the circle, written as JavaScript writes a double.
583
+ * An arc turns as far as its ends stand apart about the centre, the way
584
+ * its sweep flag says, within the half of a turn its large-arc flag says,
585
+ * which zrender sets from the slice's exact sweep: a large arc whose ends
586
+ * meet is the whole turn zrender drew, a small one whose ends meet turns
587
+ * nothing, out to the circle and back, and one whose ends rounding crossed
588
+ * turns back the little they crossed. A slice the reader would refuse as
589
+ * ECharts wrote it, or with an arc of any radius but the pie's to
590
+ * zrender's rounding, is left so, for the reader to judge as written.
591
+ *
592
+ * Each slice stays one path, a slice of no share is still none
593
+ * (`chart-option.ts`), and no other path is touched: a legend's swatch,
594
+ * and a bar or a line chart, are ECharts' own.
595
+ *
596
+ * The bound, by its reason. zrender rounds a point to a tenth, at most
597
+ * half a tenth's diagonal, 0.1 · √2 / 2 ≈ 0.0707 pt, from where it
598
+ * belongs. Each arc the converter is handed has an end on the pie's
599
+ * circle, and its other end on it too, or zrender's, that close to it; the
600
+ * converter draws it on the circle of the pie's radius through both,
601
+ * which to first order is the pie's circle turned about the end on it, so
602
+ * that no point of an arc of a quarter turn or less stands farther off
603
+ * than its other end. One arc between two rounded ends, as zrender writes
604
+ * a quarter, has no end to turn about: its middle stood 0.10003 pt off.
605
+ * The converter draws at most a sixth of a turn as one cubic, which stands
606
+ * outside its arc by up to 2.4 · 10^-5 of the radius, 0.0062 pt on the
607
+ * widest pie, 257.64 pt in radius. Every point of a slice's outline stands
608
+ * within 0.0707 pt of its share's sector on the pie's circle, and the
609
+ * cubic's own, and every point of the sector within as much of the
610
+ * outline (`chart-arcs.test.ts`). Measured on 2026-11-13, read back by
611
+ * PDF.js, each curve sampled: at most 0.0718 pt, either way, over 90,428
612
+ * slices with arcs of 22,955 pies the renderer drew, of radii 0.12 to
613
+ * 257.64 pt -- among them each pie found printed more than 0.5 pt off its
614
+ * circle, or blank, as zrender writes it -- 688 of them past 0.0707 pt,
615
+ * by 0.0011 at most, inside the cubic's share; and 0.0707 pt on the
616
+ * quarter above.
617
+ *
618
+ * Three kinds of slice are drawn otherwise. One within 10^-4 of a radian
619
+ * of a whole turn zrender writes as a whole circle, with no line to the
620
+ * centre, its arcs written again as any other's: it stood within 0.053 pt
621
+ * of the pie's circle. One of 10^-4 of a radian or less
622
+ * zrender writes with no arc at all, a line from its start to the centre
623
+ * (graphic/helper/roundSector.js): it stands within 0.0707 pt and its own
624
+ * arc's length, at most 10^-4 of the radius, 0.026 pt on the widest pie,
625
+ * of its sector -- 0.07205 pt at most, measured, for an arc of 0.0115 pt.
626
+ * And one whose arc is shorter than a tenth's diagonal, 0.1 · √2 ≈ 0.141
627
+ * pt, may have its two ends rounded into one point: it draws no more of
628
+ * its arc than a hair out to the circle and back, and may draw no curve,
629
+ * while every point of its sector stands within 0.0707 pt of the outline
630
+ * drawn.
631
+ * A slice whose arc is shorter than 0.141 pt may so draw no curve at all.
632
+ */
633
+ /** Radians: a whole turn, and the most an arc of a slice turns once written again. */
634
+ const TURN = 2 * Math.PI;
635
+ const QUARTER = TURN / 4;
636
+ /**
637
+ * Points: how far the radius zrender writes of a slice's arc stands from
638
+ * the pie's: half a tenth, to which it rounds, and the doubles' own error
639
+ * in that, which reached 1.1 · 10^-14 over 28,904 arcs (measured on
640
+ * 2026-11-13).
641
+ */
642
+ const RADIUS_ROUNDING = .05 + 1e-9;
643
+ /** A slice as zrender writes it: a `<path>` written as the chart's own, its `d` first. Any other path is not the pie's. */
644
+ const SLICE = /<path d="([^"]*)"(?=[^>]*\secmeta_ssr_type="chart")/g;
645
+ /** `svg`, ECharts' drawing of a pie on `circle`, with every arc of its slices written again on it. */
646
+ function pieArcs(svg, circle) {
647
+ return svg.replace(SLICE, (_, d) => `<path d="${arcsOf(d, circle)}"`);
648
+ }
649
+ /**
650
+ * `d`, a slice's path, each of its arcs written again on `circle`, from
651
+ * the point the converter takes it from (`pathParts`), and everything else
652
+ * as written. A path the reader would refuse is left as written, for it to
653
+ * refuse: written again, it could pass. So is a path with an arc of any
654
+ * radius but the pie's, to zrender's rounding: written again, an arc past
655
+ * the box would pass, and one on another circle, as a donut's inner arc,
656
+ * be moved onto the pie's.
657
+ */
658
+ function arcsOf(d, circle) {
659
+ if (!heldPath(d)) return d;
660
+ const arcs = pathParts(d).filter(({ command }) => command === "A");
661
+ if (arcs.some(({ numbers: [radius] }) => Math.abs(Number(radius) - circle.radius) > RADIUS_ROUNDING)) return d;
662
+ let written = "";
663
+ let after = 0;
664
+ for (const arc of arcs) {
665
+ written += d.slice(after, arc.index) + quarters(arc, circle);
666
+ after = arc.index + arc.written.length;
667
+ }
668
+ return written + d.slice(after);
669
+ }
670
+ /**
671
+ * An arc of a slice as two arcs or more, each of at most a quarter turn on
672
+ * `circle`, ending where it ends: its turn about the centre the one, among
673
+ * those its ends allow, nearest the middle of the half its large-arc flag
674
+ * says, three quarters of a turn or a quarter. Every number of a path the
675
+ * reader holds reads as a double, so that every angle and every turn here
676
+ * is one.
677
+ */
678
+ function quarters({ from, to, numbers }, { centre: [cx, cy], radius }) {
679
+ const [, , , large, sweep] = numbers;
680
+ const way = sweep === "1" ? 1 : -1;
681
+ const angle = ([px, py]) => Math.atan2(py - cy, px - cx);
682
+ const begins = angle(from);
683
+ const apart = way * (angle(to) - begins);
684
+ const middle = large === "1" ? 3 * QUARTER : QUARTER;
685
+ const turn = apart + TURN * Math.round((middle - apart) / TURN);
686
+ const count = Math.max(2, Math.ceil(Math.abs(turn) / QUARTER));
687
+ const flag = turn < 0 === (way === 1) ? 0 : 1;
688
+ return Array.from({ length: count }, (_, index) => {
689
+ const along = begins + way * turn * (index + 1) / count;
690
+ const end = index + 1 === count ? numbers.slice(5).join(" ") : `${String(cx + radius * Math.cos(along))} ${String(cy + radius * Math.sin(along))}`;
691
+ return `A${String(radius)} ${String(radius)} 0 0 ${String(flag)} ${end}`;
692
+ }).join("");
693
+ }
694
+ // src/chart-draw.ts
695
+ /**
696
+ * A chart laid out by ECharts, and refused where its words would meet,
697
+ * leave its box or stand in its plot, or its ticks, its categories or its
698
+ * bars would be too close or too thin to read (0058). ECharts lays the
699
+ * chart out; the drawing reads where it put things and only snaps what
700
+ * ECharts chose, and pdfmake prints every word in the box the drawing
701
+ * reads back (`chart-svg.ts`).
702
+ *
703
+ * A bar or a line chart is laid out three times, every tick labelled in
704
+ * the first two:
705
+ *
706
+ * 1. **The bands.** Across the whole box, read for where the title and
707
+ * the legend stand, which no plot moves: the band at the top is the
708
+ * title's line and a gap under it, with a value label's line and its
709
+ * distance from its mark where values are labelled, or a line's
710
+ * marker's radius where they are not, which no clip of ECharts' holds
711
+ * and the box's would cut; the band at the foot is the legend's rows
712
+ * and a gap above them. A bar below zero
713
+ * labelled under its end has its room between the plot's foot and the
714
+ * category labels, which the option stands that much further down
715
+ * (`chart-option.ts`), and ECharts fits with them.
716
+ * 2. **The plot.** ECharts fits the plot, and its axes' words, between the
717
+ * bands and the box's sides; the plot is read by `convertToPixel` at
718
+ * the lowest tick's place and the highest's, and half a slot past the
719
+ * first and the last categories' middles.
720
+ * 3. **Drawn.** The plot's top on the first half point at or below
721
+ * ECharts', and its height the most that fits above ECharts' foot with
722
+ * every interval between ticks a whole number of points, so that every
723
+ * gridline stands on its tick (zrender moves a thin line to a half
724
+ * point); every `tickEvery`-th tick labelled from the lowest, the
725
+ * fewest that set their labels `TICK_CLEARANCE` lines apart.
726
+ *
727
+ * Bars under `MIN_BAR_WIDTH` are refused in whichever layout first lays
728
+ * them out, before its words are read: ECharts draws a bar under 1 point
729
+ * at 1, and leaves undrawn the bars, and their labels, a group so widened
730
+ * pushes past its slot. Between the second layout and the third, a plot
731
+ * too short for two tick labels that far apart, and a category label
732
+ * wider than its slot less half a line, are refused: a label is never
733
+ * turned, and a tick, a category or a bar is never dropped. A pie is laid
734
+ * out twice: the bands, then drawn in the largest square centred between
735
+ * them, refused where that square is narrower than `MIN_PIE_DIAMETER`, the
736
+ * arcs of its slices written again on its circle before its drawing is
737
+ * read (`chart-arcs.ts`). Every layout is ECharts' own under
738
+ * the render's measurer (`chart-measure.ts`), disposed after it is read.
739
+ *
740
+ * The drawn layout's words are then held: two that meet, one past the
741
+ * box, or one in the plot that is not a value's label, refuse the chart
742
+ * (`chart-held.ts`, the rule an empty chart's words are held to as well).
743
+ * Every refusal here is `content-too-large`, naming the chart and its box
744
+ * and the sizes that do not fit, and quoting no word; the drawing's reader
745
+ * refuses what ECharts wrote that it does not hold to as `unsupported`. A
746
+ * font the measurer was not handed, a canvas or an image asked for, and a
747
+ * formatter asked for what the block does not have are the option's
748
+ * errors, thrown as they are: an invariant of the renderer's, which no
749
+ * report can cause.
750
+ *
751
+ * The one module that imports ECharts' code, which a document holding a
752
+ * chart loads the first time it draws one; its components are registered
753
+ * at the first draw, never at import.
754
+ */
755
+ /** Lines: printed tick labels stand at least this far apart, middle to middle. Chosen, as a table's padding is. */
756
+ const TICK_CLEARANCE = 1.25;
757
+ /**
758
+ * Points: the narrowest a bar is drawn: the least width, to the quarter
759
+ * point, at which every bar of a bar chart is a run of at least one pixel
760
+ * of its colour (each channel within 8) with a white pixel (each channel
761
+ * at least 247) between it and the next, in the page PDF.js draws at the
762
+ * density of the Studio's Preview at 100 % on a screen of device pixel
763
+ * ratio 2: 96/72 CSS pixels to the point times 2, 8/3 device pixels to the
764
+ * point.
765
+ *
766
+ * Measured on 2026-11-13 on a Mac (Apple M2), Node 22.23.4, pdfjs-dist
767
+ * 6.4.299, which draws on @napi-rs/canvas 1.0.11, and ECharts 6.1.0: bar
768
+ * charts laid out by ECharts at the option's gaps and drawn by `renderPdf`,
769
+ * 3960 of them: widths of 0.25 to 5 points in quarter points, each with one,
770
+ * two and eight series, three tick sets (the width of the value axis'
771
+ * labels, which moves the plot) and 22 left margins, twenty across one
772
+ * device pixel from 40 points and the starters' 56.69 and 42.52. The pixel
773
+ * rows judged are those inside the bars, which no gridline or axis line
774
+ * crosses. 3.25 failed on 17 of 198 charts, 3.5 and every width above it,
775
+ * to 5, on none.
776
+ *
777
+ * Why it holds wherever a chart stands: zrender writes every coordinate to
778
+ * 0.1 point, so a gap the SVG writes is a multiple of 0.1 point, at least
779
+ * a quarter of the bar less 0.15 (two edges each off by 0.05, and a width
780
+ * by 0.05); at 3.5 that is 0.8 point, 2.13 pixels, and two pixels always
781
+ * hold a whole pixel the bars leave white, wherever they stand. At 3.25 it
782
+ * is 0.7 point, 1.87 pixels, and the failures above are those. The gap is
783
+ * what sets the least: a bar of one series stands a category gap, a
784
+ * quarter of a bar, from the next, in the next slot; a bar of a group
785
+ * stands BAR_GAP of a bar from the next in its own slot, the same gap
786
+ * while BAR_GAP is BAR_CATEGORY_GAP over its complement (held in
787
+ * `chart-draw.test.ts`), and a group's category gap is wider.
788
+ *
789
+ * Other densities, by the same sweep (132 charts to a width, from 0.25 to
790
+ * 10, 20 offsets across a device pixel and the starters' margins, one, two
791
+ * and eight series, two tick sets), the least width at which none failed:
792
+ * 6.25 at 4/3 pixels to the point (100 % on ratio 1), 4.25 at 2 (75 % on
793
+ * ratio 2), 8.25 at 1; each is where the gap's least is two pixels, and
794
+ * one quarter point below it some chart failed. Never under ECharts' own
795
+ * least, 1, at which it widens the bar and drops its neighbours.
796
+ */
797
+ const MIN_BAR_WIDTH = 3.5;
798
+ /**
799
+ * Points: the narrowest a pie is drawn, its square's side: the least
800
+ * diameter, to the quarter point, at which a pie whose first slice is one
801
+ * percent of it, its seven others sharing the rest in report-spec's
802
+ * palette, shows every slice along its rim as a run of at least one pixel
803
+ * of its own colour (each channel within 8), that slice among them, its
804
+ * neighbours told apart, in the page PDF.js draws at the density of the
805
+ * Studio's Preview at 100 % on a screen of device pixel ratio 2, 8/3
806
+ * device pixels to the point, as `MIN_BAR_WIDTH`: so that a slice whose
807
+ * share prints as 1.0 % or more shows as its own colour. The rim is the
808
+ * band one pixel wide of the outermost pixels wholly inside the pie's
809
+ * circle; taken in turn from noon, clockwise, its pixels of a palette
810
+ * colour make eight runs, each of its own slice's colour and inside that
811
+ * slice's sector, so that no slice is missing, split by another's colour
812
+ * or run into its neighbour's. A pixel of no palette colour, a blend of
813
+ * two slices, breaks no run and makes none.
814
+ *
815
+ * Measured on 2026-11-16 on a Mac (Apple M2), Node 22.23.4, pdfjs-dist
816
+ * 6.4.299 on @napi-rs/canvas 1.0.11, and ECharts 6.1.0, at a load of 2.2
817
+ * to 4.1: pies drawn by `renderPdf` in a box of their diameter, with no
818
+ * title and no legend, of 20 to 50 points in quarter points, each at 22
819
+ * places: twenty across one device pixel from 40 points, its left and its
820
+ * top each at every twentieth of one, and the starters' margins, 56.69
821
+ * and 42.52 points in from the left and 56.69 down. Below 24.75 some
822
+ * diameter failed at up to 10 of the 22, 24.5 at 1; 24.75 and every
823
+ * diameter above it, to 50, at none. At 400 places, every pair of
824
+ * twentieths of a pixel, from 23 to 31 points: 24.5 failed at 33, 24.75
825
+ * to 31 at none. A pie of eight equal slices, measured the same way the
826
+ * day before, told them apart from 3.25 points, which leaves a slice
827
+ * under about an eighth of the pie under a pixel of its rim: Daniel ruled
828
+ * for the slice of one percent. A smaller share is a thinner slice, as a
829
+ * smaller value is a shorter bar, and is held to nothing.
830
+ */
831
+ const MIN_PIE_DIAMETER = 24.75;
832
+ /** Lines: what the bands keep between the title, or the legend, and the plot's words. Chosen. */
833
+ const BAND_GAP = .5;
834
+ let registered = false;
835
+ /**
836
+ * ECharts' components, registered once, at the first draw; and refused
837
+ * where ECharts resolves another zrender than the renderer's, whose
838
+ * platform the measurer replaces (`chart-measure.ts`): through another,
839
+ * ECharts would measure every word in widths nobody chose, unseen. Both
840
+ * copies' `setPlatformAPI` is one function only where they are one copy.
841
+ */
842
+ function register(chart) {
843
+ if (setPlatformAPI !== setPlatformAPI$1) throw new RenderRefusal("unsupported", `${named(chart)}cannot be laid out: ECharts measures through another copy of zrender than the one the renderer measures it with`, chart.id);
844
+ if (registered) return;
845
+ use([
846
+ BarChart,
847
+ LineChart,
848
+ PieChart,
849
+ GridComponent,
850
+ LegendComponent,
851
+ TitleComponent,
852
+ SVGRenderer
853
+ ]);
854
+ registered = true;
855
+ }
856
+ function layOut(chart, faces, widths, layout) {
857
+ const option = chartOption(chart, faces, layout);
858
+ const { svg, plot } = withMeasurer(faces, widths, () => {
859
+ const laid = init(null, null, {
860
+ renderer: "svg",
861
+ ssr: true,
862
+ width: chart.width,
863
+ height: chart.height
864
+ });
865
+ try {
866
+ laid.setOption(option);
867
+ const written = laid.renderToSVGString();
868
+ if (chart.chart === "pie") return { svg: layout.plot === void 0 ? written : pieArcs(written, pieCircle(layout.plot)) };
869
+ const read = plotOf(chart, laid);
870
+ thickEnough(chart, read);
871
+ return {
872
+ svg: written,
873
+ plot: read
874
+ };
875
+ } finally {
876
+ laid.dispose();
877
+ }
878
+ });
879
+ const drawing = readChartSvg(svg, chart, chartWords(chart, layout), faces, widths);
880
+ return plot === void 0 ? { drawing } : {
881
+ drawing,
882
+ plot
883
+ };
884
+ }
885
+ /**
886
+ * `chart` drawn in `faces` by `widths`: laid out by ECharts as the module
887
+ * says, its words held to the rules, and refused, naming it, where they
888
+ * do not hold. Synchronous, for a chart that is not empty, whose words
889
+ * and title `faces` and `widths` measure.
890
+ */
891
+ function drawChart(chart, faces, widths) {
892
+ register(chart);
893
+ const { line } = faces.words;
894
+ const bands = bandsOf(chart, layOut(chart, faces, widths, { tickEvery: 1 }).drawing.words, line);
895
+ if (chart.chart === "pie") {
896
+ const square = squareOf(chart, bands);
897
+ const { svg, words } = layOut(chart, faces, widths, {
898
+ tickEvery: 1,
899
+ bands,
900
+ plot: square
901
+ }).drawing;
902
+ return {
903
+ svg,
904
+ words: held$1(chart, words, square)
905
+ };
906
+ }
907
+ if (bands.top + bands.bottom >= chart.height) tooLarge(chart, "has no room for its plot: its title and its legend would stand in it");
908
+ const fitted = layOut(chart, faces, widths, {
909
+ tickEvery: 1,
910
+ bands
911
+ });
912
+ const plot = snapped(chart, fitted.plot);
913
+ const tickEvery = tickEveryOf(chart, plot, line);
914
+ fitsAcross(chart, plot, fitted.drawing.words, line);
915
+ const { svg, words } = layOut(chart, faces, widths, {
916
+ tickEvery,
917
+ bands,
918
+ plot
919
+ }).drawing;
920
+ return {
921
+ svg,
922
+ words: held$1(chart, words, plot)
923
+ };
924
+ }
925
+ /**
926
+ * The bands `chart` is laid out between, from `words`, those of a layout
927
+ * across the whole box, in faces whose words' line is `line`: the title's
928
+ * box and a gap under it, and the legend's highest row and a gap above
929
+ * it; and where values are labelled, room above the plot for a label of a
930
+ * bar or a point at the highest tick, its line and its distance from its
931
+ * mark. Where a line's are not, room for its marker at the highest tick,
932
+ * `POINT_RADIUS` above its place: ECharts leaves only half a tick label's
933
+ * line above the plot, which in a face of a short line is less, and the
934
+ * marker would stand past the box, where the converter cuts it. The label
935
+ * of a bar below zero at the lowest tick stands between the plot's foot
936
+ * and the category labels, in room the option keeps there; a marker at
937
+ * the lowest tick stands in the category labels' margin, which ECharts
938
+ * keeps with every label empty.
939
+ */
940
+ function bandsOf(chart, words, line) {
941
+ const gap = BAND_GAP * line;
942
+ const title = words.find(({ key }) => key === "title");
943
+ const legend = words.filter(({ key }) => key.startsWith("legend/")).map(({ top }) => top);
944
+ const labelled = chart.chart !== "pie" && chart.valueLabels;
945
+ const marked = chart.chart === "line" ? 2 : 0;
946
+ return {
947
+ top: (title === void 0 ? 0 : title.top + title.height + gap) + (labelled ? line + 5 : marked),
948
+ bottom: legend.length === 0 ? 0 : chart.height - Math.min(...legend) + gap
949
+ };
950
+ }
951
+ /** A pie's square: the largest centred between `bands`, refused where they leave none, or one narrower than `MIN_PIE_DIAMETER`. */
952
+ function squareOf(chart, bands) {
953
+ const room = chart.height - bands.top - bands.bottom;
954
+ if (room <= 0) tooLarge(chart, "has no room for its pie: its title and its legend would stand in it");
955
+ const side = Math.min(chart.width, room);
956
+ if (side < 24.75) tooLarge(chart, `has a pie ${points(side)} points across, narrower than the ${String(MIN_PIE_DIAMETER)} points a pie is drawn at least`);
957
+ return {
958
+ left: (chart.width - side) / 2,
959
+ top: bands.top + (room - side) / 2,
960
+ width: side,
961
+ height: side
962
+ };
963
+ }
964
+ /**
965
+ * The plot ECharts laid `chart` out in: its foot and its top at the
966
+ * lowest tick's place and the highest's, and its sides half a slot past
967
+ * the first and the last categories' middles, a slot being the plot's
968
+ * width over the categories. Of a chart of one category, whose one middle
969
+ * says nothing of its slot, each side is where the plot ends: found, to a
970
+ * billionth of a point, as the last point `containPixel` says the plot
971
+ * holds.
972
+ */
973
+ function plotOf(chart, laid) {
974
+ const foot = laid.convertToPixel({ yAxisIndex: 0 }, 0);
975
+ const top = laid.convertToPixel({ yAxisIndex: 0 }, chart.ticks.length - 1);
976
+ const categories = chart.categories.length;
977
+ const first = laid.convertToPixel({ xAxisIndex: 0 }, "c0");
978
+ if (categories > 1) {
979
+ const slot = (laid.convertToPixel({ xAxisIndex: 0 }, `c${String(categories - 1)}`) - first) / (categories - 1);
980
+ return {
981
+ left: first - slot / 2,
982
+ top,
983
+ width: slot * categories,
984
+ height: foot - top
985
+ };
986
+ }
987
+ const middle = (foot + top) / 2;
988
+ const side = (outside) => {
989
+ let [held, past] = [first, outside];
990
+ while (Math.abs(past - held) > 1e-9) {
991
+ const between = (held + past) / 2;
992
+ if (laid.containPixel({ gridIndex: 0 }, [between, middle])) held = between;
993
+ else past = between;
994
+ }
995
+ return held;
996
+ };
997
+ const [left, right] = [side(-1), side(chart.width + 1)];
998
+ return {
999
+ left,
1000
+ top,
1001
+ width: right - left,
1002
+ height: foot - top
1003
+ };
1004
+ }
1005
+ /**
1006
+ * `fitted` snapped: its top moved down to the first half point at or
1007
+ * below it, and its height cut to the most that fits above its foot with
1008
+ * every interval between ticks a whole number of points, so that every
1009
+ * tick stands on a half point, where zrender leaves a thin gridline. The
1010
+ * plot only shrinks, and stays where ECharts fitted its words. Its sides
1011
+ * as ECharts laid them.
1012
+ */
1013
+ function snapped(chart, fitted) {
1014
+ const intervals = chart.ticks.length - 1;
1015
+ const top = Math.ceil(fitted.top - .5) + .5;
1016
+ const room = fitted.top + fitted.height - top;
1017
+ return {
1018
+ left: fitted.left,
1019
+ top,
1020
+ width: fitted.width,
1021
+ height: Math.max(0, Math.floor(room / intervals)) * intervals
1022
+ };
1023
+ }
1024
+ /**
1025
+ * Every how many ticks `chart` labels on `plot`, from the lowest: the
1026
+ * fewest that set two labels `TICK_CLEARANCE` lines of `line` apart. A
1027
+ * plot on which no two can stand that far apart -- the lowest and the
1028
+ * highest -- is refused, naming its height.
1029
+ */
1030
+ function tickEveryOf(chart, plot, line) {
1031
+ const intervals = chart.ticks.length - 1;
1032
+ const pitch = plot.height / intervals;
1033
+ const tickEvery = Array.from({ length: intervals }, (_, index) => index + 1).find((every) => every * pitch >= TICK_CLEARANCE * line);
1034
+ if (tickEvery === void 0) tooLarge(chart, `has a plot ${points(plot.height)} points tall, too short to label two of its ${String(chart.ticks.length)} ticks ${String(TICK_CLEARANCE)} lines apart`);
1035
+ return tickEvery;
1036
+ }
1037
+ /**
1038
+ * `chart`'s category labels, as `words` place them, refused where one is
1039
+ * wider than its slot on `plot` less half a `line`: each prints across,
1040
+ * centred under its slot, and is never turned, so that two that fit stand
1041
+ * half a line apart or more. The drawn layout's words are held apart
1042
+ * besides, these among them.
1043
+ */
1044
+ function fitsAcross(chart, plot, words, line) {
1045
+ const slot = plot.width / chart.categories.length;
1046
+ if (words.some(({ key, width }) => key.startsWith("category/") && width > slot - line / 2)) tooLarge(chart, `has category labels too wide for their slots of ${points(slot)} points across, and never turned`);
1047
+ }
1048
+ /** `chart`'s bars on `plot`, refused where ECharts would lay them out narrower than `MIN_BAR_WIDTH`, by the width it gives a bar in a slot of it (`barWidth`). */
1049
+ function thickEnough(chart, plot) {
1050
+ if (chart.chart !== "bar") return;
1051
+ const width = barWidth(plot.width / chart.categories.length, chart.series.length);
1052
+ if (width < 3.5) tooLarge(chart, `has bars ${points(width)} points wide, narrower than the ${String(MIN_BAR_WIDTH)} points a bar is drawn at least`);
1053
+ }
1054
+ export { BAND_GAP, MIN_BAR_WIDTH, MIN_PIE_DIAMETER, TICK_CLEARANCE, drawChart };
1055
+
1056
+ //# sourceMappingURL=chart-draw-CUcWXjN9.mjs.map