@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,237 @@
1
+ // ECharts 地图数据注册表。
2
+ //
3
+ // echarts 6 不再自带地图数据(v4 的 map/ 目录已从 npm 包移除),地图 GeoJSON 随包分发。
4
+ // 地图数据几十 KB,只在 option 真用到 map/geo 系列时动态载入 —— 不进 Worker 冷启动路径。
5
+ //
6
+ // 名字即 option 里的地图名:series.type=map 的 map 字段、geo 组件的 map 字段都填它。
7
+ // {"type":"map","map":"USA","data":[{"name":"California","value":1}]}
8
+ // WORLD 是世界地图(自然地球投影,等积)—— 投影好的底图随包分发(投影是构建期的事)。
9
+ // 未收录的地图名不注册,echarts 自己报 "Map xxx not exists"(错误消息更贴切)。
10
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
11
+ /** 地图名 → GeoJSON 载入器(动态 import:未用到就不下载) */
12
+ const MAPS = {
13
+ USA: () => import('./vendor/us-states.js'),
14
+ CN: () => import('./vendor/china.js'),
15
+ EU: () => import('./vendor/eu.js'),
16
+ JP: () => import('./vendor/japan.js'),
17
+ BR: () => import('./vendor/br.js'),
18
+ AU: () => import('./vendor/au.js'),
19
+ DE: () => import('./vendor/de.js'),
20
+ KR: () => import('./vendor/kr.js'),
21
+ WORLD: () => import('./vendor/world.js'),
22
+ };
23
+ /**
24
+ * 投影产物是**屏幕坐标(y 向下)**,echarts 却按「北为正」读地图坐标
25
+ * (实测:数据里 y=100 的点会画在屏幕上方)。两边差一个翻转 —— 在这里翻一次,
26
+ * 数据文件保持投影原样(不用在每份数据里写死负号),注册与浏览器端拿到的是同一份。
27
+ */
28
+ function flipY(geo) {
29
+ const walk = (v) => {
30
+ if (!Array.isArray(v))
31
+ return v;
32
+ if (typeof v[0] === 'number')
33
+ return [v[0], -v[1]];
34
+ return v.map(walk);
35
+ };
36
+ const g = geo;
37
+ if (!g || !Array.isArray(g.features))
38
+ return geo;
39
+ return {
40
+ ...g,
41
+ features: g.features.map((f) => ({
42
+ ...f,
43
+ geometry: { ...f.geometry, coordinates: walk(f.geometry?.coordinates) },
44
+ })),
45
+ };
46
+ }
47
+ /** 地图 GeoJSON(按地图名取,已翻成 echarts 认的方向):浏览器端注册地图要用同一份 */
48
+ export async function loadMapGeoJson(name) {
49
+ const load = MAPS[name];
50
+ if (!load)
51
+ throw new Error(`unknown map: ${name}`);
52
+ const mod = await load();
53
+ return flipY(mod.usStatesGeoJson ?? mod.chinaGeoJson ?? mod.euGeoJson ?? mod.japanGeoJson
54
+ ?? mod.brGeoJson ?? mod.auGeoJson ?? mod.deGeoJson ?? mod.krGeoJson ?? mod.worldGeoJson);
55
+ }
56
+ /**
57
+ * US 各州的 GeoJSON(Albers USA 投影,50 州 + DC)—— 随包分发,随取随用。
58
+ * 浏览器端的 echarts 也要注册同一份地图数据,自己那一份没有地图 —— 用这个。
59
+ * 按需载入(静态 import 会把 68KB 拖进冷启动路径)。
60
+ */
61
+ export async function loadUsStatesGeoJson() {
62
+ const mod = await import('./vendor/us-states.js');
63
+ return mod.usStatesGeoJson;
64
+ }
65
+ /** 已注册地图的纵横比(投影平面坐标的 bbox 宽高比):布局缺省按它算尺寸 */
66
+ const aspects = new Map();
67
+ /** GeoJSON 平面坐标的 bbox 纵横比(地图的真实形状比) */
68
+ function aspectOf(geo) {
69
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
70
+ const walk = (v) => {
71
+ if (!Array.isArray(v))
72
+ return;
73
+ if (typeof v[0] === 'number') {
74
+ const x = v[0], y = v[1];
75
+ if (x < x0)
76
+ x0 = x;
77
+ if (x > x1)
78
+ x1 = x;
79
+ if (y < y0)
80
+ y0 = y;
81
+ if (y > y1)
82
+ y1 = y;
83
+ return;
84
+ }
85
+ v.forEach(walk);
86
+ };
87
+ const feats = geo.features ?? [];
88
+ for (const f of feats)
89
+ walk(f.geometry?.coordinates);
90
+ const h = y1 - y0;
91
+ return h > 0 ? (x1 - x0) / h : 1;
92
+ }
93
+ /** 已注册地图的纵横比(未注册返回 undefined) */
94
+ export function mapAspect(name) {
95
+ return aspects.get(name);
96
+ }
97
+ /** option 里引用到的地图名:series.type=map 的 map 字段 + geo 组件的 map 字段 */
98
+ export function mapNamesOf(option) {
99
+ const names = new Set();
100
+ const o = (option ?? {});
101
+ const series = Array.isArray(o.series) ? o.series : isObj(o.series) ? [o.series] : [];
102
+ for (const s of series) {
103
+ if (isObj(s) && s.type === 'map' && typeof s.map === 'string')
104
+ names.add(s.map);
105
+ }
106
+ const geo = Array.isArray(o.geo) ? o.geo : isObj(o.geo) ? [o.geo] : [];
107
+ for (const g of geo) {
108
+ if (isObj(g) && typeof g.map === 'string')
109
+ names.add(g.map);
110
+ }
111
+ return [...names];
112
+ }
113
+ /**
114
+ * 世界地图的**经纬度**版本(球面用)—— 动态载入(静态 import 会拖进冷启动路径)。
115
+ * 坐标粗一点(球上本来就小)。
116
+ */
117
+ export async function loadWorldSphericalGeoJson() {
118
+ const mod = await import('./vendor/world-geo.js');
119
+ return mod.worldSphericalGeoJson;
120
+ }
121
+ // ── 世界地图「绕一圈」────────────────────────────────────────────────────────
122
+ //
123
+ // 视图挪到某个经度时(series.center),底图得绕着地球转过去 —— 不然那一侧是空的:
124
+ // 世界地图的数据只覆盖 -180°..180°,挪到东边时,画布右边露出的是画布底色(看着像地图缺一块)。
125
+ //
126
+ // 做法:底图左右各加一份(整体平移一个世界宽)—— 数据还是同一份,只是多几份拷贝,
127
+ // 于是「往东挪」和「往西挪」都有东西接着。布局要跟着放大(份数倍),不然地图被压成三分之一。
128
+ //
129
+ // 三个函数都**自包含**(不引模块外任何东西):浏览器端(explore 页重画)直接跑同一份源码,
130
+ // 两边不会走偏 —— 与 headLayout 同一套路。
131
+ /** 绕圈后的份数(底图 + 左右各一份) */
132
+ export const WORLD_WRAP_COPIES = 3;
133
+ /**
134
+ * option 里有没有「挪到某个经度」的世界地图(要绕圈的场合)。
135
+ * 自包含:浏览器端直接跑同一份源码。
136
+ */
137
+ export function worldWrapNeeded(option) {
138
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
139
+ const o = (option ?? {});
140
+ const series = Array.isArray(o.series) ? o.series : isObj(o.series) ? [o.series] : [];
141
+ for (const s of series) {
142
+ if (!isObj(s))
143
+ continue;
144
+ if (s.type !== 'map' || s.map !== 'WORLD')
145
+ continue;
146
+ if (s.center !== undefined && s.center !== null)
147
+ return true;
148
+ }
149
+ return false;
150
+ }
151
+ /**
152
+ * 底图左右各加一份(整体平移一个世界宽)。
153
+ * 自包含:浏览器端直接跑同一份源码。
154
+ */
155
+ export function worldWrapGeo(geo) {
156
+ const g = geo;
157
+ const feats = g?.features ?? [];
158
+ if (!feats.length)
159
+ return geo;
160
+ // 世界宽 = 底图外接框的宽(世界地图的数据正好覆盖 -180°..180°)
161
+ let x0 = Infinity, x1 = -Infinity;
162
+ const walk = (v) => {
163
+ if (!Array.isArray(v))
164
+ return;
165
+ if (typeof v[0] === 'number') {
166
+ const x = v[0];
167
+ if (x < x0)
168
+ x0 = x;
169
+ if (x > x1)
170
+ x1 = x;
171
+ return;
172
+ }
173
+ v.forEach(walk);
174
+ };
175
+ for (const f of feats)
176
+ walk(f.geometry?.coordinates);
177
+ const w = x1 - x0;
178
+ if (!(w > 0))
179
+ return geo;
180
+ const shifted = (dx) => {
181
+ const sh = (v) => {
182
+ if (!Array.isArray(v))
183
+ return v;
184
+ if (typeof v[0] === 'number')
185
+ return [v[0] + dx, v[1]];
186
+ return v.map(sh);
187
+ };
188
+ return feats.map((f) => ({ ...f, geometry: { ...f.geometry, coordinates: sh(f.geometry?.coordinates) } }));
189
+ };
190
+ return { ...g, features: [...feats, ...shifted(w), ...shifted(-w)] };
191
+ }
192
+ /**
193
+ * 绕圈后布局要按份数放大 —— 数据多了左右两份,地图还是原来那么大,
194
+ * 不然会被压成三分之一(看着像缩小了一圈)。
195
+ * 自包含:浏览器端直接跑同一份源码。
196
+ */
197
+ export function worldWrapLayout(option) {
198
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
199
+ const series = Array.isArray(option.series) ? option.series : isObj(option.series) ? [option.series] : [];
200
+ for (const s of series) {
201
+ if (!isObj(s))
202
+ continue;
203
+ if (s.type !== 'map' || s.map !== 'WORLD')
204
+ continue;
205
+ if (s.center === undefined || s.center === null)
206
+ continue;
207
+ const n = 3; // WORLD_WRAP_COPIES —— 抄一份在这儿,免得这个函数引模块外的东西
208
+ const size = s.layoutSize;
209
+ if (typeof size === 'string' && size.trim().endsWith('%')) {
210
+ const v = parseFloat(size);
211
+ if (Number.isFinite(v))
212
+ s.layoutSize = `${(v * n).toFixed(2)}%`;
213
+ }
214
+ else if (typeof size === 'number' && Number.isFinite(size)) {
215
+ s.layoutSize = size * n;
216
+ }
217
+ }
218
+ }
219
+ /**
220
+ * Register the map data an ECharts option refers to. Must run before `setOption`:
221
+ * echarts resolves `series.map` / `geo.map` against its registered map table.
222
+ */
223
+ export async function registerMaps(echarts, option) {
224
+ for (const name of mapNamesOf(option)) {
225
+ const load = MAPS[name];
226
+ if (!load)
227
+ continue;
228
+ const base = await loadMapGeoJson(name);
229
+ // 纵横比按**底图**算(不是绕圈后的):布局按底图定尺,再由 worldWrapLayout 乘份数
230
+ const aspect = aspectOf(base);
231
+ // 世界地图挪到某个经度 ⇒ 底图绕一圈(否则那一侧是空的)
232
+ const geo = name === 'WORLD' && worldWrapNeeded(option) ? worldWrapGeo(base) : base;
233
+ echarts.registerMap(name, geo);
234
+ if (!aspects.has(name))
235
+ aspects.set(name, aspect);
236
+ }
237
+ }
@@ -55,6 +55,5 @@ export interface PlainGeo {
55
55
  top: number;
56
56
  bottom: number;
57
57
  xLabelY: number;
58
- legendY: number;
59
58
  }
