@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,142 @@
1
+ import { TAB, card } from '../theme.js';
2
+ import { esc, fmtNum, niceTicks, r2, textW, topLegend, trunc, svgDoc, titleBlock, yAxisGrid, findPeak, onVar, sVar, pushBarLabelsAllOrNothing, labelStride, LabelPlacer, reserveBands } from './svg.js';
3
+ import { yTickInset, tickColW } from './measure.js';
4
+ export function renderBarStacked(spec, o) {
5
+ let width = o.width;
6
+ let height = o.height;
7
+ const { version, skin } = o;
8
+ const k = spec.series.length;
9
+ const colors = spec.series.map((_, i) => sVar(i % skin.series.length));
10
+ const n = spec.labels.length;
11
+ const totals = spec.labels.map((_, pi) => spec.series.reduce((s, ser) => s + ser.values[pi], 0));
12
+ const gMax = Math.max(...totals);
13
+ // 全局最大段(num=peak 时只标它)
14
+ const [peakS, peakP] = findPeak(spec.series);
15
+ const pad = 24;
16
+ const fixedTop = pad + (spec.title ? 32 : 0) + (spec.unit ? 18 : 0) + 24;
17
+ // 刻度上限:5 档刻度更贴近数据(41842 → 50000,而非 4 档的 60000),减少顶部浪费
18
+ const ticks0 = niceTicks(gMax, 5);
19
+ const yMax0 = ticks0[ticks0.length - 1];
20
+ // 极端量级差(最小组的总量连一行标签都放不下,如 40 倍差)→ 自动切 100% 百分比堆叠:
21
+ // 各组满高、构成清晰,柱顶标总量补回绝对量;无需参数
22
+ const plotH0 = height - pad - 30 - fixedTop;
23
+ const smallestTotal = Math.min(...totals.filter((t) => t > 0));
24
+ const pctMode = o.autoHeight === true && (smallestTotal / yMax0) * plotH0 < 14;
25
+ // 非百分比模式下温和拉高(封顶 1.5×),补一点可读空间但不夸张
26
+ if (!pctMode && o.autoHeight) {
27
+ const groupMaxSeg = spec.labels.map((_, pi) => Math.max(...spec.series.map((s) => s.values[pi])));
28
+ const smallest = Math.min(...groupMaxSeg.filter((v) => v > 0));
29
+ const segPx = (smallest / yMax0) * plotH0;
30
+ if (segPx > 0 && segPx < 10) {
31
+ height = Math.round(height * Math.min(1.5, 10 / segPx));
32
+ }
33
+ }
34
+ // 百分比模式柱顶要标总量,绘图区需下移到图例之下,否则总量与图例文字重叠
35
+ const contentTop = pctMode ? Math.max(fixedTop, pad + 16 + 30) : fixedTop;
36
+ // 百分比模式:各组的段按 pct 布局,轴刻度 0-100%
37
+ const tickVals = pctMode ? [0, 20, 40, 60, 80, 100] : niceTicks(gMax, 5);
38
+ // 左内边距 = max(规范 44, 实测刻度列;百分比模式刻度带 "%" 后缀)
39
+ const left = Math.max(pad + 44, pctMode ? tickColW(tickVals, 12, 8, '%') + 2 : yTickInset({ ticks: tickVals }));
40
+ // 组数少(<5)时宽度贴内容收缩(设计密度 5 组,槽 93.6;下限 320;显式 ?w= 不动)
41
+ if (o.autoWidth && n < 5) {
42
+ const need = left + n * 93.6 + pad;
43
+ if (need < width)
44
+ width = Math.round(Math.max(320, need));
45
+ }
46
+ const right = width - pad;
47
+ const bottom = height - pad - 30;
48
+ const yMax = pctMode ? 100 : tickVals[tickVals.length - 1];
49
+ const scaleOf = (pi, v) => (pctMode ? (v / totals[pi]) * 100 : v);
50
+ const y = (v) => bottom - (v / yMax) * (bottom - contentTop);
51
+ // 显示的百分比:最大余数法取整,且只在"标签可见"的段之间分配余数,
52
+ // 使图中能看到的数字合计恰好 100%(独立四舍五入会出 101%;隐藏小段会让合计 99%)
53
+ const plotHForLabels = bottom - contentTop;
54
+ const pctLabels = spec.labels.map((_, pi) => {
55
+ const exact = spec.series.map((s) => (s.values[pi] / totals[pi]) * 100);
56
+ const visible = exact.map((e) => (e / 100) * plotHForLabels >= 7 + 4);
57
+ const out = exact.map(() => 0);
58
+ let rest = 100;
59
+ for (let si = 0; si < out.length; si++) {
60
+ if (visible[si]) {
61
+ out[si] = Math.floor(exact[si]);
62
+ rest -= out[si];
63
+ }
64
+ }
65
+ const order = exact
66
+ .map((e, i) => ({ i, rem: e - Math.floor(e) }))
67
+ .filter((o) => visible[o.i])
68
+ .sort((a, b) => b.rem - a.rem);
69
+ for (const o of order) {
70
+ if (rest <= 0)
71
+ break;
72
+ out[o.i]++;
73
+ rest--;
74
+ }
75
+ return out;
76
+ });
77
+ const parts = [
78
+ card(width, height),
79
+ topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i] })), width - pad, pad + 16),
80
+ ];
81
+ if (pctMode) {
82
+ for (const t of tickVals) {
83
+ const gy = y(t);
84
+ if (t > 0)
85
+ parts.push(`<line x1="${left}" y1="${r2(gy)}" x2="${right}" y2="${r2(gy)}" stroke="var(--d-grid)" stroke-width="1"/>`);
86
+ parts.push(`<text x="${left - 8}" y="${r2(gy + 4)}" text-anchor="end" font-size="12" fill="var(--d-muted)" style="${TAB}">${t}%</text>`);
87
+ }
88
+ parts.push(`<line x1="${left}" y1="${r2(bottom)}" x2="${right}" y2="${r2(bottom)}" stroke="var(--d-baseline)" stroke-width="1"/>`);
89
+ }
90
+ else {
91
+ yAxisGrid(parts, tickVals, y, left, right, bottom, skin.rules.grid, skin.rules.gridDash);
92
+ }
93
+ const step = (right - left) / n;
94
+ const barW = Math.min(56, Math.max(6, step * 0.55));
95
+ const num = o.valueLabels ?? skin.rules.num;
96
+ const numItems = [];
97
+ const xStride = labelStride(spec.labels, step);
98
+ spec.labels.forEach((label, pi) => {
99
+ const x = left + step * pi + (step - barW) / 2;
100
+ let cursor = bottom;
101
+ spec.series.forEach((s, si) => {
102
+ const v = s.values[pi];
103
+ if (v <= 0)
104
+ return; // 零值段:不画也不标(0 高度段标注是噪音)
105
+ // 百分比模式:按该组占比布局(各组满高,构成清晰)
106
+ const scaled = scaleOf(pi, v);
107
+ const segH = (scaled / yMax) * (bottom - contentTop);
108
+ // 微小段保底可见高度,否则 <1px 的段+白描边会渲染成白片
109
+ const drawH = Math.max(segH, 1.6);
110
+ const yTop = cursor - drawH;
111
+ const isTopSeg = si === k - 1 || spec.series.slice(si + 1).every((ss) => ss.values[pi] === 0);
112
+ const m = isTopSeg ? Math.min(4, barW / 2, drawH) : 0;
113
+ const path = `M${r2(x)} ${r2(cursor)}V${r2(yTop + m)}Q${r2(x)} ${r2(yTop)} ${r2(x + m)} ${r2(yTop)}` +
114
+ `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yTop)} ${r2(x + barW)} ${r2(yTop + m)}V${r2(cursor)}Z`;
115
+ // 分隔白描边按段高自适应:段太矮时描边会盖掉颜色
116
+ const sw = segH >= 6 ? 2 : 0;
117
+ parts.push(`<path d="${path}" fill="${colors[si]}"${sw ? ` stroke="var(--d-card)" stroke-width="${sw}"` : ''}/>`);
118
+ const isPeakSeg = si === peakS && pi === peakP;
119
+ if (num === 'all' || (num === 'peak' && isPeakSeg)) {
120
+ // 数值一律入柱(像 900/1k 那样),字号自适应缩小;
121
+ // 连 7px 都装不下的微小段不标——悬浮数字比缺一个数更难看
122
+ const text = pctMode ? `${pctLabels[pi][si]}%` : fmtNum(v);
123
+ const fs = isPeakSeg ? 12 : 11;
124
+ const minFs = 7;
125
+ if (barW >= textW(text, minFs) + 4 && segH >= minFs + 4) {
126
+ numItems.push({ x, yt: yTop, w: barW, hAvail: segH, text, fs, peak: isPeakSeg, fill: onVar(si % skin.series.length), center: true, haloColor: colors[si] });
127
+ }
128
+ }
129
+ cursor = yTop;
130
+ });
131
+ if (pi % xStride === 0)
132
+ parts.push(`<text x="${r2(x + barW / 2)}" y="${r2(bottom + 20)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(trunc(label, 12))}</text>`);
133
+ // 百分比模式:柱顶标该组总量(补回绝对量)
134
+ if (pctMode) {
135
+ parts.push(`<text x="${r2(x + barW / 2)}" y="${r2(contentTop - 8)}" text-anchor="middle" font-size="11" font-weight="500" fill="var(--d-ink)" paint-order="stroke" stroke="var(--d-halo)" stroke-width="3" stroke-linejoin="round" style="${TAB}">${fmtNum(totals[pi])}</text>`);
136
+ }
137
+ });
138
+ const placer = new LabelPlacer();
139
+ reserveBands(placer, left, right, contentTop, bottom, bottom + 20, spec.series, width - pad, pad + 16);
140
+ pushBarLabelsAllOrNothing(parts, numItems, placer);
141
+ return svgDoc(width, height, 'bar', version, spec.title ?? 'stacked bar chart', spec, skin, titleBlock(spec.title) + parts.join(''));
142
+ }
@@ -0,0 +1,3 @@
1
+ import type { ChartSpec } from '../specs/index.js';
2
+ import { type RenderOpts } from './svg.js';
3
+ export declare function renderBar(spec: ChartSpec, o: RenderOpts): string;
@@ -0,0 +1,74 @@
1
+ import { card } from '../theme.js';
2
+ import { esc, fmtNum, niceTicks, r2, trunc, svgDoc, titleBlock, yAxisGrid, pushBarLabelsAllOrNothing, labelStride, textW, LabelPlacer, reserveBands } from './svg.js';
3
+ import { yTickInset } from './measure.js';
4
+ export function renderBar(spec, o) {
5
+ const { height, version, skin } = o;
6
+ let width = o.width;
7
+ const values = spec.data.map((d) => d.value);
8
+ const max = Math.max(...values);
9
+ const peakIdx = values.indexOf(max);
10
+ const pad = 24;
11
+ const contentTop = pad + (spec.title ? 32 : 0) + (spec.unit ? 18 : 0) + 20;
12
+ // 柱宽不足以容纳数值标签时自动加宽画布(封顶 2.5×),让数字留在柱内
13
+ const nBars = spec.data.length;
14
+ // 按缩字号下限(7px)估标签宽:只有"扩了真能装进柱"才扩宽(封顶 1.5×),
15
+ // 装不下(如 corner 柱宽封顶 22 < 标签宽)就保持默认宽度、数字走回退——白扩不加宽
16
+ const maxLabelW = Math.max(...spec.data.map((d) => textW(fmtNum(d.value), 7)));
17
+ const needSlot = (maxLabelW + 10) / 0.55;
18
+ if (o.autoWidth && nBars > 0 && (width - 68 - pad) / nBars < needSlot) {
19
+ const w2 = Math.round(Math.min(width * 1.5, 68 + pad + needSlot * nBars));
20
+ const barW2 = Math.min(56, ((w2 - 68 - pad) / nBars) * 0.55);
21
+ if (barW2 >= maxLabelW + 4)
22
+ width = w2;
23
+ }
24
+ const ticks = niceTicks(max, 4);
25
+ // 左内边距 = max(规范 44, 实测刻度列):长刻度/窄画布不裁字
26
+ const left = Math.max(pad + 44, yTickInset({ ticks }));
27
+ // 组数少(<5)时宽度贴内容收缩(设计密度 5 组,槽 93.6;下限 320;显式 ?w= 不动)
28
+ if (o.autoWidth && nBars < 5) {
29
+ const need = left + nBars * 93.6 + pad;
30
+ if (need < width)
31
+ width = Math.round(Math.max(320, need));
32
+ }
33
+ const right = width - pad;
34
+ const bottom = height - pad - 30;
35
+ const yMax = ticks[ticks.length - 1];
36
+ const y = (v) => bottom - (v / yMax) * (bottom - contentTop);
37
+ const parts = [
38
+ card(width, height),
39
+ // 柱体渐变(顶部亮 → 底部深)
40
+ `<defs><linearGradient id="dg-bar" x1="0" y1="0" x2="0" y2="1">` +
41
+ `<stop offset="0" stop-color="var(--d-ramp-a)"/><stop offset="1" stop-color="var(--d-ramp-b)"/></linearGradient></defs>`,
42
+ ];
43
+ // 网格线 + 刻度 + 基线
44
+ yAxisGrid(parts, ticks, y, left, right, bottom, skin.rules.grid, skin.rules.gridDash);
45
+ // 柱体:墨色、仅顶角圆角 4px
46
+ const n = spec.data.length;
47
+ const step = (right - left) / n;
48
+ const barW = Math.min(56, Math.max(6, step * 0.55));
49
+ const num = o.valueLabels ?? skin.rules.num;
50
+ const labelColor = 'var(--d-on-s1)'; // 渐变顶端即标签所在处的底色
51
+ const numItems = [];
52
+ const xStride = labelStride(spec.data.map((d) => d.label), step);
53
+ spec.data.forEach((d, i) => {
54
+ const x = left + step * i + (step - barW) / 2;
55
+ const yt = y(d.value);
56
+ const m = Math.min(4, barW / 2, bottom - yt);
57
+ const path = `M${r2(x)} ${r2(bottom)}V${r2(yt + m)}Q${r2(x)} ${r2(yt)} ${r2(x + m)} ${r2(yt)}` +
58
+ `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yt)} ${r2(x + barW)} ${r2(yt + m)}V${r2(bottom)}Z`;
59
+ parts.push(`<path d="${path}" fill="url(#dg-bar)"/>`);
60
+ const isPeak = i === peakIdx;
61
+ // 零值不标:没有柱子的"0"是噪音(标注克制原则)
62
+ if (d.value > 0 && (num === 'all' || (num === 'peak' && isPeak))) {
63
+ // 数值入柱;矮柱(极小值)回退柱顶上方;过密相撞才整层不标
64
+ numItems.push({ x, yt, w: barW, hAvail: bottom - yt, text: fmtNum(d.value), fs: isPeak ? 13 : 11, peak: isPeak, fill: labelColor, haloColor: 'var(--d-s1)' });
65
+ }
66
+ if (i % xStride === 0)
67
+ parts.push(`<text x="${r2(x + barW / 2)}" y="${r2(bottom + 20)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(trunc(d.label, 12))}</text>`);
68
+ });
69
+ const placer = new LabelPlacer();
70
+ // 预留 Y 刻度带与 X 标签带:数值标签不得压刻度
71
+ reserveBands(placer, left, right, contentTop, bottom, bottom + 20, [], 0, 0);
72
+ pushBarLabelsAllOrNothing(parts, numItems, placer);
73
+ return svgDoc(width, height, 'bar', version, spec.title ?? 'bar chart', spec, skin, titleBlock(spec.title) + parts.join(''));
74
+ }
@@ -0,0 +1,3 @@
1
+ import type { ComboSpec } from '../specs/index.js';
2
+ import { type RenderOpts } from './svg.js';
3
+ export declare function renderCombo(spec: ComboSpec, o: RenderOpts): string;
@@ -0,0 +1,256 @@
1
+ import { TAB, card } from '../theme.js';
2
+ import { esc, fmtNum, niceTicks, r2, topLegend, trunc, textW, LabelPlacer, pushLineLabel, pushBarLabelsAllOrNothing, smoothPath, svgDoc, titleBlock, findPeak, onVar, sVar, labelStride, reserveBands, reserveEdges, toSegments } from './svg.js';
3
+ import { yTickInset, tickColW } from './measure.js';
4
+ export function renderCombo(spec, o) {
5
+ if (o.skin.rules.comboMode === 'evil')
6
+ return renderComboEvil(spec, o);
7
+ const { height, version, skin } = o;
8
+ let width = o.width;
9
+ const n = spec.labels.length;
10
+ const colors = spec.series.map((_, i) => sVar(i % skin.series.length));
11
+ const bars = spec.series.filter((s) => s.kind === 'bar');
12
+ const lines = spec.series.filter((s) => s.kind === 'line');
13
+ const gMax = Math.max(...spec.series.flatMap((s) => s.values));
14
+ const [peakS, peakP] = findPeak(spec.series);
15
+ const pad = 24;
16
+ // 双轴:量级差 >5 倍时线系列走右侧独立 y 轴
17
+ const stacked = spec.stack === true && bars.length > 0;
18
+ const barTotals = stacked ? spec.labels.map((_, pi) => bars.reduce((s, b) => s + b.values[pi], 0)) : [];
19
+ const barMax = stacked ? Math.max(...barTotals) : bars.length ? Math.max(...bars.flatMap((s) => s.values)) : 0;
20
+ const lineMax = lines.length ? Math.max(...lines.flatMap((s) => s.values)) : 0;
21
+ const dual = bars.length > 0 && lines.length > 0 && (lineMax * 5 < barMax || barMax * 5 < lineMax);
22
+ // 双轴时绘图区下移,避免图例压顶部刻度
23
+ const contentTop = pad + (spec.title ? 32 : 0) + (spec.unit ? 18 : 0) + 24 + (dual ? 16 : 0);
24
+ const ticks = niceTicks(dual ? barMax : gMax, stacked ? 5 : 4); // 双轴时左轴只管柱;堆叠用 5 档收紧上限
25
+ const lineTicks = dual ? niceTicks(lineMax, 4) : ticks;
26
+ // 组数少(<5)时宽度贴内容收缩(下限 320)
27
+ if (o.autoWidth && n < 5) {
28
+ const leftIns = Math.max(pad + 48, yTickInset({ ticks }));
29
+ const rightIns = dual ? pad + Math.max(36, tickColW(lineTicks, 12, 8) + 4) : pad;
30
+ const need = leftIns + rightIns + n * 93.6;
31
+ if (need < width)
32
+ width = Math.round(Math.max(320, need));
33
+ }
34
+ // 左列 = max(规范 48, 实测刻度);双轴右带 = max(规范 36, 实测右轴刻度列)
35
+ const left = Math.max(pad + 48, yTickInset({ ticks }));
36
+ const right = dual ? width - pad - Math.max(36, tickColW(lineTicks, 12, 8) + 4) : width - pad;
37
+ const bottom = height - pad - 30;
38
+ const yMax = ticks[ticks.length - 1];
39
+ const y = (v) => bottom - (v / yMax) * (bottom - contentTop);
40
+ const lineYMax = lineTicks[lineTicks.length - 1];
41
+ const yLine = (v) => bottom - (v / lineYMax) * (bottom - contentTop);
42
+ const parts = [
43
+ card(width, height),
44
+ topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i] })), width - pad, pad + 16),
45
+ ];
46
+ for (const t of ticks) {
47
+ const gy = r2(y(t));
48
+ if (t > 0)
49
+ parts.push(`<line x1="${left}" y1="${gy}" x2="${right}" y2="${gy}" stroke="var(--d-grid)" stroke-width="1"/>`);
50
+ parts.push(`<text x="${left - 8}" y="${r2(y(t) + 4)}" text-anchor="end" font-size="12" fill="var(--d-muted)" style="${TAB}">${fmtNum(t)}</text>`);
51
+ }
52
+ if (dual) {
53
+ // 右轴刻度(线系列),颜色取首个线系列以示归属
54
+ const lineColor = colors[spec.series.findIndex((s) => s.kind === 'line')];
55
+ for (const t of lineTicks) {
56
+ parts.push(`<text x="${right + 8}" y="${r2(yLine(t) + 4)}" font-size="12" fill="${lineColor}" style="${TAB}">${fmtNum(t)}</text>`);
57
+ }
58
+ }
59
+ parts.push(`<line x1="${left}" y1="${bottom}" x2="${right}" y2="${bottom}" stroke="var(--d-baseline)" stroke-width="1"/>`);
60
+ const step = (right - left) / n;
61
+ const num = o.valueLabels ?? skin.rules.num;
62
+ // 线穿过各组中心;先画线再画柱,线始终连续
63
+ const cx = (pi) => left + step * pi + step / 2;
64
+ const lineLabels = [];
65
+ const lineSvg = [];
66
+ const lineSegs = [];
67
+ lines.forEach((s) => {
68
+ const gIdx = spec.series.indexOf(s);
69
+ const pts = s.values.map((v, pi) => [cx(pi), (dual ? yLine : y)(v)]);
70
+ lineSegs.push(...toSegments(pts));
71
+ lineSvg.push(`<path d="${smoothPath(pts)}" fill="none" stroke="${colors[gIdx]}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>`);
72
+ pts.forEach(([lx, ly], pi) => {
73
+ lineSvg.push(`<circle cx="${r2(lx)}" cy="${r2(ly)}" r="2.5" fill="${colors[gIdx]}" stroke="#ffffff" stroke-width="1.5"/>`);
74
+ const isPeak = gIdx === peakS && pi === peakP;
75
+ if (num === 'all' || (num === 'peak' && isPeak)) {
76
+ lineLabels.push({ px: lx, py: ly, text: fmtNum(s.values[pi]), isPeak });
77
+ }
78
+ });
79
+ });
80
+ // 柱系列:stack 时上下堆叠(段内标值,微小段不标),否则并排分组
81
+ const k = bars.length;
82
+ const placer = new LabelPlacer();
83
+ const barLabels = [];
84
+ const withinStack = [];
85
+ const pendingBarLabels = []; // 折线之后才输出的柱内标签
86
+ if (k > 0) {
87
+ const barW = stacked ? Math.min(56, Math.max(6, step * 0.55)) : Math.max(4, Math.min(40, (step * 0.66) / k));
88
+ // 回退位:组中线 + 组内最高柱顶(同组标签在组上方单列堆叠)
89
+ const groupTop = spec.labels.map((_, pi) => Math.min(...bars.map((s) => y(s.values[pi]))));
90
+ const cursor = spec.labels.map(() => bottom);
91
+ bars.forEach((s, bi) => {
92
+ const gIdx = spec.series.indexOf(s);
93
+ s.values.forEach((v, pi) => {
94
+ if (stacked && v <= 0)
95
+ return;
96
+ const isPeak = gIdx === peakS && pi === peakP;
97
+ if (stacked) {
98
+ const x = left + step * pi + (step - barW) / 2;
99
+ const segH = (v / yMax) * (bottom - contentTop);
100
+ const drawH = Math.max(segH, 1.6);
101
+ const yTop = cursor[pi] - drawH;
102
+ cursor[pi] = yTop;
103
+ const isTopSeg = bi === k - 1 || bars.slice(bi + 1).every((ss) => ss.values[pi] === 0);
104
+ const m = isTopSeg ? Math.min(4, barW / 2, drawH) : 0;
105
+ // 细段描边会吃掉颜色,够高才画
106
+ const sw = segH >= 12 ? 2 : 0;
107
+ parts.push(`<path d="M${r2(x)} ${r2(yTop + drawH)}V${r2(yTop + m)}Q${r2(x)} ${r2(yTop)} ${r2(x + m)} ${r2(yTop)}` +
108
+ `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yTop)} ${r2(x + barW)} ${r2(yTop + m)}V${r2(yTop + drawH)}Z" fill="${colors[gIdx]}"${sw ? ` stroke="var(--d-card)" stroke-width="${sw}"` : ''}/>`);
109
+ // 堆叠段一律入柱,微小段不标
110
+ if (num === 'all' || (num === 'peak' && isPeak)) {
111
+ const text = fmtNum(v);
112
+ if (barW >= textW(text, 7) + 4 && segH >= 7 + 4) {
113
+ withinStack.push({ x, yt: yTop, w: barW, hAvail: segH, text, fs: isPeak ? 12 : 11, peak: isPeak, fill: onVar(gIdx % skin.series.length), center: true, haloColor: colors[gIdx] });
114
+ }
115
+ }
116
+ }
117
+ else {
118
+ const groupX = left + step * pi + step / 2 - (barW * k) / 2;
119
+ const x = groupX + bi * barW;
120
+ const yt = y(v);
121
+ const m = Math.min(3, barW / 2, bottom - yt);
122
+ parts.push(`<path d="M${r2(x)} ${r2(bottom)}V${r2(yt + m)}Q${r2(x)} ${r2(yt)} ${r2(x + m)} ${r2(yt)}` +
123
+ `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yt)} ${r2(x + barW)} ${r2(yt + m)}V${r2(bottom)}Z" fill="${colors[gIdx]}"/>`);
124
+ // 零值不标(标注克制原则:零高柱上飘"0"是噪音)
125
+ if (v > 0 && (num === 'all' || (num === 'peak' && isPeak))) {
126
+ barLabels.push({ x, yt, v, color: colors[gIdx], isPeak, barW, row: bi, fx: left + step * pi + step / 2, fyt: groupTop[pi] });
127
+ }
128
+ }
129
+ });
130
+ });
131
+ }
132
+ parts.push(...lineSvg); // 折线在柱之上:始终连续、形状完整
133
+ // 堆叠柱内标签:规划(占用 placer 供线标签避让),输出延后到折线之后
134
+ if (stacked && withinStack.length > 0) {
135
+ reserveBands(placer, left, right, contentTop, bottom, null, spec.series, width - pad, pad + 16);
136
+ // 折线始终在上且连续;堆叠柱内标签靠同色描边遮线,不传 lineSegs(传了会整层放弃)
137
+ pushBarLabelsAllOrNothing(pendingBarLabels, withinStack, placer);
138
+ }
139
+ // 数值标注:全有或全无——任一标签放不下(回退位也相撞)则整层不标,
140
+ // 避免"有些标了有些没标"(2026-09-24 用户反馈);矮柱回退柱顶上方。
141
+ // 顺序:柱标签先放(位置受约束),线标签四候选位弹性后放
142
+ if (!stacked) {
143
+ // 分组路径同样要预留 Y 刻度带/X 标签带/图例带(此前只有堆叠分支预留,
144
+ // 分组密集时柱标签回退位可压图例,线标签峰值位可撞右轴刻度)
145
+ reserveBands(placer, left, right, contentTop, bottom, bottom + 20, spec.series, width - pad, pad + 16);
146
+ if (dual)
147
+ placer.reserve(right + 2, contentTop - 10, Math.max(width - pad - right - 2, 1), bottom - contentTop + 20); // 双轴右刻度带
148
+ reserveEdges(placer, width, height);
149
+ }
150
+ if (num !== 'none' && (barLabels.length > 0 || lineLabels.length > 0)) {
151
+ const out = [];
152
+ let allPlaced = true;
153
+ if (barLabels.length > 0) {
154
+ const barOut = [];
155
+ const ok = pushBarLabelsAllOrNothing(barOut, barLabels.map((l) => ({ x: l.x, yt: l.yt, w: l.barW, hAvail: bottom - l.yt, text: fmtNum(l.v), fs: l.isPeak ? 12 : 10.5, peak: l.isPeak, fill: onVar(0), row: l.row, fx: l.fx, fyt: l.fyt, insideOnly: true })), // 只进柱:放不下整层不标(同 bar-grouped)
156
+ placer, lineSegs);
157
+ if (!ok)
158
+ allPlaced = false;
159
+ else
160
+ out.push(...barOut);
161
+ }
162
+ if (allPlaced) {
163
+ const sorted = [...lineLabels].sort((a, b) => Number(b.isPeak) - Number(a.isPeak));
164
+ for (const l of sorted) {
165
+ const probe = [];
166
+ pushLineLabel(probe, placer, l.px, l.py, l.text, l.isPeak, lineSegs);
167
+ if (probe.length === 0) {
168
+ allPlaced = false;
169
+ break;
170
+ }
171
+ out.push(...probe); // 带引线时是"引线+文字"两个元素
172
+ }
173
+ }
174
+ if (allPlaced)
175
+ parts.push(...out);
176
+ }
177
+ parts.push(...pendingBarLabels); // 堆叠柱内标签(规划时已横向避开折线)
178
+ // 类别标签
179
+ const xStride = labelStride(spec.labels, step);
180
+ spec.labels.forEach((l, pi) => {
181
+ if (pi % xStride === 0)
182
+ parts.push(`<text x="${r2(cx(pi))}" y="${r2(bottom + 20)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(trunc(l, 12))}</text>`);
183
+ });
184
+ return svgDoc(width, height, 'combo', version, spec.title ?? 'combo chart', spec, skin, titleBlock(spec.title) + parts.join(''));
185
+ }
186
+ // 混合图 1 · Evil 柱线组合(规范 combo-1,960×500):
187
+ // 紫色圆角柱(0-100)+ 绿色折线(独立量程),虚线网格,右上方块图例,无数值标注
188
+ function renderComboEvil(spec, o) {
189
+ const { width, height, version, skin } = o;
190
+ const n = spec.labels.length;
191
+ const bars = spec.series.filter((s) => s.kind === 'bar');
192
+ const lines = spec.series.filter((s) => s.kind === 'line');
193
+ const barMax = bars.length ? Math.max(...bars.flatMap((s) => s.values)) : 0;
194
+ const lineMax = lines.length ? Math.max(...lines.flatMap((s) => s.values)) : 0;
195
+ const barIdx = spec.series.findIndex((s) => s.kind === 'bar');
196
+ const lineIdx = spec.series.findIndex((s) => s.kind === 'line');
197
+ const barColor = barIdx >= 0 ? sVar(barIdx % skin.series.length) : 'var(--d-s1)';
198
+ const lineColor = lineIdx >= 0 ? sVar(lineIdx % skin.series.length) : 'var(--d-s2)';
199
+ // 几何(规范 960×500 实测):绘图区 72..892 × 118..438,网格 0-100 步 20
200
+ const x0 = Math.round(width * 0.075);
201
+ const y0 = Math.round(height * 0.876);
202
+ const w = width * 0.854;
203
+ const h = height * 0.64;
204
+ const contentTop = y0 - h;
205
+ const slot = w / n;
206
+ const ticks = niceTicks(barMax, 5);
207
+ const barYMax = ticks[ticks.length - 1];
208
+ const yBar = (v) => y0 - (v / barYMax) * h;
209
+ const lineTicks = niceTicks(lineMax, 4);
210
+ const lineYMax = lineTicks[lineTicks.length - 1];
211
+ const yLine = (v) => y0 - (v / lineYMax) * h;
212
+ const parts = [card(width, height, true)];
213
+ for (const t of ticks) {
214
+ const gyN = yBar(t);
215
+ parts.push(`<line x1="${x0}" y1="${r2(gyN)}" x2="${r2(x0 + w)}" y2="${r2(gyN)}" stroke="var(--d-grid)" stroke-dasharray="4 6"/>`);
216
+ parts.push(`<text x="${r2(x0 - 18)}" y="${r2(gyN + 4)}" text-anchor="end" font-size="11" fill="var(--d-muted)" style="${TAB}">${fmtNum(t)}</text>`);
217
+ }
218
+ // 柱:圆角 rx5,槽内缩 12
219
+ const barW = Math.max(4, slot - Math.min(24, width * 0.025));
220
+ bars.forEach((s) => {
221
+ s.values.forEach((v, i) => {
222
+ if (v <= 0)
223
+ return;
224
+ parts.push(`<rect x="${r2(x0 + i * slot + (slot - barW) / 2)}" y="${r2(yBar(v))}" width="${r2(barW)}" height="${r2(y0 - yBar(v))}" rx="5" fill="${barColor}"/>`);
225
+ });
226
+ });
227
+ // 线:独立量程,平滑折线 + r4 实心点
228
+ lines.forEach((s) => {
229
+ const pts = s.values.map((v, i) => [x0 + i * slot + slot / 2, yLine(v)]);
230
+ parts.push(`<path d="${smoothPath(pts)}" fill="none" stroke="${lineColor}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`);
231
+ pts.forEach(([px, py]) => {
232
+ parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="4" fill="${lineColor}"/>`);
233
+ });
234
+ });
235
+ const xStride = labelStride(spec.labels, slot);
236
+ spec.labels.forEach((l, i) => {
237
+ if (i % xStride === 0)
238
+ parts.push(`<text x="${r2(x0 + i * slot + slot / 2)}" y="${r2(height * 0.936)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(trunc(l, 12))}</text>`);
239
+ });
240
+ // 右上图例(方块 11×11 rx3,13px)
241
+ const items = [
242
+ ...(bars.length ? [{ name: bars[0].name, color: barColor }] : []),
243
+ ...(lines.length ? [{ name: lines[0].name, color: lineColor }] : []),
244
+ ];
245
+ let lx = x0 + w;
246
+ const legendY = Math.round(height * 0.116);
247
+ for (let i = items.length - 1; i >= 0; i--) {
248
+ const it = items[i];
249
+ const tw = textW(it.name, 13);
250
+ parts.push(`<text x="${r2(lx)}" y="${r2(legendY)}" text-anchor="end" font-size="13" fill="var(--d-muted)">${esc(it.name)}</text>`);
251
+ lx -= tw + 16;
252
+ parts.push(`<rect x="${r2(lx)}" y="${r2(legendY - 9)}" width="11" height="11" rx="3" fill="${it.color}"/>`);
253
+ lx -= 27;
254
+ }
255
+ return svgDoc(width, height, 'combo', version, spec.title ?? 'combo chart', spec, skin, parts.join(''));
256
+ }
@@ -0,0 +1,3 @@
1
+ import type { RenderOpts } from './svg.js';
2
+ import type { StoredChart } from '../store.js';
3
+ export declare function renderStored(doc: StoredChart, o: RenderOpts): string;
@@ -0,0 +1,69 @@
1
+ // 模板分发:ChartTemplate(+ChartInput/存档 spec)→ 渲染器。短链与 create 共用。
2
+ import { ApiError, parseChartSpec, parseSeriesSpec, parseGaugeSpec, parseScatterSpec, parseComboSpec, looksMultiSeries } from '../specs/index.js';
3
+ import { renderPie } from './pie.js';
4
+ import { renderBar } from './bar.js';
5
+ import { renderBarGrid } from './bar-grid.js';
6
+ import { renderBarMulti } from './bar-grouped.js';
7
+ import { renderBarStacked } from './bar-stacked.js';
8
+ import { renderLine } from './line.js';
9
+ import { renderAreaByMode } from './area.js';
10
+ import { renderLineMulti } from './line-multi.js';
11
+ import { renderRadarByMode } from './radar.js';
12
+ import { renderHbarByMode } from './hbar-spec.js';
13
+ import { renderGauge } from './gauge.js';
14
+ import { renderScatter } from './scatter.js';
15
+ import { renderCombo } from './combo.js';
16
+ import { renderQR, requireQRText, parseColor, QR_DEFAULTS } from './qr.js';
17
+ import { renderSankey } from './sankey.js';
18
+ import { parseSankeySpec } from '../specs/sankey.js';
19
+ function dispatch(template, input, o, stack = false) {
20
+ switch (template) {
21
+ case 'pie':
22
+ if (input.multi)
23
+ throw new ApiError(400, 'multi-series is not supported for pie');
24
+ return renderPie(input.spec, o);
25
+ case 'bar':
26
+ if (o.skin.rules.barMode === 'grid') {
27
+ if (input.multi)
28
+ throw new ApiError(400, 'grid bar (t=grid) takes a single series');
29
+ return renderBarGrid(input.spec, o);
30
+ }
31
+ if (!input.multi)
32
+ return renderBar(input.spec, o);
33
+ return stack ? renderBarStacked(input.spec, o) : renderBarMulti(input.spec, o);
34
+ case 'line':
35
+ return input.multi ? renderLineMulti(input.spec, o) : renderLine(input.spec, o);
36
+ case 'area':
37
+ return renderAreaByMode(input, o);
38
+ case 'hbar':
39
+ return renderHbarByMode(input, o);
40
+ case 'radar':
41
+ return renderRadarByMode(input, o);
42
+ default:
43
+ throw new ApiError(400, `template ${template} cannot be rendered here`);
44
+ }
45
+ }
46
+ // 短链存档 → SVG(结构校验后分发)
47
+ export function renderStored(doc, o) {
48
+ if (doc.template === 'qr') {
49
+ // 存档可能早于校验规则改动:渲染前按 create 同一规则复验(文本长度/颜色必为 hex)
50
+ const s = doc.spec;
51
+ const text = requireQRText(typeof s.text === 'string' ? s.text : null);
52
+ const fg = parseColor(typeof s.fg === 'string' ? s.fg : null, QR_DEFAULTS.fg, 'fg');
53
+ const bg = parseColor(typeof s.bg === 'string' ? s.bg : null, QR_DEFAULTS.bg, 'bg');
54
+ return renderQR(text, fg, bg, o.width, o.height, o.version, o.skin);
55
+ }
56
+ const specJson = JSON.stringify(doc.spec);
57
+ if (doc.template === 'gauge')
58
+ return renderGauge(parseGaugeSpec(specJson), o);
59
+ if (doc.template === 'scatter')
60
+ return renderScatter(parseScatterSpec(specJson), o);
61
+ if (doc.template === 'combo')
62
+ return renderCombo(parseComboSpec(specJson), o);
63
+ if (doc.template === 'sankey')
64
+ return renderSankey(parseSankeySpec(specJson), o);
65
+ const input = looksMultiSeries(specJson)
66
+ ? { multi: true, spec: parseSeriesSpec(specJson, doc.template === 'line' || doc.template === 'area' ? 'line' : 'bar') }
67
+ : { multi: false, spec: parseChartSpec(specJson, doc.template) };
68
+ return dispatch(doc.template, input, o, doc.stack === true);
69
+ }
@@ -0,0 +1,3 @@
1
+ import { type GaugeSpec } from '../specs/index.js';
2
+ import { type RenderOpts } from './svg.js';
3
+ export declare function renderGauge(spec: GaugeSpec, o: RenderOpts): string;