@x-cmd/draw 0.2.5 → 0.4.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 (131) hide show
  1. package/README.md +80 -166
  2. package/dist/lib.d.ts +27 -1
  3. package/dist/lib.js +39 -1
  4. package/dist/node/cli.js +109 -11
  5. package/dist/render/anno.d.ts +50 -0
  6. package/dist/render/anno.js +589 -0
  7. package/dist/render/arch.d.ts +106 -0
  8. package/dist/render/arch.js +1011 -0
  9. package/dist/render/archmap.d.ts +157 -0
  10. package/dist/render/archmap.js +683 -0
  11. package/dist/render/area.js +20 -14
  12. package/dist/render/bar-grouped.js +8 -5
  13. package/dist/render/bar-stacked.js +11 -7
  14. package/dist/render/bar.js +8 -3
  15. package/dist/render/butterfly.d.ts +3 -0
  16. package/dist/render/butterfly.js +355 -0
  17. package/dist/render/calendar.d.ts +6 -0
  18. package/dist/render/calendar.js +448 -0
  19. package/dist/render/combo.js +16 -8
  20. package/dist/render/compass.d.ts +6 -0
  21. package/dist/render/compass.js +77 -0
  22. package/dist/render/dispatch.js +26 -1
  23. package/dist/render/echarts-ssr.d.ts +51 -0
  24. package/dist/render/echarts-ssr.js +511 -0
  25. package/dist/render/gantt.d.ts +46 -0
  26. package/dist/render/gantt.js +415 -0
  27. package/dist/render/gantt2.d.ts +24 -0
  28. package/dist/render/gantt2.js +198 -0
  29. package/dist/render/hbar.js +8 -4
  30. package/dist/render/icons.d.ts +3 -0
  31. package/dist/render/icons.js +78 -0
  32. package/dist/render/kinds.d.ts +11 -0
  33. package/dist/render/kinds.js +176 -0
  34. package/dist/render/ladder.d.ts +21 -0
  35. package/dist/render/ladder.js +230 -0
  36. package/dist/render/layout.d.ts +46 -0
  37. package/dist/render/layout.js +57 -0
  38. package/dist/render/line-multi.js +7 -5
  39. package/dist/render/line.js +9 -5
  40. package/dist/render/maps.d.ts +46 -0
  41. package/dist/render/maps.js +237 -0
  42. package/dist/render/measure.d.ts +0 -1
  43. package/dist/render/measure.js +0 -1
  44. package/dist/render/mermaid.d.ts +30 -0
  45. package/dist/render/mermaid.js +277 -0
  46. package/dist/render/mindmap.d.ts +10 -0
  47. package/dist/render/mindmap.js +388 -0
  48. package/dist/render/orgicon.d.ts +12 -0
  49. package/dist/render/orgicon.js +31 -0
  50. package/dist/render/pie.js +1 -1
  51. package/dist/render/png.d.ts +21 -0
  52. package/dist/render/png.js +109 -0
  53. package/dist/render/quadrant.d.ts +6 -0
  54. package/dist/render/quadrant.js +201 -0
  55. package/dist/render/query.d.ts +2 -0
  56. package/dist/render/query.js +108 -1
  57. package/dist/render/route.d.ts +86 -0
  58. package/dist/render/route.js +1077 -0
  59. package/dist/render/scatter.js +87 -12
  60. package/dist/render/seq.d.ts +41 -0
  61. package/dist/render/seq.js +248 -0
  62. package/dist/render/svg.d.ts +34 -2
  63. package/dist/render/svg.js +159 -20
  64. package/dist/render/table.d.ts +30 -0
  65. package/dist/render/table.js +134 -0
  66. package/dist/render/tokei.d.ts +18 -0
  67. package/dist/render/tokei.js +230 -0
  68. package/dist/render/uc.d.ts +58 -0
  69. package/dist/render/uc.js +319 -0
  70. package/dist/render/units.d.ts +32 -0
  71. package/dist/render/units.js +84 -0
  72. package/dist/render/vendor/au.js +10 -0
  73. package/dist/render/vendor/br.js +10 -0
  74. package/dist/render/vendor/china.js +11 -0
  75. package/dist/render/vendor/de.js +10 -0
  76. package/dist/render/vendor/eu.js +10 -0
  77. package/dist/render/vendor/japan.js +10 -0
  78. package/dist/render/vendor/kr.js +10 -0
  79. package/dist/render/vendor/mermaid-flow-parser.js +1164 -0
  80. package/dist/render/vendor/mermaid-gantt-parser.js +810 -0
  81. package/dist/render/vendor/us-states.js +11 -0
  82. package/dist/render/vendor/world-geo.d.ts +22 -0
  83. package/dist/render/vendor/world-geo.js +9 -0
  84. package/dist/render/vendor/world.d.ts +13 -0
  85. package/dist/render/vendor/world.js +12 -0
  86. package/dist/specs/base.d.ts +16 -0
  87. package/dist/specs/base.js +34 -1
  88. package/dist/specs/butterfly.d.ts +46 -0
  89. package/dist/specs/butterfly.js +241 -0
  90. package/dist/specs/calendar.d.ts +90 -0
  91. package/dist/specs/calendar.js +296 -0
  92. package/dist/specs/compass.d.ts +27 -0
  93. package/dist/specs/compass.js +111 -0
  94. package/dist/specs/index.d.ts +5 -0
  95. package/dist/specs/index.js +5 -0
  96. package/dist/specs/ladder.d.ts +43 -0
  97. package/dist/specs/ladder.js +261 -0
  98. package/dist/specs/quadrant.d.ts +41 -0
  99. package/dist/specs/quadrant.js +200 -0
  100. package/dist/specs/scatter.d.ts +14 -8
  101. package/dist/specs/scatter.js +54 -5
  102. package/dist/specs/table.d.ts +24 -0
  103. package/dist/specs/table.js +154 -0
  104. package/dist/store.d.ts +1 -1
  105. package/dist/store.js +1 -1
  106. package/dist/styles/butterfly.d.ts +2 -0
  107. package/dist/styles/butterfly.js +74 -0
  108. package/dist/styles/calendar.d.ts +2 -0
  109. package/dist/styles/calendar.js +51 -0
  110. package/dist/styles/compass.d.ts +2 -0
  111. package/dist/styles/compass.js +19 -0
  112. package/dist/styles/fonts-banner.d.ts +5 -0
  113. package/dist/styles/fonts-banner.js +9 -0
  114. package/dist/styles/fonts-cjk.d.ts +2 -0
  115. package/dist/styles/fonts-cjk.js +6 -0
  116. package/dist/styles/fonts-ttf.d.ts +2 -0
  117. package/dist/styles/fonts-ttf.js +6 -0
  118. package/dist/styles/index.js +13 -0
  119. package/dist/styles/ladder.d.ts +3 -0
  120. package/dist/styles/ladder.js +66 -0
  121. package/dist/styles/quadrant.d.ts +2 -0
  122. package/dist/styles/quadrant.js +19 -0
  123. package/dist/styles/table.d.ts +2 -0
  124. package/dist/styles/table.js +12 -0
  125. package/dist/styles/types.d.ts +1 -0
  126. package/dist/styles/types.js +1 -0
  127. package/dist/theme.d.ts +1 -1
  128. package/dist/theme.js +3 -4
  129. package/dist/types/dagre.d.ts +39 -0
  130. package/dist/types/dagre.js +3 -0
  131. package/package.json +28 -3
