@x-cmd/draw 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +228 -0
  2. package/README.cn.md +235 -0
  3. package/README.md +235 -2
  4. package/dist/lib.d.ts +25 -0
  5. package/dist/lib.js +50 -0
  6. package/dist/node/cli.d.ts +2 -0
  7. package/dist/node/cli.js +79 -0
  8. package/dist/render/area.d.ts +8 -0
  9. package/dist/render/area.js +414 -0
  10. package/dist/render/bar-grid.d.ts +3 -0
  11. package/dist/render/bar-grid.js +52 -0
  12. package/dist/render/bar-grouped.d.ts +3 -0
  13. package/dist/render/bar-grouped.js +131 -0
  14. package/dist/render/bar-stacked.d.ts +3 -0
  15. package/dist/render/bar-stacked.js +142 -0
  16. package/dist/render/bar.d.ts +3 -0
  17. package/dist/render/bar.js +74 -0
  18. package/dist/render/combo.d.ts +3 -0
  19. package/dist/render/combo.js +256 -0
  20. package/dist/render/dispatch.d.ts +3 -0
  21. package/dist/render/dispatch.js +69 -0
  22. package/dist/render/gauge.d.ts +3 -0
  23. package/dist/render/gauge.js +216 -0
  24. package/dist/render/hbar-spec.d.ts +7 -0
  25. package/dist/render/hbar-spec.js +265 -0
  26. package/dist/render/hbar.d.ts +3 -0
  27. package/dist/render/hbar.js +55 -0
  28. package/dist/render/line-multi.d.ts +3 -0
  29. package/dist/render/line-multi.js +89 -0
  30. package/dist/render/line.d.ts +11 -0
  31. package/dist/render/line.js +123 -0
  32. package/dist/render/measure.d.ts +60 -0
  33. package/dist/render/measure.js +75 -0
  34. package/dist/render/pie.d.ts +5 -0
  35. package/dist/render/pie.js +439 -0
  36. package/dist/render/qr.d.ts +8 -0
  37. package/dist/render/qr.js +52 -0
  38. package/dist/render/query.d.ts +14 -0
  39. package/dist/render/query.js +220 -0
  40. package/dist/render/radar.d.ts +5 -0
  41. package/dist/render/radar.js +221 -0
  42. package/dist/render/sankey.d.ts +3 -0
  43. package/dist/render/sankey.js +280 -0
  44. package/dist/render/scatter.d.ts +3 -0
  45. package/dist/render/scatter.js +98 -0
  46. package/dist/render/svg.d.ts +93 -0
  47. package/dist/render/svg.js +471 -0
  48. package/dist/specs/base.d.ts +34 -0
  49. package/dist/specs/base.js +159 -0
  50. package/dist/specs/combo.d.ts +15 -0
  51. package/dist/specs/combo.js +135 -0
  52. package/dist/specs/csv.d.ts +1 -0
  53. package/dist/specs/csv.js +40 -0
  54. package/dist/specs/gauge.d.ts +15 -0
  55. package/dist/specs/gauge.js +108 -0
  56. package/dist/specs/index.d.ts +8 -0
  57. package/dist/specs/index.js +9 -0
  58. package/dist/specs/input.d.ts +11 -0
  59. package/dist/specs/input.js +33 -0
  60. package/dist/specs/multi.d.ts +12 -0
  61. package/dist/specs/multi.js +112 -0
  62. package/dist/specs/sankey.d.ts +13 -0
  63. package/dist/specs/sankey.js +112 -0
  64. package/dist/specs/scatter.d.ts +20 -0
  65. package/dist/specs/scatter.js +121 -0
  66. package/dist/store.d.ts +15 -0
  67. package/dist/store.js +121 -0
  68. package/dist/styles/area.d.ts +2 -0
  69. package/dist/styles/area.js +106 -0
  70. package/dist/styles/bar.d.ts +2 -0
  71. package/dist/styles/bar.js +52 -0
  72. package/dist/styles/combo.d.ts +2 -0
  73. package/dist/styles/combo.js +37 -0
  74. package/dist/styles/common.d.ts +34 -0
  75. package/dist/styles/common.js +259 -0
  76. package/dist/styles/gauge.d.ts +2 -0
  77. package/dist/styles/gauge.js +51 -0
  78. package/dist/styles/handlee.d.ts +1 -0
  79. package/dist/styles/handlee.js +2 -0
  80. package/dist/styles/hbar.d.ts +2 -0
  81. package/dist/styles/hbar.js +66 -0
  82. package/dist/styles/index.d.ts +7 -0
  83. package/dist/styles/index.js +79 -0
  84. package/dist/styles/inter.d.ts +3 -0
  85. package/dist/styles/inter.js +10 -0
  86. package/dist/styles/line.d.ts +2 -0
  87. package/dist/styles/line.js +97 -0
  88. package/dist/styles/pie.d.ts +2 -0
  89. package/dist/styles/pie.js +163 -0
  90. package/dist/styles/qr.d.ts +2 -0
  91. package/dist/styles/qr.js +12 -0
  92. package/dist/styles/radar.d.ts +2 -0
  93. package/dist/styles/radar.js +50 -0
  94. package/dist/styles/sankey.d.ts +2 -0
  95. package/dist/styles/sankey.js +29 -0
  96. package/dist/styles/scatter.d.ts +2 -0
  97. package/dist/styles/scatter.js +21 -0
  98. package/dist/styles/types.d.ts +105 -0
  99. package/dist/styles/types.js +70 -0
  100. package/dist/theme.d.ts +3 -0
  101. package/dist/theme.js +11 -0
  102. package/dist/types.d.ts +17 -0
  103. package/dist/types.js +1 -0
  104. package/dist/version.d.ts +6 -0
  105. package/dist/version.js +16 -0
  106. package/package.json +53 -4
