@joplo-app/core 0.2.18 → 0.4.1

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 (61) hide show
  1. package/dist/actions.d.ts +6 -0
  2. package/dist/actions.js +34 -0
  3. package/dist/agent-skill.d.ts +9 -15
  4. package/dist/agent-skill.js +41 -44
  5. package/dist/auto-caption.d.ts +3 -0
  6. package/dist/auto-caption.js +33 -0
  7. package/dist/catalog.d.ts +39 -47
  8. package/dist/catalog.js +27 -334
  9. package/dist/compile.d.ts +2 -8
  10. package/dist/compile.js +230 -393
  11. package/dist/content-i18n.js +27 -16
  12. package/dist/feature-diff.d.ts +9 -9
  13. package/dist/feature-diff.js +28 -6
  14. package/dist/focus.d.ts +6 -2
  15. package/dist/focus.js +28 -36
  16. package/dist/guide.d.ts +10 -12
  17. package/dist/guide.js +372 -594
  18. package/dist/index.d.ts +3 -1
  19. package/dist/index.js +3 -1
  20. package/dist/media.d.ts +10 -0
  21. package/dist/media.js +43 -0
  22. package/dist/node.d.ts +1 -2
  23. package/dist/node.js +1 -2
  24. package/dist/outline.js +1 -1
  25. package/dist/pace.d.ts +4 -1
  26. package/dist/pace.js +7 -3
  27. package/dist/player.d.ts +8 -41
  28. package/dist/player.js +83 -147
  29. package/dist/playground.d.ts +38 -0
  30. package/dist/playground.js +111 -0
  31. package/dist/plugin-data.d.ts +11 -0
  32. package/dist/plugin-data.js +96 -0
  33. package/dist/plugins/compiler.d.ts +67 -0
  34. package/dist/plugins/compiler.js +434 -0
  35. package/dist/plugins/data.d.ts +12 -0
  36. package/dist/plugins/data.js +120 -0
  37. package/dist/result.d.ts +1 -1
  38. package/dist/result.js +1 -0
  39. package/dist/runtime.d.ts +22 -0
  40. package/dist/runtime.js +18 -0
  41. package/dist/schema.d.ts +593 -112
  42. package/dist/schema.js +62 -52
  43. package/dist/scope.js +14 -5
  44. package/dist/step-identity.d.ts +1 -1
  45. package/dist/step-identity.js +1 -1
  46. package/dist/themes.d.ts +7 -0
  47. package/dist/themes.js +5 -0
  48. package/dist/traits.d.ts +7 -0
  49. package/dist/traits.js +26 -0
  50. package/dist/validate.js +17 -4
  51. package/package.json +7 -4
  52. package/dist/diagram/elk.d.ts +0 -6
  53. package/dist/diagram/elk.js +0 -56
  54. package/dist/diagram/graph-layout.d.ts +0 -123
  55. package/dist/diagram/graph-layout.js +0 -620
  56. package/dist/diagram/index.d.ts +0 -41
  57. package/dist/diagram/index.js +0 -92
  58. package/dist/diagram/model.d.ts +0 -217
  59. package/dist/diagram/model.js +0 -189
  60. package/dist/diagram/sequence-layout.d.ts +0 -12
  61. package/dist/diagram/sequence-layout.js +0 -185