@@ -0,0 +1,388 @@
1
+ // /draw/mindmap(x-cmd-hub/draw#17/#20):树形导图 — 结构图家族"树→自动布局"侧。
2
+ // 与 archmap(布局外置)相反:邻接即全部语义,坐标纯属噪音 → 引擎布局严格更优。
3
+ // 参数:重复 n=<根/枝/叶 路径>(文件树式,读者扫路径即重建整棵树);style 三形态:
4
+ // organic(缺省)— 有机贝塞尔 + 文字节点 + 根胶囊(XMind 经典)
5
+ // tree — 盒节点 + 直角肘形连线(逻辑树;一级分支实心着色盒)
6
+ // radial — 根居中,叶在外圈均匀分角,扇形辐射(泡泡/辐射导图)
7
+ // 布局:叶顺序取槽位(线性)或均匀分角(辐射),父节点居中于子代均值;列距按各深度最大标签宽错落。
8
+ import { ApiError } from '../specs/index.js';
9
+ import { resolveVersion } from '../version.js';
10
+ import { resolveSkin } from '../styles/index.js';
11
+ import { esc, r2, sVar, onVar, svgDoc, textW } from './svg.js';
12
+ import { clampInt, schemeParam } from './query.js';
13
+ const PAD = 26;
14
+ const COL_GAP = 44; // 列间距(父文字尾 → 子文字头)
15
+ const LEAF_STEP = 27; // 叶槽位步进(13px 文本行高+呼吸)
16
+ const ROOT_FS = 15;
17
+ const NODE_FS = 13;
18
+ const BOX_PAD = 10; // tree 形态盒内边距
19
+ const BOX_H = 24; // tree 形态盒高
20
+ const RAD_GAP = 56; // radial 形态环间距
21
+ const LEAF_SIDE_NEED = 24; // radial 侧面叶的切向占位(径向排版只需行高+呼吸)
22
+ const MAX_DEPTH = 8;
23
+ const MAX_NODES = 500;
24
+ const STYLES = ['organic', 'tree', 'radial', 'bubble'];
25
+ const N_EXAMPLE = 'n=Product/Features/Speed&n=Product/Markets/EU';
26
+ function bad(detail) {
27
+ throw new ApiError(400, `${detail} Example: /draw/mindmap?${N_EXAMPLE}`);
28
+ }
29
+ // 路径集 → 前缀树;公共前缀自动合并
30
+ function buildTree(paths) {
31
+ const root = { label: '', children: [], depth: 0, branch: -1, x: 0, y: 0, w: 0, anchor: 'start', angle: 0 };
32
+ let count = 0;
33
+ for (const p of paths) {
34
+ if (!p.trim())
35
+ bad('every n= path must be non-empty');
36
+ const segs = p.split('/').map(s => s.trim());
37
+ if (segs.some(s => !s))
38
+ bad(`"${p}": path segments must be non-empty (no "//" or leading/trailing "/")`);
39
+ if (segs.length > MAX_DEPTH)
40
+ bad(`"${p}": deeper than ${MAX_DEPTH} levels`);
41
+ if (root.label === '')
42
+ root.label = segs[0];
43
+ else if (segs[0] !== root.label)
44
+ bad(`"${p}": mindmap takes one tree — root "${segs[0]}" differs from "${root.label}"`);
45
+ let cur = root;
46
+ for (let d = 1; d < segs.length; d++) {
47
+ let next = cur.children.find(c => c.label === segs[d]);
48
+ if (!next) {
49
+ if (++count > MAX_NODES)
50
+ bad(`too many nodes (>${MAX_NODES})`);
51
+ next = { label: segs[d], children: [], depth: d, branch: -1, x: 0, y: 0, w: 0, anchor: 'start', angle: 0 };
52
+ cur.children.push(next);
53
+ }
54
+ cur = next;
55
+ }
56
+ }
57
+ return root;
58
+ }
59
+ // 文本宽度 + 分支着色(一级分支按序轮转,后代继承)
60
+ function measure(root, boxed) {
61
+ const colW = [];
62
+ const walk = (n) => {
63
+ n.w = textW(n.label, n.depth === 0 ? ROOT_FS : NODE_FS) + (boxed ? BOX_PAD * 2 : 0);
64
+ colW[n.depth] = Math.max(colW[n.depth] ?? 0, n.w);
65
+ n.children.forEach(walk);
66
+ };
67
+ walk(root);
68
+ root.children.forEach((c, i) => {
69
+ const paint = (m) => {
70
+ m.branch = i;
71
+ m.children.forEach(paint);
72
+ };
73
+ paint(c);
74
+ });
75
+ return colW;
76
+ }
77
+ // 线性布局(organic/tree):叶顺序取槽位,父 = 子代均值;列 x 按各深度最大宽错落
78
+ function layoutLinear(root, colW) {
79
+ const colX = [];
80
+ let x = PAD;
81
+ for (let d = 0; d < colW.length; d++) {
82
+ colX[d] = d === 0 ? PAD : x + COL_GAP / 2;
83
+ x = colX[d] + (colW[d] ?? 0) + COL_GAP / 2;
84
+ }
85
+ let nextY = PAD + LEAF_STEP / 2;
86
+ let maxY = 0;
87
+ const place = (n) => {
88
+ n.x = colX[n.depth];
89
+ if (!n.children.length) {
90
+ n.y = nextY;
91
+ nextY += LEAF_STEP;
92
+ }
93
+ else {
94
+ n.children.forEach(place);
95
+ n.y = (n.children[0].y + n.children[n.children.length - 1].y) / 2;
96
+ }
97
+ maxY = Math.max(maxY, n.y);
98
+ };
99
+ place(root);
100
+ return { W: colX[colW.length - 1] + (colW[colW.length - 1] ?? 0) + PAD, H: maxY + LEAF_STEP / 2 + PAD / 2 };
101
+ }
102
+ // 辐射布局:叶在外圈全局均匀分角(分支扇区自动 ∝ 叶数),父 = 子代角均值;半径按环累计
103
+ function layoutRadial(root, colW) {
104
+ const radius = [];
105
+ let r = 0;
106
+ for (let d = 0; d < colW.length; d++) {
107
+ radius[d] = d === 0 ? 0 : r + RAD_GAP / 2;
108
+ r = radius[d] + (colW[d] ?? 0) + RAD_GAP / 2;
109
+ }
110
+ const leaves = [];
111
+ const collect = (n) => {
112
+ if (!n.children.length)
113
+ leaves.push(n);
114
+ n.children.forEach(collect);
115
+ };
116
+ collect(root);
117
+ const L = Math.max(leaves.length, 1);
118
+ let minX = 0, maxX = 0, minY = 0, maxY = 0;
119
+ // 第一遍:均匀分角,只为判定每个叶落在侧面(径向排版,占角小)还是顶底(水平排版,占角=字宽/半径)
120
+ let li = 0;
121
+ const placeUniform = (n) => {
122
+ if (!n.children.length) {
123
+ n.angle = -Math.PI / 2 + (2 * Math.PI * li++) / L;
124
+ }
125
+ else {
126
+ n.children.forEach(placeUniform);
127
+ n.angle = (n.children[0].angle + n.children[n.children.length - 1].angle) / 2;
128
+ }
129
+ };
130
+ placeUniform(root);
131
+ root.angle = -Math.PI / 2;
132
+ // 第二遍:叶槽位按占角需求分配(比例归一铺满整圈),溢出则整体放大半径
133
+ const angularNeed = (leaf) => {
134
+ const r = radius[leaf.depth] || 120;
135
+ const c = Math.cos(leaf.angle);
136
+ return c > 0.35 || c < -0.35 ? LEAF_SIDE_NEED / r : (leaf.w + 26) / r;
137
+ };
138
+ const needs = leaves.map(angularNeed);
139
+ const total = needs.reduce((a, b) => a + b, 0);
140
+ const BUDGET = Math.PI * 2 * 0.92; // 全局留 8% 呼吸
141
+ if (total > BUDGET) {
142
+ const grow = total / BUDGET;
143
+ for (let d = 1; d < radius.length; d++)
144
+ radius[d] *= grow;
145
+ }
146
+ let a = -Math.PI / 2;
147
+ leaves.forEach((leaf, i) => {
148
+ const slot = (needs[i] / total) * Math.PI * 2;
149
+ leaf.angle = a + slot / 2; // 槽位中心
150
+ a += slot;
151
+ });
152
+ const reCenter = (n) => {
153
+ if (n.children.length) {
154
+ n.children.forEach(reCenter);
155
+ n.angle = (n.children[0].angle + n.children[n.children.length - 1].angle) / 2;
156
+ }
157
+ };
158
+ reCenter(root);
159
+ root.angle = -Math.PI / 2;
160
+ const project = (n) => {
161
+ const a = n.angle;
162
+ const rr = radius[n.depth];
163
+ const cosA = Math.cos(a); // 右侧左对齐/左侧右对齐,正上下方居中
164
+ n.anchor = cosA > 0.35 ? 'start' : cosA < -0.35 ? 'end' : 'middle';
165
+ n.x = rr * Math.cos(a);
166
+ n.y = rr * Math.sin(a);
167
+ const w = n.depth === 0 ? n.w + 20 : n.w;
168
+ const x0 = n.anchor === 'start' ? n.x : n.x - w;
169
+ minX = Math.min(minX, x0);
170
+ maxX = Math.max(maxX, x0 + w);
171
+ minY = Math.min(minY, n.y - 14);
172
+ maxY = Math.max(maxY, n.y + 14);
173
+ n.children.forEach(project);
174
+ };
175
+ project(root);
176
+ return { W: maxX - minX + PAD * 2, H: maxY - minY + PAD * 2, dx: PAD - minX, dy: PAD - minY };
177
+ }
178
+ // ── organic ────────────────────────────────────────────────────────────────
179
+ // interactive(explore 落地页)时:节点 g 带 data-node=<全路径>/data-tip,
180
+ // 连线带 data-link=<子节点全路径> —— 客户端点击可整棵子树高亮(前缀匹配)
181
+ function nodeTip(path, n) {
182
+ const pretty = path.replace(/\//g, ' / ');
183
+ return n.children.length ? `${pretty} · ${n.children.length}${n.children.length > 1 ? ' branches' : ' branch'}` : `${pretty} · leaf`;
184
+ }
185
+ const nodeIA = (path, n) => ` data-node="${esc(path)}" data-tip="${esc(nodeTip(path, n))}" tabindex="0"`;
186
+ function drawOrganic(root, interactive = false) {
187
+ const { W, H } = layoutLinear(root, measure(root, false));
188
+ const out = [];
189
+ const walk = (n, path) => {
190
+ for (const c of n.children) {
191
+ const x1 = n.x + n.w;
192
+ const mx = (x1 + c.x) / 2;
193
+ const width = Math.max(1.2, 2.4 - c.depth * 0.4);
194
+ const cp = `${path}/${c.label}`;
195
+ const ia = interactive ? ` data-link="${esc(cp)}"` : '';
196
+ out.push(`<path${ia} d="M${r2(x1)} ${r2(n.y)}C${r2(mx)} ${r2(n.y)},${r2(mx)} ${r2(c.y)},${r2(c.x)} ${r2(c.y)}" fill="none" stroke="${sVar(c.branch % 10)}" stroke-width="${r2(width)}" stroke-linecap="round"/>`);
197
+ walk(c, cp);
198
+ }
199
+ };
200
+ walk(root, root.label);
201
+ const ra = interactive ? nodeIA(root.label, root) : '';
202
+ out.push(`<g${ra}><rect x="${r2(root.x - 10)}" y="${r2(root.y - 13)}" width="${r2(root.w + 20)}" height="26" rx="13" fill="var(--d-ink)"/>` +
203
+ `<text x="${r2(root.x)}" y="${r2(root.y)}" dominant-baseline="middle" font-size="${ROOT_FS}" font-weight="600" fill="var(--d-card)">${esc(root.label)}</text></g>`);
204
+ const walkText = (n, path) => {
205
+ for (const c of n.children) {
206
+ const cp = `${path}/${c.label}`;
207
+ const attrs = c.depth === 1 ? `font-weight="600" fill="${sVar(c.branch % 10)}"` : `fill="var(--d-text)"`;
208
+ const ia = interactive ? nodeIA(cp, c) : '';
209
+ out.push(`<g${ia}><text x="${r2(c.x)}" y="${r2(c.y)}" dominant-baseline="middle" font-size="${NODE_FS}" ${attrs}>${esc(c.label)}</text></g>`);
210
+ walkText(c, cp);
211
+ }
212
+ };
213
+ walkText(root, root.label);
214
+ return { svg: out.join(''), W, H };
215
+ }
216
+ // ── tree:盒节点 + 直角肘形 ────────────────────────────────────────────────
217
+ function drawTree(root, interactive = false) {
218
+ const { W, H } = layoutLinear(root, measure(root, true));
219
+ const out = [];
220
+ const right = (n) => n.x + n.w; // 盒右缘(x 已含 BOX_PAD*2)
221
+ const left = (n) => n.x;
222
+ const walk = (n, path) => {
223
+ for (const c of n.children) {
224
+ const midX = (right(n) + left(c)) / 2;
225
+ const d = `M${r2(right(n))} ${r2(n.y)}H${r2(midX)}V${r2(c.y)}H${r2(left(c))}`;
226
+ const cp = `${path}/${c.label}`;
227
+ const ia = interactive ? ` data-link="${esc(cp)}"` : '';
228
+ out.push(`<path${ia} d="${d}" fill="none" stroke="${sVar(c.branch % 10)}" stroke-width="1.4"/>`);
229
+ walk(c, cp);
230
+ }
231
+ };
232
+ walk(root, root.label);
233
+ const box = (n, fill, stroke, textFill, bold, ia = '') => {
234
+ out.push(`<g${ia}><rect x="${r2(n.x)}" y="${r2(n.y - BOX_H / 2)}" width="${r2(n.w)}" height="${BOX_H}" rx="6" fill="${fill}" stroke="${stroke}" stroke-width="1"/>`);
235
+ out.push(`<text x="${r2(n.x + n.w / 2)}" y="${r2(n.y)}" dominant-baseline="middle" text-anchor="middle" font-size="${NODE_FS}"${bold ? ' font-weight="600"' : ''} fill="${textFill}">${esc(n.label)}</text></g>`);
236
+ };
237
+ // 根:大号 ink 胶囊
238
+ const ra = interactive ? nodeIA(root.label, root) : '';
239
+ out.push(`<g${ra}><rect x="${r2(root.x)}" y="${r2(root.y - 16)}" width="${r2(root.w)}" height="32" rx="16" fill="var(--d-ink)"/>` +
240
+ `<text x="${r2(root.x + root.w / 2)}" y="${r2(root.y)}" dominant-baseline="middle" text-anchor="middle" font-size="${ROOT_FS}" font-weight="600" fill="var(--d-card)">${esc(root.label)}</text></g>`);
241
+ const walkBox = (n, path) => {
242
+ for (const c of n.children) {
243
+ const cp = `${path}/${c.label}`;
244
+ if (c.depth === 1)
245
+ box(c, sVar(c.branch % 10), 'none', onVar(c.branch % 10), true, interactive ? nodeIA(cp, c) : '');
246
+ else
247
+ box(c, 'var(--d-card)', 'var(--d-border)', 'var(--d-text)', false, interactive ? nodeIA(cp, c) : '');
248
+ walkBox(c, cp);
249
+ }
250
+ };
251
+ walkBox(root, root.label);
252
+ return { svg: out.join(''), W, H };
253
+ }
254
+ // ── radial:根居中,扇形辐射 ────────────────────────────────────────────────
255
+ function drawRadial(root, interactive = false) {
256
+ const colW = measure(root, false);
257
+ const { W, H, dx, dy } = layoutRadial(root, colW);
258
+ const out = [];
259
+ const walk = (n, path) => {
260
+ for (const c of n.children) {
261
+ // 控制点取两代半径中点、各自角度 → 螺旋感平滑曲线
262
+ const rr = (d) => (d === 0 ? 0 : radiusOf(colW, d));
263
+ const aP = n.depth === 0 ? c.angle : n.angle;
264
+ const midR = (rr(n.depth) + rr(c.depth)) / 2;
265
+ const c1 = pol(midR, aP);
266
+ const c2 = pol(midR, c.angle);
267
+ const p0 = pol(rr(n.depth), aP);
268
+ const p1 = pol(rr(c.depth), c.angle);
269
+ const width = Math.max(1.2, 2.4 - c.depth * 0.4);
270
+ const cp = `${path}/${c.label}`;
271
+ const ia = interactive ? ` data-link="${esc(cp)}"` : '';
272
+ out.push(`<path${ia} d="M${r2(p0[0])} ${r2(p0[1])}C${r2(c1[0])} ${r2(c1[1])},${r2(c2[0])} ${r2(c2[1])},${r2(p1[0])} ${r2(p1[1])}" fill="none" stroke="${sVar(c.branch % 10)}" stroke-width="${r2(width)}" stroke-linecap="round"/>`);
273
+ walk(c, cp);
274
+ }
275
+ };
276
+ walk(root, root.label);
277
+ const ra = interactive ? nodeIA(root.label, root) : '';
278
+ out.push(`<g${ra}><rect x="${r2(root.x - 10)}" y="${r2(root.y - 13)}" width="${r2(root.w + 20)}" height="26" rx="13" fill="var(--d-ink)"/>` +
279
+ `<text x="${r2(root.x)}" y="${r2(root.y)}" dominant-baseline="middle" font-size="${ROOT_FS}" font-weight="600" fill="var(--d-card)">${esc(root.label)}</text></g>`);
280
+ const walkText = (n, path) => {
281
+ for (const c of n.children) {
282
+ const cp = `${path}/${c.label}`;
283
+ const attrs = c.depth === 1 ? `font-weight="600" fill="${sVar(c.branch % 10)}"` : `fill="var(--d-text)"`;
284
+ const ia = interactive ? nodeIA(cp, c) : '';
285
+ out.push(`<g${ia}><text x="${r2(c.x)}" y="${r2(c.y)}" text-anchor="${c.anchor}" dominant-baseline="middle" font-size="${NODE_FS}" ${attrs}>${esc(c.label)}</text></g>`);
286
+ walkText(c, cp);
287
+ }
288
+ };
289
+ walkText(root, root.label);
290
+ // 角度→坐标在 layoutRadial 已完成;此处的 pol 只服务连线控制点
291
+ return { svg: `<g transform="translate(${r2(dx)} ${r2(dy)})">${out.join('')}</g>`, W, H };
292
+ }
293
+ // ── bubble:现代胶囊风(XMind/MindMeister 主流主题方向)──────────────────
294
+ // 全盒节点:根=ink 胶囊、一级分支=分支色实心胶囊(反色字)、后代=同色 12% 淡填充;
295
+ // 连线为分支色贝塞尔,近根粗、远端细(视觉重心在主干)
296
+ function drawBubble(root, interactive = false) {
297
+ const { W, H } = layoutLinear(root, measure(root, true));
298
+ const out = [];
299
+ const walk = (n, path) => {
300
+ for (const c of n.children) {
301
+ const cp = `${path}/${c.label}`;
302
+ const ia = interactive ? ` data-link="${esc(cp)}"` : '';
303
+ const px = n.x + n.w;
304
+ const mx = (px + c.x) / 2;
305
+ const width = Math.max(1.4, 3.4 - c.depth * 0.7);
306
+ out.push(`<path${ia} d="M${r2(px)} ${r2(n.y)}C${r2(mx)} ${r2(n.y)},${r2(mx)} ${r2(c.y)},${r2(c.x)} ${r2(c.y)}" fill="none" stroke="${sVar(c.branch % 10)}" stroke-width="${r2(width)}" stroke-linecap="round"/>`);
307
+ walk(c, cp);
308
+ }
309
+ };
310
+ walk(root, root.label);
311
+ const pill = (n, path) => {
312
+ const ia = interactive ? nodeIA(path, n) : '';
313
+ if (n.depth === 0) {
314
+ out.push(`<g${ia}><rect x="${r2(n.x)}" y="${r2(n.y - 16)}" width="${r2(n.w)}" height="32" rx="16" fill="var(--d-ink)"/><text x="${r2(n.x + n.w / 2)}" y="${r2(n.y)}" dominant-baseline="middle" text-anchor="middle" font-size="${ROOT_FS}" font-weight="600" fill="var(--d-card)">${esc(n.label)}</text></g>`);
315
+ }
316
+ else if (n.depth === 1) {
317
+ out.push(`<g${ia}><rect x="${r2(n.x)}" y="${r2(n.y - BOX_H / 2)}" width="${r2(n.w)}" height="${BOX_H}" rx="12" fill="${sVar(n.branch % 10)}"/><text x="${r2(n.x + n.w / 2)}" y="${r2(n.y)}" dominant-baseline="middle" text-anchor="middle" font-size="${NODE_FS}" font-weight="600" fill="${onVar(n.branch % 10)}">${esc(n.label)}</text></g>`);
318
+ }
319
+ else {
320
+ out.push(`<g${ia}><rect x="${r2(n.x)}" y="${r2(n.y - BOX_H / 2)}" width="${r2(n.w)}" height="${BOX_H}" rx="12" fill="${sVar(n.branch % 10)}" fill-opacity="0.12"/><text x="${r2(n.x + n.w / 2)}" y="${r2(n.y)}" dominant-baseline="middle" text-anchor="middle" font-size="${NODE_FS}" fill="var(--d-ink)">${esc(n.label)}</text></g>`);
321
+ }
322
+ n.children.forEach(c => pill(c, `${path}/${c.label}`));
323
+ };
324
+ pill(root, root.label);
325
+ return { svg: out.join(''), W, H };
326
+ }
327
+ const pol = (r, a) => [r * Math.cos(a), r * Math.sin(a)];
328
+ function radiusOf(colW, d) {
329
+ let r = 0;
330
+ for (let k = 1; k <= d; k++)
331
+ r += (colW[k - 1] ?? 0) + RAD_GAP;
332
+ return r;
333
+ }
334
+ /**
335
+ * Render a mindmap from a URL's query params (`/draw/mindmap`).
336
+ *
337
+ * Each repeated `n=` carries one root-to-leaf path (`Product/Features/Speed`);
338
+ * shared prefixes merge. `style` picks the form: `organic` (bezier + text,
339
+ * default), `tree` (boxes + elbows), `radial` (root-centred fan). Throws
340
+ * ApiError(400) with a corrective example on malformed params.
341
+ */
342
+ export function renderMindmapFromUrl(url, interactive = false) {
343
+ const params = url.searchParams;
344
+ const paths = params.getAll('n');
345
+ if (!paths.length)
346
+ bad('at least one n=<path> is required');
347
+ const styleParam = params.get('style') ?? 'organic';
348
+ if (!STYLES.includes(styleParam))
349
+ bad(`unknown style "${styleParam}" (one of ${STYLES.join('|')})`);
350
+ const style = styleParam;
351
+ const root = buildTree(paths);
352
+ if (!root.children.length)
353
+ bad('the root needs at least one branch (path depth ≥ 2)');
354
+ const title = params.get('title')?.trim() || undefined;
355
+ const v = resolveVersion(params.get('v'));
356
+ const skin = resolveSkin('sankey', params.get('t'), schemeParam(params));
357
+ const { svg: body, W, H } = style === 'tree'
358
+ ? drawTree(root, interactive)
359
+ : style === 'radial'
360
+ ? drawRadial(root, interactive)
361
+ : style === 'bubble'
362
+ ? drawBubble(root, interactive)
363
+ : drawOrganic(root, interactive);
364
+ // 无标题也留 30px 角标带(#44):Edit 胶囊占右上 y≈25–45,不留带会压住顶部节点
365
+ const titleH = title ? 40 : 30;
366
+ const width = Math.max(W, clampInt(params, 'w', 0, 200, 2400));
367
+ const height = Math.max(H + titleH, clampInt(params, 'h', 0, 140, 2000));
368
+ const titleSvg = title
369
+ ? `<text x="${PAD}" y="${PAD + 14}" font-size="18" font-weight="500" letter-spacing="-0.02em" fill="var(--d-ink)">${esc(title)}</text>`
370
+ : '';
371
+ // interactive 悬停强调 + 点击整棵子树高亮(前缀匹配);脚本在 explore 落地页。
372
+ // 悬停 = 提亮(盒) + 下划线(文字);选中 = 下划线 + 未选中淡化;不用 transform
373
+ // (会被入场动画 fill-both 终态锁死)
374
+ const iStyle = interactive
375
+ ? `<style>#mm [data-node]{cursor:pointer;transition:filter .12s ease,opacity .15s ease}` +
376
+ `#mm [data-node]:focus{outline:none}` +
377
+ `#mm [data-node]:hover,#mm [data-node]:focus-visible{filter:brightness(1.2)}` +
378
+ `#mm [data-node]:hover text,#mm [data-node]:focus-visible text{text-decoration:underline}` +
379
+ `#mm.hl [data-node]{opacity:.42}#mm.hl [data-node].on{opacity:1}` +
380
+ `#mm.hl [data-node].on text{text-decoration:underline}` +
381
+ `#mm.hl path[data-link]{opacity:.2}#mm.hl path[data-link].on{opacity:1}</style>`
382
+ : '';
383
+ const inner = iStyle + `<g id="mm">` + body + `</g>`;
384
+ const children = titleH ? titleSvg + `<g transform="translate(0 ${titleH})">` + inner + `</g>` : inner;
385
+ const spec = { type: 'mindmap', style, ...(title ? { title } : {}), paths };
386
+ const svg = svgDoc(width, height, 'mindmap', v.version, title ?? `mindmap: ${root.label}`, spec, skin, children, url.search);
387
+ return { svg, version: v.version, cacheControl: v.cacheControl };
388
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * 机构剪影的路径(24×24 网格)。
3
+ * 墙体带门廊缺口;四扇窗是 evenodd 的洞。
4
+ */
5
+ export declare const GROUP_ICON_D: string;
6
+ /** 视图框边长(路径按这个网格画)。 */
7
+ export declare const GROUP_ICON_VIEW = 24;
8
+ /**
9
+ * 画组图标:在 (x, y) 处画一个 size×size 的方框。
10
+ * @param fill 填充色(通常是节点的语义色)
11
+ */
12
+ export declare function groupIcon(x: number, y: number, size: number, fill: string): string;
@@ -0,0 +1,31 @@
1
+ // 组图标:「公司/机构」的通用字形 —— 自绘,不对应任何一家公司。
2
+ //
3
+ // 为什么自绘:公开层要画它。`org:` 前缀的图标在内部图库里(私有仓),公开请求查不到,
4
+ // 于是画这个。**公开层的输出里一个第三方商标图形都不能有** —— 所以它是我们自己的美术,
5
+ // 不是任何品牌的 logo,也不进任何"图标素材库"。
6
+ //
7
+ // 画法:24×24 的**平顶办公楼**剪影(墙体 + 四扇窗 + 门廊缺口)。平顶才像"机构/公司",
8
+ // 坡屋顶会读成"房子" —— 在域名后缀的图里恰恰是最不该出现的联想。
9
+ // 单色填充,颜色跟节点的语义色走(var(--d-sN);中性类型则是 var(--d-muted)),
10
+ // 明暗两套皮肤都合适,也跟图里的类型配色一致 —— 它看着像个正经元素,不像"图片挂了"。
11
+ //
12
+ // 授权层(登录后)命中内部图库时,由调用方把节点换成真 logo;组图标只在没有真 logo 时出现。
13
+ import { r2 } from './svg.js';
14
+ /**
15
+ * 机构剪影的路径(24×24 网格)。
16
+ * 墙体带门廊缺口;四扇窗是 evenodd 的洞。
17
+ */
18
+ export const GROUP_ICON_D = 'M5 4h14v18h-5v-5h-4v5H5V4Z' +
19
+ 'M7.5 7h3v2.5h-3ZM13.5 7h3v2.5h-3Z' +
20
+ 'M7.5 11.5h3v2.5h-3ZM13.5 11.5h3v2.5h-3Z';
21
+ /** 视图框边长(路径按这个网格画)。 */
22
+ export const GROUP_ICON_VIEW = 24;
23
+ /**
24
+ * 画组图标:在 (x, y) 处画一个 size×size 的方框。
25
+ * @param fill 填充色(通常是节点的语义色)
26
+ */
27
+ export function groupIcon(x, y, size, fill) {
28
+ const s = size / GROUP_ICON_VIEW;
29
+ return `<g transform="translate(${r2(x)} ${r2(y)}) scale(${r2(s)})">` +
30
+ `<path d="${GROUP_ICON_D}" fill="${fill}" fill-rule="evenodd"/></g>`;
31
+ }
@@ -79,7 +79,7 @@ export function segPath(cx, cy, R, r, a0, a1, corner) {
79
79
  `${filletArc(oeO, oeC, oeR, c)}L${PT(ieR)}${filletArc(ieR, ieC, ieI, c)}` +
80
80
  `A${r2(r)} ${r2(r)} 0 ${large} 1 ${PT(isI)}${filletArc(isI, isC, isR, c)}Z`);
81
81
  }
82
- const HALO_ATTRS = 'paint-order="stroke" stroke="var(--d-halo)" stroke-width="3" stroke-linejoin="round"';
82
+ const HALO_ATTRS = ''; // 描边已按 2026-11-03 决定移除
83
83
  /**
84
84
  * Donut chart (solid pie with `o.donut = false`); label placement follows the skin.
85
85
  */
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Bake a rendered SVG into a flat SVG: resolve every `var(--d-*)` to a concrete
3
+ * color for the given scheme and strip all `<style>` blocks (skin vars, font
4
+ * faces, hover CSS). Works on any renderer's output — core, echarts, archmap,
5
+ * mindmap — because the var table is parsed from the SVG itself.
6
+ */
7
+ export declare function bakeFlatSvg(svg: string, scheme: 'light' | 'dark'): string;
8
+ /** Workers 入口专用:把打包期拿到的 wasm Module 注入(见 src/index.ts)。 */
9
+ export declare function injectResvgWasm(mod: WebAssembly.Module): void;
10
+ export interface PngOptions {
11
+ /** 像素倍率(2 = retina);画布尺寸取 SVG 固有 width/height × scale */
12
+ scale?: number;
13
+ }
14
+ /**
15
+ * Rasterize a rendered draw SVG to PNG. The SVG is baked flat for `scheme`
16
+ * first (var() colors resolved, style blocks stripped), then rendered by
17
+ * resvg with the repo's embedded Inter/Handlee subsets.
18
+ *
19
+ * @throws ApiError(400/500) when the rasterizer is unavailable or fails
20
+ */
21
+ export declare function svgToPng(svg: string, scheme: 'light' | 'dark', opts?: PngOptions): Promise<Uint8Array>;
@@ -0,0 +1,109 @@
1
+ // PNG 导出层(x-cmd-hub/draw#24):SVG → 渲染期烘焙 → resvg-wasm 光栅化。
2
+ //
3
+ // 烘焙 = 从 SVG 自带的皮肤 <style> 解析 var→色值映射(亮/暗两套),按 scheme 固化,
4
+ // 替换全部 var() 引用并剥离 <style>(含 @font-face 与 echarts 的 hover CSS——光栅
5
+ // 化都不需要)。这对核心手写层 / echarts / archmap / mindmap / 短链的全部产出通用,
6
+ // 渲染器零改动。位图没有"自适应明暗",PNG 强制固化 scheme(缺省 light)。
7
+ //
8
+ // resvg-wasm 是仓库第一个 wasm 依赖,全运行时同一份(Node/Deno/Workers),lazy init:
9
+ // Node/Deno 从 node_modules 读 index_bg.wasm(exports 显式暴露该子路径);
10
+ // Workers 由入口(src/index.ts)静态 import 拿 WebAssembly.Module 后注入 —— 两种
11
+ // 来源 initWasm 通吃。字体喂仓内 base64 TTF 子集(Inter + 手绘 Handlee;fontdb
12
+ // 不认 woff2,故用 fonts-ttf.ts 的解压版,家族名同源),不读系统字体(wasm 沙盒内
13
+ // 本就无系统字体)。中文另有 Noto Sans SC 子集(GB2312 一级 3755 字 + 中文标点,
14
+ // 见 fonts-cjk.ts):SVG 里出现 CJK 才挂载 —— 拉丁图表的 PNG 不付那 2.3MB;
15
+ // 子集外的生僻字仍无字形(#24 已知边界)。
16
+ import { ApiError } from '../specs/index.js';
17
+ import { INTER_TTF_B64, HANDEE_TTF_B64 } from '../styles/fonts-ttf.js';
18
+ import { FONT_FILES_B64 } from '../styles/fonts-banner.js';
19
+ import { CJK_REGULAR_TTF_B64, CJK_BOLD_TTF_B64 } from '../styles/fonts-cjk.js';
20
+ // ── 烘焙:var() → 具体色值,产出平面 SVG ─────────────────────────────────────
21
+ // Edit @X-CMD 角标已上移至 svgDoc(核心/archmap/mindmap)与 decorate(echarts),
22
+ // SVG 层统一注入 → PNG 烘焙后自动保留,此处不再重复注入(#27)
23
+ /**
24
+ * Bake a rendered SVG into a flat SVG: resolve every `var(--d-*)` to a concrete
25
+ * color for the given scheme and strip all `<style>` blocks (skin vars, font
26
+ * faces, hover CSS). Works on any renderer's output — core, echarts, archmap,
27
+ * mindmap — because the var table is parsed from the SVG itself.
28
+ */
29
+ export function bakeFlatSvg(svg, scheme) {
30
+ const styles = [...svg.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)].map((m) => m[1]).join('\n');
31
+ const lightCss = styles.replace(/@media[\s\S]*$/, ''); // @media(prefers-color-scheme: dark){...} 截掉
32
+ const darkCss = /@media[^{]*prefers-color-scheme[^{]*\{([\s\S]*)\}\s*$/.exec(styles)?.[1] ?? '';
33
+ const varsOf = (css) => {
34
+ const m = {};
35
+ for (const [, k, v] of css.matchAll(/(--d-[a-z0-9-]+)\s*:\s*([^;}]+)/g))
36
+ m[k] = v.trim();
37
+ return m;
38
+ };
39
+ const map = varsOf(lightCss); // 单 scheme 渲染(scheme=dark)时唯一一套即暗色
40
+ if (scheme === 'dark')
41
+ Object.assign(map, varsOf(darkCss));
42
+ let out = svg.replace(/<style[^>]*>[\s\S]*?<\/style>/g, '');
43
+ for (const [k, v] of Object.entries(map)) {
44
+ out = out.replaceAll(`var(${k})`, v); // 闭括号定界,var(--d-s1) 不会误伤 var(--d-s10)
45
+ }
46
+ return out;
47
+ }
48
+ // ── wasm 引擎:一次 init,四运行时 ──────────────────────────────────────────
49
+ let injected; // Workers 入口注入(打包期静态 import)
50
+ let engine;
51
+ /** Workers 入口专用:把打包期拿到的 wasm Module 注入(见 src/index.ts)。 */
52
+ export function injectResvgWasm(mod) {
53
+ injected = mod;
54
+ }
55
+ async function wasmSource() {
56
+ if (injected !== undefined)
57
+ return injected;
58
+ // Node / Deno:exports 显式暴露 ./index_bg.wasm,resolve 后读文件
59
+ const { createRequire } = await import('node:module');
60
+ const { readFileSync } = await import('node:fs');
61
+ const req = createRequire(import.meta.url);
62
+ return readFileSync(req.resolve('@resvg/resvg-wasm/index_bg.wasm'));
63
+ }
64
+ function resvgEngine() {
65
+ engine ??= (async () => {
66
+ const m = await import('@resvg/resvg-wasm');
67
+ await m.initWasm(await wasmSource());
68
+ return m;
69
+ })();
70
+ return engine;
71
+ }
72
+ // base64 TTF → 字节(与 SVG 内嵌 woff2 子集同源,宽度测量与渲染零偏差)
73
+ const fontBytes = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
74
+ let fonts;
75
+ /**
76
+ * Rasterize a rendered draw SVG to PNG. The SVG is baked flat for `scheme`
77
+ * first (var() colors resolved, style blocks stripped), then rendered by
78
+ * resvg with the repo's embedded Inter/Handlee subsets.
79
+ *
80
+ * @throws ApiError(400/500) when the rasterizer is unavailable or fails
81
+ */
82
+ export async function svgToPng(svg, scheme, opts = {}) {
83
+ const scale = opts.scale ?? 1;
84
+ if (!(scale >= 1 && scale <= 3)) {
85
+ throw new ApiError(400, `"scale" must be between 1 and 3, got ${JSON.stringify(scale)}`);
86
+ }
87
+ fonts ??= [fontBytes(INTER_TTF_B64), fontBytes(HANDEE_TTF_B64), ...FONT_FILES_B64.map((f) => fontBytes(f.native))];
88
+ // CJK 按需挂载:SVG 含 CJK 才解码 Noto 子集(2.3MB),拉丁图表的 PNG 不付这笔内存/时间
89
+ if (/[⺀-鿿 -〿＀-￯]/.test(svg))
90
+ fonts = [...fonts, fontBytes(CJK_REGULAR_TTF_B64), fontBytes(CJK_BOLD_TTF_B64)];
91
+ let Resvg;
92
+ try {
93
+ ({ Resvg } = await resvgEngine());
94
+ }
95
+ catch (e) {
96
+ throw new ApiError(500, `png engine failed to load (${e instanceof Error ? e.message : 'wasm init error'})`);
97
+ }
98
+ try {
99
+ const r = new Resvg(bakeFlatSvg(svg, scheme), {
100
+ fitTo: scale === 1 ? { mode: 'original' } : { mode: 'zoom', value: scale },
101
+ background: 'rgba(0,0,0,0)',
102
+ font: { fontBuffers: fonts, defaultFontFamily: 'DrawInter', loadSystemFonts: false },
103
+ });
104
+ return r.render().asPng();
105
+ }
106
+ catch (e) {
107
+ throw new ApiError(400, `png rendering failed: ${e instanceof Error ? e.message : String(e)}`);
108
+ }
109
+ }
@@ -0,0 +1,6 @@
1
+ import type { QuadrantSpec } from '../specs/index.js';
2
+ import { type RenderOpts } from './svg.js';
3
+ /**
4
+ * Quadrant chart: a 2×2 matrix (box) or a two-axis cross, with optional points.
5
+ */
6
+ export declare function renderQuadrant(spec: QuadrantSpec, o: RenderOpts): string;