@fengwk/kchart 0.0.0-stage → 0.1.1

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 (201) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE.md +11 -0
  4. package/README.md +68 -2
  5. package/README.zh-CN.md +69 -0
  6. package/dist/LICENSE +21 -0
  7. package/dist/NOTICE.md +11 -0
  8. package/dist/assets/ICONS-LICENSE.txt +53 -0
  9. package/dist/assets/maps/LICENSE.md +75 -0
  10. package/dist/assets/maps/METADATA.md +9 -0
  11. package/dist/assets/maps/REGIONS.md +28 -0
  12. package/dist/assets/maps/us-states.geojson +1 -0
  13. package/dist/assets/maps/world.geojson +1 -0
  14. package/dist/esm/_virtual/_kchart-families.js +48 -0
  15. package/dist/esm/_virtual/_rolldown/runtime.js +12 -0
  16. package/dist/esm/assets/icons.js +11 -0
  17. package/dist/esm/assets/maps/us-states.js +3 -0
  18. package/dist/esm/assets/maps/world.js +3 -0
  19. package/dist/esm/assets/themes/claude.js +69 -0
  20. package/dist/esm/assets/themes/cloudmusic.js +62 -0
  21. package/dist/esm/assets/themes/kanagawa.js +67 -0
  22. package/dist/esm/assets/themes/obsidian.js +67 -0
  23. package/dist/esm/assets/themes/paper.js +61 -0
  24. package/dist/esm/assets/themes/terminal.js +60 -0
  25. package/dist/esm/assets/themes/tokyo.js +62 -0
  26. package/dist/esm/chart/basic.js +1313 -0
  27. package/dist/esm/chart/catalog.js +476 -0
  28. package/dist/esm/chart/composition.js +844 -0
  29. package/dist/esm/chart/context.js +189 -0
  30. package/dist/esm/chart/distribution.js +442 -0
  31. package/dist/esm/chart/fields.js +67 -0
  32. package/dist/esm/chart/maps.js +563 -0
  33. package/dist/esm/chart/mindmap.js +629 -0
  34. package/dist/esm/chart/multivariate.js +1229 -0
  35. package/dist/esm/chart/registry.js +108 -0
  36. package/dist/esm/chart/relations.js +949 -0
  37. package/dist/esm/chart/spec.js +1415 -0
  38. package/dist/esm/chart/stat-compare.js +302 -0
  39. package/dist/esm/chart/stat-trend.js +181 -0
  40. package/dist/esm/chart/statistics.js +1007 -0
  41. package/dist/esm/chart/unit-variants.js +645 -0
  42. package/dist/esm/chart/variants.js +552 -0
  43. package/dist/esm/core/color.js +197 -0
  44. package/dist/esm/core/context.js +256 -0
  45. package/dist/esm/core/diagnostics.js +23 -0
  46. package/dist/esm/core/format.js +167 -0
  47. package/dist/esm/core/geometry.js +130 -0
  48. package/dist/esm/core/icon-data.js +5 -0
  49. package/dist/esm/core/icons.js +173 -0
  50. package/dist/esm/core/scale.js +112 -0
  51. package/dist/esm/core/scene.js +234 -0
  52. package/dist/esm/core/svg.js +89 -0
  53. package/dist/esm/core/text.js +184 -0
  54. package/dist/esm/core/theme.js +318 -0
  55. package/dist/esm/diagram/agentflow.js +596 -0
  56. package/dist/esm/diagram/architecture.js +729 -0
  57. package/dist/esm/diagram/block.js +988 -0
  58. package/dist/esm/diagram/blocks.js +687 -0
  59. package/dist/esm/diagram/c4.js +1002 -0
  60. package/dist/esm/diagram/class.js +1158 -0
  61. package/dist/esm/diagram/cynefin.js +749 -0
  62. package/dist/esm/diagram/emphasis.js +7 -0
  63. package/dist/esm/diagram/er.js +657 -0
  64. package/dist/esm/diagram/eventmodeling.js +948 -0
  65. package/dist/esm/diagram/gantt-date.js +323 -0
  66. package/dist/esm/diagram/gantt.js +661 -0
  67. package/dist/esm/diagram/gitgraph.js +472 -0
  68. package/dist/esm/diagram/graph-layout.js +4046 -0
  69. package/dist/esm/diagram/graph-parse.js +1366 -0
  70. package/dist/esm/diagram/graph-route.js +490 -0
  71. package/dist/esm/diagram/graph.js +553 -0
  72. package/dist/esm/diagram/ishikawa.js +496 -0
  73. package/dist/esm/diagram/journey.js +512 -0
  74. package/dist/esm/diagram/kanban.js +280 -0
  75. package/dist/esm/diagram/label.js +56 -0
  76. package/dist/esm/diagram/layers.js +385 -0
  77. package/dist/esm/diagram/map-label.js +44 -0
  78. package/dist/esm/diagram/mindmap.js +277 -0
  79. package/dist/esm/diagram/numeric-composition.js +78 -0
  80. package/dist/esm/diagram/numeric-model.js +86 -0
  81. package/dist/esm/diagram/numeric-parse.js +205 -0
  82. package/dist/esm/diagram/numeric-radar.js +355 -0
  83. package/dist/esm/diagram/numeric-sankey.js +201 -0
  84. package/dist/esm/diagram/numeric-xy.js +422 -0
  85. package/dist/esm/diagram/packet.js +175 -0
  86. package/dist/esm/diagram/presentation.js +252 -0
  87. package/dist/esm/diagram/quadrant.js +297 -0
  88. package/dist/esm/diagram/railroad-parse.js +465 -0
  89. package/dist/esm/diagram/railroad.js +294 -0
  90. package/dist/esm/diagram/registry.js +296 -0
  91. package/dist/esm/diagram/relations.js +966 -0
  92. package/dist/esm/diagram/requirement.js +341 -0
  93. package/dist/esm/diagram/sequence.js +1228 -0
  94. package/dist/esm/diagram/shapes.js +366 -0
  95. package/dist/esm/diagram/source.js +538 -0
  96. package/dist/esm/diagram/support.js +153 -0
  97. package/dist/esm/diagram/swimlane-mermaid.js +140 -0
  98. package/dist/esm/diagram/swimlane.js +1186 -0
  99. package/dist/esm/diagram/time.js +748 -0
  100. package/dist/esm/diagram/timeline.js +376 -0
  101. package/dist/esm/diagram/tree-family-icon.js +22 -0
  102. package/dist/esm/diagram/treeview.js +293 -0
  103. package/dist/esm/diagram/usecase.js +852 -0
  104. package/dist/esm/diagram/venn.js +1038 -0
  105. package/dist/esm/diagram/wardley.js +838 -0
  106. package/dist/esm/index.d.ts +133 -0
  107. package/dist/esm/index.js +92 -0
  108. package/dist/esm/interaction.js +561 -0
  109. package/dist/esm/mermaid.d.ts +28 -0
  110. package/dist/esm/mermaid.js +70 -0
  111. package/dist/esm/node.d.ts +68 -0
  112. package/dist/esm/node.js +373 -0
  113. package/dist/esm/package.json +1 -0
  114. package/dist/esm/page-api.js +65 -0
  115. package/dist/esm/runtime.js +352 -0
  116. package/dist/esm/src/families.js +209 -0
  117. package/dist/page-api.js +1 -0
  118. package/dist/units/chart/basic.js +1 -0
  119. package/dist/units/chart/catalog.js +1 -0
  120. package/dist/units/chart/composition.js +1 -0
  121. package/dist/units/chart/context.js +1 -0
  122. package/dist/units/chart/distribution.js +1 -0
  123. package/dist/units/chart/fields.js +1 -0
  124. package/dist/units/chart/maps.js +1 -0
  125. package/dist/units/chart/mindmap.js +1 -0
  126. package/dist/units/chart/multivariate.js +1 -0
  127. package/dist/units/chart/registry.js +1 -0
  128. package/dist/units/chart/relations.js +1 -0
  129. package/dist/units/chart/spec.js +3 -0
  130. package/dist/units/chart/stat-compare.js +1 -0
  131. package/dist/units/chart/stat-trend.js +1 -0
  132. package/dist/units/chart/statistics.js +1 -0
  133. package/dist/units/chart/unit-variants.js +1 -0
  134. package/dist/units/chart/variants.js +1 -0
  135. package/dist/units/core/color.js +1 -0
  136. package/dist/units/core/context.js +1 -0
  137. package/dist/units/core/diagnostics.js +1 -0
  138. package/dist/units/core/format.js +1 -0
  139. package/dist/units/core/geometry.js +1 -0
  140. package/dist/units/core/icon-data.js +1 -0
  141. package/dist/units/core/icons.js +1 -0
  142. package/dist/units/core/scale.js +1 -0
  143. package/dist/units/core/scene.js +1 -0
  144. package/dist/units/core/svg.js +1 -0
  145. package/dist/units/core/text.js +2 -0
  146. package/dist/units/core/theme.js +1 -0
  147. package/dist/units/diagram/agentflow.js +12 -0
  148. package/dist/units/diagram/architecture.js +4 -0
  149. package/dist/units/diagram/block.js +2 -0
  150. package/dist/units/diagram/blocks.js +2 -0
  151. package/dist/units/diagram/c4.js +6 -0
  152. package/dist/units/diagram/class.js +5 -0
  153. package/dist/units/diagram/cynefin.js +4 -0
  154. package/dist/units/diagram/emphasis.js +1 -0
  155. package/dist/units/diagram/er.js +9 -0
  156. package/dist/units/diagram/eventmodeling.js +5 -0
  157. package/dist/units/diagram/gantt-date.js +1 -0
  158. package/dist/units/diagram/gantt.js +3 -0
  159. package/dist/units/diagram/gitgraph.js +2 -0
  160. package/dist/units/diagram/graph-layout.js +4 -0
  161. package/dist/units/diagram/graph-parse.js +9 -0
  162. package/dist/units/diagram/graph-route.js +1 -0
  163. package/dist/units/diagram/graph.js +1 -0
  164. package/dist/units/diagram/ishikawa.js +2 -0
  165. package/dist/units/diagram/journey.js +5 -0
  166. package/dist/units/diagram/kanban.js +2 -0
  167. package/dist/units/diagram/label.js +4 -0
  168. package/dist/units/diagram/layers.js +1 -0
  169. package/dist/units/diagram/map-label.js +1 -0
  170. package/dist/units/diagram/mindmap.js +2 -0
  171. package/dist/units/diagram/numeric-composition.js +1 -0
  172. package/dist/units/diagram/numeric-model.js +1 -0
  173. package/dist/units/diagram/numeric-parse.js +2 -0
  174. package/dist/units/diagram/numeric-radar.js +3 -0
  175. package/dist/units/diagram/numeric-sankey.js +2 -0
  176. package/dist/units/diagram/numeric-xy.js +2 -0
  177. package/dist/units/diagram/packet.js +2 -0
  178. package/dist/units/diagram/presentation.js +2 -0
  179. package/dist/units/diagram/quadrant.js +2 -0
  180. package/dist/units/diagram/railroad-parse.js +4 -0
  181. package/dist/units/diagram/railroad.js +1 -0
  182. package/dist/units/diagram/registry.js +2 -0
  183. package/dist/units/diagram/relations.js +3 -0
  184. package/dist/units/diagram/requirement.js +3 -0
  185. package/dist/units/diagram/sequence.js +2 -0
  186. package/dist/units/diagram/shapes.js +60 -0
  187. package/dist/units/diagram/source.js +20 -0
  188. package/dist/units/diagram/support.js +3 -0
  189. package/dist/units/diagram/swimlane-mermaid.js +3 -0
  190. package/dist/units/diagram/swimlane.js +2 -0
  191. package/dist/units/diagram/time.js +3 -0
  192. package/dist/units/diagram/timeline.js +2 -0
  193. package/dist/units/diagram/tree-family-icon.js +1 -0
  194. package/dist/units/diagram/treeview.js +2 -0
  195. package/dist/units/diagram/usecase.js +3 -0
  196. package/dist/units/diagram/venn.js +2 -0
  197. package/dist/units/diagram/wardley.js +4 -0
  198. package/dist/units/interaction.js +1 -0
  199. package/dist/units/runtime.js +1 -0
  200. package/dist/units.json +712 -0
  201. package/package.json +30 -4
