@x-cmd/draw 0.0.0-stage → 0.1.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 (105) hide show
  1. package/LICENSE +228 -0
  2. package/README.md +224 -2
  3. package/dist/lib.d.ts +25 -0
  4. package/dist/lib.js +50 -0
  5. package/dist/node/cli.d.ts +2 -0
  6. package/dist/node/cli.js +76 -0
  7. package/dist/render/area.d.ts +8 -0
  8. package/dist/render/area.js +414 -0
  9. package/dist/render/bar-grid.d.ts +3 -0
  10. package/dist/render/bar-grid.js +52 -0
  11. package/dist/render/bar-grouped.d.ts +3 -0
  12. package/dist/render/bar-grouped.js +131 -0
  13. package/dist/render/bar-stacked.d.ts +3 -0
  14. package/dist/render/bar-stacked.js +142 -0
  15. package/dist/render/bar.d.ts +3 -0
  16. package/dist/render/bar.js +74 -0
  17. package/dist/render/combo.d.ts +3 -0
  18. package/dist/render/combo.js +256 -0
  19. package/dist/render/dispatch.d.ts +3 -0
  20. package/dist/render/dispatch.js +69 -0
  21. package/dist/render/gauge.d.ts +3 -0
  22. package/dist/render/gauge.js +216 -0
  23. package/dist/render/hbar-spec.d.ts +7 -0
  24. package/dist/render/hbar-spec.js +265 -0
  25. package/dist/render/hbar.d.ts +3 -0
  26. package/dist/render/hbar.js +55 -0
  27. package/dist/render/line-multi.d.ts +3 -0
  28. package/dist/render/line-multi.js +89 -0
  29. package/dist/render/line.d.ts +11 -0
  30. package/dist/render/line.js +123 -0
  31. package/dist/render/measure.d.ts +60 -0
  32. package/dist/render/measure.js +75 -0
  33. package/dist/render/pie.d.ts +5 -0
  34. package/dist/render/pie.js +439 -0
  35. package/dist/render/qr.d.ts +8 -0
  36. package/dist/render/qr.js +52 -0
  37. package/dist/render/query.d.ts +14 -0
  38. package/dist/render/query.js +220 -0
  39. package/dist/render/radar.d.ts +5 -0
  40. package/dist/render/radar.js +221 -0
  41. package/dist/render/sankey.d.ts +3 -0
  42. package/dist/render/sankey.js +280 -0
  43. package/dist/render/scatter.d.ts +3 -0
  44. package/dist/render/scatter.js +98 -0
  45. package/dist/render/svg.d.ts +93 -0
  46. package/dist/render/svg.js +471 -0
  47. package/dist/specs/base.d.ts +34 -0
  48. package/dist/specs/base.js +159 -0
  49. package/dist/specs/combo.d.ts +15 -0
  50. package/dist/specs/combo.js +135 -0
  51. package/dist/specs/csv.d.ts +1 -0
  52. package/dist/specs/csv.js +40 -0
  53. package/dist/specs/gauge.d.ts +15 -0
  54. package/dist/specs/gauge.js +108 -0
  55. package/dist/specs/index.d.ts +8 -0
  56. package/dist/specs/index.js +9 -0
  57. package/dist/specs/input.d.ts +11 -0
  58. package/dist/specs/input.js +33 -0
  59. package/dist/specs/multi.d.ts +12 -0
  60. package/dist/specs/multi.js +112 -0
  61. package/dist/specs/sankey.d.ts +13 -0
  62. package/dist/specs/sankey.js +112 -0
  63. package/dist/specs/scatter.d.ts +20 -0
  64. package/dist/specs/scatter.js +121 -0
  65. package/dist/store.d.ts +15 -0
  66. package/dist/store.js +121 -0
  67. package/dist/styles/area.d.ts +2 -0
  68. package/dist/styles/area.js +106 -0
  69. package/dist/styles/bar.d.ts +2 -0
  70. package/dist/styles/bar.js +52 -0
  71. package/dist/styles/combo.d.ts +2 -0
  72. package/dist/styles/combo.js +37 -0
  73. package/dist/styles/common.d.ts +34 -0
  74. package/dist/styles/common.js +259 -0
  75. package/dist/styles/gauge.d.ts +2 -0
  76. package/dist/styles/gauge.js +51 -0
  77. package/dist/styles/handlee.d.ts +1 -0
  78. package/dist/styles/handlee.js +2 -0
  79. package/dist/styles/hbar.d.ts +2 -0
  80. package/dist/styles/hbar.js +66 -0
  81. package/dist/styles/index.d.ts +7 -0
  82. package/dist/styles/index.js +79 -0
  83. package/dist/styles/inter.d.ts +3 -0
  84. package/dist/styles/inter.js +10 -0
  85. package/dist/styles/line.d.ts +2 -0
  86. package/dist/styles/line.js +97 -0
  87. package/dist/styles/pie.d.ts +2 -0
  88. package/dist/styles/pie.js +163 -0
  89. package/dist/styles/qr.d.ts +2 -0
  90. package/dist/styles/qr.js +12 -0
  91. package/dist/styles/radar.d.ts +2 -0
  92. package/dist/styles/radar.js +50 -0
  93. package/dist/styles/sankey.d.ts +2 -0
  94. package/dist/styles/sankey.js +29 -0
  95. package/dist/styles/scatter.d.ts +2 -0
  96. package/dist/styles/scatter.js +21 -0
  97. package/dist/styles/types.d.ts +105 -0
  98. package/dist/styles/types.js +70 -0
  99. package/dist/theme.d.ts +3 -0
  100. package/dist/theme.js +11 -0
  101. package/dist/types.d.ts +17 -0
  102. package/dist/types.js +1 -0
  103. package/dist/version.d.ts +6 -0
  104. package/dist/version.js +16 -0
  105. package/package.json +47 -4
