@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,1011 @@
1
+ // /draw/arch —— 架构图 v2:同一套 URL 模型(data 和布局都写在 URL 里),换一张更像架构图的脸。
2
+ //
3
+ // 与 /draw/archmap 的关系:模型一模一样(n=/e=/b=),只是长相不同:
4
+ // - 节点按语义类型着色(淡填色 + 同色描边),不再是一根色条
5
+ // - 左上角一个类型角标(F/B/D/C/S/M/V/X)
6
+ // - 底部一行图例:类型 + 个数
7
+ // - 轨道间距、节点尺寸、画布留白都更松,图能撑到该有的那么大
8
+ // - 边标签带底衬,线不再从字上穿过
9
+ // - 边界用虚线框 + 标签胶囊
10
+ //
11
+ // 老路径 /draw/archmap 一行未动(它的输出与 v2 之前逐字节相同)。
12
+ import { ApiError } from '../specs/index.js';
13
+ import { packGrid, parseBoundaries, parseEdges, parseNodes, TYPE_COLOR, } from './archmap.js';
14
+ import { gridLayout, labelGaps } from './layout.js';
15
+ import { routeEdges } from './route.js';
16
+ import { resolveSkin } from '../styles/index.js';
17
+ import { clampInt, dirParam, schemeParam } from './query.js';
18
+ import { esc, r2, roundedPath, svgDoc, textW, trunc } from './svg.js';
19
+ import { iconOf } from './icons.js';
20
+ import { groupIcon } from './orgicon.js';
21
+ /**
22
+ * `org:` 前缀 = 公司/机构图标。那族图标在私有仓的内部图库里(商标图形不能公开分发),
23
+ * 公开请求查不到 → 画组图标(自绘的通用机构剪影),不是"图片挂了"。
24
+ * 其余前缀(aws/azure/gcp)是云服务图标,公开可用,行为不变。
25
+ */
26
+ const isOrgIcon = (name) => name.startsWith('org:');
27
+ /* ---------------------------------------------------------------- 视觉常量 */
28
+ const PAD = 44; // 画布留白
29
+ const GAP_X = 64; // 轨道横距
30
+ const GAP_Y = 56; // 轨道纵距
31
+ const LEGEND_H = 46; // 图例带的高度
32
+ const NODE_MIN_W = 176;
33
+ const NODE_R = 12; // 节点圆角
34
+ const BADGE = 20; // 角标边长
35
+ const LABEL_FS = 14; // 节点标题字号
36
+ const SUB_FS = 11.5; // 节点副标题字号
37
+ const EDGE_FS = 11.5; // 边标签字号
38
+ /** 语义类型 → (展示名, 角标字母) */
39
+ export const TYPE_META = {
40
+ fe: { name: 'Frontend', badge: 'F', color: 0 },
41
+ be: { name: 'Backend', badge: 'B', color: 1 },
42
+ db: { name: 'Database', badge: 'D', color: 2 },
43
+ cloud: { name: 'Cloud', badge: 'C', color: 3 },
44
+ sec: { name: 'Security', badge: 'S', color: 4 },
45
+ bus: { name: 'Message bus', badge: 'M', color: 5 },
46
+ svc: { name: 'Service', badge: 'V', color: 6 },
47
+ ext: { name: 'External', badge: 'X', color: -1 },
48
+ };
49
+ const TYPE_ORDER = ['fe', 'be', 'db', 'cloud', 'sec', 'bus', 'svc', 'ext'];
50
+ /** 架构图这套词汇(别的图种传自己的一套进来) */
51
+ export const ARCH_TYPES = { meta: TYPE_META, order: [...TYPE_ORDER] };
52
+ /** 云架构(大图标版):节点就是图标,名字在下面 —— diagrams + 那种海报的画法 */
53
+ export const CLOUD_TYPES = { ...ARCH_TYPES, icons: 'big' };
54
+ const sVar = (i) => `var(--d-s${i + 1})`;
55
+ /** v2 的节点尺寸:更宽更松,标题 14px;副标题多行时按行数长高 */
56
+ // 大图标节点的排版:图标 → 名字 → 副标题,每一步都留够空当
57
+ // (图标底到名字的字头 10px;名字的伸部到副标题的字头 7px)
58
+ const ICON_BIG = 64; // 图标边长
59
+ const ICON_GAP = 10; // 图标底 → 名字字头
60
+ const CAP = (fs) => fs * 0.72; // 字头高
61
+ const DESC = (fs) => fs * 0.22; // 伸部高
62
+ const ICON_NAME_DY = ICON_BIG + ICON_GAP + CAP(14); // 名字基线(相对框顶)
63
+ const ICON_SUB_DY = ICON_NAME_DY + DESC(14) + 7 + CAP(11.5); // 副标题基线
64
+ /** 节点副标题可以多行(用 \n 分隔)—— ERD 的字段表、class 的成员表靠它 */
65
+ const linesOf = (n) => n.sub ? n.sub.split('\n').filter((l) => l !== '') : [];
66
+ const v2Size = (n, types) => {
67
+ if (types.rows === 'fields')
68
+ return fieldsSize(n);
69
+ const lines = linesOf(n);
70
+ // 大图标节点:图标占一块,名字在下面 —— 宽度由名字决定(图标不会更宽)
71
+ // 图标库里没有这个图标 → 按普通节点算,别在顶上留一块空地(很难看)
72
+ // (org: 查不到也有图标 —— 画组图标,节点还是图标节点,不是普通方框)
73
+ if (types.icons === 'big' && n.icon && (n.iconData || isOrgIcon(n.icon))) {
74
+ const w = Math.max(ICON_BIG, textW(n.label, LABEL_FS) + 8, ...lines.map((l) => textW(l, SUB_FS) + 8));
75
+ const h = n.sub ? ICON_SUB_DY + DESC(11.5) + 4 : ICON_NAME_DY + DESC(14) + 4;
76
+ return { w, h };
77
+ }
78
+ const w = Math.max(NODE_MIN_W, textW(n.label, LABEL_FS) + 52, ...lines.map((l) => textW(l, SUB_FS) + 52));
79
+ const h = lines.length > 1 ? 34 + lines.length * 17 : n.sub ? 62 : 48;
80
+ return { w: Math.min(w, 420), h };
81
+ };
82
+ const KEY_MARK_RE = /\((pk|fk|uk)\)\s*$/i;
83
+ const VIS_MARK_RE = /^([+\-#])\s+/;
84
+ /**
85
+ * 解析字段表的一行:
86
+ * id:int (pk) → 名字 id,类型 int,主键
87
+ * user_id:int (fk) → 外键
88
+ * + gateway: Payment → UML 公有成员
89
+ * greet(): void → 方法
90
+ * charge(amount: Money): Result → 参数里的冒号不算,类型是 Result
91
+ */
92
+ function parseFieldRow(line) {
93
+ let s = line.trim();
94
+ const row = { name: s };
95
+ const vm = VIS_MARK_RE.exec(s);
96
+ if (vm) {
97
+ row.vis = vm[1];
98
+ s = s.slice(vm[0].length).trim();
99
+ }
100
+ const km = KEY_MARK_RE.exec(s);
101
+ if (km) {
102
+ row.key = km[1].toLowerCase();
103
+ s = s.slice(0, km.index).trim();
104
+ }
105
+ // 括号外的第一个冒号才是「名字 : 类型」的分界
106
+ let depth = 0;
107
+ let ci = -1;
108
+ for (let i = 0; i < s.length; i++) {
109
+ const ch = s[i];
110
+ if (ch === '(' || ch === '<' || ch === '[')
111
+ depth++;
112
+ else if (ch === ')' || ch === '>' || ch === ']')
113
+ depth--;
114
+ else if (ch === ':' && depth === 0) {
115
+ ci = i;
116
+ break;
117
+ }
118
+ }
119
+ row.name = ci < 0 ? s : s.slice(0, ci).trim();
120
+ const type = ci < 0 ? '' : s.slice(ci + 1).trim();
121
+ if (type)
122
+ row.type = type;
123
+ return row;
124
+ }
125
+ const fieldRowsOf = (n) => n.sub ? n.sub.split('\n').filter((l) => l.trim() !== '').map(parseFieldRow) : [];
126
+ const KEY_BADGE_W = 26; // 键标记(PK/FK/UK)那一列的宽
127
+ const VIS_W = 14; // 可见性标记那一列的宽
128
+ const ROW_H = 19; // 一行字段的高
129
+ const HEAD_H = 30; // 标题条的高
130
+ const COL_GAP = 18; // 名字列与类型列之间的空档
131
+ const ROW_TOP = HEAD_H + 16; // 第一行字段的基线:离标题条下沿留一口气(贴着看不清)
132
+ /** 字段表模式的节点尺寸:名字左、类型右,两列都要放得下 */
133
+ function fieldsSize(n) {
134
+ const rows = fieldRowsOf(n);
135
+ const keyCol = rows.some((r) => r.key) ? KEY_BADGE_W : 0;
136
+ const visCol = rows.some((r) => r.vis) ? VIS_W : 0;
137
+ const nameW = Math.max(0, ...rows.map((r) => textW(r.name, SUB_FS)));
138
+ const typeW = Math.max(0, ...rows.map((r) => textW(r.type ?? '', SUB_FS)));
139
+ const bodyW = keyCol + visCol + nameW + (typeW ? COL_GAP + typeW : 0);
140
+ const w = Math.max(NODE_MIN_W, textW(n.label, LABEL_FS) + 52, bodyW + 26);
141
+ const h = rows.length ? ROW_TOP + (rows.length - 1) * ROW_H + 12 : HEAD_H + 24;
142
+ return { w: Math.min(w, 460), h };
143
+ }
144
+ /* ---------------------------------------------------------------- 节点 */
145
+ function drawNodeV2(n, interactive, degree, types) {
146
+ const b = n.box;
147
+ const icon = n.iconData;
148
+ // org: 前缀但图库里查不到 → 组图标(公开层的默认长相:这是个机构,但不给你看 mark)
149
+ const orgFallback = !!n.icon && !icon && isOrgIcon(n.icon);
150
+ const meta = types.meta[n.type] ?? { name: n.type, badge: '?', color: -1 };
151
+ const neutral = meta.color < 0;
152
+ const color = neutral ? 'var(--d-muted)' : sVar(meta.color);
153
+ const fill = neutral ? 'var(--d-card)' : color;
154
+ const fillOp = neutral ? 1 : 0.1;
155
+ const strokeOp = neutral ? 1 : 0.5;
156
+ const dash = neutral ? ' stroke-dasharray="5 3"' : '';
157
+ const titleW = textW(n.label, LABEL_FS);
158
+ const subW = n.sub ? textW(n.sub, SUB_FS) : 0;
159
+ // 角标在左上角;标题居中,若会撞上角标就右移半个角标
160
+ const bx = b.x + 12;
161
+ const by = b.y + 12;
162
+ const badgeRight = bx + BADGE;
163
+ let tx = b.x + b.w / 2;
164
+ if (n.sub) {
165
+ if (tx - titleW / 2 < badgeRight + 6)
166
+ tx = badgeRight + 6 + titleW / 2;
167
+ }
168
+ else if (tx - titleW / 2 < badgeRight + 6 && bx < b.x + b.w / 2) {
169
+ tx = badgeRight + 6 + titleW / 2;
170
+ }
171
+ const lines = linesOf(n);
172
+ const titleY = n.sub ? b.y + 26 : b.y + b.h / 2 + 5;
173
+ const tip = `${n.label}${n.sub ? ` · ${n.sub.replace(/\n/g, ', ')}` : ''} · ${meta.name}${degree ? ` · ${degree} link${degree > 1 ? 's' : ''}` : ''}`;
174
+ const ia = interactive
175
+ ? ` data-node="${esc(n.id)}" data-tip="${esc(tip)}" tabindex="0"`
176
+ : '';
177
+ const badgeFill = neutral ? 'var(--d-muted)' : color;
178
+ const shape = types.shape?.[n.type] ?? 'rect';
179
+ const fillAttrs = ` fill="${fill}" fill-opacity="${fillOp}" stroke="${color}" stroke-opacity="${strokeOp}" stroke-width="1.3"${dash}`;
180
+ let frame;
181
+ if (shape === 'cylinder') {
182
+ const ry = 9;
183
+ frame =
184
+ `<path d="M${r2(b.x)} ${r2(b.y + ry)}A${r2(b.w / 2)} ${ry} 0 0 1 ${r2(b.x + b.w)} ${r2(b.y + ry)}V${r2(b.y + b.h - ry)}A${r2(b.w / 2)} ${ry} 0 0 1 ${r2(b.x)} ${r2(b.y + b.h - ry)}Z"${fillAttrs}/>` +
185
+ `<ellipse cx="${r2(b.x + b.w / 2)}" cy="${r2(b.y + ry)}" rx="${r2(b.w / 2)}" ry="${ry}" fill="none" stroke="${color}" stroke-opacity="${strokeOp}" stroke-width="1.3"/>`;
186
+ }
187
+ else if (shape === 'diamond') {
188
+ const cx = b.x + b.w / 2;
189
+ const cy = b.y + b.h / 2;
190
+ frame = `<polygon points="${r2(cx)},${r2(b.y)} ${r2(b.x + b.w)},${r2(cy)} ${r2(cx)},${r2(b.y + b.h)} ${r2(b.x)},${r2(cy)}"${fillAttrs}/>`;
191
+ }
192
+ else if (shape === 'round') {
193
+ frame = `<rect x="${r2(b.x)}" y="${r2(b.y)}" width="${r2(b.w)}" height="${r2(b.h)}" rx="${r2(b.h / 2)}"${fillAttrs}/>`;
194
+ }
195
+ else {
196
+ frame = `<rect x="${r2(b.x)}" y="${r2(b.y)}" width="${r2(b.w)}" height="${r2(b.h)}" rx="${NODE_R}"${fillAttrs}/>`;
197
+ }
198
+ // 字段表模式(ERD 的字段、class 的成员):标题条 + 一行一项
199
+ if (types.rows === 'fields') {
200
+ return drawFieldNodeV2(n, frame, badgeFill, color, neutral, meta, ia, titleW, badgeRight);
201
+ }
202
+ // 大图标模式(diagrams + 那种云架构海报):图标就是节点,名字在下面
203
+ if (types.icons === 'big' && (icon || orgFallback)) {
204
+ const ix = b.x + (b.w - ICON_BIG) / 2;
205
+ const name = trunc(n.label, 22);
206
+ const sub = n.sub ? trunc(n.sub, 26) : '';
207
+ // 名字垫一块画布色:竖着下来的连线会从名字后面过,垫一下字才读得清
208
+ const cw = Math.max(textW(name, LABEL_FS), sub ? textW(sub, SUB_FS) : 0) + 10;
209
+ const chip = (y, h) => `<rect x="${r2(b.x + b.w / 2 - cw / 2)}" y="${r2(y)}" width="${r2(cw)}" height="${r2(h)}" rx="4" fill="var(--d-card)"/>`;
210
+ // 没有真 logo → 组图标(自绘,跟节点的语义色走)
211
+ const graphic = icon
212
+ ? `<image href="${icon}" x="${r2(ix)}" y="${r2(b.y)}" width="${ICON_BIG}" height="${ICON_BIG}" preserveAspectRatio="xMidYMid meet"/>`
213
+ : groupIcon(ix, b.y, ICON_BIG, color);
214
+ return (`<g${ia}>` +
215
+ graphic +
216
+ chip(b.y + ICON_NAME_DY - 11, 15) +
217
+ `<text x="${r2(b.x + b.w / 2)}" y="${r2(b.y + ICON_NAME_DY)}" text-anchor="middle" font-size="${LABEL_FS}" font-weight="600" fill="var(--d-ink)">${esc(name)}</text>` +
218
+ (sub ? chip(b.y + ICON_SUB_DY - 9, 13) + `<text x="${r2(b.x + b.w / 2)}" y="${r2(b.y + ICON_SUB_DY)}" text-anchor="middle" font-size="${SUB_FS}" fill="var(--d-muted)">${esc(sub)}</text>` : '') +
219
+ `</g>`);
220
+ }
221
+ // 角标:有图标(diagrams 图标库)就用图标,没有才画类型字母
222
+ // org: 前缀查不到 → 角标位画组图标(自绘的机构剪影),不是类型字母
223
+ const badge = icon
224
+ ? `<image href="${icon}" x="${r2(bx - 2)}" y="${r2(by - 2)}" width="${r2(BADGE + 4)}" height="${r2(BADGE + 4)}" preserveAspectRatio="xMidYMid meet"/>`
225
+ : orgFallback
226
+ ? groupIcon(bx, by, BADGE, color)
227
+ : `<rect x="${r2(bx)}" y="${r2(by)}" width="${BADGE}" height="${BADGE}" rx="6"` +
228
+ ` fill="${badgeFill}" fill-opacity="${neutral ? 0.18 : 0.2}" stroke="${badgeFill}" stroke-opacity="${neutral ? 0.5 : 0.55}" stroke-width="1"/>` +
229
+ `<text x="${r2(bx + BADGE / 2)}" y="${r2(by + BADGE / 2 + 3.6)}" text-anchor="middle" font-size="10.5" font-weight="700" fill="${color}">${esc(meta.badge)}</text>`;
230
+ return (`<g${ia}>` +
231
+ frame +
232
+ badge +
233
+ `<text x="${r2(tx)}" y="${r2(titleY)}" text-anchor="middle" font-size="${LABEL_FS}" font-weight="600" fill="var(--d-ink)">${esc(n.label)}</text>` +
234
+ (n.sub
235
+ ? lines.length
236
+ ? lines.map((l, i) => `<text x="${r2(b.x + b.w / 2)}" y="${r2(b.y + 44 + i * 17)}" text-anchor="middle" font-size="${SUB_FS}" fill="var(--d-muted)">${esc(l)}</text>`).join('')
237
+ : `<text x="${r2(b.x + b.w / 2)}" y="${r2(b.y + 44)}" text-anchor="middle" font-size="${SUB_FS}" fill="var(--d-muted)">${esc(n.sub)}</text>`
238
+ : '') +
239
+ `</g>`);
240
+ }
241
+ /**
242
+ * 字段表节点(ERD 的表、class 的类):标题条 + 一行一项
243
+ * —— 键标记(PK/FK/UK)在最左,名字靠左,类型靠右(等宽字体,一眼能对上行)。
244
+ */
245
+ function drawFieldNodeV2(n, frame, badgeFill, color, neutral, meta, ia, titleW, badgeRight) {
246
+ const b = n.box;
247
+ const rows = fieldRowsOf(n);
248
+ const keyCol = rows.some((r) => r.key) ? KEY_BADGE_W : 0;
249
+ const visCol = rows.some((r) => r.vis) ? VIS_W : 0;
250
+ const nameX = b.x + 12 + keyCol + visCol;
251
+ const typeX = b.x + b.w - 12;
252
+ const parts = [];
253
+ // 标题条:上圆角、下直角,正好贴住盒子的上边
254
+ const barOp = neutral ? 0.1 : 0.16;
255
+ parts.push(`<path d="M${r2(b.x)} ${r2(b.y + NODE_R)}A${NODE_R} ${NODE_R} 0 0 1 ${r2(b.x + NODE_R)} ${r2(b.y)}` +
256
+ `H${r2(b.x + b.w - NODE_R)}A${NODE_R} ${NODE_R} 0 0 1 ${r2(b.x + b.w)} ${r2(b.y + NODE_R)}` +
257
+ `V${r2(b.y + HEAD_H)}H${r2(b.x)}Z" fill="${color}" fill-opacity="${barOp}"/>`);
258
+ // 角标 + 标题(标题左对齐,跟在角标后面)
259
+ const bx = b.x + 12;
260
+ const by = b.y + (HEAD_H - BADGE) / 2;
261
+ parts.push(`<rect x="${r2(bx)}" y="${r2(by)}" width="${BADGE}" height="${BADGE}" rx="6"` +
262
+ ` fill="${badgeFill}" fill-opacity="${neutral ? 0.18 : 0.2}" stroke="${badgeFill}" stroke-opacity="${neutral ? 0.5 : 0.55}" stroke-width="1"/>`, `<text x="${r2(bx + BADGE / 2)}" y="${r2(by + BADGE / 2 + 3.6)}" text-anchor="middle" font-size="10.5" font-weight="700" fill="${color}">${esc(meta.badge)}</text>`, `<text x="${r2(badgeRight + 8)}" y="${r2(b.y + HEAD_H / 2 + 5)}" font-size="${LABEL_FS}" font-weight="600" fill="var(--d-ink)">${esc(n.label)}</text>`);
263
+ // 字段行
264
+ rows.forEach((r, i) => {
265
+ const y = b.y + ROW_TOP + i * ROW_H;
266
+ let x = b.x + 12;
267
+ if (keyCol) {
268
+ if (r.key) {
269
+ const keyColor = r.key === 'pk' ? 'var(--d-s3)' : r.key === 'fk' ? 'var(--d-s5)' : 'var(--d-s4)';
270
+ parts.push(`<rect x="${r2(x)}" y="${r2(y - 8)}" width="21" height="12" rx="4" fill="${keyColor}" fill-opacity="0.18" stroke="${keyColor}" stroke-opacity="0.5" stroke-width="1"/>`, `<text x="${r2(x + 10.5)}" y="${r2(y + 1)}" text-anchor="middle" font-size="8" font-weight="700" letter-spacing="0.4" fill="${keyColor}">${esc(r.key.toUpperCase())}</text>`);
271
+ }
272
+ x += keyCol;
273
+ }
274
+ if (visCol) {
275
+ if (r.vis) {
276
+ parts.push(`<text x="${r2(x + 8)}" y="${r2(y)}" text-anchor="middle" font-size="11" font-weight="700" fill="var(--d-faint)">${esc(r.vis)}</text>`);
277
+ }
278
+ x += visCol;
279
+ }
280
+ parts.push(`<text x="${r2(nameX)}" y="${r2(y)}" font-size="${SUB_FS}" fill="var(--d-ink)">${esc(r.name)}</text>`);
281
+ if (r.type) {
282
+ parts.push(`<text x="${r2(typeX)}" y="${r2(y)}" text-anchor="end" font-size="${SUB_FS}" font-family="ui-monospace,SFMono-Regular,Menlo,monospace" fill="var(--d-muted)">${esc(r.type)}</text>`);
283
+ }
284
+ });
285
+ return `<g${ia}>` + frame + parts.join('') + `</g>`;
286
+ }
287
+ /**
288
+ * v2 的走线:几何交给布线内核(见 render/route.ts)。
289
+ *
290
+ * 内核只管「线怎么走」,这里的样式(线宽、箭头、虚实)还是渲染层的事 ——
291
+ * 引擎换不换,图的样子不变。
292
+ */
293
+ function computeRoutesV2(placed, edges, bounds = [], iconsBig = false, routing, dir = 'LR') {
294
+ // 大图标节点:连线只接图标那块(名字在图标下面,别从名字里穿过去)
295
+ //
296
+ // **端口要落在图标上**,不是落在格子上:格子是摆位留下的空位,通常比图标宽得多
297
+ // (一列对齐了就一样宽)。端口落在格子上,线就从图标旁边的空处冒出来 ——
298
+ // 看着像从虚空里长出来一根线(#29)。
299
+ const portBoxOf = (p) => {
300
+ if (!iconsBig)
301
+ return p.box;
302
+ if (!p.iconData && !(p.icon && isOrgIcon(p.icon)))
303
+ return p.box;
304
+ return { x: p.box.x + (p.box.w - ICON_BIG) / 2, y: p.box.y, w: ICON_BIG, h: ICON_BIG };
305
+ };
306
+ const byId = new Map(placed.map((p) => [p.id, p]));
307
+ const ctx = {
308
+ nodes: placed,
309
+ boxes: new Map(placed.map((p) => [p.id, p.box])),
310
+ edges,
311
+ bounds,
312
+ dir,
313
+ portBox: (id) => portBoxOf(byId.get(id)),
314
+ };
315
+ const paths = (routing ?? routeEdges)(ctx);
316
+ return edges.map((e, i) => {
317
+ const style = e.variant === 'main'
318
+ ? { stroke: 'var(--d-ink)', width: 1.8, marker: 'am-m', dash: '' }
319
+ : e.variant === 'dash'
320
+ ? { stroke: 'var(--d-faint)', width: 1.4, marker: 'am-d', dash: ' stroke-dasharray="5 4"' }
321
+ : { stroke: 'var(--d-muted)', width: 1.4, marker: 'am-p', dash: '' };
322
+ return { e, pts: paths[i] ?? [], ...style };
323
+ });
324
+ }
325
+ /* ---------------------------------------------------------------- 边 */
326
+ function drawRoutesV2(routed, interactive, types) {
327
+ return routed.map((rt) => {
328
+ // 直角走线的拐角改成圆角(#116):地铁图那样,比生硬的 90° 好看
329
+ const d = roundedPath(rt.pts, 10);
330
+ const ia = interactive ? ` data-from="${esc(rt.e.from)}" data-to="${esc(rt.e.to)}"` : '';
331
+ const s = rt;
332
+ const feet = types.crows === 'erd' ? crowFeetV2(rt, s.stroke) : '';
333
+ // UML 记号:extends 用实线空心三角,implements 用虚线空心三角
334
+ const uml = types.uml ? umlKind(rt.e.label) : undefined;
335
+ const marker = feet ? '' : ` marker-end="url(#${uml ? 'am-h' : rt.marker})"`;
336
+ const dash = uml === 'implements' ? ' stroke-dasharray="5 4"' : rt.dash;
337
+ return `<path d="${d}"${ia} fill="none" stroke="${s.stroke}" stroke-width="${s.width}"${dash}${marker}/>` + feet;
338
+ }).join('');
339
+ }
340
+ /** 边的标签写的是什么,就画什么记号(继承=实线空心三角,实现=虚线空心三角) */
341
+ function umlKind(label) {
342
+ if (!label)
343
+ return undefined;
344
+ const t = label.trim().toLowerCase();
345
+ if (/^(extends|inherit|inherits|继承)$/.test(t))
346
+ return 'extends';
347
+ if (/^(implements|realize|realizes|实现)$/.test(t))
348
+ return 'implements';
349
+ return undefined;
350
+ }
351
+ /* ---------------------------------------------------------------- 鱼尾符号
352
+ ERD 的基数记号:一端一根竖杠(「一」),另一端三根岔开的爪(「多」)。
353
+ 基数写在边的标签上(1:N / N:1 / 1:1 / N:M),画在边上,不另设参数。 */
354
+ // 基数可以在标签的前面,后面跟动词:「1:N」「1:N placed by」
355
+ const CARD_RE = /^\s*(1|n|zero|many|\*)\s*[:/]\s*(1|n|zero|many|\*)\b/i;
356
+ /**
357
+ * 边的标签是不是一个基数(1:N 这种)?是的话返回 [源端, 目标端]。
358
+ * 基数后面可以跟一个动词(「1:N placed by」)—— 动词留给标签,基数画鱼尾。
359
+ */
360
+ function cardinalityOf(label) {
361
+ if (!label)
362
+ return undefined;
363
+ const m = CARD_RE.exec(label);
364
+ if (!m)
365
+ return undefined;
366
+ const side = (s) => (s === '1' || s.toLowerCase() === 'zero' ? 'one' : 'many');
367
+ return [side(m[1]), side(m[2])];
368
+ }
369
+ /** 标签里的基数部分(「1:N placed by」→「1:N」);没有基数就原样返回 */
370
+ function cardinalityPart(label) {
371
+ const m = CARD_RE.exec(label);
372
+ return m ? m[0].trim() : label;
373
+ }
374
+ /** 一端的记号:「一」是一根横杠,「多」是三根爪(爪尖落在实体边上,爪根在线上) */
375
+ function footMarks(p, into, kind, color) {
376
+ const len = Math.hypot(into[0], into[1]) || 1;
377
+ const ux = into[0] / len;
378
+ const uy = into[1] / len;
379
+ const px = -uy;
380
+ const py = ux;
381
+ if (kind === 'one') {
382
+ // 横杠:垂直于线的方向,画在端点上
383
+ const h = 6;
384
+ return `<path d="M${r2(p[0] - px * h)} ${r2(p[1] - py * h)}L${r2(p[0] + px * h)} ${r2(p[1] + py * h)}" fill="none" stroke="${color}" stroke-width="1.5"/>`;
385
+ }
386
+ // 三根爪:爪根在线上(离实体边 12px),爪尖落在实体边上,中间那根与线重合
387
+ const L = 12;
388
+ const spread = 9;
389
+ const heel = [p[0] - ux * L, p[1] - uy * L];
390
+ const toes = [
391
+ [p[0] + px * spread, p[1] + py * spread],
392
+ [p[0], p[1]],
393
+ [p[0] - px * spread, p[1] - py * spread],
394
+ ];
395
+ return toes
396
+ .map((t) => `<path d="M${r2(heel[0])} ${r2(heel[1])}L${r2(t[0])} ${r2(t[1])}" fill="none" stroke="${color}" stroke-width="1.5"/>`)
397
+ .join('');
398
+ }
399
+ /** 一条边两端的鱼尾:标签写 1:N,源端是「一」,目标端是「多」 */
400
+ function crowFeetV2(rt, color) {
401
+ const card = cardinalityOf(rt.e.label);
402
+ if (!card)
403
+ return '';
404
+ const pts = rt.pts;
405
+ if (pts.length < 2)
406
+ return '';
407
+ const p0 = pts[0];
408
+ const pN = pts[pts.length - 1];
409
+ const p1 = pts[1];
410
+ const pM = pts[pts.length - 2];
411
+ // 端点处「进入实体」的方向:源端是 p1→p0,目标端是 pM→pN
412
+ const d0 = [p0[0] - p1[0], p0[1] - p1[1]];
413
+ const dN = [pN[0] - pM[0], pN[1] - pM[1]];
414
+ return footMarks(p0, d0, card[0], color) + footMarks(pN, dN, card[1], color);
415
+ }
416
+ const polyAt = (pts, t) => {
417
+ let total = 0;
418
+ const segs = [];
419
+ for (let i = 1; i < pts.length; i++) {
420
+ const d = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
421
+ segs.push(d);
422
+ total += d;
423
+ }
424
+ let want = total * t;
425
+ for (let i = 0; i < segs.length; i++) {
426
+ if (want <= segs[i] || i === segs.length - 1) {
427
+ const f = segs[i] ? want / segs[i] : 0;
428
+ const x = pts[i][0] + (pts[i + 1][0] - pts[i][0]) * f;
429
+ const y = pts[i][1] + (pts[i + 1][1] - pts[i][1]) * f;
430
+ return { p: [x, y], horiz: Math.abs(pts[i + 1][0] - pts[i][0]) >= Math.abs(pts[i + 1][1] - pts[i][1]) };
431
+ }
432
+ want -= segs[i];
433
+ }
434
+ return { p: pts[0], horiz: true };
435
+ };
436
+ const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
437
+ /** 两个矩形压在一起的面积(用来挑「最不糟」的位置) */
438
+ const overlapArea = (a, b) => {
439
+ const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
440
+ const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
441
+ return w > 0 && h > 0 ? w * h : 0;
442
+ };
443
+ /**
444
+ * 边标签往哪儿放 —— 一套办法,不是一堆补丁:
445
+ *
446
+ * 1. **槽位**:折线的每一段都提供几个位置(段中 + 段的两侧偏一点),
447
+ * 每个位置有「线的两侧」两种方向。标签只落在槽位上 —— 它永远贴着
448
+ * 自己那条线,读者一眼认得出这是哪条边的说明。
449
+ * 2. **代价**:槽位压住多少东西(节点框、分组的框线、已经放下的标签)。
450
+ * 代价 = 重叠面积之和。
451
+ * 3. **挑**:第一个代价为 0 的槽位直接用;都没有就挑代价最小的
452
+ * (标签比两个节点之间的空档还宽时,只能压着点,挑最不糟的)。
453
+ *
454
+ * 放下的标签占住位置,后面的标签要避开 —— 两段线挨着时,标签不会叠在一起。
455
+ */
456
+ function labelSlots(pts) {
457
+ const out = [];
458
+ // 先把「同一条直线上的中转点」合掉 —— 网格走线会留下几个共线的碎点
459
+ // (并排位置就是 ±7px 一格一格挪过去的),不合并的话每段都短得放不下标签。
460
+ const simple = [];
461
+ for (const p of pts) {
462
+ const n = simple.length;
463
+ if (n >= 2) {
464
+ const a = simple[n - 2];
465
+ const b = simple[n - 1];
466
+ const collinear = (a[0] === b[0] && b[0] === p[0]) || (a[1] === b[1] && b[1] === p[1]);
467
+ if (collinear) {
468
+ simple[n - 1] = p;
469
+ continue;
470
+ }
471
+ }
472
+ simple.push(p);
473
+ }
474
+ for (let i = 1; i < simple.length; i++) {
475
+ const a = simple[i - 1];
476
+ const b = simple[i];
477
+ const horiz = Math.abs(b[0] - a[0]) >= Math.abs(b[1] - a[1]);
478
+ const len = Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1]);
479
+ if (len < 1)
480
+ continue;
481
+ // 太短的段落放不下标签,跳过(免得标签骑在拐角上)
482
+ if (horiz && len < 40)
483
+ continue;
484
+ if (!horiz && len < 24)
485
+ continue;
486
+ // 多给几个位置:一条线上能放的地方越多,越容易找到一个不压东西的
487
+ for (const f of [0.5, 0.3, 0.7, 0.15, 0.85, 0.4, 0.6]) {
488
+ out.push({
489
+ p: [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f],
490
+ horiz,
491
+ });
492
+ }
493
+ }
494
+ return out;
495
+ }
496
+ function placeEdgeLabels(routed, avoid, splitCardinality = false) {
497
+ const out = [];
498
+ // 已经放下的标签 —— 后面的标签要避开它们(不然两个标签会叠在一起)
499
+ const taken = [];
500
+ for (const rt of routed) {
501
+ let text = rt.e.label;
502
+ if (!text)
503
+ continue;
504
+ // ERD:标签写成「1:N placed by」时,基数画鱼尾,标签只留动词
505
+ if (splitCardinality) {
506
+ const card = cardinalityPart(text);
507
+ if (card !== text.trim())
508
+ text = text.slice(card.length).trim() || card;
509
+ }
510
+ const w = textW(text, EDGE_FS) + 12;
511
+ const h = EDGE_FS + 8;
512
+ // 标签的框:横线上的压在线的上方/下方,竖线上的放在线的左/右
513
+ const rectOf = (p, horiz, mirror) => horiz
514
+ ? { x: p[0] - w / 2, y: mirror ? p[1] + 3 : p[1] - 3 - h, w, h }
515
+ : { x: mirror ? p[0] - 3 - w : p[0] + 3, y: p[1] - h / 2, w, h };
516
+ const blockers = [...avoid, ...taken];
517
+ let place;
518
+ let best;
519
+ let bestCost = Infinity;
520
+ for (const slot of labelSlots(rt.pts)) {
521
+ for (const mirror of [false, true]) {
522
+ const cost = blockers.reduce((s, b) => s + overlapArea(rectOf(slot.p, slot.horiz, mirror), b), 0);
523
+ if (cost === 0) {
524
+ place = { ...slot, mirror };
525
+ break;
526
+ }
527
+ if (cost < bestCost) {
528
+ bestCost = cost;
529
+ best = { ...slot, mirror };
530
+ }
531
+ }
532
+ if (place)
533
+ break;
534
+ }
535
+ // 实在没地方放(标签比两个节点之间的空档还宽),挑压得最少的那个
536
+ if (!place) {
537
+ const mid = labelSlots(rt.pts)[0] ?? { p: rt.pts[0], horiz: true };
538
+ place = best ?? { ...mid, mirror: false };
539
+ }
540
+ const p = place.p;
541
+ const x = place.horiz ? p[0] : p[0] + (place.mirror ? -8 : 8);
542
+ const y = place.horiz ? p[1] + (place.mirror ? 15 : -7) : p[1] + 4;
543
+ const anchor = place.horiz ? 'middle' : place.mirror ? 'end' : 'start';
544
+ out.push({ text, x, y, anchor, horiz: place.horiz, edge: rt.e });
545
+ // 这个标签占的位置,后面的标签也得避开
546
+ taken.push({
547
+ x: anchor === 'middle' ? x - w / 2 : anchor === 'end' ? x - w : x,
548
+ y: y - EDGE_FS - 3, w, h,
549
+ });
550
+ }
551
+ return out;
552
+ }
553
+ function drawEdgeLabelsV2(spots, interactive) {
554
+ return spots.map((s) => {
555
+ const w = textW(s.text, EDGE_FS) + 12;
556
+ const h = EDGE_FS + 8;
557
+ const rx = s.anchor === 'middle' ? s.x - w / 2 : s.anchor === 'end' ? s.x - w : s.x;
558
+ const ry = s.y - EDGE_FS - 1;
559
+ const ia = interactive ? ` data-edge-label="${esc(s.edge.from)} ${esc(s.edge.to)}"` : '';
560
+ return (`<g${ia}>` +
561
+ `<rect x="${r2(rx)}" y="${r2(ry)}" width="${r2(w)}" height="${r2(h)}" rx="5" fill="var(--d-card)" stroke="var(--d-border)" stroke-width="1"/>` +
562
+ `<text x="${r2(s.x)}" y="${r2(s.y)}" text-anchor="${s.anchor}" font-size="${EDGE_FS}" fill="var(--d-text)">${esc(s.text)}</text>` +
563
+ `</g>`);
564
+ }).join('');
565
+ }
566
+ /* ---------------------------------------------------------------- 边界 */
567
+ /**
568
+ * 边界的颜色:
569
+ * - 作者在 b= 的第三段指定了色板编号就用它(b=名称;id id…;9)
570
+ * - 没指定就按顺序取「这套词汇里没被类型占用的颜色」——
571
+ * 边界是框,盒子是类型,两者撞色就分不清了。
572
+ */
573
+ function boundaryColors(boundaries, types) {
574
+ const used = new Set(Object.values(types.meta).map((m) => m.color).filter((c) => c >= 0));
575
+ const free = [];
576
+ for (let i = 0; i < 10; i++)
577
+ if (!used.has(i))
578
+ free.push(i);
579
+ return boundaries.map((bd, i) => {
580
+ if (bd.color)
581
+ return sVar(bd.color - 1);
582
+ if (!free.length)
583
+ return 'var(--d-faint)';
584
+ return sVar(free[i % free.length]);
585
+ });
586
+ }
587
+ /**
588
+ * v2 的边界盒:比 v1 多留一圈 —— 边要从「区域」里绕行时,通道得待在框内,
589
+ * 否则那条线看起来像是跑出了这个区域。
590
+ */
591
+ const BOUNDARY_PAD = 30;
592
+ const grow = (b, p) => ({ x: b.x - p, y: b.y - p, w: b.w + p * 2, h: b.h + p * 2 });
593
+ /**
594
+ * 分组框:成员的包围盒 + 边距。
595
+ *
596
+ * 边距默认 30px(给绕行的线留出通道,牌子也放得下),但**两个框会撞上时一起收** ——
597
+ * 收到刚好不撞为止。收的是边距,不是成员的位置(成员是作者摆的,不动)。
598
+ * 成员本身就交叠的,收不了 —— 那是摆位的问题。
599
+ *
600
+ * **套着的两个框不算撞**:一个分组在另一个分组里面(嵌套),本来就该套着 ——
601
+ * 收边距会把内外两层的留白一起收没,框就贴着节点了。
602
+ */
603
+ function boundaryBoxes(placed, boundaries) {
604
+ const byId = new Map(placed.map((p) => [p.id, p]));
605
+ const inner = boundaries.map((bd) => {
606
+ const boxes = bd.ids.map((id) => byId.get(id).box);
607
+ const x = Math.min(...boxes.map((o) => o.x));
608
+ const y = Math.min(...boxes.map((o) => o.y));
609
+ return {
610
+ x, y,
611
+ w: Math.max(...boxes.map((o) => o.x + o.w)) - x,
612
+ h: Math.max(...boxes.map((o) => o.y + o.h)) - y,
613
+ };
614
+ });
615
+ const contains = (a, b) => a.x <= b.x + 0.5 && a.y <= b.y + 0.5 &&
616
+ a.x + a.w >= b.x + b.w - 0.5 && a.y + a.h >= b.y + b.h - 0.5;
617
+ const pads = inner.map(() => BOUNDARY_PAD);
618
+ for (let round = 0; round < 8; round++) {
619
+ let hit = false;
620
+ for (let i = 0; i < inner.length; i++) {
621
+ for (let j = i + 1; j < inner.length; j++) {
622
+ const a = grow(inner[i], pads[i]);
623
+ const b = grow(inner[j], pads[j]);
624
+ const ox = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
625
+ const oy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
626
+ if (ox > 0 && oy > 0) {
627
+ if (contains(a, b) || contains(b, a))
628
+ continue; // 套着 —— 不算撞
629
+ const d = Math.min(ox, oy) / 2 + 0.5; // 撞上多少,两边各让一半
630
+ pads[i] = Math.max(0, pads[i] - d);
631
+ pads[j] = Math.max(0, pads[j] - d);
632
+ hit = true;
633
+ }
634
+ }
635
+ }
636
+ if (!hit)
637
+ break;
638
+ }
639
+ return inner.map((b, i) => grow(b, pads[i]));
640
+ }
641
+ export const BOUNDARY_STYLES = ['dash', 'faint', 'glow', 'tint', 'plain'];
642
+ /** bstyle= —— 分组怎么画;不写就是默认那套(区域底色) */
643
+ export function boundaryStyleParam(params) {
644
+ const raw = params.get('bstyle');
645
+ if (raw === null || raw === '')
646
+ return undefined;
647
+ const v = raw.trim().toLowerCase();
648
+ if (BOUNDARY_STYLES.includes(v))
649
+ return v;
650
+ throw new ApiError(400, `"bstyle" must be one of: ${BOUNDARY_STYLES.join(', ')}. Got: ${JSON.stringify(raw)}`);
651
+ }
652
+ function drawBoundariesV2(boundaries, bboxes, interactive, colors, style = 'tint') {
653
+ return boundaries.map((bd, i) => {
654
+ const box = bboxes[i];
655
+ const ia = interactive ? ` data-boundary="${esc(bd.ids.join(' '))}"` : '';
656
+ const c = colors[i];
657
+ const rect = `<rect x="${r2(box.x)}" y="${r2(box.y)}" width="${r2(box.w)}" height="${r2(box.h)}" rx="14"`;
658
+ let body;
659
+ switch (style) {
660
+ case 'faint':
661
+ body = `${rect} fill="none" stroke="${c}" stroke-opacity="0.28" stroke-width="1" stroke-dasharray="3 5"/>`;
662
+ break;
663
+ case 'glow':
664
+ // 荧光线:宽而淡的几层叠出光晕,底下那几层不吃字
665
+ body =
666
+ `${rect} fill="none" stroke="${c}" stroke-opacity="0.10" stroke-width="7"/>` +
667
+ `${rect} fill="none" stroke="${c}" stroke-opacity="0.16" stroke-width="3.5"/>` +
668
+ `${rect} fill="none" stroke="${c}" stroke-opacity="0.85" stroke-width="1.4"/>`;
669
+ break;
670
+ case 'tint':
671
+ // 区域底色:只有一块淡色,没有边 —— 边会跟线打架
672
+ body = `${rect} fill="${c}" fill-opacity="0.07"/>`;
673
+ break;
674
+ case 'plain':
675
+ body = '';
676
+ break;
677
+ default:
678
+ body = `${rect} fill="none" stroke="${c}" stroke-opacity="0.65" stroke-width="1.4" stroke-dasharray="7 5"/>`;
679
+ }
680
+ return `<g${ia}>${body}</g>`;
681
+ }).join('');
682
+ }
683
+ /** 边界的标签胶囊:画在走线之上,线不会压在字上 */
684
+ function drawBoundaryLabelsV2(boundaries, bboxes, colors, style = 'tint', memberBoxes = []) {
685
+ return boundaries.map((bd, i) => {
686
+ const box = bboxes[i];
687
+ // 牌子挂在框的左上角 —— 但框的边距被别的框挤扁时(见 boundaryBoxes 的收边距),
688
+ // 牌子会压到成员身上。成员的上沿是底线:牌子不许越过它。
689
+ const member = memberBoxes[i];
690
+ const chipY = member ? Math.min(box.y - 9, member.y - 20) : box.y - 9;
691
+ const label = bd.label.toUpperCase();
692
+ const w = textW(label, 10) + bd.label.length * 1.2 + 20;
693
+ const c = colors[i];
694
+ // 区域底色那套:牌子直接用底色垫,不再垫画布色(否则白方块浮在色块上)
695
+ const chip = style === 'tint'
696
+ ? `<rect x="${r2(box.x + 14)}" y="${r2(chipY)}" width="${r2(w)}" height="20" rx="6" fill="${c}" fill-opacity="0.14"/>`
697
+ : `<rect x="${r2(box.x + 14)}" y="${r2(chipY)}" width="${r2(w)}" height="20" rx="6" fill="var(--d-card)"/>` +
698
+ `<rect x="${r2(box.x + 15)}" y="${r2(chipY + 1)}" width="${r2(w - 2)}" height="18" rx="5" fill="${c}" fill-opacity="0.16"/>`;
699
+ return (`<g>` +
700
+ chip +
701
+ `<text x="${r2(box.x + 14 + w / 2)}" y="${r2(chipY + 13)}" text-anchor="middle" font-size="10" font-weight="700" letter-spacing="1.2" fill="${c}">${esc(label)}</text>` +
702
+ `</g>`);
703
+ }).join('');
704
+ }
705
+ /* ---------------------------------------------------------------- 图例 */
706
+ function drawLegend(placed, vocab) {
707
+ const counts = new Map();
708
+ for (const p of placed)
709
+ counts.set(p.type, (counts.get(p.type) ?? 0) + 1);
710
+ const types = vocab.order.filter((t) => counts.has(t));
711
+ if (!types.length)
712
+ return { svg: '', h: 0 };
713
+ let x = PAD;
714
+ let y = 0;
715
+ const parts = [];
716
+ for (const t of types) {
717
+ const meta = vocab.meta[t];
718
+ const neutral = meta.color < 0;
719
+ const color = neutral ? 'var(--d-muted)' : sVar(meta.color);
720
+ const n = counts.get(t) ?? 0;
721
+ const nameW = textW(meta.name, 11.5);
722
+ const countW = textW(String(n), 11.5);
723
+ parts.push(`<rect x="${r2(x)}" y="${r2(y - 10)}" width="14" height="14" rx="4" fill="${color}" fill-opacity="${neutral ? 0.18 : 0.2}" stroke="${color}" stroke-opacity="0.55" stroke-width="1"/>`, `<text x="${r2(x + 20)}" y="${r2(y + 1)}" font-size="11.5" fill="var(--d-muted)">${esc(meta.name)}</text>`, `<text x="${r2(x + 26 + nameW)}" y="${r2(y + 1)}" font-size="11.5" font-weight="700" fill="var(--d-ink)">${n}</text>`);
724
+ x += 20 + nameW + 8 + countW + 26;
725
+ }
726
+ return { svg: `<g data-legend="types">${parts.join('')}</g>`, h: LEGEND_H };
727
+ }
728
+ /* ---------------------------------------------------------------- 入口 */
729
+ const DEFS = `<defs>` +
730
+ `<marker id="am-p" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="var(--d-muted)"/></marker>` +
731
+ `<marker id="am-m" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="var(--d-ink)"/></marker>` +
732
+ `<marker id="am-d" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="var(--d-faint)"/></marker>` +
733
+ // UML 记号:空心三角(继承用实线,实现用虚线)
734
+ `<marker id="am-h" viewBox="0 0 14 14" refX="13" refY="7" markerWidth="11" markerHeight="11" orient="auto-start-reverse"><path d="M1.5 1.5L13 7L1.5 12.5z" fill="var(--d-card)" stroke="var(--d-muted)" stroke-width="1.6"/></marker>` +
735
+ // 画布纸:很淡的方格,让大图有个「纸」的感觉
736
+ `<pattern id="am-paper" width="26" height="26" patternUnits="userSpaceOnUse"><path d="M26 0H0V26" fill="none" stroke="var(--d-grid)" stroke-width="1"/></pattern>` +
737
+ `</defs>`;
738
+ /**
739
+ * 渲染 v2 架构图。
740
+ */
741
+ /**
742
+ * ERD 的自动摆位:按外键关系分层。
743
+ *
744
+ * 一张真实的表有十几张,按作者写的顺序往网格里塞,读者看不出谁引谁 ——
745
+ * 把「被引用的表」放左边、「引用别人的表」放右边,关系就顺下来了。
746
+ * 深度 = 从根表(没人引用它)算起最长的一条引用链。
747
+ */
748
+ function placeErdByRelation(nodes, edges) {
749
+ const byId = new Map(nodes.map((n) => [n.id, n]));
750
+ const depth = new Map();
751
+ const calc = (id, seen) => {
752
+ const cached = depth.get(id);
753
+ if (cached !== undefined)
754
+ return cached;
755
+ if (seen.has(id))
756
+ return 0; // 环:兜底,别无限递归
757
+ seen.add(id);
758
+ const parents = edges.filter((e) => e.to === id).map((e) => e.from).filter((p) => byId.has(p));
759
+ const d = parents.length ? Math.max(...parents.map((p) => calc(p, seen))) + 1 : 0;
760
+ depth.set(id, d);
761
+ return d;
762
+ };
763
+ for (const n of nodes)
764
+ calc(n.id, new Set());
765
+ // 已经占掉的格子(作者自己写了位置的)
766
+ const taken = new Set();
767
+ for (const n of nodes) {
768
+ if (!n.grid)
769
+ continue;
770
+ for (let r = n.grid.row; r < n.grid.row + n.grid.h; r++)
771
+ for (let c = n.grid.col; c < n.grid.col + n.grid.w; c++)
772
+ taken.add(`${r},${c}`);
773
+ }
774
+ const byDepth = new Map();
775
+ for (const n of nodes) {
776
+ const d = depth.get(n.id) ?? 0;
777
+ byDepth.set(d, [...(byDepth.get(d) ?? []), n.id]);
778
+ }
779
+ for (const d of [...byDepth.keys()].sort((a, b) => a - b)) {
780
+ (byDepth.get(d) ?? []).forEach((id, i) => {
781
+ const n = byId.get(id);
782
+ if (n.grid || n.px)
783
+ return;
784
+ let r = i;
785
+ let c = d;
786
+ while (taken.has(`${r},${c}`)) {
787
+ r++;
788
+ if (r > 60) {
789
+ r = 0;
790
+ c++;
791
+ }
792
+ }
793
+ n.grid = { row: r, col: c, w: 1, h: 1 };
794
+ taken.add(`${r},${c}`);
795
+ });
796
+ }
797
+ }
798
+ export function renderArchCore(o) {
799
+ const types = o.types ?? ARCH_TYPES;
800
+ // 图标解析一次(渲染前填进节点):调用方注入的优先 —— 那是有权限的一方带进来的真 logo
801
+ // (比如私有仓里的公司图标库);否则查内置图标库。org: 前缀两处都没有 → 画组图标。
802
+ for (const n of o.nodes) {
803
+ if (!n.icon)
804
+ continue;
805
+ const hit = o.icons?.[n.icon] || iconOf(n.icon);
806
+ if (hit)
807
+ n.iconData = hit;
808
+ }
809
+ const sizeOf = (n) => v2Size(n, types);
810
+ // 大图标的节点窄(64px 的图标),列与列之间要多留一点空当,不然挤成一坨
811
+ const gapX = types.icons === 'big' ? 52 : GAP_X;
812
+ // 行与行之间:图标模式下要给边界框的小牌子留位置(两个边界挨着,牌子会压到对方的框线上)
813
+ const gapY = types.icons === 'big' ? 58 : GAP_Y;
814
+ // 边标签有多宽(渲染层按字体量好,引擎不碰字体)
815
+ const labelW = (e) => (e.label ? textW(e.label, EDGE_FS) + 44 : 0);
816
+ // 没人写位置 → 交给摆位引擎(站上装的是更好的那个;库里是通用的);
817
+ // 写了位置 → 照旧按格子摆(作者说了算);grid= 明确要格子也走格子
818
+ const explicit = o.nodes.some((n) => n.grid || n.px);
819
+ const auto = !explicit && types.crows !== 'erd' && !o.gridForced;
820
+ let placed;
821
+ let W;
822
+ let H;
823
+ if (auto) {
824
+ const engine = o.layout ?? gridLayout;
825
+ const res = engine({
826
+ nodes: o.nodes,
827
+ edges: o.edges,
828
+ boundaries: o.boundaries,
829
+ sizeOf,
830
+ gapX,
831
+ gapY,
832
+ pad: PAD,
833
+ dir: o.dir ?? 'LR',
834
+ labelW,
835
+ });
836
+ placed = o.nodes.map((n) => ({
837
+ ...n,
838
+ box: res.boxes.get(n.id),
839
+ color: TYPE_COLOR[n.type] ?? -1,
840
+ }));
841
+ W = res.W;
842
+ H = res.H;
843
+ }
844
+ else {
845
+ // ERD:没写位置的表按关系摆 —— 被引用的在左,引用别人的在右(按外键深度分层)
846
+ if (types.crows === 'erd')
847
+ placeErdByRelation(o.nodes, o.edges);
848
+ // 第一遍:定格子(没写位置的节点会被自动放进去);第二遍:按边标签把列撑开
849
+ packGrid(o.nodes, o.gridCols, { gapX, gapY, pad: PAD, sizeOf, edges: o.edges });
850
+ const r = packGrid(o.nodes, o.gridCols, {
851
+ gapX, gapY, pad: PAD, sizeOf, gapAfter: labelGaps(o.nodes, o.edges, labelW),
852
+ });
853
+ placed = r.placed;
854
+ W = r.W;
855
+ H = r.H;
856
+ }
857
+ const titleH = o.title ? 46 : 0;
858
+ let width = Math.max(W, 320);
859
+ let bodyH = H;
860
+ const byIdEarly = new Map(placed.map((p) => [p.id, p]));
861
+ for (const p of placed) {
862
+ width = Math.max(width, p.box.x + p.box.w + PAD);
863
+ bodyH = Math.max(bodyH, p.box.y + p.box.h + PAD);
864
+ }
865
+ // 分组框:算一次,画框、画牌子、算画布、给标签避让,都用同一份
866
+ const bboxes = boundaryBoxes(placed, o.boundaries);
867
+ // 边界框比它的成员大一圈:画布要给它留出位置,不然图例会压在边界上
868
+ for (const bb of bboxes) {
869
+ width = Math.max(width, bb.x + bb.w + PAD);
870
+ bodyH = Math.max(bodyH, bb.y + bb.h + PAD);
871
+ }
872
+ const legend = o.legend ? drawLegend(placed, types) : { svg: '', h: 0 };
873
+ const byId = new Map(placed.map((p) => [p.id, p]));
874
+ const boxes = placed.map((p) => p.box);
875
+ const routed = computeRoutesV2(placed, o.edges, bboxes, types.icons === 'big', o.routing, o.dir ?? 'LR');
876
+ const avoid = [
877
+ ...boxes.map((b) => ({ x: b.x - 2, y: b.y - 2, w: b.w + 4, h: b.h + 4 })),
878
+ ...o.boundaries.map((bd, i) => {
879
+ const bb = bboxes[i];
880
+ const w = textW(bd.label.toUpperCase(), 10) + bd.label.length * 1.2 + 20;
881
+ return { x: bb.x + 14, y: bb.y - 12, w, h: 22 };
882
+ }),
883
+ // 分组的框线:只挡「边框那一圈」—— 框里的标签是正常的,压在框线上才是压线
884
+ ...bboxes.flatMap((bb) => {
885
+ const t = 4;
886
+ return [
887
+ { x: bb.x - t, y: bb.y - t, w: bb.w + t * 2, h: t * 2 },
888
+ { x: bb.x - t, y: bb.y + bb.h - t, w: bb.w + t * 2, h: t * 2 },
889
+ { x: bb.x - t, y: bb.y + t, w: t * 2, h: bb.h - t * 2 },
890
+ { x: bb.x + bb.w - t, y: bb.y + t, w: t * 2, h: bb.h - t * 2 },
891
+ ];
892
+ }),
893
+ ];
894
+ const spots = placeEdgeLabels(routed, avoid, types.crows === 'erd');
895
+ // 画布要盖住走线和边标签:绕行的边会走到节点盒外面,标签又贴在走线上 ——
896
+ // 只按节点盒算尺寸,那一段就会被裁掉(字看不全)。
897
+ for (const rt of routed) {
898
+ for (const p of rt.pts) {
899
+ width = Math.max(width, p[0] + PAD);
900
+ bodyH = Math.max(bodyH, p[1] + PAD);
901
+ }
902
+ }
903
+ for (const s of spots) {
904
+ const w = textW(s.text, EDGE_FS) + 12;
905
+ const h = EDGE_FS + 8;
906
+ const rx = s.anchor === 'middle' ? s.x - w / 2 : s.anchor === 'end' ? s.x - w : s.x;
907
+ width = Math.max(width, rx + w + PAD);
908
+ bodyH = Math.max(bodyH, s.y - EDGE_FS - 1 + h + PAD);
909
+ }
910
+ width = Math.max(width, o.minW ?? 0);
911
+ // 边界的小牌子探出边界框 9px;标题的字底也在这一带 —— 身子要让开,
912
+ // 不然牌子会压在标题上(「Inside draw」那张就压住了)。
913
+ const bTop = bboxes.length ? Math.min(...bboxes.map((bb) => bb.y - 9)) : 0;
914
+ const titleBottom = o.title ? PAD + 26 : 0; // 标题的字底(含下伸部)
915
+ const headH = o.boundaries.length ? Math.max(titleH, titleBottom - bTop) : titleH;
916
+ const height = Math.max(bodyH + headH + legend.h + 14, o.minH ?? 0);
917
+ const degree = new Map();
918
+ if (o.interactive)
919
+ for (const e of o.edges) {
920
+ degree.set(e.from, (degree.get(e.from) ?? 0) + 1);
921
+ degree.set(e.to, (degree.get(e.to) ?? 0) + 1);
922
+ }
923
+ const iStyle = o.interactive
924
+ ? `<style>#am g[data-node]{cursor:pointer;transition:filter .12s ease,opacity .15s ease}` +
925
+ `#am g[data-node]:focus{outline:none}` +
926
+ `#am g[data-node]:hover,#am g[data-node]:focus-visible{filter:brightness(1.25)}` +
927
+ `#am g[data-node].on{filter:brightness(1.25)}` +
928
+ `#am.hl g[data-node]{opacity:.4}#am.hl g[data-node].on{opacity:1}` +
929
+ `#am.hl g[data-boundary]{opacity:.35}#am.hl g[data-boundary].on{opacity:1}` +
930
+ `#am.hl path[data-from]{opacity:.22}#am.hl path[data-from].on{opacity:1}` +
931
+ `#am.hl g[data-edge-label]{opacity:.3}#am.hl g[data-edge-label].on{opacity:1}</style>`
932
+ : '';
933
+ const titleSvg = o.title
934
+ ? `<text x="${PAD}" y="${PAD + 16}" font-size="19" font-weight="600" letter-spacing="-0.02em" fill="var(--d-ink)">${esc(o.title)}</text>`
935
+ : '';
936
+ const bColors = boundaryColors(o.boundaries, types);
937
+ const paperSvg = o.paper
938
+ ? `<rect x="0" y="0" width="${r2(width)}" height="${r2(height)}" fill="url(#am-paper)"/>`
939
+ : '';
940
+ const body = iStyle + DEFS
941
+ + drawBoundariesV2(o.boundaries, bboxes, o.interactive, bColors, o.boundaryStyle)
942
+ + drawRoutesV2(routed, o.interactive, types)
943
+ + drawEdgeLabelsV2(spots, o.interactive)
944
+ + placed.map((p) => drawNodeV2(p, o.interactive, degree.get(p.id) ?? 0, types)).join('')
945
+ + drawBoundaryLabelsV2(o.boundaries, bboxes, bColors, o.boundaryStyle,
946
+ // 成员的外框 —— 牌子不许压到成员身上
947
+ o.boundaries.map((bd) => {
948
+ const ms = o.nodes.filter((n) => bd.ids.includes(n.id)).map((n) => placed.find((p) => p.id === n.id).box);
949
+ if (!ms.length)
950
+ return { x: 0, y: 0, w: 0, h: 0 };
951
+ const x = Math.min(...ms.map((m) => m.x));
952
+ const y = Math.min(...ms.map((m) => m.y));
953
+ return { x, y, w: Math.max(...ms.map((m) => m.x + m.w)) - x, h: Math.max(...ms.map((m) => m.y + m.h)) - y };
954
+ }));
955
+ // 图例在身子下面 —— 要跟着身子一起往下挪(dy),不然身子一被推下去,
956
+ // 图例就留在原地、压进身子里面
957
+ const dy = headH + Math.max(0, (height - headH - legend.h - bodyH) / 2);
958
+ const legendSvg = legend.svg
959
+ ? `<g transform="translate(0 ${r2(dy + bodyH + 14)})">${legend.svg}</g>`
960
+ : '';
961
+ const children = paperSvg + titleSvg + `<g id="am" transform="translate(0 ${r2(dy)})">${body}</g>` + legendSvg;
962
+ // 身子被往下推了,画布也得跟着长(不然底下的图例会被切掉)
963
+ const spec = { type: 'arch', title: o.title, nodes: o.nodes, edges: o.edges, boundaries: o.boundaries };
964
+ const svg = svgDoc(width, height, o.template ?? 'arch2', o.version, o.aria ?? o.title ?? `architecture map, ${o.nodes.length} nodes`, spec, o.skin, children, o.tagQuery, o.template ?? 'arch2');
965
+ return { svg, version: o.version, cacheControl: o.cacheControl };
966
+ }
967
+ /** /draw/cloud —— 大图标版的架构图(节点就是图标) */
968
+ export function renderCloudFromUrl(url, interactive = false, opts = {}) {
969
+ return renderArchFromUrl(url, interactive, CLOUD_TYPES, opts);
970
+ }
971
+ export function renderArchFromUrl(url, interactive = false, types = ARCH_TYPES, opts = {}) {
972
+ const params = url.searchParams;
973
+ const nRaw = params.getAll('n');
974
+ if (!nRaw.length)
975
+ throw new ApiError(400, `at least one node is required. Example: /draw/arch?n=api;be;API Gateway;auth;r1c0w2`);
976
+ const nodes = parseNodes(nRaw);
977
+ const seen = new Set();
978
+ for (const n of nodes) {
979
+ if (seen.has(n.id))
980
+ throw new ApiError(400, `duplicate node id "${n.id}"`);
981
+ seen.add(n.id);
982
+ }
983
+ const edges = parseEdges(params.getAll('e'), seen);
984
+ const boundaries = parseBoundaries(params.getAll('b'), seen);
985
+ const title = params.get('title')?.trim() || undefined;
986
+ const gridCols = clampInt(params, 'grid', 0, 1, 12);
987
+ const dir = dirParam(params);
988
+ const boundaryStyle = boundaryStyleParam(params);
989
+ const legendRaw = params.get('legend');
990
+ const legend = legendRaw === null || legendRaw === '' ? true : legendRaw !== '0' && legendRaw !== 'false';
991
+ const paperRaw = params.get('paper');
992
+ const paper = paperRaw !== null && paperRaw !== '' && paperRaw !== '0' && paperRaw !== 'false';
993
+ const v = parseInt(params.get('v') ?? '1', 10) || 1;
994
+ const skin = resolveSkin('sankey', params.get('t'), schemeParam(params));
995
+ return renderArchCore({
996
+ nodes, edges, boundaries, title, gridCols, legend, paper, interactive,
997
+ types,
998
+ gridForced: gridCols > 0,
999
+ dir,
1000
+ boundaryStyle,
1001
+ layout: opts.layout,
1002
+ routing: opts.routing,
1003
+ icons: opts.icons,
1004
+ template: 'arch2', tagQuery: url.search,
1005
+ version: v,
1006
+ cacheControl: 'public, max-age=300',
1007
+ skin,
1008
+ minW: clampInt(params, 'w', 0, 200, 2400),
1009
+ minH: clampInt(params, 'h', 0, 140, 2400),
1010
+ });
1011
+ }