@@ -1,620 +0,0 @@
1
- /**
2
- * 架构图 / 状态机的布局(D69):ELK layered + 层级处理(hierarchyHandling = INCLUDE_CHILDREN),正交走线。
3
- *
4
- * 可读性修复(D69 补充,用户看了 v2 的效果:“几乎看不到谁调用了谁”):
5
- * - 比例适应舞台:同时试几种候选(方向 right / down × 是否压缩层次),取外框比例最接近目标(舞台)比例的一种;
6
- * 作者写了 direction 时只在这个方向里选。ELK 在层级图里不支持“分组各自的方向”和图换行,所以靠这两个杠杆:
7
- * - 方向;
8
- * - 压缩层次:节点有多个上游时,把它推到最深处的那条次要连线(优先 async)在分层时反向,图变浅、变宽。
9
- * - 连线可读:端口沿节点边均匀分散,平行连线之间至少 16px;上→下时标签不占层,布局后贴在自己的线段中部(带底色)。
10
- *
11
- * 本文件是纯函数,ELK 由调用方注入(Node 入口 diagram/elk.ts 同步运行 elkjs)。流程:
12
- * 1. 结构 → ELK 图:节点尺寸来自 model.ts 的估算;分组是复合节点(顶部留出标题条);连线标签带尺寸,ELK 为它们留位置。
13
- * 2. 回边(让图成环的连线,如“工具调用”回到 Biz Server、“回复”回到客户端)自己按源码顺序做 DFS 找出,
14
- * 交给 ELK 前先反向,布局后再把折线反回来:方向由作者的书写顺序决定,结果稳定、可预期。
15
- * 另外“指回上游所在分组”的连线也按回边处理,避免把一个分组拉成横跨整张图的长条。
16
- * 3. 布局结果平移到 (M, M)、坐标取 0.5px,分组标题沿顶部标题条找一个没有连线穿过的位置。
17
- *
18
- * 同一结构总是得到同一结果:ELK 的随机种子固定,输入按源码顺序,算法本身是确定的(测试覆盖)。
19
- */
20
- import { GROUP_HEAD, GROUP_PAD, START, groupTitleWidth } from "./model.js";
21
- /** 电脑舞台的目标比例:1280 × 800 的舞台留出四周边距后约 1232 × 756。 */
22
- export const DEFAULT_ASPECT = 1232 / 756;
23
- const M = 12;
24
- const r2 = (n) => Math.round(n * 2) / 2;
25
- /** 不参与分层的连线用到的看不见的点(D69 补充),以及它的两段连线的后缀。 */
26
- const VIA = '__via:';
27
- const VIA_A = '#a';
28
- const VIA_B = '#b';
29
- /**
30
- * 根图的 ELK 选项。间距宁可宽松也不挤:平行连线之间 ≥ 16px、端口沿节点边均匀分散,
31
- * 整图缩小到舞台上时仍能分清每一条线(D69 补充)。
32
- */
33
- export function rootOptions(direction) {
34
- return {
35
- 'elk.algorithm': 'layered',
36
- 'elk.direction': direction === 'down' ? 'DOWN' : 'RIGHT',
37
- 'elk.hierarchyHandling': 'INCLUDE_CHILDREN',
38
- 'elk.edgeRouting': 'ORTHOGONAL',
39
- 'elk.randomSeed': '1',
40
- 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
41
- 'elk.layered.cycleBreaking.strategy': 'MODEL_ORDER',
42
- 'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX',
43
- 'elk.layered.thoroughness': '20',
44
- 'elk.layered.mergeEdges': 'false',
45
- // 上→下:同层(横向)间距放宽、层间(纵向)间距收紧,让图更接近横向舞台的比例
46
- 'elk.spacing.nodeNode': direction === 'down' ? '56' : '32',
47
- 'elk.layered.spacing.nodeNodeBetweenLayers': direction === 'down' ? '48' : '48',
48
- 'elk.spacing.edgeNode': '18',
49
- 'elk.spacing.edgeEdge': '16',
50
- 'elk.spacing.portPort': '18',
51
- 'elk.portAlignment.default': 'DISTRIBUTED',
52
- 'elk.layered.spacing.edgeNodeBetweenLayers': '18',
53
- 'elk.layered.spacing.edgeEdgeBetweenLayers': '16',
54
- 'elk.spacing.edgeLabel': '4',
55
- 'elk.spacing.componentComponent': '40',
56
- 'elk.edgeLabels.placement': 'CENTER',
57
- 'elk.json.edgeCoords': 'ROOT',
58
- 'elk.json.shapeCoords': 'ROOT',
59
- 'elk.padding': `[top=${M},left=${M},bottom=${M},right=${M}]`,
60
- };
61
- }
62
- /**
63
- * 回边:按源码顺序做 DFS(先从没有入边的节点出发,pin="start" 的最先、pin="end" 的最后),指向栈上节点的连线是回边;
64
- * 再加上“指回上游所在分组”的连线(u → v,v 所在、不包含 u 的最外层分组里有别的成员能走到 u)。
65
- * 连到分组的连线不参与(交给 ELK 自己处理)。
66
- */
67
- export function feedbackEdges(s) {
68
- const ids = new Set(s.nodes.map((n) => n.id));
69
- const order = new Map(s.nodes.map((n, i) => [n.id, i]));
70
- const pinOf = new Map(s.nodes.map((n) => [n.id, n.pin]));
71
- const plain = s.edges.filter((e) => ids.has(e.from) && ids.has(e.to) && e.from !== e.to);
72
- const out = new Map();
73
- const indeg = new Map();
74
- for (const e of plain) {
75
- out.set(e.from, [...(out.get(e.from) ?? []), e]);
76
- indeg.set(e.to, (indeg.get(e.to) ?? 0) + 1);
77
- }
78
- const rank = (id) => (pinOf.get(id) === 'start' ? 0 : pinOf.get(id) === 'end' ? 2 : 1);
79
- const roots = [...s.nodes]
80
- .map((n) => n.id)
81
- .sort((a, b) => rank(a) - rank(b) || (indeg.get(a) ? 1 : 0) - (indeg.get(b) ? 1 : 0) || order.get(a) - order.get(b));
82
- const back = new Set();
83
- const state = new Map(); // 1 = 在栈上,2 = 完成
84
- const visit = (v) => {
85
- state.set(v, 1);
86
- for (const e of out.get(v) ?? []) {
87
- const st = state.get(e.to);
88
- if (st === 1 || pinOf.get(e.to) === 'start' || pinOf.get(v) === 'end')
89
- back.add(e.id);
90
- else if (!st)
91
- visit(e.to);
92
- }
93
- state.set(v, 2);
94
- };
95
- for (const r of roots)
96
- if (!state.has(r))
97
- visit(r);
98
- // 指回上游所在分组的连线
99
- const parentOf = new Map(s.groups.map((g) => [g.id, g.parent]));
100
- const chain = (gid) => (gid ? [gid, ...chain(parentOf.get(gid) ?? null)] : []);
101
- const groupsOf = new Map(s.nodes.map((n) => [n.id, chain(n.parent)]));
102
- const fwd = new Map();
103
- for (const e of plain)
104
- if (!back.has(e.id))
105
- fwd.set(e.from, [...(fwd.get(e.from) ?? []), e.to]);
106
- const reaches = (a, b, skip) => {
107
- const seen = new Set([a]);
108
- const stack = [a];
109
- while (stack.length) {
110
- const x = stack.pop();
111
- if (x === b)
112
- return true;
113
- for (const y of fwd.get(x) ?? []) {
114
- if (seen.has(y) || (x === skip.from && y === skip.to))
115
- continue;
116
- seen.add(y);
117
- stack.push(y);
118
- }
119
- }
120
- return false;
121
- };
122
- for (const e of plain) {
123
- if (back.has(e.id))
124
- continue;
125
- const gu = new Set(groupsOf.get(e.from) ?? []);
126
- const outer = [...(groupsOf.get(e.to) ?? [])].reverse().find((g) => !gu.has(g));
127
- if (!outer)
128
- continue;
129
- const members = s.nodes.filter((n) => n.id !== e.to && (groupsOf.get(n.id) ?? []).includes(outer));
130
- if (members.some((m) => reaches(m.id, e.from, e)))
131
- back.add(e.id);
132
- }
133
- return back;
134
- }
135
- /** 按“有效方向”(回边已反向)算最长路径层次;有环时返回 null。 */
136
- function ranksOf(nodes, edges) {
137
- const indeg = new Map(nodes.map((n) => [n, 0]));
138
- const out = new Map();
139
- for (const [a, b] of edges) {
140
- out.set(a, [...(out.get(a) ?? []), b]);
141
- indeg.set(b, (indeg.get(b) ?? 0) + 1);
142
- }
143
- const rank = new Map(nodes.map((n) => [n, 0]));
144
- const queue = nodes.filter((n) => !indeg.get(n));
145
- let seen = 0;
146
- while (queue.length) {
147
- const v = queue.shift();
148
- seen++;
149
- for (const w of out.get(v) ?? []) {
150
- rank.set(w, Math.max(rank.get(w), rank.get(v) + 1));
151
- indeg.set(w, indeg.get(w) - 1);
152
- if (!indeg.get(w))
153
- queue.push(w);
154
- }
155
- }
156
- return seen === nodes.length ? rank : null;
157
- }
158
- /**
159
- * 压缩层次(D69 补充):ELK 的层级布局按容器逐层排——在每个容器(整张图或一个分组)里,子节点和子分组各是一个单元,
160
- * 跨单元的连线“提升”成单元之间的连线。某个单元有多个上游时,它的层次由最深的上游决定;让那条连线“不参与分层”
161
- * (相当于 Graphviz 的 constraint=false,做法见 toElk),单元就能和较浅的上游并排,整张图变浅、变宽
162
- * (例如“计费”与“大脑”并排在“控制面”下面)。只放开“还有别的入边”的连线(不让单元变成孤立的起点),
163
- * 优先 async 连线、其次写在后面的;每次只在这一层真的变浅时接受。返回这些连线的 id。
164
- */
165
- export function compactReversals(s, base) {
166
- const parentOf = new Map([...s.nodes.map((n) => [n.id, n.parent]), ...s.groups.map((g) => [g.id, g.parent])]);
167
- /** 从自己到最外层的祖先链(含自己),最后是 null(整张图)。 */
168
- const chain = (id) => {
169
- const out = [id];
170
- const seen = new Set([id]);
171
- for (let q = parentOf.get(id) ?? null; q && !seen.has(q); q = parentOf.get(q) ?? null) {
172
- seen.add(q);
173
- out.push(q);
174
- }
175
- out.push(null);
176
- return out;
177
- };
178
- const known = new Set(parentOf.keys());
179
- const order = new Map(s.edges.map((e, i) => [e.id, i]));
180
- const levels = new Map();
181
- for (const e of s.edges) {
182
- if (!known.has(e.from) || !known.has(e.to) || e.from === e.to)
183
- continue;
184
- const cu = chain(e.from);
185
- const cv = chain(e.to);
186
- const lca = cu.find((c) => c !== cu[0] && cv.includes(c) && c !== cv[0]);
187
- if (lca === undefined)
188
- continue;
189
- const u = cu[cu.indexOf(lca) - 1];
190
- const v = cv[cv.indexOf(lca) - 1];
191
- if (u === undefined || v === undefined || u === null || v === null || u === v)
192
- continue;
193
- levels.set(lca, [...(levels.get(lca) ?? []), { e, u, v }]);
194
- }
195
- const rev = new Set();
196
- for (const lifted of levels.values()) {
197
- const units = [...new Set(lifted.flatMap((l) => [l.u, l.v]))];
198
- const eff = (l) => (base.has(l.e.id) ? [l.v, l.u] : [l.u, l.v]);
199
- /** 参与分层的连线(放开的不算)。 */
200
- const active = () => lifted.filter((l) => !rev.has(l.e.id)).map(eff);
201
- for (let iter = 0; iter < 8; iter++) {
202
- const ranks = ranksOf(units, active());
203
- if (!ranks)
204
- break;
205
- const depth = Math.max(0, ...ranks.values());
206
- let best = null;
207
- const candidates = lifted
208
- .filter((l) => {
209
- const [u, v] = eff(l);
210
- if (ranks.get(v) !== ranks.get(u) + 1)
211
- return false;
212
- if (rev.has(l.e.id))
213
- return false;
214
- return lifted.some((o) => o.e.id !== l.e.id && !rev.has(o.e.id) && eff(o)[1] === v && ranks.get(eff(o)[0]) + 1 < ranks.get(v));
215
- })
216
- .sort((a, b) => Number(!!b.e.async) - Number(!!a.e.async) || order.get(b.e.id) - order.get(a.e.id));
217
- for (const l of candidates) {
218
- rev.add(l.e.id);
219
- const r = ranksOf(units, active());
220
- rev.delete(l.e.id);
221
- if (!r)
222
- continue;
223
- const d = Math.max(0, ...r.values());
224
- const sum = [...r.values()].reduce((x, y) => x + y, 0);
225
- if (d < depth && (!best || d < best.depth || (d === best.depth && sum < best.sum)))
226
- best = { l, depth: d, sum };
227
- }
228
- if (!best)
229
- break;
230
- rev.add(best.l.e.id);
231
- }
232
- }
233
- return rev;
234
- }
235
- /** 结构 → ELK JSON。连线放在根上(edgeCoords = ROOT,ELK 自己找最近的公共祖先)。 */
236
- export function toElk(s, variant = { direction: s.direction === 'down' ? 'down' : 'right', compact: false, labelsInLayout: true }) {
237
- const reversed = feedbackEdges(s);
238
- const free = variant.compact ? compactReversals(s, reversed) : new Set();
239
- const elkNode = new Map();
240
- const root = { id: '__root', layoutOptions: rootOptions(variant.direction), children: [], edges: [] };
241
- // 间距类选项不会从根图继承到分组里:每个分组复制一份,组内的层间距同样放得下贴在线上的标签
242
- const spacing = Object.fromEntries(Object.entries(rootOptions(variant.direction)).filter(([k]) => k.startsWith('elk.spacing.') || k.startsWith('elk.layered.spacing.') || k === 'elk.portAlignment.default'));
243
- const groupNode = (g) => ({
244
- id: g.id,
245
- children: [],
246
- layoutOptions: {
247
- ...spacing,
248
- // 组内略紧:层间 30px 仍放得下 18px 高、贴在线上的标签(四周各留 3px)
249
- ...(variant.direction === 'down' ? { 'elk.layered.spacing.nodeNodeBetweenLayers': '30', 'elk.spacing.nodeNode': '40', 'elk.layered.spacing.edgeNodeBetweenLayers': '12' } : {}),
250
- 'elk.padding': `[top=${GROUP_HEAD + GROUP_PAD - 4},left=${GROUP_PAD},bottom=${GROUP_PAD},right=${GROUP_PAD}]`,
251
- // 标题要放得下:分组至少和标题一样宽
252
- 'elk.nodeSize.constraints': 'MINIMUM_SIZE',
253
- 'elk.nodeSize.minimum': `(${groupTitleWidth(g.label, !!g.icon) + 2 * GROUP_PAD}, ${GROUP_HEAD + 2 * GROUP_PAD})`,
254
- ...(g.pin ? { 'elk.layered.layering.layerConstraint': g.pin === 'start' ? 'FIRST' : 'LAST' } : {}),
255
- },
256
- });
257
- for (const g of s.groups)
258
- elkNode.set(g.id, groupNode(g));
259
- const parentFor = (pid) => (pid ? elkNode.get(pid) ?? root : root);
260
- for (const n of s.nodes)
261
- elkNode.set(n.id, { id: n.id, width: n.w, height: n.h, ...(n.pin ? { layoutOptions: { 'elk.layered.layering.layerConstraint': n.pin === 'start' ? 'FIRST' : 'LAST' } } : {}) });
262
- // 节点与分组按源码顺序挂到父分组下(ELK 的 considerModelOrder 用这个顺序排同层;父分组可能写在后面,先全部建好再挂)
263
- const items = [...s.groups.map((g) => ({ seq: g.seq, id: g.id, parent: g.parent, initial: false })), ...s.nodes.map((n) => ({ seq: n.seq, id: n.id, parent: n.parent, initial: !!n.initial }))].sort((a, b) => a.seq - b.seq);
264
- for (const it of items) {
265
- const kids = parentFor(it.parent).children;
266
- if (it.initial) {
267
- // 状态机的起点:一个实心小圆点,连到初始状态
268
- const sid = `${START}${it.id}`;
269
- kids.push({ id: sid, width: 14, height: 14, layoutOptions: { 'elk.layered.layering.layerConstraint': 'FIRST' } });
270
- root.edges.push({ id: sid, sources: [sid], targets: [it.id] });
271
- }
272
- kids.push(elkNode.get(it.id));
273
- }
274
- // 空分组:给一个占位尺寸(ELK 对没有子节点的复合节点按普通节点处理)
275
- for (const g of s.groups) {
276
- const en = elkNode.get(g.id);
277
- if (!en.children.length) {
278
- en.width = groupTitleWidth(g.label, !!g.icon) + 2 * GROUP_PAD;
279
- en.height = GROUP_HEAD + 2 * GROUP_PAD + 20;
280
- delete en.children;
281
- }
282
- }
283
- const known = new Set([...s.nodes.map((n) => n.id), ...s.groups.map((g) => g.id)]);
284
- const parentOfAny = new Map([...s.nodes.map((n) => [n.id, n.parent]), ...s.groups.map((g) => [g.id, g.parent])]);
285
- const ancestors = (id) => {
286
- const out = [];
287
- for (let q = parentOfAny.get(id) ?? null; q; q = parentOfAny.get(q) ?? null)
288
- out.push(q);
289
- return [...out, null];
290
- };
291
- for (const e of s.edges) {
292
- if (!known.has(e.from) || !known.has(e.to))
293
- continue; // 编译期已报 UNKNOWN_DIAGRAM_NODE
294
- if (free.has(e.id)) {
295
- // 不参与分层的连线:from → X、to → X 两段,X 是两端最近公共容器里的一个看不见的点(在两端之后的层)。
296
- // 分层时 from 和 to 互不约束;走线仍由 ELK 完成,布局后拼成一条 from … X … to 的折线(layoutVariant)
297
- const lca = ancestors(e.from).find((c) => ancestors(e.to).includes(c)) ?? null;
298
- const via = { id: `${VIA}${e.id}`, width: 1, height: 1 };
299
- parentFor(lca).children.push(via);
300
- root.edges.push({ id: `${VIA}${e.id}${VIA_A}`, sources: [e.from], targets: [via.id] }, { id: `${VIA}${e.id}${VIA_B}`, sources: [e.to], targets: [via.id] });
301
- continue;
302
- }
303
- const rev = reversed.has(e.id);
304
- root.edges.push({
305
- id: e.id,
306
- sources: [rev ? e.to : e.from],
307
- targets: [rev ? e.from : e.to],
308
- ...(e.label && variant.labelsInLayout ? { labels: [{ text: e.label, width: e.lw, height: e.lh, layoutOptions: { 'elk.edgeLabels.inline': 'true' } }] } : {}),
309
- });
310
- }
311
- return { graph: root, reversed };
312
- }
313
- /**
314
- * 布局:结构 → 坐标(ELK),再整理成 IR 用的 GraphLayout。
315
- * 作者写了方向时只在这个方向里选;没写(auto)时 right、down 都试。每个方向再试“压缩层次”与否,
316
- * 取“放进舞台后缩放比例最大”(字最大)的一种,比例偏差、交叉、压缩略扣分。结果确定。
317
- */
318
- export function layoutGraph(s, run, goal = { aspect: DEFAULT_ASPECT }) {
319
- if (!s.nodes.length && !s.groups.length)
320
- return { kind: 'graph', engine: 'elk', width: 0, height: 0, nodes: {}, groups: {}, titles: {}, edges: {} };
321
- const dirs = s.direction === 'auto' ? ['down', 'right'] : [s.direction];
322
- const target = Math.max(0.2, Math.min(8, goal.aspect || DEFAULT_ASPECT));
323
- // 放图区域:给了就用;没给按目标比例取一个 1200 宽的区域(只用来比较候选,不影响坐标)
324
- const areaW = goal.width ?? 1200;
325
- const areaH = goal.height ?? areaW / target;
326
- let best = null;
327
- for (const direction of dirs) {
328
- const base = feedbackEdges(s);
329
- const canCompact = compactReversals(s, base).size > 0;
330
- for (const compact of canCompact ? [false, true] : [false]) {
331
- // 上→下时标签不占层(标签很矮,放在层与层之间的竖线上就够),左→右时标签占位(标签很宽,需要横向空间)
332
- const l = layoutVariant(s, run, { direction, compact, labelsInLayout: direction === 'right' });
333
- // 读得清最重要:整图放进区域后的缩放比例越大越好(取对数,与比例偏差同量纲);交叉多、压缩略扣分
334
- const fit = Math.min(1, areaW / Math.max(1, l.width), areaH / Math.max(1, l.height));
335
- const score = -Math.log(fit) + 0.25 * Math.abs(Math.log(Math.max(1, l.width) / Math.max(1, l.height) / target)) + 0.03 * crossings(l) + (compact ? 0.04 : 0);
336
- if (!best || score < best.score - 1e-9)
337
- best = { l, score };
338
- }
339
- }
340
- return best.l;
341
- }
342
- /** 两条连线(正交折线)之间的交叉数。 */
343
- export function crossings(l) {
344
- const segs = Object.entries(l.edges).flatMap(([id, e]) => e.points.slice(1).map((p, i) => ({ id, a: e.points[i], b: p })));
345
- let n = 0;
346
- for (let i = 0; i < segs.length; i++)
347
- for (let j = i + 1; j < segs.length; j++) {
348
- const s1 = segs[i];
349
- const s2 = segs[j];
350
- if (s1.id === s2.id)
351
- continue;
352
- const h1 = s1.a.y === s1.b.y;
353
- const h2 = s2.a.y === s2.b.y;
354
- if (h1 === h2)
355
- continue;
356
- const [h, v] = h1 ? [s1, s2] : [s2, s1];
357
- const x0 = Math.min(h.a.x, h.b.x);
358
- const x1 = Math.max(h.a.x, h.b.x);
359
- const y0 = Math.min(v.a.y, v.b.y);
360
- const y1 = Math.max(v.a.y, v.b.y);
361
- if (v.a.x > x0 + 0.5 && v.a.x < x1 - 0.5 && h.a.y > y0 + 0.5 && h.a.y < y1 - 0.5)
362
- n++;
363
- }
364
- return n;
365
- }
366
- /** 一种候选的完整布局。 */
367
- export function layoutVariant(s, run, variant) {
368
- const { graph, reversed } = toElk(s, variant);
369
- const res = run(graph);
370
- const nodes = {};
371
- const groups = {};
372
- const starts = {};
373
- const gids = new Set(s.groups.map((g) => g.id));
374
- const walk = (n) => {
375
- for (const c of n.children ?? []) {
376
- const b = { x: c.x ?? 0, y: c.y ?? 0, w: c.width ?? 0, h: c.height ?? 0 };
377
- if (gids.has(c.id))
378
- groups[c.id] = b;
379
- else if (c.id.startsWith(START))
380
- starts[c.id.slice(START.length)] = b;
381
- else if (!c.id.startsWith(VIA))
382
- nodes[c.id] = b;
383
- walk(c);
384
- }
385
- };
386
- walk(res);
387
- const edges = {};
388
- const allEdges = [];
389
- const collect = (n) => {
390
- allEdges.push(...(n.edges ?? []));
391
- for (const c of n.children ?? [])
392
- collect(c);
393
- };
394
- collect(res);
395
- for (const e of allEdges) {
396
- const pts = [];
397
- for (const sec of e.sections ?? []) {
398
- for (const p of [sec.startPoint, ...(sec.bendPoints ?? []), sec.endPoint]) {
399
- const last = pts[pts.length - 1];
400
- if (!last || last.x !== p.x || last.y !== p.y)
401
- pts.push({ x: p.x, y: p.y });
402
- }
403
- }
404
- if (reversed.has(e.id))
405
- pts.reverse();
406
- const l = e.labels?.[0];
407
- edges[e.id] = { points: pts, label: l && l.x !== undefined ? { x: l.x, y: l.y ?? 0, w: l.width, h: l.height } : null };
408
- }
409
- // 拼回不参与分层的连线:from → X 加上 (to → X) 反过来;去掉共线的中间点
410
- for (const id of Object.keys(edges)) {
411
- if (!id.startsWith(VIA) || !id.endsWith(VIA_A))
412
- continue;
413
- const eid = id.slice(VIA.length, -VIA_A.length);
414
- const a = edges[id].points;
415
- const b = edges[`${VIA}${eid}${VIA_B}`]?.points ?? [];
416
- delete edges[id];
417
- delete edges[`${VIA}${eid}${VIA_B}`];
418
- edges[eid] = { points: simplify([...a, ...[...b].reverse()]), label: null };
419
- }
420
- const freeLabels = !variant.labelsInLayout ? null : new Set(s.edges.filter((e) => e.label && edges[e.id] && !edges[e.id].label).map((e) => e.id));
421
- if (!variant.labelsInLayout || freeLabels?.size) {
422
- // 标签贴在自己的线段中部:避开节点、分组标题条和已放好的标签(D69 补充)
423
- const heads = Object.values(groups).map((g) => ({ x: g.x, y: g.y, w: g.w, h: GROUP_HEAD }));
424
- const placed = placeLabels(s.edges.filter((e) => e.label && edges[e.id] && (!freeLabels || freeLabels.has(e.id))), edges, [...Object.values(nodes), ...heads, ...Object.values(edges).flatMap((x) => (x.label ? [x.label] : []))]);
425
- for (const [id, box] of placed)
426
- edges[id].label = box;
427
- }
428
- return finish(s, { nodes, groups, edges, starts }, variant.direction);
429
- }
430
- /** 去掉重复点和共线的中间点。 */
431
- function simplify(points) {
432
- const out = [];
433
- for (const p of points) {
434
- const last = out[out.length - 1];
435
- if (last && Math.abs(last.x - p.x) < 0.01 && Math.abs(last.y - p.y) < 0.01)
436
- continue;
437
- out.push({ ...p });
438
- while (out.length >= 3) {
439
- const [a, b, c] = out.slice(-3);
440
- const collinear = (Math.abs(a.x - b.x) < 0.01 && Math.abs(b.x - c.x) < 0.01) || (Math.abs(a.y - b.y) < 0.01 && Math.abs(b.y - c.y) < 0.01);
441
- if (!collinear)
442
- break;
443
- out.splice(out.length - 2, 1);
444
- }
445
- }
446
- return out;
447
- }
448
- const overlapArea = (a, b) => Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y));
449
- const inflate = (b, m) => ({ x: b.x - m, y: b.y - m, w: b.w + 2 * m, h: b.h + 2 * m });
450
- /** 折线上按长度比例 t 处的点与这一段的方向。 */
451
- function pointOn(points, t) {
452
- const segs = points.slice(1).map((q, i) => Math.hypot(q.x - points[i].x, q.y - points[i].y));
453
- const total = segs.reduce((a, b) => a + b, 0);
454
- let d = total * t;
455
- for (let i = 0; i < segs.length; i++) {
456
- if (d <= segs[i] || i === segs.length - 1) {
457
- const a = points[i];
458
- const b = points[i + 1];
459
- const k = segs[i] ? Math.min(1, d / segs[i]) : 0;
460
- return { p: { x: a.x + (b.x - a.x) * k, y: a.y + (b.y - a.y) * k }, horizontal: Math.abs(b.y - a.y) < Math.abs(b.x - a.x) };
461
- }
462
- d -= segs[i];
463
- }
464
- return { p: points[0], horizontal: true };
465
- }
466
- /**
467
- * 标签贴在自己的线上:从折线中点出发沿线向两侧找位置(先压在线上,再贴在线的两侧),标签框不与节点、分组标题条、
468
- * 已放好的标签重叠,尽量不压别的连线;都不行时取代价最小的位置。按源码顺序放,结果确定。
469
- */
470
- export function placeLabels(list, routes, obstacles) {
471
- const out = new Map();
472
- const taken = [];
473
- const samplesOf = new Map(Object.entries(routes).map(([id, e]) => [id, sampleRoute(e.points)]));
474
- const ts = [0.5];
475
- for (let k = 1; k <= 18; k++)
476
- ts.push(0.5 - k * 0.025, 0.5 + k * 0.025);
477
- for (const e of list) {
478
- const pts = routes[e.id]?.points;
479
- if (!pts || pts.length < 2 || !e.label)
480
- continue;
481
- const others = [...samplesOf].filter(([id]) => id !== e.id).flatMap(([, ps]) => ps);
482
- const own = samplesOf.get(e.id) ?? [];
483
- let best = null;
484
- for (const off of [0, -1, 1]) {
485
- for (const t of ts) {
486
- const { p, horizontal } = pointOn(pts, t);
487
- // 在线上(off = 0)或贴在线的一侧:竖线时左右挪半个标签宽,横线时上下挪半个标签高
488
- const c = horizontal ? { x: p.x, y: p.y + off * (e.lh / 2 + 2) } : { x: p.x + off * (e.lw / 2 + 3), y: p.y };
489
- const box = { x: c.x - e.lw / 2, y: c.y - e.lh / 2, w: e.lw, h: e.lh };
490
- const lines = others.reduce((a, q) => a + (q.x > box.x - 1 && q.x < box.x + box.w + 1 && q.y > box.y - 1 && q.y < box.y + box.h + 1 ? 4 : 0), 0);
491
- // 短线上压着标签会把线和箭头整段盖住:按标签盖住自己这条线的比例扣分,短线时标签改贴在线旁边
492
- const covered = own.length ? own.filter((q) => q.x > box.x - 1 && q.x < box.x + box.w + 1 && q.y > box.y - 1 && q.y < box.y + box.h + 1).length / own.length : 0;
493
- const cost = obstacles.reduce((a, o) => a + overlapArea(box, inflate(o, 3)), 0) * 10 +
494
- taken.reduce((a, o) => a + overlapArea(box, inflate(o, 3)) * 20, 0) +
495
- lines +
496
- Math.max(0, covered - 0.25) * 80 +
497
- Math.abs(t - 0.5) * 40 +
498
- Math.abs(off) * 6;
499
- if (!best || cost < best.cost)
500
- best = { box, cost };
501
- }
502
- }
503
- if (best) {
504
- out.set(e.id, best.box);
505
- taken.push(best.box);
506
- }
507
- }
508
- return out;
509
- }
510
- /** 平移到 (M, M)、取 0.5px,放分组标题。 */
511
- function finish(s, l, direction) {
512
- const xs = [];
513
- const ys = [];
514
- const add = (b) => {
515
- xs.push(b.x, b.x + b.w);
516
- ys.push(b.y, b.y + b.h);
517
- };
518
- [...Object.values(l.nodes), ...Object.values(l.groups), ...Object.values(l.starts)].forEach(add);
519
- for (const e of Object.values(l.edges)) {
520
- e.points.forEach((p) => add({ x: p.x, y: p.y, w: 0, h: 0 }));
521
- if (e.label)
522
- add(e.label);
523
- }
524
- if (!xs.length)
525
- return { kind: 'graph', engine: 'elk', width: 0, height: 0, nodes: {}, groups: {}, titles: {}, edges: {} };
526
- const dx = M - Math.min(...xs);
527
- const dy = M - Math.min(...ys);
528
- const mv = (b) => ({ x: r2(b.x + dx), y: r2(b.y + dy), w: r2(b.w), h: r2(b.h) });
529
- const nodes = Object.fromEntries(Object.entries(l.nodes).map(([k, b]) => [k, mv(b)]));
530
- const groups = Object.fromEntries(Object.entries(l.groups).map(([k, b]) => [k, mv(b)]));
531
- const edges = Object.fromEntries(Object.entries(l.edges).map(([k, e]) => [k, { points: e.points.map((p) => ({ x: r2(p.x + dx), y: r2(p.y + dy) })), label: e.label ? mv(e.label) : null }]));
532
- const starts = Object.fromEntries(Object.entries(l.starts).map(([k, b]) => [k, mv(b)]));
533
- const titles = placeTitles(s, groups, edges);
534
- return {
535
- kind: 'graph',
536
- engine: 'elk',
537
- ...(direction ? { direction } : {}),
538
- width: Math.ceil(Math.max(...xs) + dx + M),
539
- height: Math.ceil(Math.max(...ys) + dy + M),
540
- nodes,
541
- groups,
542
- titles,
543
- edges,
544
- ...(Object.keys(starts).length ? { starts } : {}),
545
- };
546
- }
547
- /** 沿折线每 4px 取一个点。 */
548
- export function sampleRoute(points, step = 4) {
549
- const out = [];
550
- for (let i = 0; i < points.length - 1; i++) {
551
- const a = points[i];
552
- const b = points[i + 1];
553
- const n = Math.max(1, Math.ceil(Math.hypot(b.x - a.x, b.y - a.y) / step));
554
- for (let k = 0; k <= n; k++)
555
- out.push({ x: a.x + ((b.x - a.x) * k) / n, y: a.y + ((b.y - a.y) * k) / n });
556
- }
557
- return out;
558
- }
559
- /** 分组标题:在分组顶部标题条里,从左往右找一个没有连线穿过的位置;都有时取穿过最少的。 */
560
- export function placeTitles(s, groups, edges) {
561
- const samples = Object.values(edges).flatMap((e) => sampleRoute(e.points));
562
- const crossings = (b) => samples.filter((p) => p.x > b.x - 2 && p.x < b.x + b.w + 2 && p.y > b.y - 2 && p.y < b.y + b.h + 2).length;
563
- const titles = {};
564
- for (const g of s.groups) {
565
- const b = groups[g.id];
566
- if (!b || (!g.label && !g.icon))
567
- continue;
568
- const w = Math.min(groupTitleWidth(g.label, !!g.icon), b.w - 8);
569
- let best = null;
570
- for (let x = b.x + 6; x + w <= b.x + b.w - 4; x += 12) {
571
- const box = { x: r2(x), y: r2(b.y + 4), w, h: GROUP_HEAD - 6 };
572
- const n = crossings(box);
573
- if (!best || n < best.n)
574
- best = { box, n };
575
- if (n === 0)
576
- break;
577
- }
578
- titles[g.id] = best?.box ?? { x: r2(b.x + 6), y: r2(b.y + 4), w, h: GROUP_HEAD - 6 };
579
- }
580
- return titles;
581
- }
582
- /**
583
- * 没有布局引擎时的退化排列(测试、或绕过 server 直接调用 compile 的旧代码):按源码顺序排成网格,分组包住成员。
584
- * 只保证不重叠、结果确定;正式产物(dev / build / check)都用 ELK。
585
- */
586
- export function gridLayout(s) {
587
- const cols = Math.max(1, Math.ceil(Math.sqrt(s.nodes.length)));
588
- const nodes = {};
589
- s.nodes.forEach((n, i) => {
590
- nodes[n.id] = { x: M + (i % cols) * 240, y: M + 60 + Math.floor(i / cols) * 140, w: n.w, h: n.h };
591
- });
592
- const groups = {};
593
- const boxOf = (gid, seen = new Set()) => {
594
- if (groups[gid])
595
- return groups[gid];
596
- if (seen.has(gid))
597
- return null;
598
- seen.add(gid);
599
- const bs = [...s.nodes.filter((n) => n.parent === gid).map((n) => nodes[n.id]), ...s.groups.filter((g) => g.parent === gid).map((g) => boxOf(g.id, seen)).filter((b) => !!b)];
600
- if (!bs.length)
601
- return null;
602
- const x0 = Math.min(...bs.map((b) => b.x)) - GROUP_PAD;
603
- const y0 = Math.min(...bs.map((b) => b.y)) - GROUP_PAD - GROUP_HEAD;
604
- const x1 = Math.max(...bs.map((b) => b.x + b.w)) + GROUP_PAD;
605
- const y1 = Math.max(...bs.map((b) => b.y + b.h)) + GROUP_PAD;
606
- return (groups[gid] = { x: x0, y: y0, w: x1 - x0, h: y1 - y0 });
607
- };
608
- for (const g of s.groups)
609
- boxOf(g.id);
610
- const center = (b) => ({ x: b.x + b.w / 2, y: b.y + b.h / 2 });
611
- const edges = {};
612
- for (const e of s.edges) {
613
- const a = nodes[e.from] ?? groups[e.from];
614
- const b = nodes[e.to] ?? groups[e.to];
615
- if (a && b)
616
- edges[e.id] = { points: [center(a), center(b)], label: null };
617
- }
618
- const l = finish(s, { nodes, groups, edges, starts: {} });
619
- return { ...l, engine: 'grid' };
620
- }
@@ -1,41 +0,0 @@
1
- /**
2
- * 关系类图表(D69)的公共入口:给编译器挂布局、给 trace 建索引。浏览器安全(不加载 ELK)。
3
- */
4
- import type { SceneNode } from '../schema.js';
5
- import { type LayoutGoal } from './graph-layout.js';
6
- import { type DiagramLayout, type DiagramRootType, type GraphLayout, type GraphStructure } from './model.js';
7
- export * from './model.js';
8
- export { layoutSequence, SEQ_BADGE } from './sequence-layout.js';
9
- export { DEFAULT_ASPECT, compactReversals, crossings, gridLayout, layoutGraph, layoutVariant, feedbackEdges, placeLabels, toElk, rootOptions, sampleRoute, type ElkNode, type ElkEdge, type ElkRun, type LayoutGoal, type LayoutVariant } from './graph-layout.js';
10
- /** 编译期注入的图布局引擎(Node 入口的 elkLayout)。没有时退化为网格(只在测试或旧调用方出现)。 */
11
- export type GraphLayoutEngine = (s: GraphStructure, goal?: LayoutGoal) => GraphLayout;
12
- /**
13
- * 一张图的目标外框比例(D69 补充):作者写了 aspect 就用它;写了数字高度 h 时按“舞台宽度 / h”;
14
- * 否则(h="100%" 或不写,通常是层级里铺满舞台的图)用舞台画面区域的比例。
15
- */
16
- export declare function diagramGoal(node: SceneNode, viewport?: 'desktop' | 'mobile'): LayoutGoal;
17
- /** 算一张图表的布局;ELK 出错时退回网格,并通过 onError 报告(编译器转成 DIAGRAM_LAYOUT_FAILED 警告)。 */
18
- export declare function layoutFor(node: SceneNode, engine?: GraphLayoutEngine, onError?: (message: string) => void, viewport?: 'desktop' | 'mobile'): DiagramLayout | null;
19
- /** 给一棵画面树里的每张图表挂上布局(就地修改)。嵌套的图表各自布局。viewport:画面的设备(决定目标比例)。 */
20
- export declare function attachLayouts(root: SceneNode, engine?: GraphLayoutEngine, onError?: (node: SceneNode, message: string) => void, viewport?: 'desktop' | 'mobile'): void;
21
- /**
22
- * 一张图表里能被 trace 引用的东西:节点(架构图节点、状态、时序图参与者;以及有 id 的分组)、连线(连线、转换、消息),
23
- * 以及每个节点的父分组链(trace 经过时分组也被点亮)。
24
- */
25
- export type DiagramIndex = {
26
- id: string;
27
- type: DiagramRootType;
28
- nodes: Set<string>;
29
- edges: {
30
- id: string;
31
- from: string;
32
- to: string;
33
- }[];
34
- /** 节点 / 分组 → 由内到外的父分组(不含自己)。 */
35
- groupsOf: Map<string, string[]>;
36
- /** 有作者 id 的分组(可以被连线连接、出现在 trace 路径里)。 */
37
- groupIds: Set<string>;
38
- };
39
- export declare function diagramsIn(root: SceneNode): DiagramIndex[];
40
- /** 时序图的消息类型名(compile 生成缺省 id 用)。 */
41
- export declare const MESSAGE_TYPES: ReadonlySet<string>;