@@ -0,0 +1,471 @@
1
+ // SVG 生成通用工具:转义、数字格式化、好看刻度、metadata 嵌入、文档包装与公共图元。
2
+ import { FONT, TAB } from '../theme.js';
3
+ import { ticks as d3Ticks, tickStep } from 'd3-array';
4
+ import { INTER_FACE_CSS, INTER_WIDTHS } from '../styles/inter.js';
5
+ export function esc(s) {
6
+ return s
7
+ .replace(/&/g, '&')
8
+ .replace(/</g, '&lt;')
9
+ .replace(/>/g, '&gt;')
10
+ .replace(/"/g, '&quot;')
11
+ .replace(/'/g, '&apos;');
12
+ }
13
+ const trim1 = (x) => {
14
+ const s = x.toFixed(1);
15
+ return s.endsWith('.0') ? s.slice(0, -2) : s;
16
+ };
17
+ // 紧凑格式:1234 -> "1.2k", 1500000 -> "1.5M"
18
+ export function fmtNum(n) {
19
+ const abs = Math.abs(n);
20
+ if (abs >= 1e9)
21
+ return trim1(n / 1e9) + 'B';
22
+ if (abs >= 1e6)
23
+ return trim1(n / 1e6) + 'M';
24
+ if (abs >= 1e3)
25
+ return trim1(n / 1e3) + 'k';
26
+ if (abs > 0 && abs < 0.01)
27
+ return n.toPrecision(2); // 微值不用固定 2 位小数(会抹成 0)
28
+ return String(Math.round(n * 100) / 100);
29
+ }
30
+ // 完整格式:4821 -> "4,821"
31
+ export function fmtFull(n) {
32
+ const r = Math.round(n * 100) / 100;
33
+ return r.toLocaleString('en-US', { maximumFractionDigits: 2 });
34
+ }
35
+ export function trunc(s, n) {
36
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
37
+ }
38
+ export const r2 = (n) => Math.round(n * 100) / 100;
39
+ // "好看"步长:d3 的 1/2/5×10ⁿ 阶梯
40
+ export function niceStep(raw) {
41
+ if (!(raw > 0))
42
+ return 1;
43
+ return tickStep(0, raw, 1);
44
+ }
45
+ // 按步长量级取精度再取整(固定 2 位小数会把 0.0001 之类的微值刻度抹成 0 → NaN)
46
+ export function snap(v, step) {
47
+ const decimals = Math.max(0, -Math.floor(Math.log10(step)) + 2);
48
+ const p = Math.pow(10, decimals);
49
+ return Math.round(v * p) / p;
50
+ }
51
+ // 0..max 的刻度:0 起步、顶格向上取整(数据不超轴顶),刻度数 count±2(d3 惯例)
52
+ export function niceTicks(max, count = 4) {
53
+ if (!(max > 0))
54
+ return [0, 1];
55
+ const t = d3Ticks(0, max, count);
56
+ if (t.length >= 2 && t[t.length - 1] >= max - 1e-9)
57
+ return t;
58
+ const step = niceStep(max / count);
59
+ const n = Math.ceil(max / step - 1e-9);
60
+ const out = [];
61
+ for (let i = 0; i <= n; i++)
62
+ out.push(snap(i * step, step));
63
+ return out;
64
+ }
65
+ // 任意区间 [min,max] 的"好看"刻度(散点图等不从 0 开始的轴)
66
+ export function rangeTicks(min, max, count = 4) {
67
+ if (!(max > min))
68
+ return [min];
69
+ const step = niceStep((max - min) / count);
70
+ const out = [];
71
+ for (let v = Math.ceil(min / step) * step; v <= max + 1e-9; v += step) {
72
+ out.push(snap(v, step));
73
+ }
74
+ return out.length > 0 ? out : [min, max];
75
+ }
76
+ // 内嵌结构化 metadata:数据 + 模板 + 版本,AI 可直接读取
77
+ function metaTag(template, version, spec) {
78
+ const json = JSON.stringify({ generator: 'draw', template, version, spec });
79
+ return `<metadata>${esc(json)}</metadata>`;
80
+ }
81
+ // 顶部图例:anchor='left' 从左往右(shadcn 圆点) | 'right' 从右往左(Evil 方块)
82
+ export function topLegend(items, x, y, anchor = 'right', shape = 'circle') {
83
+ const parts = [];
84
+ const swatch = (sx, color) => shape === 'square'
85
+ ? `<rect x="${r2(sx - 5)}" y="${r2(y - 9)}" width="11" height="11" rx="3" fill="${color}"/>`
86
+ : `<circle cx="${r2(sx)}" cy="${r2(y - 4)}" r="5" fill="${color}"/>`;
87
+ const gap = shape === 'square' ? 18 : 13;
88
+ if (anchor === 'left') {
89
+ let cx = x;
90
+ for (const it of items) {
91
+ const w = textW(it.name, 12);
92
+ parts.push(swatch(cx, it.color));
93
+ parts.push(`<text x="${r2(cx + gap)}" y="${r2(y)}" font-size="12" font-weight="500" fill="var(--d-text)">${esc(it.name)}</text>`);
94
+ cx += gap + w + 26;
95
+ }
96
+ }
97
+ else {
98
+ let cx = x;
99
+ for (let i = items.length - 1; i >= 0; i--) {
100
+ const it = items[i];
101
+ const w = textW(it.name, 12);
102
+ parts.push(`<text x="${r2(cx)}" y="${r2(y)}" text-anchor="end" font-size="12" font-weight="500" fill="var(--d-text)">${esc(it.name)}</text>`);
103
+ parts.push(swatch(cx - w - (shape === 'square' ? 18 : 10), it.color));
104
+ cx -= w + 28 + (shape === 'square' ? 8 : 0);
105
+ }
106
+ }
107
+ return parts.join('');
108
+ }
109
+ // 系列色 / 系列上文字色的 var 引用(渲染器一律使用)
110
+ export const sVar = (i) => `var(--d-s${i + 1})`;
111
+ export const onVar = (i) => `var(--d-on-s${i + 1})`;
112
+ const lumaHex = (hex) => {
113
+ const h = hex.replace('#', '');
114
+ return 0.299 * parseInt(h.slice(0, 2), 16) + 0.587 * parseInt(h.slice(2, 4), 16) + 0.114 * parseInt(h.slice(4, 6), 16);
115
+ };
116
+ const onDuo = (d) => ({
117
+ light: lumaHex(d.light) > 150 ? '#18181b' : '#ffffff',
118
+ dark: lumaHex(d.dark) > 150 ? '#18181b' : '#ffffff',
119
+ });
120
+ // 皮肤 → 内嵌样式块(auto=双套+media query,dark/light=单套);含 Inter 子集 @font-face
121
+ function skinStyle(skin) {
122
+ const n = skin.neutrals;
123
+ const varsOf = (side) => {
124
+ const items = [];
125
+ skin.series.forEach((d, i) => items.push(`--d-s${i + 1}:${d[side]}`, `--d-on-s${i + 1}:${onDuo(d)[side]}`));
126
+ items.push(`--d-ramp-a:${skin.ramp[0][side]}`, `--d-ramp-b:${skin.ramp[1][side]}`, `--d-ink:${n.ink[side]}`, `--d-text:${n.text[side]}`, `--d-muted:${n.muted[side]}`, `--d-faint:${n.faint[side]}`, `--d-grid:${n.grid[side]}`, `--d-baseline:${n.baseline[side]}`, `--d-border:${n.border[side]}`, `--d-card:${n.card[side]}`, `--d-halo:${n.halo[side]}`);
127
+ return `:root{color-scheme:${side};${items.join(';')}}`;
128
+ };
129
+ if (skin.scheme === 'auto') {
130
+ return `<style>${INTER_FACE_CSS}${varsOf('light')}@media (prefers-color-scheme: dark){${varsOf('dark')}}</style>`;
131
+ }
132
+ return `<style>${INTER_FACE_CSS}${varsOf(skin.scheme)}</style>`;
133
+ }
134
+ // 统一 SVG 文档包装:外壳 + 皮肤变量 + metadata(渲染器不再各自拼 <svg>)
135
+ export function svgDoc(width, height, template, version, aria, spec, skin, children) {
136
+ return (`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" ` +
137
+ `font-family="${FONT}" role="img" aria-label="${esc(aria)}">` +
138
+ skinStyle(skin) + metaTag(template, version, spec) + children + `</svg>`);
139
+ }
140
+ // 标题块:plain = 18px/500(Evil 系);editorial = 30px/600 自然语言大标题(OpenData 系)
141
+ // editorial 超宽换行至多 2 行(Latin 按词、CJK 逐字),装不下省略号截断
142
+ export function editorialTitle(title, width, pad) {
143
+ const maxW = width - pad * 2;
144
+ // 切分原子:Latin 词(含尾部空格)与单个 CJK 字符
145
+ const atoms = title.match(/[A-Za-z0-9'’\-]+\s*|[^\s]/g) ?? [...title];
146
+ const lines = [];
147
+ let cur = '';
148
+ let truncated = false;
149
+ for (const atom of atoms) {
150
+ if (textW(cur + atom, 16) <= maxW) {
151
+ cur += atom;
152
+ continue;
153
+ }
154
+ if (cur.trim())
155
+ lines.push(cur.trimEnd());
156
+ cur = atom.trimStart();
157
+ if (lines.length === 2) {
158
+ truncated = true;
159
+ cur = '';
160
+ break;
161
+ }
162
+ }
163
+ if (cur.trim() && lines.length < 2)
164
+ lines.push(cur.trimEnd());
165
+ if (truncated && lines.length) {
166
+ let last = lines[lines.length - 1];
167
+ while (last.length > 1 && textW(last + '…', 16) > maxW)
168
+ last = last.slice(0, -1);
169
+ lines[lines.length - 1] = last + '…';
170
+ }
171
+ const svg = lines
172
+ .map((l, i) => `<text x="${pad}" y="${pad + 30 + i * 34.5}" font-size="30" font-weight="600" letter-spacing="-0.02em" fill="var(--d-ink)">${esc(l)}</text>`)
173
+ .join('');
174
+ return { svg, height: lines.length * 34.5 + 10 };
175
+ }
176
+ export function titleBlock(title, pad = 24) {
177
+ if (!title)
178
+ return '';
179
+ return `<text x="${pad}" y="${pad + 14}" font-size="18" font-weight="500" letter-spacing="-0.02em" fill="var(--d-ink)">${esc(title)}</text>`;
180
+ }
181
+ // Y 轴三件套:网格线 + 刻度文字 + 基线;inline = 刻度悬在网格线上方(OpenData 风)
182
+ export function yAxisGrid(parts, ticks, y, left, right, bottom, grid = 'solid', gridDash = '3 8', inline = false, baseline = 'line', xDots = [], tickFs = 12, tickGap = 8) {
183
+ for (const t of ticks) {
184
+ const gy = r2(y(t));
185
+ // 无基线模式(规范 area-1)0 刻度也画网格线,充当底边
186
+ if ((t > 0 || baseline === 'none') && grid !== 'none') {
187
+ const dash = grid === 'dashed' ? ` stroke-dasharray="${gridDash}"` : '';
188
+ parts.push(`<line x1="${left}" y1="${gy}" x2="${right}" y2="${gy}" stroke="var(--d-grid)" stroke-width="1"${dash}/>`);
189
+ }
190
+ if (inline) {
191
+ parts.push(`<text x="${left}" y="${r2(y(t) - 6)}" text-anchor="start" font-size="${tickFs}" fill="var(--d-muted)" style="${TAB}">${fmtNum(t)}</text>`);
192
+ }
193
+ else {
194
+ parts.push(`<text x="${r2(left - tickGap)}" y="${r2(y(t) + 4)}" text-anchor="end" font-size="${tickFs}" fill="var(--d-muted)" style="${TAB}">${fmtNum(t)}</text>`);
195
+ }
196
+ }
197
+ if (baseline === 'line') {
198
+ parts.push(`<line x1="${left}" y1="${bottom}" x2="${right}" y2="${bottom}" stroke="var(--d-baseline)" stroke-width="1"/>`);
199
+ }
200
+ else if (baseline === 'dots') {
201
+ for (const dx of xDots) {
202
+ parts.push(`<circle cx="${r2(dx)}" cy="${r2(bottom + 12)}" r="3" fill="var(--d-baseline)" fill-opacity="0.8"/>`);
203
+ }
204
+ }
205
+ }
206
+ // 旋转 Y 轴标题(取 unit;OpenData 风)
207
+ export function axisTitleY(unit, midY, x = 32) {
208
+ if (!unit)
209
+ return '';
210
+ return `<text x="${x}" y="${r2(midY)}" text-anchor="middle" font-size="15" font-weight="500" fill="var(--d-ink)" transform="rotate(-90, ${x}, ${r2(midY)})">${esc(unit)}</text>`;
211
+ }
212
+ // 多系列全局峰值(系列号, 点号),num=peak 与加粗用
213
+ export function findPeak(series) {
214
+ let ps = 0;
215
+ let pp = 0;
216
+ series.forEach((s, si) => s.values.forEach((v, pi) => {
217
+ if (v > series[ps].values[pp]) {
218
+ ps = si;
219
+ pp = pi;
220
+ }
221
+ }));
222
+ return [ps, pp];
223
+ }
224
+ // 文字宽度:与内嵌 Inter 子集同源的 advance 表,宽度 = fs × Σ(advance/em)。
225
+ // 中文/全角 1em;子集外字符保守 1em(宁宽勿窄)
226
+ export function textW(s, fs) {
227
+ let em = 0;
228
+ for (const ch of s) {
229
+ em += ch.charCodeAt(0) > 0x2e80 ? 1 : INTER_WIDTHS[ch] ?? 1; // CJK=1em;未知拉丁按 1em(保守)
230
+ }
231
+ return em * fs;
232
+ }
233
+ // Catmull-Rom 平滑曲线转三次贝塞尔(t≈0.2),折线类共用
234
+ export function smoothPath(pts) {
235
+ if (pts.length < 3)
236
+ return `M${pts.map((p) => `${r2(p[0])} ${r2(p[1])}`).join('L')}`;
237
+ let d = `M${r2(pts[0][0])} ${r2(pts[0][1])}`;
238
+ for (let i = 0; i < pts.length - 1; i++) {
239
+ const p0 = pts[i - 1] ?? pts[i];
240
+ const p1 = pts[i];
241
+ const p2 = pts[i + 1];
242
+ const p3 = pts[i + 2] ?? p2;
243
+ const t = 0.2;
244
+ const c1x = p1[0] + (p2[0] - p0[0]) * t;
245
+ const c1y = p1[1] + (p2[1] - p0[1]) * t;
246
+ const c2x = p2[0] - (p3[0] - p1[0]) * t;
247
+ const c2y = p2[1] - (p3[1] - p1[1]) * t;
248
+ d += `C${r2(c1x)} ${r2(c1y)} ${r2(c2x)} ${r2(c2y)} ${r2(p2[0])} ${r2(p2[1])}`;
249
+ }
250
+ return d;
251
+ }
252
+ // 按底色亮度选字色:亮底→墨色,深底→白色
253
+ export function onColor(hex) {
254
+ const h = hex.replace('#', '');
255
+ const r = parseInt(h.slice(0, 2), 16);
256
+ const g = parseInt(h.slice(2, 4), 16);
257
+ const b = parseInt(h.slice(4, 6), 16);
258
+ return 0.299 * r + 0.587 * g + 0.114 * b > 150 ? '#18181b' : '#ffffff';
259
+ }
260
+ // 标签白描边属性(压在任意底色上都可读;仅 pushLineLabel 内部使用)
261
+ const HALO = 'paint-order="stroke" stroke="var(--d-halo)" stroke-width="3" stroke-linejoin="round"';
262
+ // 标签碰撞检测:重叠即舍弃,保证任何情况下数字不重叠
263
+ export class LabelPlacer {
264
+ boxes = [];
265
+ fits(x, y, w, h) {
266
+ for (const [bx, by, bw, bh] of this.boxes) {
267
+ if (x < bx + bw && x + w > bx && y < by + bh && y + h > by)
268
+ return false;
269
+ }
270
+ this.boxes.push([x, y, w, h]);
271
+ return true;
272
+ }
273
+ /** 无条件占位:柱内标签等"位置已定"的文字,让后续标签(如线标签)避让 */
274
+ reserve(x, y, w, h) {
275
+ this.boxes.push([x, y, w, h]);
276
+ }
277
+ }
278
+ // 预留固定文字区(图例/刻度带/X 标签带):数值标签不得压上,避不开则整层不标
279
+ export function reserveBands(placer, left, right, contentTop, bottom, xLabelY, legendItems, legendX, legendY) {
280
+ placer.reserve(0, contentTop - 10, Math.max(left - 8, 1), bottom - contentTop + 20); // Y 刻度带
281
+ if (xLabelY !== null)
282
+ placer.reserve(left - 40, xLabelY - 12, right - left + 80, 18); // X 标签带
283
+ if (legendItems.length) {
284
+ const w = legendItems.reduce((s, it) => s + 15 + textW(it.name, 12) + 26, -26);
285
+ placer.reserve(legendX - w - 8, legendY - 14, w + 16, 22);
286
+ }
287
+ }
288
+ // X 轴标签抽稀步长:按最宽标签与槽宽决定隔几个显示一个(不重叠)
289
+ export function labelStride(labels, slot, fs = 12) {
290
+ if (slot <= 0)
291
+ return 1;
292
+ const maxW = Math.max(...labels.map((l) => textW(trunc(l, 12), fs)));
293
+ return Math.max(1, Math.ceil((maxW + 4) / slot));
294
+ }
295
+ // 预留画布四边边带:标签候选位越出画布即不可放(LabelPlacer 不感知画布尺寸)
296
+ export function reserveEdges(placer, width, height) {
297
+ placer.reserve(-2, -2, width + 4, 2); // 上
298
+ placer.reserve(-2, height, width + 4, 2); // 下
299
+ placer.reserve(-2, -2, 2, height + 4); // 左
300
+ placer.reserve(width, -2, 2, height + 4); // 右
301
+ }
302
+ // 数据点(hollow=空心描边 / filled=实心+白描边),折线/面积系列共用
303
+ export function pushPoints(parts, pts, color, rules) {
304
+ if (rules.points === 'none')
305
+ return;
306
+ for (const [px, py] of pts) {
307
+ const attrs = rules.points === 'hollow'
308
+ ? `fill="var(--d-halo)" stroke="${color}" stroke-width="2.5"`
309
+ : `fill="${color}" stroke="var(--d-halo)" stroke-width="3"`;
310
+ parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="${rules.pointR}" ${attrs}/>`);
311
+ }
312
+ }
313
+ // 全有或全无的柱内数值标注:入柱(字号可缩到 7px)→ 回退柱顶/柱右侧 → 整层不标
314
+ export function pushBarLabelsAllOrNothing(parts, items, sharedPlacer, segments = []) {
315
+ const out = [];
316
+ const placer = sharedPlacer ?? new LabelPlacer();
317
+ for (const l of items) {
318
+ // 优先入柱:宽度/高度不够先自动缩字号(下限 7px)
319
+ let fs = l.fs;
320
+ let tw = textW(l.text, fs);
321
+ while (fs > 7 && (l.w < tw + 4 || l.hAvail < fs + 4)) {
322
+ fs -= 0.5;
323
+ tw = textW(l.text, fs);
324
+ }
325
+ if (l.w >= tw + 4 && l.hAvail >= fs + 4) {
326
+ // 柱内 3×3 挪位避开穿过的折线(线保持连续)
327
+ const tyTop = l.yt + 1 + fs;
328
+ const tyMax = Math.max(tyTop, l.yt + (l.center ? l.hAvail - 1 : l.hAvail - 2));
329
+ const xs3 = [0.5, 0.26, 0.74];
330
+ // 纵向自柱顶逐级下移
331
+ const ys = [];
332
+ for (let ty = tyTop; ty <= tyMax && ys.length < 3; ty += fs + 3)
333
+ ys.push(ty);
334
+ if (ys.length === 0)
335
+ ys.push(tyTop);
336
+ let placed = false;
337
+ for (const ty of ys) {
338
+ for (const xf of xs3) {
339
+ const cx = l.x + l.w * xf;
340
+ const bx = cx - tw / 2 - 1;
341
+ if (segments.some(([sx1, sy1, sx2, sy2]) => segRectIntersect(sx1, sy1, sx2, sy2, bx - 1, ty - fs - 1, tw + 2, fs + 2)))
342
+ continue;
343
+ if (!placer.fits(bx, ty - fs, tw + 2, fs + 2))
344
+ continue;
345
+ const halo = l.haloColor ? `paint-order="stroke" stroke="${l.haloColor}" stroke-width="3" stroke-linejoin="round" ` : '';
346
+ out.push(`<text x="${r2(cx)}" y="${r2(ty)}" text-anchor="middle" font-size="${r2(fs)}" ${l.peak ? 'font-weight="600" ' : ''}fill="${l.fill}" ${halo}style="${TAB}">${l.text}</text>`);
347
+ placed = true;
348
+ break;
349
+ }
350
+ if (placed)
351
+ break;
352
+ }
353
+ if (placed)
354
+ continue;
355
+ // 柱内挪不开 → 交给下面的回退
356
+ }
357
+ // "只准柱内"(分组柱):放不下整层不标,避免柱顶堆出一列数字
358
+ if (l.insideOnly)
359
+ return false;
360
+ // 回退位按原字号渲染,宽度须按原字号重算
361
+ const fTw = textW(l.text, l.fs);
362
+ if (l.side) {
363
+ // 柱右侧回退:纵向多档尝试,避折线与其他标签
364
+ const baseTy = l.yt + Math.max(l.hAvail / 2, l.fs * 0.36);
365
+ const bx = l.x + l.w + 4;
366
+ const step = l.fs + 3;
367
+ let ok = false;
368
+ for (const ty of [baseTy, baseTy - step, baseTy + step, baseTy - 2 * step, baseTy + 2 * step]) {
369
+ if (segments.some(([sx1, sy1, sx2, sy2]) => segRectIntersect(sx1, sy1, sx2, sy2, bx - 1, ty - l.fs - 1, fTw + 2, l.fs + 2)))
370
+ continue;
371
+ if (!placer.fits(bx, ty - l.fs, fTw + 2, l.fs + 2))
372
+ continue;
373
+ out.push(`<text x="${r2(bx)}" y="${r2(ty)}" text-anchor="start" font-size="${l.fs}" ${l.peak ? 'font-weight="600" ' : ''}fill="${l.fallFill ?? 'var(--d-ink)'}" ${HALO} style="${TAB}">${l.text}</text>`);
374
+ ok = true;
375
+ break;
376
+ }
377
+ if (!ok)
378
+ return false;
379
+ }
380
+ else {
381
+ // 矮柱/窄柱回退:收拢到组中线(fx)上方按 row 堆叠
382
+ const cx = l.fx ?? l.x + l.w / 2;
383
+ const ty = (l.fyt ?? l.yt) - 6 - (l.row ?? 0) * (l.fs + 4);
384
+ const bx = cx - fTw / 2 - 1;
385
+ if (!placer.fits(bx, ty - l.fs, fTw + 2, l.fs + 2))
386
+ return false;
387
+ out.push(`<text x="${r2(cx)}" y="${r2(ty)}" text-anchor="middle" font-size="${l.fs}" ${l.peak ? 'font-weight="600" ' : ''}fill="var(--d-ink)" paint-order="stroke" stroke="var(--d-halo)" stroke-width="3" stroke-linejoin="round" style="${TAB}">${l.text}</text>`);
388
+ }
389
+ }
390
+ parts.push(...out);
391
+ return true;
392
+ }
393
+ // 全有或全无的线点标签:两位置尝试,任一失败整层放弃
394
+ export function pushLineLabelsAllOrNothing(parts, placer, items, segments = []) {
395
+ const out = [];
396
+ for (const l of items) {
397
+ const probe = [];
398
+ pushLineLabel(probe, placer, l.px, l.py, l.text, l.isPeak, segments);
399
+ if (probe.length === 0)
400
+ return false;
401
+ out.push(...probe);
402
+ }
403
+ parts.push(...out);
404
+ return true;
405
+ }
406
+ // 线段与矩形是否相交(Liang-Barsky 参数裁剪)
407
+ export function segRectIntersect(x1, y1, x2, y2, rx, ry, rw, rh) {
408
+ let t0 = 0;
409
+ let t1 = 1;
410
+ const dx = x2 - x1;
411
+ const dy = y2 - y1;
412
+ const p = [-dx, dx, -dy, dy];
413
+ const q = [x1 - rx, rx + rw - x1, y1 - ry, ry + rh - y1];
414
+ for (let i = 0; i < 4; i++) {
415
+ if (p[i] === 0) {
416
+ if (q[i] < 0)
417
+ return false;
418
+ }
419
+ else {
420
+ const r = q[i] / p[i];
421
+ if (p[i] < 0) {
422
+ if (r > t1)
423
+ return false;
424
+ if (r > t0)
425
+ t0 = r;
426
+ }
427
+ else {
428
+ if (r < t0)
429
+ return false;
430
+ if (r < t1)
431
+ t1 = r;
432
+ }
433
+ }
434
+ }
435
+ return true;
436
+ }
437
+ /** 由点序列构造折线障碍段 */
438
+ export function toSegments(pts) {
439
+ const out = [];
440
+ for (let i = 1; i < pts.length; i++)
441
+ out.push([pts[i - 1][0], pts[i - 1][1], pts[i][0], pts[i][1]]);
442
+ return out;
443
+ }
444
+ // 线点数值标签:近位(上下左右)→ 远位,共 8 个候选;还需避开折线本身
445
+ export function pushLineLabel(parts, placer, px, py, text, isPeak, segments = []) {
446
+ const fs = isPeak ? 13 : 11;
447
+ const w = textW(text, fs);
448
+ const candidates = [
449
+ { x: px, y: py - 12, anchor: 'middle' },
450
+ { x: px, y: py + 16, anchor: 'middle' },
451
+ { x: px + 10, y: py + 4, anchor: 'start' },
452
+ { x: px - 10, y: py + 4, anchor: 'end' },
453
+ { x: px, y: py - 30, anchor: 'middle' },
454
+ { x: px, y: py + 34, anchor: 'middle' },
455
+ { x: px + 26, y: py + 4, anchor: 'start' },
456
+ { x: px - 26, y: py + 4, anchor: 'end' },
457
+ ];
458
+ // 排除与该点相连的线段(必然贴边)
459
+ const relevant = segments.filter(([x1, y1, x2, y2]) => Math.hypot(x1 - px, y1 - py) > 0.6 && Math.hypot(x2 - px, y2 - py) > 0.6);
460
+ for (const c of candidates) {
461
+ const bx = c.anchor === 'middle' ? c.x - w / 2 : c.anchor === 'start' ? c.x : c.x - w;
462
+ const by = c.y - fs;
463
+ // 折线横穿标签框 → 换位置
464
+ if (relevant.some(([sx1, sy1, sx2, sy2]) => segRectIntersect(sx1, sy1, sx2, sy2, bx - 1, by - 1, w + 2, fs + 2)))
465
+ continue;
466
+ if (placer.fits(bx, by, w, fs)) {
467
+ parts.push(`<text x="${r2(c.x)}" y="${r2(c.y)}" text-anchor="${c.anchor}" font-size="${fs}" ${isPeak ? 'font-weight="600" ' : ''}fill="${isPeak ? 'var(--d-ink)' : 'var(--d-text)'}" ${HALO} style="${TAB}">${text}</text>`);
468
+ return;
469
+ }
470
+ }
471
+ }
@@ -0,0 +1,34 @@
1
+ export declare class ApiError extends Error {
2
+ status: number;
3
+ constructor(status: number, message: string);
4
+ }
5
+ export interface Datum {
6
+ label: string;
7
+ value: number;
8
+ }
9
+ export interface ChartSpec {
10
+ title?: string;
11
+ subtitle?: string;
12
+ source?: string;
13
+ unit?: string;
14
+ data: Datum[];
15
+ }
16
+ export declare const LIMITS: {
17
+ readonly title: 80;
18
+ readonly subtitle: 96;
19
+ readonly source: 96;
20
+ readonly unit: 16;
21
+ readonly label: 64;
22
+ readonly maxPie: 100;
23
+ readonly maxBar: 30;
24
+ readonly maxLine: 60;
25
+ readonly maxRadar: 12;
26
+ readonly maxSeries: 6;
27
+ readonly seriesName: 24;
28
+ readonly maxScatter: 200;
29
+ };
30
+ export declare const MAX_BY_KIND: Record<string, number>;
31
+ export declare function parseChartSpec(raw: string | null, kind: 'pie' | 'bar' | 'hbar' | 'line' | 'area' | 'radar'): ChartSpec;
32
+ export declare function specFromParams(params: URLSearchParams, kind: 'pie' | 'bar' | 'hbar' | 'line' | 'area' | 'radar'): string | null;
33
+ export declare function flatList(params: URLSearchParams, key: string): string[];
34
+ export declare function clip(s: string, n: number): string;
@@ -0,0 +1,159 @@
1
+ // 公共解析基础:ApiError、LIMITS、单系列 ChartSpec(扁平参数/JSON)、统一入口 parseInput。
2
+ // 各图表专属解析器在本目录独立文件;新增图表 = 新增 specs/xxx.ts + render/xxx.ts。
3
+ export class ApiError extends Error {
4
+ status;
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.status = status;
8
+ }
9
+ }
10
+ export const LIMITS = {
11
+ title: 80,
12
+ subtitle: 96,
13
+ source: 96,
14
+ unit: 16,
15
+ label: 64,
16
+ maxPie: 100,
17
+ maxBar: 30,
18
+ maxLine: 60,
19
+ maxRadar: 12,
20
+ maxSeries: 6,
21
+ seriesName: 24,
22
+ maxScatter: 200,
23
+ };
24
+ export const MAX_BY_KIND = {
25
+ pie: LIMITS.maxPie,
26
+ bar: LIMITS.maxBar,
27
+ hbar: LIMITS.maxBar,
28
+ line: LIMITS.maxLine,
29
+ area: LIMITS.maxLine,
30
+ radar: LIMITS.maxRadar,
31
+ };
32
+ const EXAMPLE = encodeURIComponent(JSON.stringify({ title: 'Demo', data: [{ label: 'A', value: 1 }, { label: 'B', value: 2 }] }));
33
+ const EXAMPLE_FLAT = 'title=Demo&labels=A,B&values=1,2';
34
+ export function parseChartSpec(raw, kind) {
35
+ if (raw === null || raw === '') {
36
+ throw new ApiError(400, `Missing data. Use flat params: ?${EXAMPLE_FLAT} — or JSON: ?d=${EXAMPLE}`);
37
+ }
38
+ let obj;
39
+ try {
40
+ obj = JSON.parse(raw);
41
+ }
42
+ catch {
43
+ throw new ApiError(400, `"d" is not valid JSON (remember to URL-encode it). Example: ?d=${EXAMPLE}`);
44
+ }
45
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
46
+ throw new ApiError(400, `"d" must be a JSON object like {"title":"...","data":[{"label":"A","value":1}]}`);
47
+ }
48
+ const o = obj;
49
+ let title;
50
+ if (o.title !== undefined) {
51
+ if (typeof o.title !== 'string')
52
+ throw new ApiError(400, `"title" must be a string, got ${jsonType(o.title)}`);
53
+ title = clip(o.title, LIMITS.title);
54
+ }
55
+ let unit;
56
+ if (o.unit !== undefined) {
57
+ if (typeof o.unit !== 'string')
58
+ throw new ApiError(400, `"unit" must be a string, got ${jsonType(o.unit)}`);
59
+ unit = clip(o.unit, LIMITS.unit);
60
+ }
61
+ let subtitle;
62
+ if (o.subtitle !== undefined) {
63
+ if (typeof o.subtitle !== 'string')
64
+ throw new ApiError(400, `"subtitle" must be a string, got ${jsonType(o.subtitle)}`);
65
+ subtitle = clip(o.subtitle, LIMITS.subtitle);
66
+ }
67
+ let source;
68
+ if (o.source !== undefined) {
69
+ if (typeof o.source !== 'string')
70
+ throw new ApiError(400, `"source" must be a string, got ${jsonType(o.source)}`);
71
+ source = clip(o.source, LIMITS.source);
72
+ }
73
+ if (!Array.isArray(o.data) || o.data.length === 0) {
74
+ throw new ApiError(400, `"data" must be a non-empty array of {"label":string,"value":number}`);
75
+ }
76
+ const max = MAX_BY_KIND[kind];
77
+ if (o.data.length > max) {
78
+ throw new ApiError(400, `"data" has ${o.data.length} points; ${kind} chart supports at most ${max}. Aggregate the rest into fewer points.`);
79
+ }
80
+ const data = o.data.map((it, i) => {
81
+ if (typeof it !== 'object' || it === null || Array.isArray(it)) {
82
+ throw new ApiError(400, `data[${i}] must be an object with "label" and "value"`);
83
+ }
84
+ const d = it;
85
+ let label;
86
+ if (typeof d.label === 'string')
87
+ label = clip(d.label, LIMITS.label);
88
+ else if (typeof d.label === 'number' && Number.isFinite(d.label))
89
+ label = String(d.label);
90
+ else
91
+ throw new ApiError(400, `data[${i}].label must be a string, got ${jsonType(d.label)}`);
92
+ if (typeof d.value !== 'number' || !Number.isFinite(d.value)) {
93
+ throw new ApiError(400, `data[${i}].value must be a number, got ${jsonType(d.value)}`);
94
+ }
95
+ if (d.value < 0) {
96
+ throw new ApiError(400, `data[${i}].value must be >= 0, got ${d.value}`);
97
+ }
98
+ return { label, value: d.value };
99
+ });
100
+ const total = data.reduce((s, d) => s + d.value, 0);
101
+ if (!(total > 0)) {
102
+ throw new ApiError(400, `"data" values must sum to more than 0, got ${total}`);
103
+ }
104
+ return { title, subtitle, source, unit, data };
105
+ }
106
+ // 扁平参数 → JSON 字符串:让 URL 永远可读,无需百分号编码。
107
+ // 支持两种形态:?labels=A,B&values=1,2(逗号)或 ?labels=A&labels=B&values=1&values=2(重复参数,标签含逗号时用)
108
+ export function specFromParams(params, kind) {
109
+ const d = params.get('d');
110
+ if (d !== null && d !== '')
111
+ return d;
112
+ if (!params.has('labels') && !params.has('values'))
113
+ return null;
114
+ const labels = flatList(params, 'labels');
115
+ const values = flatList(params, 'values');
116
+ if (labels.length === 0)
117
+ throw new ApiError(400, `"labels" is empty. Example: ?${EXAMPLE_FLAT}`);
118
+ if (values.length !== labels.length) {
119
+ throw new ApiError(400, `got ${labels.length} labels but ${values.length} values — they must match`);
120
+ }
121
+ const nums = values.map((v, i) => {
122
+ const n = Number(v);
123
+ if (!Number.isFinite(n))
124
+ throw new ApiError(400, `values[${i}] is not a number: ${JSON.stringify(v)}`);
125
+ return n;
126
+ });
127
+ const obj = {
128
+ data: labels.map((label, i) => ({ label, value: nums[i] })),
129
+ };
130
+ const title = params.get('title');
131
+ if (title)
132
+ obj.title = title;
133
+ const subtitle = params.get('subtitle');
134
+ if (subtitle)
135
+ obj.subtitle = subtitle;
136
+ const source = params.get('source');
137
+ if (source)
138
+ obj.source = source;
139
+ const unit = params.get('unit');
140
+ if (unit)
141
+ obj.unit = unit;
142
+ return JSON.stringify(obj);
143
+ }
144
+ export function flatList(params, key) {
145
+ const all = params.getAll(key);
146
+ if (all.length > 1)
147
+ return all; // 重复参数形态
148
+ return all[0] !== undefined && all[0] !== '' ? all[0].split(',') : [];
149
+ }
150
+ function jsonType(v) {
151
+ if (v === null)
152
+ return 'null';
153
+ if (Array.isArray(v))
154
+ return 'an array';
155
+ return typeof v;
156
+ }
157
+ export function clip(s, n) {
158
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
159
+ }
@@ -0,0 +1,15 @@
1
+ export interface ComboSeries {
2
+ name: string;
3
+ values: number[];
4
+ kind: 'bar' | 'line';
5
+ }
6
+ export interface ComboSpec {
7
+ title?: string;
8
+ unit?: string;
9
+ labels: string[];
10
+ series: ComboSeries[];
11
+ /** 柱系列堆叠(而非并排),折线仍叠加在上 */
12
+ stack?: boolean;
13
+ }
14
+ export declare function parseComboSpec(raw: string | null): ComboSpec;
15
+ export declare function comboSpecFromParams(params: URLSearchParams): string | null;