60
59
  export declare function plainGeo(w: number, h: number, hasTitle: boolean, m?: GeoMeasure): PlainGeo;
@@ -70,6 +70,5 @@ export function plainGeo(w, h, hasTitle, m = {}) {
70
70
  top: Math.round(h * (hasTitle ? 0.185 : 0.163)),
71
71
  bottom: Math.round(h * 0.80),
72
72
  xLabelY: Math.round(h * 0.896),
73
- legendY: Math.round(h * (hasTitle ? 0.096 : 0.077)),
74
73
  };
75
74
  }
@@ -0,0 +1,30 @@
1
+ import { type DrawResult } from './query.js';
2
+ interface FlowDoc {
3
+ direction: string;
4
+ nodes: {
5
+ id: string;
6
+ label: string;
7
+ shape: string;
8
+ }[];
9
+ edges: {
10
+ from: string;
11
+ to: string;
12
+ label: string;
13
+ dotted: boolean;
14
+ thick: boolean;
15
+ }[];
16
+ groups: {
17
+ title: string;
18
+ nodes: string[];
19
+ }[];
20
+ }
21
+ /** jison 收集器:挂 yy 回调,解析产出 FlowDoc(冒烟已验证的接线:yy.lex.firstGraph / addLink 笛卡尔积 / link.text.text) */
22
+ export declare function parseFlow(text: string): FlowDoc;
23
+ /**
24
+ * Render a mermaid flowchart from URL params (`/draw/mermaid?m=<code>`).
25
+ * v1 subset: graph/flowchart with node shapes, edge styles/labels and
26
+ * subgraphs (→ boundary groups). Everything renders through the archmap
27
+ * engine — styles, interactivity, PNG and caching all inherited.
28
+ */
29
+ export declare function renderMermaidFromUrl(url: URL, interactive?: boolean): DrawResult;
30
+ export {};
@@ -0,0 +1,277 @@
1
+ // dagre 无官方类型:类型用本仓自绘的最小面(普通模块,非 ambient 声明 ——
2
+ // ambient 属全局类型改动,JSR 不许发布)
3
+ // @ts-types="../types/dagre.ts"
4
+ import dagreRaw from 'dagre';
5
+ const dagre = dagreRaw;
6
+ import { ApiError } from '../specs/index.js';
7
+ import { resolveVersion } from '../version.js';
8
+ import { resolveSkin } from '../styles/index.js';
9
+ import { clampInt, schemeParam } from './query.js';
10
+ import { mermaidFlowParser } from './vendor/mermaid-flow-parser.js';
11
+ import { renderGanttFromUrl } from './gantt.js';
12
+ import { renderArchmapCore, naturalSize } from './archmap.js';
13
+ const M_MAX = 6000;
14
+ const N_EXAMPLE = 'm=' + encodeURIComponent('graph LR\n A[Browser] --> B{Gateway}\n B --> C[API]');
15
+ const asText = (v, fb = '') => {
16
+ if (v == null)
17
+ return fb;
18
+ if (typeof v === 'string')
19
+ return v.trim();
20
+ if (Array.isArray(v))
21
+ return v.map((x) => asText(x)).filter(Boolean).join(' '); // 分组成员是嵌套单元素数组
22
+ if (typeof v === 'object')
23
+ return String(v.text ?? '').trim();
24
+ return String(v).trim();
25
+ };
26
+ /** mermaid 顶点形状 → archmap 形状/语义色:菱形=判定,圆柱=存储,其余盒型 */
27
+ function toShape(type) {
28
+ switch (type) {
29
+ case 'diamond':
30
+ case 'hexagon':
31
+ case 'question':
32
+ return { shape: 'diamond', nodeType: 'be' };
33
+ case 'cylinder':
34
+ return { shape: 'cylinder', nodeType: 'db' };
35
+ case 'round':
36
+ case 'stadium':
37
+ case 'circle':
38
+ case 'ellipse':
39
+ case 'doublecircle':
40
+ return { shape: 'round', nodeType: 'fe' };
41
+ default:
42
+ return { shape: 'rect', nodeType: 'be' };
43
+ }
44
+ }
45
+ /** jison 收集器:挂 yy 回调,解析产出 FlowDoc(冒烟已验证的接线:yy.lex.firstGraph / addLink 笛卡尔积 / link.text.text) */
46
+ export function parseFlow(text) {
47
+ const doc = { direction: 'TD', nodes: [], edges: [], groups: [] };
48
+ const byId = new Map();
49
+ const pending = [];
50
+ let first = true;
51
+ const endInfo = (str) => {
52
+ const s = String(str);
53
+ return {
54
+ type: s.includes('>') || s.includes('<') ? 'arrow_point' : 'arrow_open',
55
+ stroke: s.includes('.') ? 'dotted' : s.includes('=') ? 'thick' : 'normal',
56
+ length: 1,
57
+ };
58
+ };
59
+ // 连线两端可能从没作为独立节点声明过(subgraph 里的写法)——补一个占位节点,
60
+ // 免得布局阶段查不到盒子。
61
+ const ensureVertex = (id) => {
62
+ if (byId.has(id))
63
+ return;
64
+ const n = { id, label: id, shape: 'rect' };
65
+ byId.set(id, n);
66
+ doc.nodes.push(n);
67
+ };
68
+ const yy = {
69
+ // mermaid FlowDB 约定:lexer 通过 yy.lex.firstGraph 区分首行方向
70
+ lex: { firstGraph() { const r = first; first = false; return r; } },
71
+ setDirection(d) { doc.direction = (d ?? 'TD').trim().toUpperCase(); },
72
+ addVertex(id, text, type) {
73
+ if (byId.has(id))
74
+ return;
75
+ const n = { id, label: asText(text, id) || id, shape: typeof type === 'string' ? type : 'rect' };
76
+ byId.set(id, n);
77
+ doc.nodes.push(n);
78
+ },
79
+ destructLink(endStr, startStr) {
80
+ const info = endInfo(endStr);
81
+ if (startStr !== undefined && startStr !== null && String(startStr).trim() !== '') {
82
+ const si = endInfo(startStr);
83
+ if (si.stroke !== info.stroke)
84
+ return { type: 'INVALID', stroke: 'INVALID' };
85
+ }
86
+ pending.push(info);
87
+ return info;
88
+ },
89
+ addLink(sources, targets, link) {
90
+ const label = asText(link && link.text);
91
+ for (const s of sources)
92
+ for (const t of targets) {
93
+ // subgraph 里写的连线不会先触发 addVertex —— 两端自己补上,
94
+ // 否则布局阶段找不到节点就炸了(500)。
95
+ ensureVertex(s);
96
+ ensureVertex(t);
97
+ const info = pending[0] ?? { stroke: 'normal' };
98
+ doc.edges.push({ from: s, to: t, label, dotted: info.stroke === 'dotted', thick: info.stroke === 'thick' });
99
+ }
100
+ pending.length = 0;
101
+ },
102
+ addSubGraph(id, list) {
103
+ const title = asText(id) || 'group';
104
+ // 成员可能是嵌套数组,也可能是「GW CDN」这样一整行文本 —— 摊平后按空白切开,
105
+ // 再只留下确实是节点的 id(否则边界框找不到节点,渲染时 500)。
106
+ const nodes = (Array.isArray(list) ? list : [list])
107
+ .flatMap((x) => asText(x).split(/\s+/))
108
+ .filter(Boolean)
109
+ .filter((nid) => byId.has(nid));
110
+ if (nodes.length)
111
+ doc.groups.push({ title, nodes });
112
+ },
113
+ // 以下均为渲染态/交互态特性,v1 不消费,静默吞掉
114
+ setClass() { }, setClickEvent() { }, setTooltip() { }, setLink() { },
115
+ setAccTitle() { }, setAccDescription() { }, addClass() { },
116
+ updateLink() { }, updateLinkInterpolate() { },
117
+ };
118
+ const p = mermaidFlowParser;
119
+ p.yy = yy;
120
+ try {
121
+ p.parse(text);
122
+ }
123
+ catch (e) {
124
+ throw new ApiError(400, `mermaid syntax error: ${e instanceof Error ? e.message.split('\n')[0] : String(e)}. Example: /draw/mermaid?${N_EXAMPLE}`);
125
+ }
126
+ if (!doc.nodes.length)
127
+ throw new ApiError(400, `no nodes found — is it a flowchart? Only "graph/flowchart" is supported in v1. Example: /draw/mermaid?${N_EXAMPLE}`);
128
+ return doc;
129
+ }
130
+ /** dagre 层次布局 → 每个节点的像素盒(左上角);W/H 为内容外沿 */
131
+ function layout(doc, sizes) {
132
+ const g = new dagre.graphlib.Graph();
133
+ g.setGraph({ rankdir: doc.direction === 'LR' || doc.direction === 'RL' ? 'LR' : 'TB', nodesep: 56, ranksep: 72, marginx: 24, marginy: 24 });
134
+ g.setDefaultEdgeLabel(() => ({}));
135
+ for (const n of doc.nodes) {
136
+ const sz = sizes.get(n.id) ?? { w: 120, h: 40 };
137
+ g.setNode(n.id, { width: sz.w, height: sz.h });
138
+ }
139
+ for (const e of doc.edges)
140
+ g.setEdge(e.from, e.to);
141
+ dagre.layout(g);
142
+ // 同层对齐 + 层重心平滑:mermaid 观感的关键——dagre 按"总弯曲最小"摆位,
143
+ // 单节点层的中心仍会漂(被分支拉偏),主流向呈 S 弯。两步修:
144
+ // ① 层内平移到共同中心(保留层内相对分布);② 层中心向父/子层中心靠拢
145
+ // (两轮迭代)→ 主流纯直线,分支围绕主流张开。
146
+ const lr = doc.direction === 'LR' || doc.direction === 'RL';
147
+ const rankOf = (id) => {
148
+ const nd = g.node(id);
149
+ return String(Math.round(lr ? nd.x : nd.y));
150
+ };
151
+ const rankIds = new Map();
152
+ for (const id of g.nodes()) {
153
+ const k = rankOf(id);
154
+ (rankIds.get(k) ?? rankIds.set(k, []).get(k)).push(id);
155
+ }
156
+ const memberMean = new Map();
157
+ for (const [k, ids] of rankIds) {
158
+ const arr = ids.map(id => (lr ? g.node(id).y : g.node(id).x));
159
+ memberMean.set(k, arr.reduce((a, b) => a + b, 0) / arr.length);
160
+ }
161
+ // 主链对齐:最长路径(忽略回边)上的节点 = 主流,全部钉到同一轴线(主流纯水平/垂直);
162
+ // 含主链节点的层整体平移(保留层内分支展开),纯分支层沿用平滑结果
163
+ const adj = new Map();
164
+ for (const e of doc.edges) {
165
+ (adj.get(e.from) ?? adj.set(e.from, []).get(e.from)).push(e.to);
166
+ }
167
+ const dp = new Map();
168
+ const next = new Map();
169
+ const onStack = new Set();
170
+ const visit = (id) => {
171
+ if (dp.has(id))
172
+ return dp.get(id);
173
+ if (onStack.has(id))
174
+ return 0; // 回边,断链
175
+ onStack.add(id);
176
+ let best = 0;
177
+ for (const t of adj.get(id) ?? []) {
178
+ const v = visit(t) + 1;
179
+ if (v > best) {
180
+ best = v;
181
+ next.set(id, t);
182
+ }
183
+ }
184
+ onStack.delete(id);
185
+ dp.set(id, best);
186
+ return best;
187
+ };
188
+ let head = doc.nodes[0]?.id;
189
+ for (const n of doc.nodes)
190
+ if (visit(n.id) > (head ? (dp.get(head) ?? 0) : -1))
191
+ head = n.id;
192
+ const chain = new Set();
193
+ for (let cur = head; cur && !chain.has(cur); cur = next.get(cur)) {
194
+ chain.add(cur);
195
+ }
196
+ const axisVals = [...chain].map(id => (lr ? g.node(id).y : g.node(id).x));
197
+ const axis = axisVals.length ? axisVals.reduce((a, b) => a + b, 0) / axisVals.length : (memberMean.values().next().value ?? 0);
198
+ const chainRank = new Map();
199
+ for (const id of chain)
200
+ chainRank.set(rankOf(id), id);
201
+ const centers = new Map(memberMean);
202
+ for (const [k, ids] of rankIds) {
203
+ const mainId = chainRank.get(k);
204
+ if (mainId) {
205
+ const mainVal = lr ? g.node(mainId).y : g.node(mainId).x;
206
+ centers.set(k, (memberMean.get(k) ?? mainVal) + (axis - mainVal));
207
+ }
208
+ }
209
+ const boxes = new Map();
210
+ let W = 0, H = 0;
211
+ for (const id of g.nodes()) {
212
+ const nd = g.node(id);
213
+ const sz = sizes.get(id) ?? { w: 120, h: 40 };
214
+ const key = rankOf(id);
215
+ const aligned = centers.get(key) ?? (lr ? nd.y : nd.x);
216
+ const own = lr ? nd.y : nd.x;
217
+ const shifted = aligned + (own - (memberMean.get(key) ?? own));
218
+ const cx = lr ? nd.x : shifted;
219
+ const cy = lr ? shifted : nd.y;
220
+ const x = Math.round(cx - sz.w / 2), y = Math.round(cy - sz.h / 2);
221
+ boxes.set(id, { x, y, w: sz.w, h: sz.h });
222
+ W = Math.max(W, x + sz.w);
223
+ H = Math.max(H, y + sz.h);
224
+ }
225
+ return { boxes, W, H };
226
+ }
227
+ /**
228
+ * Render a mermaid flowchart from URL params (`/draw/mermaid?m=<code>`).
229
+ * v1 subset: graph/flowchart with node shapes, edge styles/labels and
230
+ * subgraphs (→ boundary groups). Everything renders through the archmap
231
+ * engine — styles, interactivity, PNG and caching all inherited.
232
+ */
233
+ export function renderMermaidFromUrl(url, interactive = false) {
234
+ const params = url.searchParams;
235
+ const m = params.get('m');
236
+ if (m === null || m.trim() === '')
237
+ throw new ApiError(400, `"m" (mermaid source) is required. Example: /draw/mermaid?${N_EXAMPLE}`);
238
+ if (m.length > M_MAX)
239
+ throw new ApiError(400, `"m" too long: ${m.length} > ${M_MAX}`);
240
+ const head = m.trim().split(/\s+/)[0]?.toLowerCase() ?? '';
241
+ if (head === 'gantt')
242
+ return renderGanttFromUrl(url, interactive);
243
+ if (head !== 'graph' && head !== 'flowchart') {
244
+ throw new ApiError(400, `only "graph/flowchart" and "gantt" are supported, got "${head || '(empty)'}"`);
245
+ }
246
+ const doc = parseFlow(m);
247
+ const v = resolveVersion(params.get('v'));
248
+ const tParam = params.get('t');
249
+ const style = tParam === 'mono' || tParam === 'soft' ? tParam : 'base';
250
+ const skin = resolveSkin('sankey', style === 'base' ? tParam : null, schemeParam(params));
251
+ const title = params.get('title')?.trim() || undefined;
252
+ // 尺寸测量与 archmap 同源(naturalSize),布局后转 archmap 像素节点
253
+ const archNodes = doc.nodes.map((n) => ({ id: n.id, type: toShape(n.shape).nodeType, label: n.label, shape: toShape(n.shape).shape }));
254
+ const sizes = new Map(archNodes.map((n) => [n.id, naturalSize(n)]));
255
+ const { boxes } = layout(doc, sizes);
256
+ const placedNodes = archNodes.map((n) => {
257
+ const b = boxes.get(n.id);
258
+ return { ...n, px: { x: b.x + 26, y: b.y + 26 } }; // +PAD 对齐 archmap 画布留白
259
+ });
260
+ const edges = doc.edges.map((e) => ({
261
+ from: e.from, to: e.to, label: e.label || undefined,
262
+ variant: e.dotted ? 'dash' : 'plain',
263
+ }));
264
+ const boundaries = doc.groups.map((g) => ({ label: g.title, ids: [...g.nodes] }));
265
+ const opts = {
266
+ nodes: placedNodes, edges, boundaries, title, style, interactive,
267
+ gridCols: 0,
268
+ minW: clampInt(params, 'w', 0, 200, 2400),
269
+ minH: clampInt(params, 'h', 0, 140, 2000),
270
+ v, skin,
271
+ aria: title ?? `mermaid flowchart, ${doc.nodes.length} nodes`,
272
+ edgeMode: 'straight',
273
+ straightDir: doc.direction === 'LR' || doc.direction === 'RL' ? 'LR' : 'TB',
274
+ tagQuery: url.search, tagKind: 'mermaid', // 角标直链 explore(#44)
275
+ };
276
+ return renderArchmapCore(opts);
277
+ }
@@ -0,0 +1,10 @@
1
+ import { type DrawResult } from './query.js';
2
+ /**
3
+ * Render a mindmap from a URL's query params (`/draw/mindmap`).
4
+ *
5
+ * Each repeated `n=` carries one root-to-leaf path (`Product/Features/Speed`);
6
+ * shared prefixes merge. `style` picks the form: `organic` (bezier + text,
7
+ * default), `tree` (boxes + elbows), `radial` (root-centred fan). Throws
8
+ * ApiError(400) with a corrective example on malformed params.
9
+ */
10
+ export declare function renderMindmapFromUrl(url: URL, interactive?: boolean): DrawResult;