@@ -0,0 +1,1229 @@
1
+ import { __exportAll } from "../_virtual/_rolldown/runtime.js";
2
+ import { register } from "./registry.js";
3
+ import { columnHeaders } from "../core/geometry.js";
4
+ import { contrast, pushContrast } from "../core/color.js";
5
+ // src/chart/multivariate.js
6
+ var multivariate_exports = /* @__PURE__ */ __exportAll({
7
+ diagramCombo: () => diagramCombo,
8
+ install: () => install
9
+ });
10
+ var diagramCombo = Symbol("diagram combo");
11
+ var finite = Number.isFinite;
12
+ var number = (ctx, field, values, zero = false) => {
13
+ const result = ctx.ticks(values.filter(finite), field, { zero });
14
+ const meta = ctx.field(field);
15
+ const min = meta.domain?.[0] ?? result.min;
16
+ const max = meta.domain?.[1] ?? result.max;
17
+ if (zero && !(min <= 0 && max >= 0)) ctx.fit(/^en(?:-|$)/i.test(ctx.lang) ? "This measure requires a domain including zero" : "该度量必须使用包含0的基线范围", /^en(?:-|$)/i.test(ctx.lang) ? "Expand the field domain to include zero" : "扩大字段domain使其包含0后重试");
18
+ if (values.some((v) => finite(v) && (v < min || v > max))) ctx.fit(/^en(?:-|$)/i.test(ctx.lang) ? "Values exceed the explicit domain" : "数值超出显式domain", /^en(?:-|$)/i.test(ctx.lang) ? "Expand the field domain and retry" : "扩大字段domain后重试");
19
+ return {
20
+ min,
21
+ max,
22
+ ticks: result.ticks
23
+ };
24
+ };
25
+ var chart = (spec, ctx) => {
26
+ const { width } = ctx, enc = spec.encode || {}, pad = {
27
+ l: 56,
28
+ r: 28,
29
+ t: 48,
30
+ b: 58
31
+ };
32
+ const children = [], english = /^en(?:-|$)/i.test(ctx.lang), title = spec.title || spec.chart;
33
+ const msg = (zh, en) => english ? en : zh;
34
+ const plot = (top = pad.t, bottom = 330, left = pad.l + 16, right = width - pad.r - 24) => ({
35
+ x: left,
36
+ y: top,
37
+ w: Math.max(1, right - left),
38
+ h: Math.max(1, bottom - top)
39
+ });
40
+ const bandX = (i, n, p) => p.x + (i + .5) * p.w / n;
41
+ const reserveEdgeCategories = (categories, p) => {
42
+ if (!categories.length) return;
43
+ const widths = categories.map((value) => ctx.measure(String(value), 12));
44
+ const minimum = categories.length === 1 ? widths[0] + 16 : (widths[0] + widths.at(-1) + 6) / (1 - 1 / categories.length);
45
+ p.w = Math.max(p.w, minimum);
46
+ };
47
+ const catLabels = (categories, p, y = p.y + p.h + 22) => {
48
+ const n = categories.length, centers = categories.map((_, i) => bandX(i, n, p));
49
+ const widths = categories.map((value) => ctx.measure(String(value), 12)), shown = /* @__PURE__ */ new Set();
50
+ const minX = 2, maxX = Math.max(width, p.x + p.w) - 2;
51
+ const anchors = categories.map((_, i) => {
52
+ if (n > 1 && i === 0 && centers[i] - widths[i] / 2 < minX) return "start";
53
+ if (n > 1 && i === n - 1 && centers[i] + widths[i] / 2 > maxX) return "end";
54
+ return "middle";
55
+ });
56
+ const bounds = (i) => {
57
+ const left = centers[i] - widths[i] * (anchors[i] === "start" ? 0 : anchors[i] === "end" ? 1 : .5);
58
+ return {
59
+ left,
60
+ right: left + widths[i]
61
+ };
62
+ };
63
+ const fits = (i) => {
64
+ const candidate = bounds(i);
65
+ return candidate.left >= minX && candidate.right <= maxX && [...shown].every((j) => {
66
+ const other = bounds(j);
67
+ return candidate.right + 6 <= other.left || other.right + 6 <= candidate.left;
68
+ });
69
+ };
70
+ for (let i = 0; i < n; i++) if (fits(i)) shown.add(i);
71
+ if (n > 1 && !shown.has(n - 1)) {
72
+ const last = n - 1;
73
+ for (const i of [...shown].filter((j) => j !== 0).reverse()) {
74
+ shown.delete(i);
75
+ if (fits(last)) break;
76
+ shown.add(i);
77
+ }
78
+ if (fits(last)) shown.add(last);
79
+ }
80
+ for (const i of shown) children.push(ctx.text(centers[i], y, String(categories[i]), {
81
+ anchor: anchors[i],
82
+ size: 12
83
+ }));
84
+ };
85
+ const legend = (items, y = 350) => {
86
+ const out = ctx.legend(items, width - pad.l - pad.r);
87
+ children.push(ctx.el("g", { transform: `translate(${pad.l},${y})` }, out.children));
88
+ return out.height;
89
+ };
90
+ const endScene = (bottom = 330) => ctx.scene(bottom + 28, children, title);
91
+ const asPath = (pts) => pts.map((p, i) => `${i ? "L" : "M"}${p[0]},${p[1]}`).join(" ");
92
+ const linePath = (values, xs, ys) => {
93
+ let d = "", active = false;
94
+ values.forEach((v, i) => {
95
+ if (!finite(v)) {
96
+ active = false;
97
+ return;
98
+ }
99
+ d += `${active ? "L" : "M"}${xs[i]},${ys(v, i)}`;
100
+ active = true;
101
+ });
102
+ return d;
103
+ };
104
+ const data = spec.data || [];
105
+ if (spec.chart === "stream") {
106
+ const t = ctx.table(spec), cats = t.categories, series = t.series;
107
+ if (series.some((s) => s.values.some((v) => !finite(v)))) ctx.fit(msg("stream需要每个时点都有完整非负序列", "Stream requires complete, non-negative observations at every time"), msg("补齐有效观测或选择允许缺失的图型;不要把缺失当作0", "Provide complete observations or choose a chart that supports missing values; do not treat missing as zero"));
108
+ const totals = cats.map((_, i) => series.reduce((s, a) => s + a.values[i], 0));
109
+ const maximum = Math.max(1, ...totals), vertical = ctx.ticks([-maximum / 2, maximum / 2], series[0]?.field, { count: 4 });
110
+ const offsetLabels = vertical.ticks.map((tick) => ctx.format(tick, series[0]?.field, false));
111
+ const p = plot(72, 330, Math.max(36, ...offsetLabels.map((label) => ctx.measure(label, 12))) + 16, width - 24);
112
+ reserveEdgeCategories(cats, p);
113
+ const xs = cats.map((_, i) => bandX(i, cats.length, p));
114
+ const scale = Math.max(Math.abs(vertical.min), Math.abs(vertical.max)) / (p.h / 2);
115
+ const lower = cats.map((_, i) => -totals[i] / 2), center = p.y + p.h / 2;
116
+ vertical.ticks.forEach((tick) => {
117
+ const y = center - tick / scale;
118
+ children.push(ctx.line(p.x, y, p.x + p.w, y, { stroke: tick === 0 ? ctx.color("axis") : ctx.color("grid") }));
119
+ });
120
+ series.forEach((s, k) => {
121
+ const top = [], bottom = [];
122
+ s.values.forEach((v, i) => {
123
+ const amount = v || 0;
124
+ bottom.push(lower[i]);
125
+ lower[i] += amount;
126
+ top.push(lower[i]);
127
+ });
128
+ const toPoint = (v, i) => [xs[i], center - v / scale];
129
+ const points = [...top.map(toPoint), ...bottom.map(toPoint).reverse()];
130
+ children.push(ctx.el("polygon", {
131
+ points: points.map((q) => q.join(",")).join(" "),
132
+ fill: ctx.color(`tone${k % 6 + 1}`),
133
+ "fill-opacity": .82,
134
+ stroke: ctx.color("bg"),
135
+ "stroke-width": 1
136
+ }));
137
+ });
138
+ vertical.ticks.forEach((tick, index) => {
139
+ const y = center - tick / scale;
140
+ children.push(ctx.text(p.x - 8, y + 4, offsetLabels[index], {
141
+ anchor: "end",
142
+ size: 12
143
+ }));
144
+ });
145
+ children.push(ctx.textLines(p.x, 48, ctx.wrap(msg("纵轴为相对中心的厚度偏移;正值在上,负值在下", "Vertical axis is thickness offset from center; positive above, negative below"), p.w, 12), { size: 12 }));
146
+ catLabels(cats, p);
147
+ const h = legend(series.map((s, i) => ({
148
+ label: s.label,
149
+ color: ctx.color(`tone${i % 6 + 1}`)
150
+ })), p.y + p.h + 42);
151
+ const scene = endScene(p.y + p.h + 42 + h);
152
+ scene.width = Math.max(width, p.x + p.w + 24);
153
+ return scene;
154
+ }
155
+ if (spec.chart === "split-compare") {
156
+ const cats = ctx.table(spec).categories, rowsByCategory = cats.map((c) => data.find((r) => r[enc.category] === c)), upper = rowsByCategory.map((r) => r?.[enc.upper]), lower = rowsByCategory.map((r) => r?.[enc.lower]);
157
+ const upperScale = ctx.ticks(upper.filter(finite), enc.upper, {
158
+ zero: true,
159
+ count: 4
160
+ });
161
+ const lowerScale = ctx.ticks(lower.filter(finite), enc.lower, {
162
+ zero: true,
163
+ count: 4,
164
+ length: 220
165
+ });
166
+ const leftGutter = Math.max(36, ...upperScale.labels.map((label) => ctx.measure(label, 12))) + 16;
167
+ const rightGutter = Math.max(36, ...lowerScale.labels.map((label) => ctx.measure(label, 12))) + 16;
168
+ const p = plot(64, 330, leftGutter, width - rightGutter);
169
+ reserveEdgeCategories(cats, p);
170
+ const mid = p.y + p.h * .48, gap = 28, upH = mid - p.y - gap / 2, lowY = mid + gap / 2, lowH = p.y + p.h - lowY;
171
+ const su = {
172
+ min: upperScale.min,
173
+ max: upperScale.max,
174
+ ticks: upperScale.ticks,
175
+ labels: upperScale.labels
176
+ };
177
+ const sl = {
178
+ min: lowerScale.min,
179
+ max: lowerScale.max,
180
+ ticks: lowerScale.ticks,
181
+ labels: lowerScale.labels
182
+ };
183
+ const uy = (v) => p.y + (v - su.min) / (su.max - su.min || 1) * upH;
184
+ const ly = (v) => lowY + lowH - (v - sl.min) / (sl.max - sl.min || 1) * lowH;
185
+ const bw = Math.max(2, p.w / cats.length * .56);
186
+ upper.forEach((v, i) => {
187
+ if (!finite(v)) return;
188
+ const y = uy(v);
189
+ children.push(ctx.rect(bandX(i, cats.length, p) - bw / 2, p.y, bw, Math.max(1, y - p.y), { fill: ctx.color("tone2") }));
190
+ });
191
+ children.push(ctx.line(p.x, p.y, p.x + p.w, p.y, { stroke: ctx.color("axis") }));
192
+ const pts = lower.map((v, i) => [bandX(i, cats.length, p), ly(finite(v) ? v : sl.min)]);
193
+ children.push(ctx.path(`${asPath(pts)} L${pts.at(-1)[0]},${lowY + lowH} L${pts[0][0]},${lowY + lowH} Z`, {
194
+ fill: ctx.color("tone1"),
195
+ "fill-opacity": .18,
196
+ stroke: "none"
197
+ }));
198
+ children.push(ctx.path(asPath(pts), {
199
+ fill: "none",
200
+ stroke: ctx.color("tone1"),
201
+ "stroke-width": 2
202
+ }));
203
+ su.ticks.forEach((tick, i) => {
204
+ const uyPos = uy(tick);
205
+ children.push(ctx.line(p.x, uyPos, p.x + p.w, uyPos, { stroke: ctx.color("grid") }));
206
+ children.push(ctx.text(p.x - 8, uyPos + 4, su.labels[i], {
207
+ anchor: "end",
208
+ size: 12
209
+ }));
210
+ });
211
+ sl.ticks.forEach((tick, i) => {
212
+ const lyPos = ly(tick);
213
+ children.push(ctx.line(p.x, lyPos, p.x + p.w, lyPos, { stroke: ctx.color("grid") }));
214
+ children.push(ctx.text(p.x + p.w + 8, lyPos + 4, sl.labels[i], {
215
+ anchor: "start",
216
+ size: 12
217
+ }));
218
+ });
219
+ const axisCaption = (fieldName) => {
220
+ const meta = ctx.field(fieldName);
221
+ const unit = meta.unit || (meta.format === "percent" ? "%" : "");
222
+ return [meta.label, unit].filter(Boolean).join(" · ");
223
+ };
224
+ children.push(ctx.text(p.x, p.y - 8, axisCaption(enc.upper), { size: 12 }));
225
+ children.push(ctx.text(p.x, lowY - 6, axisCaption(enc.lower), { size: 12 }));
226
+ children.push(ctx.line(p.x, lowY + lowH, p.x + p.w, lowY + lowH, { stroke: ctx.color("axis") }));
227
+ catLabels(cats, {
228
+ ...p,
229
+ y: lowY,
230
+ h: lowH
231
+ });
232
+ const scene = endScene(p.y + p.h + 36);
233
+ scene.width = Math.max(width, p.x + p.w + rightGutter);
234
+ return scene;
235
+ }
236
+ if (spec.chart === "combo") {
237
+ const diagramPanel = spec[diagramCombo];
238
+ const cats = ctx.table(spec).categories, layers = spec.layers;
239
+ const axisFields = (axis) => [...new Set(layers.filter((l) => l.axis === axis).map((l) => l.field))];
240
+ const leftFields = axisFields("left"), rightFields = axisFields("right");
241
+ const rowsByCategory = cats.map((c) => data.find((r) => r[enc.category] === c));
242
+ const allValues = (f) => rowsByCategory.map((r) => r?.[f]);
243
+ const fieldsByAxis = {
244
+ left: leftFields,
245
+ right: rightFields
246
+ };
247
+ const scales = {}, axisTicks = {};
248
+ for (const axis of ["left", "right"]) {
249
+ const names = fieldsByAxis[axis];
250
+ if (!names.length) continue;
251
+ if (new Set(names.map((f) => `${ctx.field(f).unit || ""}|${ctx.field(f).format || ""}`)).size !== 1) ctx.fit(msg(`combo ${axis}轴的多个字段单位必须一致`, `Combo fields on the ${axis} axis must use matching units`), msg("统一字段单位与格式后重试", "Use a consistent unit and format on the axis"));
252
+ const baseline = layers.some((l) => l.axis === axis && ["area", "column"].includes(l.mark));
253
+ const ranges = names.map((f) => number(ctx, f, allValues(f), baseline));
254
+ const annotations = (spec.annotations || []).filter((a) => names.includes(a.field)).flatMap((a) => a.kind === "rule" ? [a.value] : a.kind === "band" ? [a.from, a.to] : []);
255
+ const min = Math.min(...ranges.map((r) => r.min), ...annotations);
256
+ const max = Math.max(...ranges.map((r) => r.max), ...annotations);
257
+ const primary = Object.values(axisTicks)[0];
258
+ const nice = ctx.ticks([min, max], names[0], {
259
+ zero: baseline,
260
+ length: Math.max(120, width - 160),
261
+ percentSymbol: false,
262
+ ...primary ? { intervals: primary.ticks.length - 1 } : {}
263
+ });
264
+ axisTicks[axis] = nice;
265
+ names.forEach((f) => {
266
+ scales[f] = nice;
267
+ });
268
+ }
269
+ const leftGutter = Math.max(36, ...(axisTicks.left?.labels || ["0"]).map((label) => ctx.measure(label, 12))) + 16;
270
+ const rightGutter = Math.max(28, ...(axisTicks.right?.labels || [""]).map((label) => ctx.measure(label, 12))) + 16;
271
+ const annotationRows = (spec.annotations || []).filter((annotation) => annotation.label || annotation.text).length;
272
+ const p = plot(36 + annotationRows * 16, 302, leftGutter, width - rightGutter);
273
+ reserveEdgeCategories(cats, p);
274
+ const yFor = (field, v) => p.y + p.h - (v - scales[field].min) / (scales[field].max - scales[field].min || 1) * p.h;
275
+ const y0 = (field) => yFor(field, Math.max(scales[field].min, Math.min(scales[field].max, 0)));
276
+ const gridAxis = axisTicks.left || axisTicks.right;
277
+ gridAxis.ticks.forEach((_, i) => {
278
+ const y = p.y + p.h - i / (gridAxis.ticks.length - 1) * p.h;
279
+ children.push(ctx.line(p.x, y, p.x + p.w, y, { stroke: ctx.color("grid") }));
280
+ if (axisTicks.left) children.push(ctx.text(p.x - 8, y + 4, axisTicks.left.labels[i], {
281
+ anchor: "end",
282
+ size: 12
283
+ }));
284
+ if (axisTicks.right) children.push(ctx.text(p.x + p.w + 8, y + 4, axisTicks.right.labels[i], { size: 12 }));
285
+ });
286
+ children.push(ctx.line(p.x, p.y + p.h, p.x + p.w, p.y + p.h, { stroke: ctx.color("axis") }));
287
+ const xs = cats.map((_, i) => bandX(i, cats.length, p));
288
+ const traces = [], columnLayers = [];
289
+ layers.forEach((layer, index) => {
290
+ const vals = allValues(layer.field), ys = vals.map((v) => finite(v) ? yFor(layer.field, v) : NaN);
291
+ const color = ctx.color(`tone${index % 6 + 1}`);
292
+ if (layer.mark === "column") {
293
+ columnLayers.push({
294
+ layer,
295
+ index,
296
+ ys,
297
+ color
298
+ });
299
+ return;
300
+ }
301
+ if (layer.mark === "area") {
302
+ let segment = [];
303
+ const close = () => {
304
+ if (segment.length) {
305
+ const base = y0(layer.field), pts = [
306
+ ...segment,
307
+ [segment.at(-1)[0], base],
308
+ [segment[0][0], base]
309
+ ];
310
+ children.push(ctx.path(`${asPath(pts)} Z`, {
311
+ fill: color,
312
+ "fill-opacity": .2,
313
+ stroke: "none"
314
+ }));
315
+ segment = [];
316
+ }
317
+ };
318
+ ys.forEach((y, i) => {
319
+ if (finite(y)) segment.push([xs[i], y]);
320
+ else close();
321
+ });
322
+ close();
323
+ }
324
+ const points = ys.flatMap((y, i) => finite(y) ? [[xs[i], y]] : []);
325
+ if (points.length) traces.push({
326
+ d: linePath(vals, xs, (v) => yFor(layer.field, v)),
327
+ points,
328
+ color
329
+ });
330
+ });
331
+ const traceMarks = ({ d, points }, ink, rim = false) => [ctx.path(d, {
332
+ fill: "none",
333
+ stroke: ink,
334
+ "stroke-width": rim ? 4 : 2,
335
+ ...rim ? {
336
+ "stroke-linejoin": "round",
337
+ "stroke-linecap": "round"
338
+ } : {}
339
+ }), ...points.map(([x, y]) => ctx.circle(x, y, rim ? 3.6 : 2.6, { fill: ink }))];
340
+ const markContrast = 3;
341
+ for (const { layer, index, ys, color } of columnLayers) {
342
+ const group = columnLayers.filter((item) => item.layer.axis === layer.axis);
343
+ const slot = group.findIndex((item) => item.index === index), bw = p.w / cats.length * .72 / group.length;
344
+ const base = y0(layer.field);
345
+ const boxes = ys.flatMap((y, i) => finite(y) ? [[
346
+ xs[i] - bw * group.length / 2 + slot * bw,
347
+ Math.min(y, base),
348
+ bw * .88,
349
+ Math.max(1, Math.abs(base - y))
350
+ ]] : []);
351
+ for (const box of boxes) children.push(ctx.rect(...box, { fill: color }));
352
+ const lowContrast = traces.filter((trace) => contrast(trace.color, color) < markContrast);
353
+ if (!boxes.length || !lowContrast.length) continue;
354
+ const clip = `combo-column-${diagramPanel ? `p${diagramPanel.index}-` : ""}${index}`;
355
+ children.push(ctx.el("defs", {}, [ctx.el("clipPath", { id: clip }, boxes.map((box) => ctx.rect(...box)))]));
356
+ children.push(ctx.el("g", { "clip-path": `url(#${clip})` }, lowContrast.flatMap((trace) => traceMarks(trace, pushContrast(trace.color, ctx.color("bg"), trace.color, markContrast), true))));
357
+ }
358
+ for (const trace of traces) children.push(...traceMarks(trace, trace.color));
359
+ const comboNotes = [];
360
+ for (const a of spec.annotations || []) {
361
+ const layer = layers.find((l) => l.field === a.field);
362
+ if (a.kind === "rule" && layer) {
363
+ const y = yFor(a.field, a.value);
364
+ children.push(ctx.line(p.x, y, p.x + p.w, y, {
365
+ stroke: ctx.color("tone6"),
366
+ "stroke-dasharray": "4 3"
367
+ }));
368
+ if (a.label) comboNotes.push({
369
+ text: a.label,
370
+ y: Math.max(p.y + 12, y - 16),
371
+ anchor: "start",
372
+ x: p.x + 4,
373
+ fill: ctx.textColor("fg")
374
+ });
375
+ }
376
+ if (a.kind === "band" && layer) {
377
+ const y1 = yFor(a.field, a.from), y2 = yFor(a.field, a.to);
378
+ children.push(ctx.rect(p.x, Math.min(y1, y2), p.w, Math.max(1, Math.abs(y2 - y1)), {
379
+ fill: ctx.color("tone6"),
380
+ "fill-opacity": .12
381
+ }));
382
+ if (a.label) comboNotes.push({
383
+ text: a.label,
384
+ y: Math.min(y1, y2) + 14,
385
+ anchor: "end",
386
+ fill: ctx.textColor("fg")
387
+ });
388
+ }
389
+ if (a.kind === "note" && enc.id) {
390
+ const row = data.find((r) => r[enc.id] === a.record), rowIndex = row ? cats.indexOf(row[enc.category]) : -1, layerForField = layers.find((l) => l.field === a.field);
391
+ if (rowIndex >= 0 && layerForField && finite(row[a.field])) comboNotes.push({
392
+ text: a.text,
393
+ y: yFor(a.field, row[a.field]) - 12,
394
+ anchor: "end",
395
+ fill: ctx.textColor("fg")
396
+ });
397
+ }
398
+ }
399
+ comboNotes.sort((a, b) => a.y - b.y).forEach((item, index) => {
400
+ const x = item.x ?? (item.anchor === "end" ? p.x + p.w - 4 : p.x + 4);
401
+ children.push(ctx.text(x, p.y - 8 - index * 16, item.text, {
402
+ anchor: item.anchor,
403
+ size: 12,
404
+ ...item.fill ? { fill: item.fill } : {}
405
+ }));
406
+ });
407
+ catLabels(cats, p);
408
+ const showAxisInLegend = !diagramPanel || leftFields.length > 0 && rightFields.length > 0;
409
+ const lh = legend(layers.map((l, i) => {
410
+ const meta = ctx.field(l.field), unit = meta.unit || (meta.format === "percent" ? "%" : "");
411
+ const axis = l.axis === "right" ? msg("右轴", "right axis") : msg("左轴", "left axis");
412
+ return {
413
+ label: [
414
+ meta.label,
415
+ unit,
416
+ showAxisInLegend ? axis : null
417
+ ].filter(Boolean).join(" · "),
418
+ color: ctx.color(`tone${i % 6 + 1}`)
419
+ };
420
+ }), p.y + p.h + 36);
421
+ const scene = endScene(p.y + p.h + 36 + lh);
422
+ scene.width = Math.max(width, p.x + p.w + rightGutter);
423
+ return scene;
424
+ }
425
+ if (spec.chart === "bubble-matrix") {
426
+ const rows = [...new Set(data.map((r) => r[enc.row]))], cols = [...new Set(data.map((r) => r[enc.column]))];
427
+ const rd = ctx.field(enc.row).domain, cd = ctx.field(enc.column).domain;
428
+ const rr = rd || rows, cc = cd || cols, vals = data.map((r) => r[enc.value]), max = Math.max(0, ...vals);
429
+ const rowCap = Math.max(72, width * .28);
430
+ const rowLines = rr.map((label) => ctx.wrap(String(label), rowCap, 12));
431
+ const rowWidth = Math.max(24, ...rowLines.flat().map((line) => ctx.measure(line, 12)));
432
+ const left = Math.min(rowCap, rowWidth) + 16;
433
+ const headers = columnHeaders(ctx, cc, {
434
+ left,
435
+ right: 16,
436
+ floor: 28
437
+ });
438
+ const cellW = headers.slot;
439
+ const cellH = Math.max(28, Math.floor(270 / Math.max(1, rr.length)));
440
+ const chartWidth = Math.max(width, left + cc.length * cellW + 16);
441
+ const gridH = rr.length * cellH;
442
+ const p = {
443
+ x: left,
444
+ y: 28,
445
+ w: cc.length * cellW,
446
+ h: gridH
447
+ };
448
+ rr.forEach((label, i) => {
449
+ const lines = ctx.wrap(String(label), rowWidth, 12);
450
+ children.push(ctx.textLines(p.x - 8, p.y + (i + .5) * cellH + 4 - (lines.length - 1) * 8, lines, {
451
+ anchor: "end",
452
+ size: 12
453
+ }));
454
+ });
455
+ const BUBBLE_OPACITY = .28;
456
+ const bubbles = [];
457
+ data.forEach((row) => {
458
+ const i = rr.indexOf(row[enc.row]), j = cc.indexOf(row[enc.column]), value = row[enc.value];
459
+ if (i < 0 || j < 0) return;
460
+ const x = p.x + (j + .5) * cellW, y = p.y + (i + .5) * cellH;
461
+ const meta = {
462
+ row: String(row[enc.row]),
463
+ column: String(row[enc.column]),
464
+ value
465
+ };
466
+ children.push(ctx.rect(p.x + j * cellW + 1, p.y + i * cellH + 1, cellW - 2, cellH - 2, { fill: ctx.color("grid") }));
467
+ const radius = value > 0 ? Math.min(cellW, cellH) * .43 * Math.sqrt(value / (max || 1)) : 0;
468
+ if (value > 0) children.push(ctx.circle(x, y, radius, {
469
+ fill: ctx.color("tone2"),
470
+ "fill-opacity": BUBBLE_OPACITY,
471
+ stroke: ctx.color("tone2"),
472
+ "stroke-width": 1.5,
473
+ meta
474
+ }));
475
+ bubbles.push({
476
+ x,
477
+ y,
478
+ radius,
479
+ value,
480
+ meta
481
+ });
482
+ });
483
+ const readout = (value) => ctx.format(value, enc.value, false);
484
+ const readoutColor = ctx.textOn("tone2", {
485
+ opacity: BUBBLE_OPACITY,
486
+ over: "grid"
487
+ });
488
+ if (bubbles.every((item) => {
489
+ if (!(item.value > 0)) return true;
490
+ const text = readout(item.value);
491
+ return ctx.measure(text, 12) + 4 <= item.radius * 2 && 12 <= item.radius * 1.6;
492
+ })) bubbles.forEach((item) => {
493
+ if (!(item.value > 0)) return;
494
+ children.push(ctx.text(item.x, item.y + 4, readout(item.value), {
495
+ anchor: "middle",
496
+ size: 12,
497
+ fill: readoutColor,
498
+ meta: {
499
+ ...item.meta,
500
+ kind: "cell-readout"
501
+ }
502
+ }));
503
+ });
504
+ const columnY = p.y + p.h + 18;
505
+ const yearY = columnY + Math.max(1, ...headers.items.map((item) => item.lines.length)) * 16;
506
+ headers.items.forEach((item, j) => {
507
+ if (item.lines.length) children.push(ctx.textLines(p.x + (j + .5) * cellW, columnY, item.lines, {
508
+ anchor: "middle",
509
+ size: 12
510
+ }));
511
+ if (item.year) children.push(ctx.text(p.x + j * cellW, yearY, item.year, {
512
+ size: 12,
513
+ fill: ctx.color("muted")
514
+ }));
515
+ });
516
+ const noteY = (headers.years ? yearY : yearY - 16) + 24;
517
+ const rowLabel = ctx.field(enc.row).label, columnLabel = ctx.field(enc.column).label, valueLabel = ctx.field(enc.value).label;
518
+ const noteLines = ctx.wrap(msg(`行:${rowLabel};列:${columnLabel};气泡面积 ∝ ${valueLabel};0 = ${ctx.format(0, enc.value)},最大 = ${ctx.format(max, enc.value)}`, `Rows: ${rowLabel}; columns: ${columnLabel}; bubble area ∝ ${valueLabel}; 0 = ${ctx.format(0, enc.value)}, max = ${ctx.format(max, enc.value)}`), Math.max(120, chartWidth - p.x - 24), 12, 400);
519
+ children.push(ctx.textLines(p.x, noteY, noteLines, { size: 12 }));
520
+ const noteWidth = Math.max(...noteLines.map((line) => ctx.measure(line, 12)));
521
+ const scene = ctx.scene(noteY + noteLines.length * 16 + 12, children, title);
522
+ scene.width = Math.max(chartWidth, p.x + noteWidth + 16);
523
+ return scene;
524
+ }
525
+ if (spec.chart === "calendar") {
526
+ const dateAt = (y, month, day) => {
527
+ const date = /* @__PURE__ */ new Date(0);
528
+ date.setUTCHours(0, 0, 0, 0);
529
+ date.setUTCFullYear(y, month, day);
530
+ return date;
531
+ };
532
+ const dateValues = data.map((row) => String(row[enc.date] ?? "")).filter((value) => /^\d{4}-\d{2}-\d{2}$/.test(value)).sort();
533
+ if (!dateValues.length) ctx.fit(msg("日历需要有效日期", "Calendar requires valid dates"), msg("提供 YYYY-MM-DD 格式的日期", "Provide dates in YYYY-MM-DD format"));
534
+ const [startYear, startMonth] = dateValues[0].split("-").map(Number);
535
+ const [lastYear, lastMonth] = dateValues.at(-1).slice(0, 7).split("-").map(Number);
536
+ const start = dateAt(startYear, startMonth - 1, 1);
537
+ const days = (dateAt(lastYear, lastMonth, 0) - start) / 864e5 + 1;
538
+ if (days > 1e4) ctx.fit(msg("日历日期跨度过长", "Calendar date span is too long"), msg("缩小到 10000 天以内的日期范围", "Limit the date range to 10000 days"));
539
+ const firstDay = new Intl.Locale(ctx.lang).weekInfo?.firstDay || (/^en-US/i.test(ctx.lang) ? 7 : 1), offset = (start.getUTCDay() - firstDay + 7) % 7;
540
+ const weeks = Math.ceil((offset + days) / 7);
541
+ const weekDay = new Intl.DateTimeFormat(ctx.lang, {
542
+ weekday: "narrow",
543
+ timeZone: "UTC"
544
+ });
545
+ const daysLabel = Array.from({ length: 7 }, (_, i) => weekDay.format(dateAt(2023, 0, 1 + (firstDay % 7 + i) % 7)));
546
+ const side = {
547
+ l: Math.max(...daysLabel.map((d) => ctx.measure(d, 12))) + 16,
548
+ r: 16
549
+ };
550
+ const slotWidth = (width - side.l - side.r) / weeks, gap = slotWidth >= 16 ? 3 : 2;
551
+ const cell = Math.max(10, Math.min(22, Math.floor(slotWidth - gap))), step = cell + gap, corner = Math.min(3, cell * .2);
552
+ const chartWidth = Math.max(width, side.l + weeks * step + side.r);
553
+ const p = {
554
+ x: side.l,
555
+ y: 48,
556
+ w: weeks * step,
557
+ h: 7 * step
558
+ };
559
+ const values = new Map(data.map((r) => [r[enc.date], r[enc.value]]));
560
+ const nums = data.map((r) => r[enc.value]);
561
+ const negativeMax = Math.max(0, ...nums.filter((v) => v < 0).map((v) => Math.abs(v)));
562
+ const positiveMax = Math.max(0, ...nums.filter((v) => v > 0));
563
+ daysLabel.forEach((d, i) => {
564
+ if ([
565
+ 0,
566
+ 2,
567
+ 4
568
+ ].includes(i)) children.push(ctx.text(p.x - 8, p.y + i * step + cell * .68, d, {
569
+ anchor: "end",
570
+ size: 12
571
+ }));
572
+ });
573
+ for (let d = 0; d < days; d++) {
574
+ const date = dateAt(startYear, startMonth - 1, d + 1).toISOString().slice(0, 10);
575
+ const index = offset + d, col = Math.floor(index / 7), row = index % 7, value = values.get(date);
576
+ const x = p.x + col * step, y = p.y + row * step;
577
+ const sideMax = value < 0 ? negativeMax : positiveMax;
578
+ if (value == null) children.push(ctx.rect(x, y, cell, cell, {
579
+ rx: corner,
580
+ fill: "none",
581
+ stroke: ctx.color("axis"),
582
+ "stroke-dasharray": "2 2",
583
+ meta: {
584
+ record: date,
585
+ value: null
586
+ }
587
+ }));
588
+ else if (spec.variant === "dots") {
589
+ const radius = value === 0 ? 2.5 : 2.5 + (cell * .35 - 2.5) * Math.sqrt(Math.abs(value) / (sideMax || 1));
590
+ children.push(ctx.circle(x + cell / 2, y + cell / 2, radius, {
591
+ fill: value < 0 ? ctx.color("tone2") : ctx.color("tone1"),
592
+ "fill-opacity": value === 0 ? .08 : .82,
593
+ stroke: value === 0 ? ctx.color("axis") : "none",
594
+ meta: {
595
+ record: date,
596
+ value
597
+ }
598
+ }));
599
+ } else {
600
+ const ratio = value === 0 ? 0 : Math.abs(value) / (sideMax || 1);
601
+ const base = value < 0 ? ctx.palette.tone2 : ctx.palette.tone1;
602
+ children.push(ctx.rect(x, y, cell, cell, {
603
+ rx: corner,
604
+ fill: ctx.mix(ctx.palette.bg, base, value === 0 ? .12 : .2 + ratio * .7),
605
+ stroke: value === 0 ? ctx.color("axis") : "none",
606
+ "stroke-width": value === 0 ? 1 : 0,
607
+ meta: {
608
+ record: date,
609
+ value
610
+ }
611
+ }));
612
+ }
613
+ }
614
+ const months = [];
615
+ for (let year = startYear, month = startMonth; year < lastYear || year === lastYear && month <= lastMonth;) {
616
+ months.push(`${year}-${String(month).padStart(2, "0")}`);
617
+ month += 1;
618
+ if (month > 12) {
619
+ year += 1;
620
+ month = 1;
621
+ }
622
+ }
623
+ ctx.compactTemporal(months).forEach((item, i) => {
624
+ const [year, month] = months[i].split("-").map(Number);
625
+ const monthStart = dateAt(year, month - 1, 1);
626
+ const col = Math.floor((offset + (monthStart - start) / 864e5) / 7);
627
+ if (item.year) children.push(ctx.text(p.x + col * step, p.y - 26, item.year, {
628
+ size: 12,
629
+ fill: ctx.color("muted")
630
+ }));
631
+ children.push(ctx.text(p.x + col * step, p.y - 10, item.label, {
632
+ size: 12,
633
+ fill: ctx.color("muted")
634
+ }));
635
+ });
636
+ const descriptionText = msg("未采集:虚线;零值:描边", "Missing: dashed; zero: outlined");
637
+ const ramps = [...positiveMax || !negativeMax ? [{
638
+ maximum: positiveMax,
639
+ color: ctx.palette.tone1,
640
+ negative: false
641
+ }] : [], ...negativeMax ? [{
642
+ maximum: negativeMax,
643
+ color: ctx.palette.tone2,
644
+ negative: true
645
+ }] : []].map((ramp) => ({
646
+ ...ramp,
647
+ label: spec.variant === "dots" ? msg(ramp.negative ? "负值面积小→大" : "正值面积小→大", ramp.negative ? "Negative area: small→large" : "Positive area: small→large") : ramp.negative ? msg("负值色阶", "Negative color scale") : negativeMax ? msg("正值色阶", "Positive color scale") : msg("色阶", "Color scale")
648
+ }));
649
+ const legendBlockWidth = Math.max(ctx.measure(descriptionText, 12), ...ramps.map((ramp) => ctx.measure(ramp.label, 12) + 16 + 106 + ctx.measure(ctx.format(ramp.negative ? -ramp.maximum : ramp.maximum, enc.value), 12)));
650
+ const sideLegend = p.x + p.w + 32 + legendBlockWidth <= chartWidth - side.r;
651
+ const legendX = sideLegend ? p.x + p.w + 32 : p.x;
652
+ let legendY = sideLegend ? p.y : p.y + p.h + 24;
653
+ const availableLegendWidth = sideLegend ? chartWidth - side.r - legendX : chartWidth - p.x - side.r;
654
+ const description = ctx.wrap(descriptionText, availableLegendWidth, 12);
655
+ children.push(ctx.textLines(legendX, legendY + 12, description, { size: 12 }));
656
+ legendY += description.length * 16 + 10;
657
+ for (const ramp of ramps) {
658
+ const labelLines = ctx.wrap(ramp.label, availableLegendWidth, 12);
659
+ children.push(ctx.textLines(legendX, legendY + 12, labelLines, { size: 12 }));
660
+ legendY += labelLines.length * 16 + 4;
661
+ for (let i = 0; i < 5; i++) {
662
+ const x = legendX + i * 22;
663
+ if (spec.variant === "dots") children.push(ctx.circle(x + 9, legendY + 5, 2.5 + i, {
664
+ fill: ramp.color,
665
+ "fill-opacity": .82
666
+ }));
667
+ else children.push(ctx.rect(x, legendY, 18, 10, {
668
+ fill: ctx.mix(ctx.palette.bg, ramp.color, .2 + i / 4 * .7),
669
+ stroke: ctx.color("axis"),
670
+ "stroke-width": .5
671
+ }));
672
+ }
673
+ children.push(ctx.text(legendX, legendY + 28, ctx.format(0, enc.value), { size: 12 }));
674
+ children.push(ctx.text(legendX + 72, legendY + 28, ctx.format(ramp.negative ? -ramp.maximum : ramp.maximum, enc.value), { size: 12 }));
675
+ legendY += 44;
676
+ }
677
+ if (sideLegend) legendY = Math.max(legendY, p.y + p.h + 24);
678
+ const scene = ctx.scene(legendY + 8, children, title);
679
+ scene.width = chartWidth;
680
+ return scene;
681
+ }
682
+ if (spec.chart === "tally") {
683
+ const t = ctx.table(spec), columns = 10;
684
+ const minSlot = Math.max(64, ctx.measure("字字", 12, 600) + 16);
685
+ const slot = width / Math.max(1, t.categories.length);
686
+ const titleDepth = Math.max(...t.categories.map((category) => ctx.wrap(String(category), Math.max(24, slot - 12), 12, 600).length));
687
+ const horizontal = width >= 520 && slot >= minSlot && titleDepth <= 3;
688
+ const categoryWidth = Math.min(width * .35, Math.max(24, ...t.categories.map((c) => ctx.measure(String(c), 12, 600))));
689
+ const valueWidth = Math.max(40, ...t.series[0].values.map((v) => ctx.measure(ctx.format(v, enc.value), 12, 600)));
690
+ const pitch = horizontal ? Math.max(7, Math.min(12, (width - 32) / (t.categories.length * columns))) : Math.max(6, Math.min(9, (width - categoryWidth - valueWidth - 36) / columns));
691
+ const dot = pitch * .7;
692
+ if (horizontal) {
693
+ const slotWidth = width / t.categories.length;
694
+ const titles = t.categories.map((category) => ctx.wrap(String(category), Math.max(24, slotWidth - 12), 12, 600));
695
+ const titleLines = Math.max(1, ...titles.map((lines) => lines.length));
696
+ const gridTop = 28 + titleLines * 16;
697
+ t.categories.forEach((category, i) => {
698
+ const value = t.series[0].values[i], center = slotWidth * (i + .5);
699
+ const categoryLines = titles[i];
700
+ children.push(ctx.textLines(center, 16 + (titleLines - categoryLines.length) * 8, categoryLines, {
701
+ anchor: "middle",
702
+ size: 12,
703
+ weight: 600,
704
+ fill: ctx.color("fg")
705
+ }));
706
+ const dotsX = center - 9 * pitch / 2;
707
+ for (let n = 0; n < 100; n++) {
708
+ const x = dotsX + n % columns * pitch, cy = gridTop + Math.floor(n / columns) * pitch;
709
+ const portion = Math.max(0, Math.min(1, value * 100 - n));
710
+ const radius = dot * (portion > 0 && portion < 1 ? .35 : .5);
711
+ children.push(ctx.circle(x, cy, radius, {
712
+ fill: portion ? ctx.color("tone1") : ctx.color("axis"),
713
+ opacity: 1,
714
+ meta: {
715
+ kind: "tally-mark",
716
+ category,
717
+ index: n,
718
+ value,
719
+ portion
720
+ }
721
+ }));
722
+ }
723
+ children.push(ctx.text(center, gridTop + 10 * pitch + 20, ctx.format(value, enc.value), {
724
+ anchor: "middle",
725
+ size: 12,
726
+ weight: 600,
727
+ fill: ctx.color("fg")
728
+ }));
729
+ });
730
+ const note = ctx.wrap(msg("每项独立百分比;点阵总量不要求相加为100%", "Independent percentages; dot totals need not sum to 100%"), width - 32, 12);
731
+ const noteY = gridTop + 10 * pitch + 52;
732
+ children.push(ctx.textLines(16, noteY, note, { size: 12 }));
733
+ return ctx.scene(noteY + note.length * 16 + 12, children, title);
734
+ }
735
+ const groupWidth = categoryWidth + 8 + columns * pitch + 12 + valueWidth;
736
+ const chartWidth = Math.max(width, groupWidth + 16);
737
+ const labelX = (chartWidth - groupWidth) / 2, dotsX = labelX + categoryWidth + 8;
738
+ const valueX = dotsX + columns * pitch + 12 + valueWidth;
739
+ const categoryLines = t.categories.map((category) => ctx.wrap(String(category), categoryWidth, 12, 600));
740
+ const rowHeights = categoryLines.map((lines) => Math.max(columns * pitch + 16, lines.length * 16 + 12));
741
+ let cursor = 24;
742
+ t.categories.forEach((category, i) => {
743
+ const value = t.series[0].values[i], rowH = rowHeights[i], y = cursor + rowH / 2;
744
+ children.push(ctx.textLines(labelX, y + 4 - (categoryLines[i].length - 1) * 8, categoryLines[i], {
745
+ size: 12,
746
+ weight: 600,
747
+ fill: ctx.color("fg")
748
+ }));
749
+ for (let n = 0; n < 100; n++) {
750
+ const x = dotsX + n % columns * pitch, cy = y - 22 + Math.floor(n / columns) * pitch;
751
+ const portion = Math.max(0, Math.min(1, value * 100 - n));
752
+ const radius = dot * (portion > 0 && portion < 1 ? .35 : .5);
753
+ children.push(ctx.circle(x, cy, radius, {
754
+ fill: portion ? ctx.color("tone1") : ctx.color("axis"),
755
+ opacity: 1,
756
+ meta: {
757
+ kind: "tally-mark",
758
+ category,
759
+ index: n,
760
+ value,
761
+ portion
762
+ }
763
+ }));
764
+ }
765
+ children.push(ctx.text(valueX, y + 4, ctx.format(value, enc.value), {
766
+ anchor: "end",
767
+ size: 12,
768
+ weight: 600,
769
+ fill: ctx.color("fg")
770
+ }));
771
+ cursor += rowH;
772
+ });
773
+ const note = ctx.wrap(msg("每项独立百分比;点阵总量不要求相加为100%", "Independent percentages; dot totals need not sum to 100%"), chartWidth - labelX - 16, 12);
774
+ const dotBottom = cursor - rowHeights.at(-1) / 2 - 22 + 9 * pitch + dot / 2;
775
+ const noteY = Math.max(cursor + 20, dotBottom + 28);
776
+ children.push(ctx.textLines(labelX, noteY, note, { size: 12 }));
777
+ const scene = ctx.scene(noteY + note.length * 16 + 12, children, title);
778
+ scene.width = chartWidth;
779
+ return scene;
780
+ }
781
+ if (spec.chart === "bump") {
782
+ const categories = ctx.field(enc.category).domain || [...new Set(data.map((r) => r[enc.category]))];
783
+ const series = [...new Set(data.map((r) => r[enc.series]))];
784
+ const ranks = data.map((r) => r[enc.rank]).filter(finite), max = Math.max(...ranks);
785
+ const LINE = 16;
786
+ const capOf = (label) => {
787
+ const full = ctx.measure(String(label), 12);
788
+ const word = Math.max(0, ...(String(label).match(/[A-Za-z0-9’'.-]+/g) || []).map((part) => ctx.measure(part, 12)));
789
+ let cap = Math.min(160, Math.max(48, Math.ceil(full / 2), Math.ceil(word)));
790
+ let lines = ctx.wrap(String(label), cap, 12);
791
+ while (lines.length > 2) {
792
+ cap += 12;
793
+ lines = ctx.wrap(String(label), cap, 12);
794
+ }
795
+ return lines;
796
+ };
797
+ const nameLines = series.map(capOf);
798
+ const nameColumn = Math.max(24, ...nameLines.flat().map((line) => ctx.measure(line, 12)));
799
+ const rankColumn = 28;
800
+ const left = 8 + nameColumn + 8 + rankColumn;
801
+ const rightReserve = nameColumn + 16;
802
+ const minPlotWidth = Math.max(1, categories.length) * 36;
803
+ const chartWidth = Math.max(width, left + minPlotWidth + rightReserve);
804
+ const rowSpan = Math.max(36, ...nameLines.map((lines) => lines.length * LINE + 4));
805
+ const p = plot(48, 48 + Math.max(220, (Math.max(1, max) - 1) * rowSpan), left, chartWidth - rightReserve);
806
+ const xs = categories.map((_, i) => bandX(i, categories.length, p));
807
+ const yOf = (rank) => p.y + (rank - 1) / Math.max(1, max - 1) * p.h;
808
+ for (let rank = 1; rank <= max; rank++) {
809
+ const y = yOf(rank);
810
+ children.push(ctx.line(p.x, y, p.x + p.w, y, { stroke: ctx.color("grid") }));
811
+ children.push(ctx.text(p.x - 8, y + 4, String(rank), {
812
+ anchor: "end",
813
+ size: 12
814
+ }));
815
+ }
816
+ const placed = {
817
+ start: [],
818
+ end: []
819
+ };
820
+ const dodge = (side, y, lines) => {
821
+ const height = lines.length * LINE;
822
+ let top = y - 14;
823
+ const lane = placed[side];
824
+ for (let guard = 0; guard < series.length + 2; guard += 1) {
825
+ const hit = lane.find((item) => top < item.bottom + 4 && top + height > item.top);
826
+ if (!hit) break;
827
+ top = hit.bottom + 4;
828
+ }
829
+ lane.push({
830
+ top,
831
+ bottom: top + height
832
+ });
833
+ return top + 12;
834
+ };
835
+ series.forEach((id, j) => {
836
+ const rows = categories.map((c) => data.find((r) => r[enc.category] === c && r[enc.series] === id));
837
+ const tone = `tone${j % 6 + 1}`, color = ctx.color(tone), labelColor = ctx.textColor(tone);
838
+ const values = rows.map((r) => r?.[enc.rank] ?? null);
839
+ children.push(ctx.path(linePath(values, xs, (v) => yOf(v)), {
840
+ fill: "none",
841
+ stroke: color,
842
+ "stroke-width": 2
843
+ }));
844
+ const lines = ctx.wrap(String(id), nameColumn, 12);
845
+ values.forEach((v, i) => {
846
+ if (!finite(v)) return;
847
+ const tied = data.filter((r) => r[enc.category] === categories[i] && r[enc.rank] === v);
848
+ const tieIndex = tied.findIndex((r) => r[enc.series] === id);
849
+ const offset = tied.length > 1 ? (tieIndex - (tied.length - 1) / 2) * 12 : 0;
850
+ const x = xs[i] + offset, y = yOf(v) + offset;
851
+ const meta = {
852
+ record: rows[i]?.[enc.id] || String(id),
853
+ series: id,
854
+ category: categories[i],
855
+ rank: v
856
+ };
857
+ children.push(ctx.circle(x, y, 5, {
858
+ fill: color,
859
+ stroke: ctx.color("bg"),
860
+ "stroke-width": 1.5,
861
+ meta
862
+ }));
863
+ if (i === 0) children.push(ctx.textLines(p.x - rankColumn, dodge("end", y, lines), lines, {
864
+ anchor: "end",
865
+ size: 12,
866
+ fill: labelColor,
867
+ leading: LINE,
868
+ meta
869
+ }));
870
+ if (i === categories.length - 1) children.push(ctx.textLines(p.x + p.w + 8, dodge("start", y, lines), lines, {
871
+ anchor: "start",
872
+ size: 12,
873
+ fill: labelColor,
874
+ leading: LINE,
875
+ meta
876
+ }));
877
+ });
878
+ });
879
+ const nameBottom = Math.max(p.y + p.h, ...placed.start.map((item) => item.bottom), ...placed.end.map((item) => item.bottom));
880
+ catLabels(categories, p, nameBottom + 20);
881
+ const scene = ctx.scene(nameBottom + 40, children, title);
882
+ scene.width = chartWidth;
883
+ return scene;
884
+ }
885
+ if (spec.chart === "radar") {
886
+ const dimensions = enc.dimensions, domains = dimensions.map((field) => ctx.field(field).domain);
887
+ const angles = dimensions.map((_, i) => -Math.PI / 2 + i * Math.PI * 2 / dimensions.length);
888
+ const rangeText = (field, domain) => {
889
+ const meta = ctx.field(field);
890
+ const bare = ctx.format(domain[0], field, false);
891
+ const full = ctx.format(domain[1], field, true);
892
+ return meta.unit || meta.format === "percent" ? `${bare}–${full}` : `${ctx.format(domain[0], field)}–${full}`;
893
+ };
894
+ const axisLabels = dimensions.map((field, i) => ({
895
+ name: String(ctx.field(field).label),
896
+ range: rangeText(field, domains[i])
897
+ }));
898
+ const chord = 2 * Math.sin(Math.PI / dimensions.length);
899
+ const labelRoom = dimensions.length >= 6 ? Math.max(48, Math.min(96, Math.ceil(width * chord * .42))) : Math.max(84, Math.min(140, Math.ceil(Math.max(72, width * .2) * chord)));
900
+ const wrapped = axisLabels.map((item) => ({
901
+ name: ctx.wrap(item.name, labelRoom, 12, 600),
902
+ range: ctx.wrap(item.range, labelRoom, 12, 400)
903
+ }));
904
+ const textWidth = Math.max(0, ...wrapped.flatMap((item) => [...item.name.map((line) => ctx.measure(line, 12, 600)), ...item.range.map((line) => ctx.measure(line, 12, 400))]));
905
+ const labelDepth = Math.max(...wrapped.map((item) => (item.name.length + item.range.length) * 16));
906
+ const radius = Math.min(180, Math.max(72, (width - textWidth * 2 - 24) / 2));
907
+ const cx = Math.max(width / 2, textWidth + radius + 12);
908
+ const cy = radius + labelDepth + 24;
909
+ const chartWidth = Math.max(width, cx + radius + textWidth + 12);
910
+ const radiusAt = (axis, value) => {
911
+ const [lo, hi] = domains[axis];
912
+ return Math.max(0, Math.min(1, (value - lo) / (hi - lo || 1))) * radius;
913
+ };
914
+ const rings = Number.isInteger(spec.rings) && spec.rings > 0 ? spec.rings : 4;
915
+ for (let ring = 1; ring <= rings; ring++) {
916
+ if (spec.graticule === "circle") {
917
+ children.push(ctx.circle(cx, cy, radius * ring / rings, {
918
+ fill: "none",
919
+ stroke: ctx.color("grid")
920
+ }));
921
+ continue;
922
+ }
923
+ const points = angles.map((angle) => [cx + Math.cos(angle) * radius * ring / rings, cy + Math.sin(angle) * radius * ring / rings]);
924
+ children.push(ctx.el("polygon", {
925
+ points: points.map((point) => point.join(",")).join(" "),
926
+ fill: "none",
927
+ stroke: ctx.color("grid")
928
+ }));
929
+ }
930
+ angles.forEach((angle, i) => {
931
+ const cos = Math.cos(angle), sin = Math.sin(angle);
932
+ children.push(ctx.line(cx, cy, cx + cos * radius, cy + sin * radius, { stroke: ctx.color("axis") }));
933
+ const horizontal = Math.abs(cos) >= Math.abs(sin);
934
+ const anchor = horizontal ? cos < 0 ? "end" : "start" : "middle";
935
+ const tx = horizontal ? cx + cos * (radius + 10) : cx + cos * radius;
936
+ const ty = horizontal ? cy + sin * radius : cy + sin * (radius + 10);
937
+ const block = wrapped[i].name.length + wrapped[i].range.length;
938
+ const firstY = horizontal ? ty - (block - 1) * 8 : sin < 0 ? ty - block * 16 - 4 : ty + 16;
939
+ children.push(ctx.textLines(tx, firstY, wrapped[i].name, {
940
+ anchor,
941
+ size: 12,
942
+ weight: 600,
943
+ fill: ctx.color("fg")
944
+ }));
945
+ children.push(ctx.textLines(tx, firstY + wrapped[i].name.length * 16, wrapped[i].range, {
946
+ anchor,
947
+ size: 12,
948
+ weight: 400,
949
+ fill: ctx.color("muted")
950
+ }));
951
+ });
952
+ data.forEach((row, rowIndex) => {
953
+ const points = dimensions.map((field, i) => [cx + Math.cos(angles[i]) * radiusAt(i, row[field]), cy + Math.sin(angles[i]) * radiusAt(i, row[field])]);
954
+ const color = ctx.color(`tone${rowIndex % 6 + 1}`);
955
+ children.push(ctx.el("polygon", {
956
+ points: points.map((point) => point.join(",")).join(" "),
957
+ fill: color,
958
+ "fill-opacity": .14,
959
+ stroke: color,
960
+ "stroke-width": 2
961
+ }));
962
+ points.forEach((point, i) => children.push(ctx.circle(point[0], point[1], 3, {
963
+ fill: color,
964
+ meta: {
965
+ record: row[enc.id] || String(rowIndex),
966
+ field: dimensions[i],
967
+ value: row[dimensions[i]]
968
+ }
969
+ })));
970
+ });
971
+ const legendY = cy + radius + labelDepth + 12;
972
+ const legendItems = data.map((row, i) => ({
973
+ label: row[enc.label],
974
+ color: ctx.color(`tone${i % 6 + 1}`),
975
+ meta: { record: row[enc.id] || String(i) }
976
+ }));
977
+ const showLegend = spec.legend !== false;
978
+ const legendBlock = showLegend ? ctx.legend(legendItems, Math.max(120, chartWidth - 32)) : {
979
+ children: [],
980
+ height: 0
981
+ };
982
+ if (showLegend) children.push(ctx.el("g", { transform: `translate(16,${legendY})` }, legendBlock.children));
983
+ const scene = ctx.scene(showLegend ? legendY + legendBlock.height + 16 : legendY - 12, children, title);
984
+ scene.width = chartWidth;
985
+ return scene;
986
+ }
987
+ if (spec.chart === "parallel") {
988
+ const dimensions = enc.dimensions;
989
+ const domainFor = (f) => ctx.field(f).domain || (() => {
990
+ const e = ctx.extent(data.map((r) => r[f]).filter(finite));
991
+ return e[0] === e[1] ? [e[0] - 1, e[1] + 1] : e;
992
+ })();
993
+ const axisTitle = (f) => {
994
+ const meta = ctx.field(f);
995
+ const unit = meta.unit || (meta.format === "percent" ? "%" : "");
996
+ return [meta.label, unit].filter(Boolean).join(" · ");
997
+ };
998
+ const titleLines = (slot) => dimensions.map((f) => ctx.wrap(axisTitle(f), Math.max(36, slot - 12), 12, 600));
999
+ const tickLabel = (f, value) => ctx.format(value, f, false);
1000
+ const tickWidth = Math.max(0, ...dimensions.flatMap((f) => {
1001
+ const domain = domainFor(f);
1002
+ return [
1003
+ 0,
1004
+ .5,
1005
+ 1
1006
+ ].map((step) => ctx.measure(tickLabel(f, domain[0] + (domain[1] - domain[0]) * step), 12));
1007
+ }));
1008
+ const titleWidth = Math.max(0, ...dimensions.map((f) => ctx.measure(axisTitle(f), 12, 600)));
1009
+ const side = Math.ceil(Math.max(tickWidth, titleWidth) / 2) + 8;
1010
+ const minSlot = Math.max(48, tickWidth + 8, ...titleLines(72).map((lines) => Math.max(...lines.map((line) => ctx.measure(line, 12, 600))) + 12));
1011
+ const gaps = Math.max(1, dimensions.length - 1);
1012
+ const slot = Math.max(minSlot, Math.floor((width - side * 2) / gaps));
1013
+ const chartWidth = Math.max(width, side + gaps * slot + side);
1014
+ const head = titleLines(slot);
1015
+ const headHeight = Math.max(...head.map((lines) => lines.length)) * 16 + 4;
1016
+ const p = plot(headHeight + 20, headHeight + 248, side, chartWidth - side);
1017
+ const xs = dimensions.map((_, i) => dimensions.length === 1 ? p.x + p.w / 2 : p.x + i * slot);
1018
+ dimensions.forEach((f, i) => {
1019
+ const d = domainFor(f);
1020
+ children.push(ctx.line(xs[i], p.y, xs[i], p.y + p.h, { stroke: ctx.color("axis") }));
1021
+ for (let k = 0; k <= 4; k++) {
1022
+ const v = d[0] + (d[1] - d[0]) * k / 4, y = p.y + p.h - k * p.h / 4;
1023
+ children.push(ctx.line(xs[i] - 3, y, xs[i] + 3, y, { stroke: ctx.color("axis") }));
1024
+ if (k === 0 || k === 4 || k === 2) children.push(ctx.text(xs[i], y - 4, tickLabel(f, v), {
1025
+ anchor: "middle",
1026
+ size: 12
1027
+ }));
1028
+ }
1029
+ children.push(ctx.textLines(xs[i], 16, head[i], {
1030
+ anchor: "middle",
1031
+ size: 12,
1032
+ weight: 600,
1033
+ fill: ctx.color("fg")
1034
+ }));
1035
+ });
1036
+ data.forEach((row, ri) => {
1037
+ const values = dimensions.map((f) => finite(row[f]) ? row[f] : null);
1038
+ const ys = values.map((v, i) => v === null ? NaN : p.y + p.h - (v - domainFor(dimensions[i])[0]) / (domainFor(dimensions[i])[1] - domainFor(dimensions[i])[0]) * p.h);
1039
+ const color = ctx.color(`tone${ri % 6 + 1}`);
1040
+ children.push(ctx.path(linePath(values, xs, (_, i) => ys[i]), {
1041
+ fill: "none",
1042
+ stroke: color,
1043
+ "stroke-width": 1.6,
1044
+ "stroke-opacity": .72,
1045
+ meta: {
1046
+ record: row[enc.id] || String(ri),
1047
+ series: row[enc.series]
1048
+ }
1049
+ }));
1050
+ });
1051
+ const legendY = p.y + p.h + 28;
1052
+ const legendItems = data.map((r, i) => ({
1053
+ label: String(r[enc.label]),
1054
+ color: ctx.color(`tone${i % 6 + 1}`),
1055
+ meta: { record: r[enc.id] || String(i) }
1056
+ }));
1057
+ const legendBlock = ctx.legend(legendItems, Math.max(120, chartWidth - 32));
1058
+ children.push(ctx.el("g", { transform: `translate(16,${legendY})` }, legendBlock.children));
1059
+ const scene = ctx.scene(legendY + legendBlock.height + 16, children, title);
1060
+ scene.width = chartWidth;
1061
+ return scene;
1062
+ }
1063
+ if (spec.chart === "launch-fan") {
1064
+ const starts = data.map((r) => r[enc.start]), values = data.map((r) => r[enc.value]);
1065
+ const side = 16;
1066
+ const max = Math.max(1, ...values), p = plot(78, 320, side, width - side);
1067
+ if (!starts.every((v) => typeof v === typeof starts[0])) ctx.fit(msg("launch-fan起点类型不一致", "launch-fan start types differ"), msg("统一使用数值时点或同一时间类型后重试", "Use numeric starts or a consistent date type"));
1068
+ const dates = typeof starts[0] === "string";
1069
+ const nums = starts.map((v) => dates ? Date.parse(v) : v);
1070
+ const labels = data.map((row, i) => `${row[enc.label]} · ${ctx.format(values[i], enc.value)}`);
1071
+ const labelWidth = Math.min(width * .27, Math.max(52, ...labels.map((label) => ctx.measure(label, 12, 400))));
1072
+ const labelLines = labels.map((label) => ctx.wrap(label, labelWidth, 12));
1073
+ const labelColumn = Math.max(...labelLines.map((lines) => Math.max(...lines.map((line) => ctx.measure(line, 12)))));
1074
+ const maxRadius = 28;
1075
+ const endX = Math.max(p.x + 128, Math.min(p.x + p.w * .84, width - side - labelColumn - maxRadius - 8));
1076
+ const chartWidth = Math.max(width, endX + maxRadius + 8 + labelColumn + side);
1077
+ const lo = Math.min(...nums), hi = Math.max(...nums);
1078
+ const timeEnd = endX - maxRadius - 16;
1079
+ const x = ctx.linear(lo, hi || lo + 1, p.x + 10, timeEnd);
1080
+ const sorted = data.map((row, i) => ({
1081
+ row,
1082
+ i,
1083
+ start: nums[i]
1084
+ })).sort((a, b) => a.start - b.start || a.i - b.i);
1085
+ const radiusOf = (i) => Math.sqrt(values[i] / max) * maxRadius;
1086
+ const circleGap = Math.max(0, ...sorted.slice(1).map((item, k) => radiusOf(sorted[k].i) + radiusOf(item.i) + 6));
1087
+ const rowGap = Math.max(36, circleGap, ...labelLines.map((lines) => lines.length * 16 + 8));
1088
+ const fanHeight = Math.max(p.h, 62 + Math.max(0, data.length - 1) * rowGap);
1089
+ const baseline = p.y + fanHeight;
1090
+ const bubbleTop = p.y + maxRadius, bubbleBottom = baseline - maxRadius - 6;
1091
+ children.push(ctx.line(p.x, baseline, timeEnd + 10, baseline, { stroke: ctx.color("axis") }));
1092
+ const startClusters = [];
1093
+ sorted.forEach((item) => {
1094
+ const sx = x(item.start), cluster = startClusters.at(-1);
1095
+ if (!cluster || sx - cluster.x >= 7) startClusters.push({
1096
+ x: sx,
1097
+ items: [item]
1098
+ });
1099
+ else cluster.items.push(item);
1100
+ });
1101
+ const startOffset = /* @__PURE__ */ new Map();
1102
+ startClusters.forEach((cluster) => {
1103
+ cluster.items.forEach((item, index) => {
1104
+ startOffset.set(item.i, (index - (cluster.items.length - 1) / 2) * 7);
1105
+ });
1106
+ });
1107
+ sorted.forEach(({ row, i, start }, rank) => {
1108
+ const sx = x(start), startY = baseline + startOffset.get(i);
1109
+ const ey = bubbleTop + rank * (bubbleBottom - bubbleTop) / Math.max(1, data.length - 1);
1110
+ const radius = Math.sqrt(values[i] / max) * maxRadius;
1111
+ const color = ctx.color(`tone${i % 6 + 1}`), id = row[enc.id] || String(i);
1112
+ children.push(ctx.path(`M${sx},${startY} Q${(sx + endX) / 2},${ey} ${endX - radius},${ey}`, {
1113
+ fill: "none",
1114
+ stroke: color,
1115
+ "stroke-width": Math.max(1, Math.sqrt(values[i] / max) * 3),
1116
+ "stroke-opacity": .6
1117
+ }));
1118
+ children.push(ctx.circle(sx, startY, 3, {
1119
+ fill: color,
1120
+ meta: {
1121
+ record: id,
1122
+ start
1123
+ }
1124
+ }));
1125
+ children.push(ctx.circle(endX, ey, radius, {
1126
+ fill: color,
1127
+ "fill-opacity": .32,
1128
+ stroke: color,
1129
+ "stroke-width": 1.5,
1130
+ meta: {
1131
+ record: id,
1132
+ value: values[i]
1133
+ }
1134
+ }));
1135
+ const lines = labelLines[i], labelY = ey - (lines.length - 1) * 8 + 4;
1136
+ children.push(ctx.textLines(endX + radius + 8, labelY, lines, {
1137
+ size: 12,
1138
+ fill: ctx.color("fg"),
1139
+ meta: {
1140
+ record: id,
1141
+ value: values[i]
1142
+ }
1143
+ }));
1144
+ });
1145
+ const timeLabel = (value, includeYear) => {
1146
+ if (!dates) return ctx.format(value, enc.start);
1147
+ const raw = String(starts.find((item) => (typeof item === "string" ? Date.parse(item) : item) === value));
1148
+ const monthOnly = /^\d{4}-\d{2}$/.test(raw);
1149
+ const options = {
1150
+ month: "short",
1151
+ timeZone: "UTC"
1152
+ };
1153
+ if (!monthOnly) options.day = "numeric";
1154
+ if (includeYear) options.year = "numeric";
1155
+ return new Intl.DateTimeFormat(ctx.lang, options).format(new Date(value));
1156
+ };
1157
+ const timeline = [...new Set(nums)].sort((a, b) => a - b).map((value) => ({
1158
+ value,
1159
+ year: dates ? new Date(value).getUTCFullYear() : null
1160
+ }));
1161
+ const withLabels = (items) => items.map((item, index) => ({
1162
+ ...item,
1163
+ label: timeLabel(item.value, dates && (index === 0 || item.year !== items[index - 1].year))
1164
+ }));
1165
+ const labelPosition = (item) => x(item.value);
1166
+ const fitsRight = (item) => labelPosition(item) + ctx.measure(item.label, 12) <= chartWidth - side;
1167
+ const labelAnchor = (item, index, count = timeline.length) => {
1168
+ if (index === 0) return "start";
1169
+ if (index === count - 1) return fitsRight(item) ? "start" : "end";
1170
+ return "middle";
1171
+ };
1172
+ const labelBounds = (item, index, count) => {
1173
+ const center = labelPosition(item), textWidth = ctx.measure(item.label, 12), anchor = labelAnchor(item, index, count);
1174
+ return [anchor === "start" ? center : anchor === "end" ? center - textWidth : center - textWidth / 2, anchor === "start" ? center + textWidth : anchor === "end" ? center : center + textWidth / 2];
1175
+ };
1176
+ let selected = [];
1177
+ timeline.forEach((item, index) => {
1178
+ const candidate = withLabels([...selected.map((entry) => ({
1179
+ value: entry.value,
1180
+ year: entry.year
1181
+ })), item]);
1182
+ const clear = candidate.every((entry, at) => at === 0 || labelBounds(candidate[at - 1], at - 1, candidate.length)[1] + 8 <= labelBounds(entry, at, candidate.length)[0]);
1183
+ const last = index === timeline.length - 1;
1184
+ if (!clear && last && candidate.length > 2) candidate.splice(-2, 1);
1185
+ const kept = withLabels(candidate.map((entry) => ({
1186
+ value: entry.value,
1187
+ year: entry.year
1188
+ })));
1189
+ const keptClear = kept.every((entry, at) => at === 0 || labelBounds(kept[at - 1], at - 1, kept.length)[1] + 8 <= labelBounds(entry, at, kept.length)[0]);
1190
+ if ((clear || last) && keptClear) selected = kept;
1191
+ });
1192
+ selected.forEach((item, index) => {
1193
+ const at = labelPosition(item), anchor = labelAnchor(item, index, selected.length);
1194
+ children.push(ctx.line(at, baseline - 1, at, baseline + 5, { stroke: ctx.color("axis") }));
1195
+ children.push(ctx.text(at, baseline + 22, item.label, {
1196
+ anchor,
1197
+ size: 12,
1198
+ fill: ctx.color("muted"),
1199
+ meta: {
1200
+ kind: "launch-fan-time",
1201
+ value: item.value
1202
+ }
1203
+ }));
1204
+ });
1205
+ const noteY = baseline + 50;
1206
+ const noteLines = ctx.wrap(msg("起点 = 开始时点;末端圆面积 = 当前量", "Start = launch date; end-circle area = current value"), chartWidth - p.x - 16, 12);
1207
+ children.push(ctx.textLines(p.x, noteY, noteLines, { size: 12 }));
1208
+ const scene = ctx.scene(noteY + noteLines.length * 16 + 12, children, title);
1209
+ scene.width = chartWidth;
1210
+ return scene;
1211
+ }
1212
+ throw new Error(`Unsupported multivariate chart: ${spec.chart}`);
1213
+ };
1214
+ function install({ register }) {
1215
+ register([
1216
+ "stream",
1217
+ "split-compare",
1218
+ "combo",
1219
+ "bubble-matrix",
1220
+ "calendar",
1221
+ "tally",
1222
+ "bump",
1223
+ "radar",
1224
+ "parallel",
1225
+ "launch-fan"
1226
+ ], chart);
1227
+ }
1228
+ install({ register });
1229
+ export { diagramCombo, install, multivariate_exports };