@@ -0,0 +1,280 @@
1
+ // 桑基图:节点高∝数值,封闭三次贝塞尔流带;最长路径分层,堆叠序跟随对端节点位置。
2
+ // 三变体(规范 sankey 1-3):basic 源色流带 / fund 每链渐变 / pipeline 蓝→紫→玫红叙事。
3
+ import { ApiError } from '../specs/index.js';
4
+ import { TAB, card } from '../theme.js';
5
+ import { esc, fmtFull, r2, sVar, trunc, svgDoc } from './svg.js';
6
+ import { C_sankeyPipeline } from '../styles/common.js';
7
+ // 分层(最长路径)+ 节点量(in/out 较大者)+ 布局
8
+ function layoutSankey(spec, left, right, top, bottom, nodeW, nodeWFor) {
9
+ const names = spec.labels;
10
+ const idx = new Map(names.map((n, i) => [n, i]));
11
+ const inSum = names.map(() => 0);
12
+ const outSum = names.map(() => 0);
13
+ const col = names.map(() => 0);
14
+ const outLinks = names.map(() => []);
15
+ const inDeg = names.map(() => 0);
16
+ spec.links.forEach((l, li) => {
17
+ const f = idx.get(l.from);
18
+ const t = idx.get(l.to);
19
+ outSum[f] += l.value;
20
+ inSum[t] += l.value;
21
+ outLinks[f].push(li);
22
+ inDeg[t]++;
23
+ });
24
+ // 最长路径分层(Kahn);环 → 400
25
+ const deg = [...inDeg];
26
+ const queue = names.map((_, i) => i).filter((i) => deg[i] === 0);
27
+ const order = [];
28
+ while (queue.length) {
29
+ const i = queue.shift();
30
+ order.push(i);
31
+ for (const li of outLinks[i]) {
32
+ const t = idx.get(spec.links[li].to);
33
+ col[t] = Math.max(col[t], col[i] + 1);
34
+ if (--deg[t] === 0)
35
+ queue.push(t);
36
+ }
37
+ }
38
+ if (order.length < names.length) {
39
+ throw new ApiError(400, 'sankey links must form a DAG (no cycles); check links= for a loop');
40
+ }
41
+ const cols = Math.max(...col) + 1;
42
+ const value = names.map((_, i) => Math.max(inSum[i], outSum[i]));
43
+ // 列总流量 → 缩放:最高列(含间隙)恰好铺满
44
+ const colSum = Array.from({ length: cols }, (_, c) => names.reduce((s, _, i) => (col[i] === c ? s + value[i] : s), 0));
45
+ const colCount = Array.from({ length: cols }, (_, c) => names.filter((_, i) => col[i] === c).length);
46
+ const maxColSum = Math.max(...colSum);
47
+ const gap = (bottom - top) * 0.052;
48
+ const maxGapTotal = Math.max(...colCount.map((c) => (c - 1) * gap));
49
+ const scale = maxColSum > 0 ? (bottom - top - maxGapTotal) / maxColSum : 0;
50
+ // 节点位置:列内自顶堆叠,余量均分为间隙;列宽可逐列指定(规范 sankey-2 中列 120/端列 115)
51
+ const wOf = (c) => (nodeWFor ? nodeWFor(c, cols) : nodeW);
52
+ const nodes = names.map((name, i) => ({
53
+ name,
54
+ value: value[i],
55
+ col: col[i],
56
+ x: left + ((right - left - wOf(col[i])) * col[i]) / Math.max(cols - 1, 1),
57
+ y: 0,
58
+ w: wOf(col[i]),
59
+ h: Math.max(value[i] * scale, 4),
60
+ colorIdx: i,
61
+ }));
62
+ for (let c = 0; c < cols; c++) {
63
+ const inCol = nodes.filter((n) => n.col === c);
64
+ const used = inCol.reduce((s, n) => s + n.h, 0);
65
+ const gapC = inCol.length > 1 ? (bottom - top - used) / (inCol.length - 1) : 0;
66
+ let y = top;
67
+ for (const n of inCol.sort((a, b) => b.value - a.value)) { // 规范:大值在上
68
+ n.y = y;
69
+ y += n.h + gapC;
70
+ }
71
+ }
72
+ // 流带(控制点 52%):堆叠序跟随对端节点纵向位置,避免与值排序的列错位交叉
73
+ const outCursor = names.map(() => 0);
74
+ const inCursor = names.map(() => 0);
75
+ const syOf = new Map();
76
+ const tyOf = new Map();
77
+ const linksOfSource = names.map(() => []);
78
+ const linksOfTarget = names.map(() => []);
79
+ spec.links.forEach((l, li) => {
80
+ linksOfSource[idx.get(l.from)].push(li);
81
+ linksOfTarget[idx.get(l.to)].push(li);
82
+ });
83
+ names.forEach((_, i) => {
84
+ for (const li of linksOfSource[i].slice().sort((a, b) => nodes[idx.get(spec.links[a].to)].y - nodes[idx.get(spec.links[b].to)].y)) {
85
+ syOf.set(li, nodes[i].y + outCursor[i]);
86
+ outCursor[i] += spec.links[li].value * scale;
87
+ }
88
+ for (const li of linksOfTarget[i].slice().sort((a, b) => nodes[idx.get(spec.links[a].from)].y - nodes[idx.get(spec.links[b].from)].y)) {
89
+ tyOf.set(li, nodes[i].y + inCursor[i]);
90
+ inCursor[i] += spec.links[li].value * scale;
91
+ }
92
+ });
93
+ const links = spec.links.map((l, li) => {
94
+ const f = idx.get(l.from);
95
+ const t = idx.get(l.to);
96
+ const fn = nodes[f];
97
+ const tn = nodes[t];
98
+ const sy1 = syOf.get(li);
99
+ const ty1 = tyOf.get(li);
100
+ const lh = l.value * scale;
101
+ const x1 = fn.x + fn.w;
102
+ const x2 = tn.x;
103
+ const c1 = x1 + (x2 - x1) * 0.52;
104
+ const c2 = x2 - (x2 - x1) * 0.52;
105
+ const d = `M${r2(x1)} ${r2(sy1)}C${r2(c1)} ${r2(sy1)} ${r2(c2)} ${r2(ty1)} ${r2(x2)} ${r2(ty1)}` +
106
+ `L${r2(x2)} ${r2(ty1 + lh)}C${r2(c2)} ${r2(ty1 + lh)} ${r2(c1)} ${r2(sy1 + lh)} ${r2(x1)} ${r2(sy1 + lh)}Z`;
107
+ return { link: l, d, from: fn, to: tn, sy: sy1, ty: ty1, lh };
108
+ });
109
+ return { nodes, links, cols };
110
+ }
111
+ // 节点/数值双行标签(外置:左列尾端锚,右列起始锚,内列贴节点右侧)
112
+ // style: two=名称+数值两行;one=单行"名称 数值"(节点密);skip=该节点不标(极密)
113
+ function nodeLabel(parts, name, value, x, yMid, anchor, muted, style) {
114
+ if (style === 'skip')
115
+ return;
116
+ const fill = muted ? 'var(--d-muted)' : 'var(--d-ink)';
117
+ if (style === 'one') {
118
+ parts.push(`<text x="${r2(x)}" y="${r2(yMid + 4)}" text-anchor="${anchor}" font-size="11" fill="${fill}">${esc(trunc(name, 16))} <tspan fill="var(--d-muted)" style="${TAB}">${fmtFull(value)}</tspan></text>`);
119
+ return;
120
+ }
121
+ parts.push(`<text x="${r2(x)}" y="${r2(yMid - 3)}" text-anchor="${anchor}" font-size="13" fill="${fill}">${esc(trunc(name, 16))}</text>`);
122
+ parts.push(`<text x="${r2(x)}" y="${r2(yMid + 13)}" text-anchor="${anchor}" font-size="11" fill="var(--d-muted)" style="${TAB}">${fmtFull(value)}</text>`);
123
+ }
124
+ // 按列节点间距决定标签形态:≥26px 两行,≥13px 单行,更密则隔一个标
125
+ function labelStyles(nodes, cols) {
126
+ const m = new Map();
127
+ for (let c = 0; c < cols; c++) {
128
+ const col = nodes.filter((n) => n.col === c).sort((a, b) => a.y - b.y);
129
+ let minGap = Infinity;
130
+ for (let i = 1; i < col.length; i++)
131
+ minGap = Math.min(minGap, col[i].y - (col[i - 1].y + col[i - 1].h));
132
+ const style = minGap >= 26 ? 'two' : minGap >= 13 ? 'one' : 'one';
133
+ const stride = minGap >= 13 ? 1 : Math.max(1, Math.ceil(13 / Math.max(minGap, 3)));
134
+ col.forEach((n, i) => m.set(n, style === 'two' ? 'two' : i % stride === 0 ? 'one' : 'skip'));
135
+ }
136
+ return m;
137
+ }
138
+ export function renderSankey(spec, o) {
139
+ const mode = o.skin.rules.sankeyMode;
140
+ if (mode === 'fund')
141
+ return renderSankeyFund(spec, o);
142
+ if (mode === 'pipeline')
143
+ return renderSankeyPipeline(spec, o);
144
+ return renderSankeyBasic(spec, o);
145
+ }
146
+ // 桑基图 1 · 基础款(规范 sankey-1,720×420):细节点(14×h rx4)+ 源色流带 .46 + 外置标签
147
+ function renderSankeyBasic(spec, o) {
148
+ const { width, height, version, skin } = o;
149
+ const nodeW = width * 0.0194; // 14/720
150
+ const { nodes, links, cols } = layoutSankey(spec, width * 0.1667, width * 0.8806, height * 0.119, height * 0.871, nodeW);
151
+ const styles = labelStyles(nodes, cols);
152
+ const parts = [card(width, height, true)];
153
+ for (const l of links) {
154
+ parts.push(`<path d="${l.d}" fill="${sVar(l.from.colorIdx % skin.series.length)}" fill-opacity="0.46"/>`);
155
+ }
156
+ for (const n of nodes) {
157
+ parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(nodeW)}" height="${r2(n.h)}" rx="${r2(nodeW * 0.286)}" fill="${sVar(n.colorIdx % skin.series.length)}"/>`);
158
+ const last = n.col === cols - 1;
159
+ const st = styles.get(n) ?? 'two';
160
+ if (n.col === 0)
161
+ nodeLabel(parts, n.name, n.value, n.x - 12, n.y + n.h / 2, 'end', false, st);
162
+ else if (last)
163
+ nodeLabel(parts, n.name, n.value, n.x + nodeW + 12, n.y + n.h / 2, 'start', false, st);
164
+ else
165
+ nodeLabel(parts, n.name, n.value, n.x + nodeW + 10, n.y + n.h / 2, 'start', true, st);
166
+ }
167
+ return svgDoc(width, height, 'sankey', version, spec.title ?? 'sankey', spec, skin, parts.join(''));
168
+ }
169
+ // 桑基图 2 · Fund Allocation(规范 sankey-2,760×460):
170
+ // 盒节点(标签内置)+ 渐变流带 .38 + 表头(标题+右注)+ 表尾三统计
171
+ function renderSankeyFund(spec, o) {
172
+ const { width, height, version, skin } = o;
173
+ const nodeW = width * 0.1513; // 115/760
174
+ // 规范 sankey-2:端列节点 115/760,中列 120/760
175
+ const { nodes, links } = layoutSankey(spec, width * 0.046, width * 0.934, height * 0.15, height * 0.83, nodeW, (col, cols) => (col === 0 || col === cols - 1 ? nodeW : width * 0.1579));
176
+ const k = skin.series.length;
177
+ const { cols: fundCols } = { cols: 0 };
178
+ void fundCols;
179
+ const parts = [
180
+ card(width, height, true),
181
+ `<defs>${links.map((l, i) => `<linearGradient id="sk-${i}" x1="0" x2="1"><stop stop-color="${sVar(l.from.colorIdx % k)}"/><stop offset="1" stop-color="${sVar(l.to.colorIdx % k)}"/></linearGradient>`).join('')}</defs>`,
182
+ ];
183
+ // 表头:标题 + 右注(unit)
184
+ if (spec.title)
185
+ parts.push(`<text x="${r2(width * 0.033)}" y="${r2(height * 0.067)}" font-size="18" font-weight="600" letter-spacing="-0.02em" fill="var(--d-ink)">${esc(trunc(spec.title, 40))}</text>`);
186
+ if (spec.unit)
187
+ parts.push(`<text x="${r2(width * 0.967)}" y="${r2(height * 0.067)}" text-anchor="end" font-size="12" fill="var(--d-muted)">${esc(trunc(spec.unit, 24))}</text>`);
188
+ for (const l of links) {
189
+ parts.push(`<path d="${l.d}" fill="url(#sk-${links.indexOf(l)})" fill-opacity="0.38"/>`);
190
+ }
191
+ for (const n of nodes) {
192
+ const c = sVar(n.colorIdx % k);
193
+ parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(n.w)}" height="${r2(n.h)}" rx="${r2(height * 0.0174)}" fill="${c}" fill-opacity="0.42" stroke="${c}" stroke-width="1.5"/>`);
194
+ if (n.h >= 34) {
195
+ parts.push(`<text x="${r2(n.x + n.w / 2)}" y="${r2(n.y + n.h / 2 - 3)}" text-anchor="middle" font-size="12" font-weight="700" fill="var(--d-ink)">${esc(trunc(n.name, 12))}</text>`);
196
+ parts.push(`<text x="${r2(n.x + n.w / 2)}" y="${r2(n.y + n.h / 2 + 14)}" text-anchor="middle" font-size="11" fill="var(--d-muted)" style="${TAB}">${fmtFull(n.value)}</text>`);
197
+ }
198
+ else {
199
+ nodeLabel(parts, n.name, n.value, n.x + n.w + 10, n.y + n.h / 2, 'start', true, 'two');
200
+ }
201
+ }
202
+ // 表尾三统计:总流量 / 节点数 / 链接数
203
+ const total = spec.links.filter((l) => !spec.links.some((m) => m.to === l.from)).reduce((s, l) => s + l.value, 0);
204
+ const stats = [
205
+ ['TOTAL FLOW', fmtFull(total)],
206
+ ['NODES', String(nodes.length)],
207
+ ['LINKS', String(links.length)],
208
+ ];
209
+ stats.forEach(([k2, v], i) => {
210
+ const x = i === 0 ? width * 0.033 : i === 1 ? width / 2 : width * 0.967;
211
+ const anchor = i === 0 ? 'start' : i === 1 ? 'middle' : 'end';
212
+ parts.push(`<text x="${r2(x)}" y="${r2(height * 0.879)}" text-anchor="${anchor}" font-size="10" letter-spacing="1" fill="var(--d-muted)">${k2}</text>`);
213
+ parts.push(`<text x="${r2(x)}" y="${r2(height * 0.951)}" text-anchor="${anchor}" font-size="25" font-weight="700" fill="var(--d-ink)" style="${TAB}">${v}</text>`);
214
+ });
215
+ return svgDoc(width, height, 'sankey', version, spec.title ?? 'fund flows', spec, skin, parts.join(''));
216
+ }
217
+ // 桑基图 3 · Revenue Pipeline(规范 sankey-3,760×400):
218
+ // 细节点 + 源→目标渐变流带 + 中央渐隐面板显示管线总额(源头之和)
219
+ function renderSankeyPipeline(spec, o) {
220
+ const { width, height, version, skin } = o;
221
+ const nodeW = width * 0.0184; // 14/760
222
+ const { nodes, links, cols } = layoutSankey(spec, width * 0.1816, width * 0.8, height * 0.145, height * 0.8475, nodeW);
223
+ const P = C_sankeyPipeline;
224
+ // 规范 sankey-3:整图是一条 蓝→紫→玫红 的叙事渐变——
225
+ // 节点按列取族色(源=蓝系 / 中列=靛紫系 / 汇=玫红系,列内自上而下轮换)
226
+ // 流带拆两半共享双渐变:pIn(蓝→紫)走左半,pOut(紫→玫红)走右半,中央留给渐隐面板
227
+ const famOf = (col) => col === 0 ? [P.blue, P['blue-deep'], P.indigo, P['indigo-deep']]
228
+ : col === cols - 1 ? [P.rose, P.red, P.pink, P.orange]
229
+ : [P.purple, P['indigo-deep'], P.indigo];
230
+ const colSeq = new Map();
231
+ for (let c = 0; c < cols; c++) {
232
+ colSeq.set(c, nodes.filter((n) => n.col === c).sort((a, b) => a.y - b.y).map((n) => n.name));
233
+ }
234
+ const nodeColor = (n) => {
235
+ const fam = famOf(n.col);
236
+ return fam[(colSeq.get(n.col) ?? []).indexOf(n.name) % fam.length] ?? fam[0];
237
+ };
238
+ const midX = width / 2;
239
+ const parts = [
240
+ card(width, height, true),
241
+ `<defs>` +
242
+ `<linearGradient id="sk-in" x1="0" x2="1"><stop stop-color="${P.blue}"/><stop offset="1" stop-color="${P.purple}"/></linearGradient>` +
243
+ `<linearGradient id="sk-out" x1="0" x2="1"><stop stop-color="${P.purple}"/><stop offset="1" stop-color="${P.rose}"/></linearGradient>` +
244
+ // 渐隐面板用 var(--d-card):auto 模式下随系统明暗切换(硬编码会在暗色图上留白带)
245
+ `<linearGradient id="sk-fade" x1="0" x2="1"><stop stop-color="transparent"/><stop offset=".32" stop-color="var(--d-card)"/><stop offset=".68" stop-color="var(--d-card)"/><stop offset="1" stop-color="transparent"/></linearGradient>` +
246
+ `</defs>`,
247
+ ];
248
+ // 流带两半:源端 → 中缝左沿(sk-in),中缝右沿 → 目标端(sk-out);
249
+ // 中缝 = 中央面板各内缩 0.0395w(规范 760 宽下为 350/410)
250
+ const xa = midX - width * 0.0395;
251
+ const xb = midX + width * 0.0395;
252
+ const half = (x1, x2, y1, y2, lh, fill) => {
253
+ const c1 = x1 + (x2 - x1) * 0.52;
254
+ const c2 = x2 - (x2 - x1) * 0.52;
255
+ return `<path d="M${r2(x1)} ${r2(y1)}C${r2(c1)} ${r2(y1)} ${r2(c2)} ${r2(y2)} ${r2(x2)} ${r2(y2)}` +
256
+ `L${r2(x2)} ${r2(y2 + lh)}C${r2(c2)} ${r2(y2 + lh)} ${r2(c1)} ${r2(y1 + lh)} ${r2(x1)} ${r2(y1 + lh)}Z" fill="${fill}" fill-opacity="0.34"/>`;
257
+ };
258
+ for (const l of links) {
259
+ parts.push(half(l.from.x + nodeW, xa, l.sy, l.ty, l.lh, 'url(#sk-in)'));
260
+ parts.push(half(xb, l.to.x, l.sy, l.ty, l.lh, 'url(#sk-out)'));
261
+ }
262
+ for (const n of nodes) {
263
+ parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(nodeW)}" height="${r2(n.h)}" rx="${r2(nodeW * 0.286)}" fill="${nodeColor(n)}"/>`);
264
+ if (n.x < midX)
265
+ nodeLabel(parts, n.name, n.value, n.x - 12, n.y + n.h / 2, 'end', false, 'two');
266
+ else
267
+ nodeLabel(parts, n.name, n.value, n.x + nodeW + 12, n.y + n.h / 2, 'start', false, 'two');
268
+ }
269
+ // 中央渐隐面板:总额(源头节点之和)+ N sources · M sinks
270
+ const panelW = width * 0.25;
271
+ const hasIn = new Set(spec.links.map((l) => l.to));
272
+ const sources = nodes.filter((n) => !hasIn.has(n.name));
273
+ const sinks = nodes.filter((n) => !spec.links.some((l) => l.from === n.name));
274
+ const total = sources.reduce((s, n) => s + n.value, 0);
275
+ parts.push(`<rect x="${r2(midX - panelW / 2)}" y="${r2(height * 0.105)}" width="${r2(panelW)}" height="${r2(height * 0.8125)}" fill="url(#sk-fade)"/>`); // 规范:42..367(0.8125h)
276
+ parts.push(`<text x="${r2(midX)}" y="${r2(height * 0.495)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(trunc(spec.title ?? 'Total booked', 20))}</text>`); // 规范 y=198/400
277
+ parts.push(`<text x="${r2(midX)}" y="${r2(height * 0.59)}" text-anchor="middle" font-size="34" font-weight="700" fill="var(--d-ink)" style="${TAB}">${fmtFull(total)}</text>`); // 规范 y=236/400
278
+ parts.push(`<text x="${r2(midX)}" y="${r2(height * 0.645)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${sources.length} sources · ${sinks.length} routes</text>`); // 规范 y=258/400
279
+ return svgDoc(width, height, 'sankey', version, spec.title ?? 'revenue pipeline', spec, skin, parts.join(''));
280
+ }
@@ -0,0 +1,3 @@
1
+ import type { ScatterSpec } from '../specs/index.js';
2
+ import { type RenderOpts } from './svg.js';
3
+ export declare function renderScatter(spec: ScatterSpec, o: RenderOpts): string;
@@ -0,0 +1,98 @@
1
+ import { TAB, card } from '../theme.js';
2
+ import { esc, fmtNum, niceStep, r2, snap, trunc, LabelPlacer, pushLineLabelsAllOrNothing, reserveBands, reserveEdges, sVar, svgDoc, titleBlock } from './svg.js';
3
+ import { tickColW } from './measure.js';
4
+ // 取整量程刻度:数据向下/向上取整到步长(规范 -18..19 → -20..20),刻度线铺满整域
5
+ function spanTicks(min, max, count) {
6
+ const step = niceStep((max - min) / count);
7
+ const lo = Math.floor(min / step) * step;
8
+ const hi = Math.ceil(max / step) * step;
9
+ const out = [];
10
+ for (let v = lo; v <= hi + 1e-9; v += step)
11
+ out.push(snap(v, step));
12
+ return out;
13
+ }
14
+ export function renderScatter(spec, o) {
15
+ const { width, height, version, skin } = o;
16
+ const series = spec.series?.length
17
+ ? spec.series
18
+ : [{ name: '', points: spec.points ?? [] }];
19
+ const all = series.flatMap((s) => s.points);
20
+ const xs = all.map((p) => p.x);
21
+ const ys = all.map((p) => p.y);
22
+ const xTicks = spanTicks(Math.min(...xs), Math.max(...xs), 4);
23
+ const yTicks = spanTicks(Math.min(...ys), Math.max(...ys), 6);
24
+ const minX = xTicks[0];
25
+ const maxX = xTicks[xTicks.length - 1];
26
+ const minY = yTicks[0];
27
+ const maxY = yTicks[yTicks.length - 1];
28
+ let peakS = 0;
29
+ let peakP = 0;
30
+ series.forEach((s, si) => s.points.forEach((p, pi) => {
31
+ if (p.y > series[peakS].points[peakP].y) {
32
+ peakS = si;
33
+ peakP = pi;
34
+ }
35
+ }));
36
+ // 几何(规范 920×490 实测):绘图区 92..852 × 90..420,刻度行 y=444,X 标题 y=470。
37
+ // 左内边距 = max(规范 0.1w, 实测刻度列 + 旋转 Y 标题带)—— 长刻度/窄画布不再压轴标题
38
+ const showTitles = width >= 320 && height >= 240;
39
+ const left = Math.round(Math.max(width * 0.1, tickColW(yTicks, 12, 16) + (showTitles ? width * 0.024 + 14 : 6)));
40
+ const right = left + Math.round(width * 0.826);
41
+ const bottom = Math.round(height * 0.857);
42
+ const top = Math.round(height * 0.184);
43
+ const tickY = Math.round(height * 0.906);
44
+ const px = (x) => maxX === minX ? (left + right) / 2 : left + ((x - minX) / (maxX - minX)) * (right - left);
45
+ const py = (y) => maxY === minY ? (top + bottom) / 2 : bottom - ((y - minY) / (maxY - minY)) * (bottom - top);
46
+ const parts = [card(width, height, true)];
47
+ // 网格 + 刻度(虚线 4 6)
48
+ for (const t of yTicks) {
49
+ const gy = py(t);
50
+ parts.push(`<line x1="${left}" y1="${r2(gy)}" x2="${right}" y2="${r2(gy)}" stroke="var(--d-grid)" stroke-dasharray="4 6"/>`);
51
+ parts.push(`<text x="${r2(left - 16)}" y="${r2(gy + 4)}" text-anchor="end" font-size="12" fill="var(--d-muted)" style="${TAB}">${fmtNum(t)}</text>`);
52
+ }
53
+ for (const t of xTicks) {
54
+ const gx = px(t);
55
+ parts.push(`<line x1="${r2(gx)}" y1="${r2(top)}" x2="${r2(gx)}" y2="${r2(bottom)}" stroke="var(--d-grid)" stroke-dasharray="4 6"/>`);
56
+ parts.push(`<text x="${r2(gx)}" y="${r2(tickY)}" text-anchor="middle" font-size="12" fill="var(--d-muted)" style="${TAB}">${fmtNum(t)}</text>`);
57
+ }
58
+ parts.push(`<line x1="${left}" y1="${r2(bottom)}" x2="${right}" y2="${r2(bottom)}" stroke="var(--d-baseline)" stroke-width="1"/>`);
59
+ // 轴标题:画布太小则省(会与刻度挤在一起)
60
+ if (showTitles) {
61
+ parts.push(`<text x="${r2((left + right) / 2)}" y="${r2(height * 0.959)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(spec.unit ?? 'X value')}</text>`);
62
+ parts.push(`<text x="${r2(width * 0.024)}" y="${r2(height / 2)}" text-anchor="middle" font-size="12" fill="var(--d-muted)" transform="rotate(-90 ${r2(width * 0.024)} ${r2(height / 2)})">Y value</text>`);
63
+ }
64
+ // 数据点:每系列一色,点径交替(每 4 个大点),半透明+白描边
65
+ const num = o.valueLabels ?? 'none';
66
+ const numItems = [];
67
+ series.forEach((s, si) => {
68
+ const color = sVar(si % skin.series.length);
69
+ s.points.forEach((p, pi) => {
70
+ const isPeak = si === peakS && pi === peakP;
71
+ parts.push(`<circle cx="${r2(px(p.x))}" cy="${r2(py(p.y))}" r="${pi % 4 === 0 ? 7 : 5}" fill="${color}" fill-opacity="0.78" stroke="var(--d-halo)" stroke-width="2"/>`);
72
+ if (num === 'all' || (num === 'peak' && isPeak)) {
73
+ numItems.push({ px: px(p.x), py: py(p.y), text: fmtNum(p.y), isPeak });
74
+ }
75
+ });
76
+ });
77
+ // 数值标签:全有或全无(num=all 时密集点必撞,整层不标优于重叠)。
78
+ // 预留 Y 刻度带/X 刻度带/图例带与画布边带:标签不得压轴文字、不得出画布
79
+ if (numItems.length > 0) {
80
+ const placer = new LabelPlacer();
81
+ reserveBands(placer, left, right, top, bottom, tickY, spec.series ?? [], right, Math.round(height * 0.09));
82
+ reserveEdges(placer, width, height);
83
+ pushLineLabelsAllOrNothing(parts, placer, numItems);
84
+ }
85
+ // 多系列:右上圆点图例
86
+ if (spec.series?.length) {
87
+ let lx = right;
88
+ const legendY = Math.round(height * 0.09);
89
+ for (let i = spec.series.length - 1; i >= 0; i--) {
90
+ const name = trunc(spec.series[i].name, 12);
91
+ parts.push(`<text x="${r2(lx)}" y="${r2(legendY)}" text-anchor="end" font-size="12" fill="var(--d-muted)">${esc(name)}</text>`);
92
+ lx -= 12 + name.length * 6.5 + 10;
93
+ parts.push(`<circle cx="${r2(lx)}" cy="${r2(legendY - 4)}" r="5" fill="${sVar(i % skin.series.length)}"/>`);
94
+ lx -= 24;
95
+ }
96
+ }
97
+ return svgDoc(width, height, 'scatter', version, spec.title ?? 'scatter chart', spec, skin, titleBlock(spec.title) + parts.join(''));
98
+ }
@@ -0,0 +1,93 @@
1
+ import type { Skin } from '../styles/types.js';
2
+ export declare function esc(s: string): string;
3
+ export declare function fmtNum(n: number): string;
4
+ export declare function fmtFull(n: number): string;
5
+ export declare function trunc(s: string, n: number): string;
6
+ export declare const r2: (n: number) => number | string;
7
+ export declare function niceStep(raw: number): number;
8
+ export declare function snap(v: number, step: number): number;
9
+ export declare function niceTicks(max: number, count?: number): number[];
10
+ export declare function rangeTicks(min: number, max: number, count?: number): number[];
11
+ export declare function topLegend(items: readonly {
12
+ name: string;
13
+ color: string;
14
+ }[], x: number, y: number, anchor?: 'left' | 'right', shape?: 'circle' | 'square'): string;
15
+ export declare const sVar: (i: number) => string;
16
+ export declare const onVar: (i: number) => string;
17
+ export declare function svgDoc(width: number, height: number, template: string, version: number, aria: string, spec: unknown, skin: Skin, children: string): string;
18
+ export declare function editorialTitle(title: string, width: number, pad: number): {
19
+ svg: string;
20
+ height: number;
21
+ };
22
+ export declare function titleBlock(title: string | undefined, pad?: number): string;
23
+ export declare function yAxisGrid(parts: string[], ticks: number[], y: (v: number) => number, left: number, right: number, bottom: number, grid?: 'solid' | 'dashed' | 'none', gridDash?: string, inline?: boolean, baseline?: 'line' | 'dots' | 'none', xDots?: number[], tickFs?: number, tickGap?: number): void;
24
+ export declare function axisTitleY(unit: string | undefined, midY: number, x?: number): string;
25
+ export declare function findPeak(series: readonly {
26
+ values: readonly number[];
27
+ }[]): [number, number];
28
+ export interface RenderOpts {
29
+ width: number;
30
+ height: number;
31
+ version: number;
32
+ skin: Skin;
33
+ /** 数值标注:all=全部(默认) peak=仅最高 none=不标 */
34
+ valueLabels?: 'all' | 'peak' | 'none';
35
+ /** 用户未显式指定 ?h=:允许渲染器按需自动调整高度(如堆叠柱量级差过大时拉高) */
36
+ autoHeight?: boolean;
37
+ /** 用户未显式指定 ?w=:允许渲染器按需自动加宽(如分组柱太密放不下时) */
38
+ autoWidth?: boolean;
39
+ /** 环形图形态:true=环形(默认) false=实心饼 */
40
+ donut?: boolean;
41
+ /** 参考线数值(hbar opendata:?ref=4.5) */
42
+ refLine?: number;
43
+ /** 参考线文案(?reflabel=WCAG AA) */
44
+ refLabel?: string;
45
+ }
46
+ export declare function textW(s: string, fs: number): number;
47
+ export declare function smoothPath(pts: [number, number][]): string;
48
+ export declare function onColor(hex: string): string;
49
+ export declare class LabelPlacer {
50
+ private boxes;
51
+ fits(x: number, y: number, w: number, h: number): boolean;
52
+ /** 无条件占位:柱内标签等"位置已定"的文字,让后续标签(如线标签)避让 */
53
+ reserve(x: number, y: number, w: number, h: number): void;
54
+ }
55
+ export declare function reserveBands(placer: LabelPlacer, left: number, right: number, contentTop: number, bottom: number, xLabelY: number | null, legendItems: readonly {
56
+ name: string;
57
+ }[], legendX: number, legendY: number): void;
58
+ export declare function labelStride(labels: readonly string[], slot: number, fs?: number): number;
59
+ export declare function reserveEdges(placer: LabelPlacer, width: number, height: number): void;
60
+ export declare function pushPoints(parts: string[], pts: readonly (readonly [number, number])[], color: string, rules: {
61
+ points: 'filled' | 'hollow' | 'none';
62
+ pointR: number;
63
+ }): void;
64
+ export declare function pushBarLabelsAllOrNothing(parts: string[], items: readonly {
65
+ x: number;
66
+ yt: number;
67
+ w: number;
68
+ hAvail: number;
69
+ text: string;
70
+ fs: number;
71
+ peak: boolean;
72
+ fill: string;
73
+ center?: boolean;
74
+ side?: boolean;
75
+ fallFill?: string;
76
+ row?: number;
77
+ fx?: number;
78
+ fyt?: number;
79
+ haloColor?: string;
80
+ insideOnly?: boolean;
81
+ }[], sharedPlacer?: LabelPlacer, segments?: readonly LineSeg[]): boolean;
82
+ export declare function pushLineLabelsAllOrNothing(parts: string[], placer: LabelPlacer, items: readonly {
83
+ px: number;
84
+ py: number;
85
+ text: string;
86
+ isPeak: boolean;
87
+ }[], segments?: readonly LineSeg[]): boolean;
88
+ export declare function segRectIntersect(x1: number, y1: number, x2: number, y2: number, rx: number, ry: number, rw: number, rh: number): boolean;
89
+ /** 折线障碍段:文字不得压线(线横穿数字会看不清) */
90
+ export type LineSeg = readonly [number, number, number, number];
91
+ /** 由点序列构造折线障碍段 */
92
+ export declare function toSegments(pts: readonly (readonly [number, number])[]): LineSeg[];
93
+ export declare function pushLineLabel(parts: string[], placer: LabelPlacer, px: number, py: number, text: string, isPeak: boolean, segments?: readonly LineSeg[]): void;