dsh-ppt 0.24.2 → 0.26.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.
- package/CHANGELOG.md +16 -0
- package/README.en.md +13 -13
- package/README.md +13 -13
- package/docs/DATA.md +2 -2
- package/docs/REFERENCE.en.md +8 -8
- package/docs/REFERENCE.zh.md +8 -8
- package/docs/USAGE.en.md +11 -7
- package/docs/USAGE.md +11 -7
- package/docs/VALIDATION.md +4 -0
- package/docs/WORKBENCH.md +4 -4
- package/docs/assets/intro/workflow-en-dark.svg +1 -1
- package/docs/assets/intro/workflow-en-light.svg +1 -1
- package/docs/assets/intro/workflow-en-mobile-dark.svg +1 -1
- package/docs/assets/intro/workflow-en-mobile-light.svg +1 -1
- package/docs/assets/intro/workflow-zh-dark.svg +1 -1
- package/docs/assets/intro/workflow-zh-light.svg +1 -1
- package/docs/assets/intro/workflow-zh-mobile-dark.svg +1 -1
- package/docs/assets/intro/workflow-zh-mobile-light.svg +1 -1
- package/lib/client.js +3435 -467
- package/lib/ecosystem.d.ts +73 -0
- package/lib/ecosystem.js +1352 -0
- package/lib/execution.d.ts +6 -1
- package/lib/execution.js +69 -0
- package/lib/tools.js +77 -0
- package/lib/types.d.ts +57 -1
- package/lib/workbench-language.js +4 -0
- package/lib/workbench.d.ts +2 -0
- package/lib/workbench.js +331 -8
- package/package.json +1 -1
- package/skills/dsh-ppt/SKILL.md +3 -3
- package/skills/dsh-ppt/package.json +1 -1
- package/skills/dsh-ppt/references/advanced.md +10 -5
- package/skills/dsh-ppt/references/syntax.md +1 -0
- package/skills/dsh-ppt/scripts/build-deck.mjs +39 -8
- package/skills/dsh-ppt/scripts/deck-advanced.mjs +50 -13
- package/skills/dsh-ppt/scripts/deck-chrome.mjs +1706 -0
- package/skills/dsh-ppt/scripts/deck-core.mjs +116 -6
- package/skills/dsh-ppt/scripts/deck-delivery.mjs +636 -41
- package/skills/dsh-ppt/scripts/deck-diagrams.mjs +2842 -0
- package/skills/dsh-ppt/scripts/deck-director.mjs +49 -3
- package/skills/dsh-ppt/scripts/deck-layouts.mjs +482 -5270
- package/skills/dsh-ppt/scripts/deck-mermaid.mjs +2737 -0
- package/skills/dsh-ppt/scripts/deck-office.mjs +1541 -0
|
@@ -0,0 +1,2737 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* deck-mermaid.mjs —— dsh-ppt 的零依赖确定性 Mermaid 编译器:
|
|
3
|
+
* 支持 Mode A(flowchart / graph TD/TB/BT/LR/RL,含 7+ 节点几何、subgraph 簇容器、链式/并发边与多线型标签)
|
|
4
|
+
* 与 Mode B(sequenceDiagram,含 participant/actor、同步/异步/返回/终止消息、activate 激活条、Note 与 alt/loop/opt/par 组合片段)。
|
|
5
|
+
*
|
|
6
|
+
* 双后端同构输出:
|
|
7
|
+
* 1. PPTX:100% 原生可编辑 PowerPoint 几何图形 <p:sp> 与真实锚点附着连接线 <p:cxnSp>(<a:stCxn> / <a:endCxn>,0=top,1=left,2=bottom,3=right)
|
|
8
|
+
* 2. HTML:语义化响应式主题自适应矢量图 <svg class="deck-mermaid-svg">
|
|
9
|
+
*
|
|
10
|
+
* 零外部运行时依赖,仅使用 Node 内置模块。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { mixHex, relativeLuminance } from './deck-themes.mjs'
|
|
14
|
+
import {
|
|
15
|
+
roundRectAdj,
|
|
16
|
+
escapeXml,
|
|
17
|
+
escapeHtml,
|
|
18
|
+
stripInlineMarkdown,
|
|
19
|
+
measureEmWidth,
|
|
20
|
+
computeTextFit,
|
|
21
|
+
ooxmlRichParagraph,
|
|
22
|
+
ooxmlShape,
|
|
23
|
+
ooxmlLine,
|
|
24
|
+
ooxmlConnector,
|
|
25
|
+
} from './deck-chrome.mjs'
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// 1. 源码提取与模式自动识别
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
export function extractMermaidSource(slideOrText) {
|
|
32
|
+
let raw = ''
|
|
33
|
+
if (typeof slideOrText === 'string') {
|
|
34
|
+
raw = slideOrText
|
|
35
|
+
} else if (slideOrText && typeof slideOrText === 'object') {
|
|
36
|
+
raw = typeof slideOrText.mermaid === 'string' && slideOrText.mermaid.trim() !== ''
|
|
37
|
+
? slideOrText.mermaid
|
|
38
|
+
: typeof slideOrText.text === 'string'
|
|
39
|
+
? slideOrText.text
|
|
40
|
+
: ''
|
|
41
|
+
}
|
|
42
|
+
let text = String(raw ?? '').replace(/\r\n?/g, '\n').trim()
|
|
43
|
+
const fenceMatch = /^(`{3,}|~{3,})\s*(?:mermaid)?[ \t]*\n([\s\S]*?)\n\1\s*$/i.exec(text)
|
|
44
|
+
if (fenceMatch) {
|
|
45
|
+
text = fenceMatch[2].trim()
|
|
46
|
+
}
|
|
47
|
+
// 移除 %%{init: ...}%% 指令块与整行 %% 注释
|
|
48
|
+
text = text.replace(/%%\{[\s\S]*?\}%%/g, '')
|
|
49
|
+
const cleanedLines = text
|
|
50
|
+
.split('\n')
|
|
51
|
+
.map((ln) => ln.replace(/\s*%%.*$/, ''))
|
|
52
|
+
.filter((ln) => ln.trim() !== '')
|
|
53
|
+
return cleanedLines.join('\n').trim()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function detectMermaidMode(slideOrText, fallbackVariant = '') {
|
|
57
|
+
const src = extractMermaidSource(slideOrText)
|
|
58
|
+
const firstLine = (src.split('\n')[0] ?? '').trim()
|
|
59
|
+
if (/^sequenceDiagram\b/i.test(firstLine)) return 'sequence'
|
|
60
|
+
if (/^(?:flowchart|graph)\b/i.test(firstLine)) return 'flowchart'
|
|
61
|
+
const v = String(fallbackVariant ?? '').trim().toLowerCase()
|
|
62
|
+
if (v === 'sequence' || v === 'sequencediagram') return 'sequence'
|
|
63
|
+
if (/(?:^|\n)\s*(?:participant|actor)\s+\S+/i.test(src) || /--?>>/.test(src)) return 'sequence'
|
|
64
|
+
return 'flowchart'
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
// 2. Mode A:Mermaid Flowchart / Graph 词法与语法解析器
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
function unquoteMermaidText(raw) {
|
|
72
|
+
let s = String(raw ?? '').trim()
|
|
73
|
+
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
|
74
|
+
s = s.slice(1, -1)
|
|
75
|
+
}
|
|
76
|
+
return s
|
|
77
|
+
.replace(/<br\s*\/?>/gi, '\n')
|
|
78
|
+
.replace(/\\n/g, '\n')
|
|
79
|
+
.split('\n')
|
|
80
|
+
.map((part) =>
|
|
81
|
+
part
|
|
82
|
+
.replace(/\*\*([^*]+)\*\*/g, '$1')
|
|
83
|
+
.replace(/`([^`]*)`/g, '$1')
|
|
84
|
+
.replace(/\s+/g, ' ')
|
|
85
|
+
.trim(),
|
|
86
|
+
)
|
|
87
|
+
.filter(Boolean)
|
|
88
|
+
.join('\n')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function splitTopLevelStatements(sourceText) {
|
|
92
|
+
const out = []
|
|
93
|
+
for (const rawLine of sourceText.split('\n')) {
|
|
94
|
+
const line = rawLine.trim()
|
|
95
|
+
if (!line) continue
|
|
96
|
+
let cur = ''
|
|
97
|
+
let quote = null
|
|
98
|
+
let sq = 0
|
|
99
|
+
let pr = 0
|
|
100
|
+
let cu = 0
|
|
101
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
102
|
+
const ch = line[i]
|
|
103
|
+
if (quote) {
|
|
104
|
+
cur += ch
|
|
105
|
+
if (ch === quote && line[i - 1] !== '\\') quote = null
|
|
106
|
+
continue
|
|
107
|
+
}
|
|
108
|
+
if (ch === '"' || ch === "'") {
|
|
109
|
+
quote = ch
|
|
110
|
+
cur += ch
|
|
111
|
+
continue
|
|
112
|
+
}
|
|
113
|
+
if (ch === '[') sq += 1
|
|
114
|
+
else if (ch === ']') sq = Math.max(0, sq - 1)
|
|
115
|
+
else if (ch === '(') pr += 1
|
|
116
|
+
else if (ch === ')') pr = Math.max(0, pr - 1)
|
|
117
|
+
else if (ch === '{') cu += 1
|
|
118
|
+
else if (ch === '}') cu = Math.max(0, cu - 1)
|
|
119
|
+
if (ch === ';' && sq === 0 && pr === 0 && cu === 0) {
|
|
120
|
+
if (cur.trim()) out.push(cur.trim())
|
|
121
|
+
cur = ''
|
|
122
|
+
} else {
|
|
123
|
+
cur += ch
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (cur.trim()) out.push(cur.trim())
|
|
127
|
+
}
|
|
128
|
+
return out
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function splitParallelAmpersand(groupStr) {
|
|
132
|
+
const parts = []
|
|
133
|
+
let cur = ''
|
|
134
|
+
let quote = null
|
|
135
|
+
let sq = 0
|
|
136
|
+
let pr = 0
|
|
137
|
+
let cu = 0
|
|
138
|
+
for (let i = 0; i < groupStr.length; i += 1) {
|
|
139
|
+
const ch = groupStr[i]
|
|
140
|
+
if (quote) {
|
|
141
|
+
cur += ch
|
|
142
|
+
if (ch === quote && groupStr[i - 1] !== '\\') quote = null
|
|
143
|
+
continue
|
|
144
|
+
}
|
|
145
|
+
if (ch === '"' || ch === "'") {
|
|
146
|
+
quote = ch
|
|
147
|
+
cur += ch
|
|
148
|
+
continue
|
|
149
|
+
}
|
|
150
|
+
if (ch === '[') sq += 1
|
|
151
|
+
else if (ch === ']') sq = Math.max(0, sq - 1)
|
|
152
|
+
else if (ch === '(') pr += 1
|
|
153
|
+
else if (ch === ')') pr = Math.max(0, pr - 1)
|
|
154
|
+
else if (ch === '{') cu += 1
|
|
155
|
+
else if (ch === '}') cu = Math.max(0, cu - 1)
|
|
156
|
+
if (ch === '&' && sq === 0 && pr === 0 && cu === 0) {
|
|
157
|
+
if (cur.trim()) parts.push(cur.trim())
|
|
158
|
+
cur = ''
|
|
159
|
+
} else {
|
|
160
|
+
cur += ch
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (cur.trim()) parts.push(cur.trim())
|
|
164
|
+
return parts
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const EDGE_INLINE_PATTERNS = [
|
|
168
|
+
{ re: /^<--\s*("[^"\n]+"|'[^'\n]+'|[^-\n]+?)\s*-->/, headArrow: true, tailArrow: true, dash: '', thick: false },
|
|
169
|
+
{ re: /^<==\s*("[^"\n]+"|'[^'\n]+'|[^=\n]+?)\s*==>/, headArrow: true, tailArrow: true, dash: '', thick: true },
|
|
170
|
+
{ re: /^<-\.\s*([\s\S]+?)\s*\.->/, headArrow: true, tailArrow: true, dash: 'dash', thick: false },
|
|
171
|
+
{ re: /^-\.\s*([\s\S]+?)\s*\.->/, headArrow: false, tailArrow: true, dash: 'dash', thick: false },
|
|
172
|
+
{ re: /^-\.\s*([\s\S]+?)\s*-\.-/, headArrow: false, tailArrow: false, dash: 'dash', thick: false },
|
|
173
|
+
{ re: /^==\s*("[^"\n]+"|'[^'\n]+'|[^=\n]+?)\s*==>/, headArrow: false, tailArrow: true, dash: '', thick: true },
|
|
174
|
+
{ re: /^==\s*("[^"\n]+"|'[^'\n]+'|[^=\n]+?)\s*===/, headArrow: false, tailArrow: false, dash: '', thick: true },
|
|
175
|
+
{ re: /^--\s*("[^"\n]+"|'[^'\n]+'|[^-=><|\n]+?)\s*-->/, headArrow: false, tailArrow: true, dash: '', thick: false },
|
|
176
|
+
{ re: /^--\s*("[^"\n]+"|'[^'\n]+'|[^-=><|\n]+?)\s*---/, headArrow: false, tailArrow: false, dash: '', thick: false },
|
|
177
|
+
]
|
|
178
|
+
|
|
179
|
+
const EDGE_DIRECT_PATTERNS = [
|
|
180
|
+
{ re: /^<-\.+->/, headArrow: true, tailArrow: true, dash: 'dash', thick: false },
|
|
181
|
+
{ re: /^<==+>/, headArrow: true, tailArrow: true, dash: '', thick: true },
|
|
182
|
+
{ re: /^<--+>/, headArrow: true, tailArrow: true, dash: '', thick: false },
|
|
183
|
+
{ re: /^-\.+->/, headArrow: false, tailArrow: true, dash: 'dash', thick: false },
|
|
184
|
+
{ re: /^-\.+-/, headArrow: false, tailArrow: false, dash: 'dash', thick: false },
|
|
185
|
+
{ re: /^==+>/, headArrow: false, tailArrow: true, dash: '', thick: true },
|
|
186
|
+
{ re: /^===+/, headArrow: false, tailArrow: false, dash: '', thick: true },
|
|
187
|
+
{ re: /^--+>/, headArrow: false, tailArrow: true, dash: '', thick: false },
|
|
188
|
+
{ re: /^---+/, headArrow: false, tailArrow: false, dash: '', thick: false },
|
|
189
|
+
]
|
|
190
|
+
|
|
191
|
+
function matchEdgeOperatorAt(str, pos) {
|
|
192
|
+
const slice = str.slice(pos)
|
|
193
|
+
for (const pat of EDGE_INLINE_PATTERNS) {
|
|
194
|
+
const m = pat.re.exec(slice)
|
|
195
|
+
if (m) {
|
|
196
|
+
return {
|
|
197
|
+
length: m[0].length,
|
|
198
|
+
edge: {
|
|
199
|
+
headArrow: pat.headArrow,
|
|
200
|
+
tailArrow: pat.tailArrow,
|
|
201
|
+
dash: pat.dash,
|
|
202
|
+
thick: pat.thick,
|
|
203
|
+
label: unquoteMermaidText(m[1]),
|
|
204
|
+
},
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
for (const pat of EDGE_DIRECT_PATTERNS) {
|
|
209
|
+
const m = pat.re.exec(slice)
|
|
210
|
+
if (m) {
|
|
211
|
+
let consumed = m[0].length
|
|
212
|
+
let label = ''
|
|
213
|
+
const after = slice.slice(consumed)
|
|
214
|
+
const pipeMatch = /^\s*\|\s*([^|]*?)\s*\|/.exec(after)
|
|
215
|
+
if (pipeMatch) {
|
|
216
|
+
consumed += pipeMatch[0].length
|
|
217
|
+
label = unquoteMermaidText(pipeMatch[1])
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
length: consumed,
|
|
221
|
+
edge: {
|
|
222
|
+
headArrow: pat.headArrow,
|
|
223
|
+
tailArrow: pat.tailArrow,
|
|
224
|
+
dash: pat.dash,
|
|
225
|
+
thick: pat.thick,
|
|
226
|
+
label,
|
|
227
|
+
},
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return null
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function tokenizeFlowChain(stmt) {
|
|
235
|
+
const nodeGroups = []
|
|
236
|
+
const edgeOps = []
|
|
237
|
+
let cur = ''
|
|
238
|
+
let quote = null
|
|
239
|
+
let sq = 0
|
|
240
|
+
let pr = 0
|
|
241
|
+
let cu = 0
|
|
242
|
+
let i = 0
|
|
243
|
+
while (i < stmt.length) {
|
|
244
|
+
const ch = stmt[i]
|
|
245
|
+
if (quote) {
|
|
246
|
+
cur += ch
|
|
247
|
+
if (ch === quote && stmt[i - 1] !== '\\') quote = null
|
|
248
|
+
i += 1
|
|
249
|
+
continue
|
|
250
|
+
}
|
|
251
|
+
if (ch === '"' || ch === "'") {
|
|
252
|
+
quote = ch
|
|
253
|
+
cur += ch
|
|
254
|
+
i += 1
|
|
255
|
+
continue
|
|
256
|
+
}
|
|
257
|
+
if (ch === '[') { sq += 1; cur += ch; i += 1; continue }
|
|
258
|
+
if (ch === ']') { sq = Math.max(0, sq - 1); cur += ch; i += 1; continue }
|
|
259
|
+
if (ch === '(') { pr += 1; cur += ch; i += 1; continue }
|
|
260
|
+
if (ch === ')') { pr = Math.max(0, pr - 1); cur += ch; i += 1; continue }
|
|
261
|
+
if (ch === '{') { cu += 1; cur += ch; i += 1; continue }
|
|
262
|
+
if (ch === '}') { cu = Math.max(0, cu - 1); cur += ch; i += 1; continue }
|
|
263
|
+
|
|
264
|
+
if (sq === 0 && pr === 0 && cu === 0 && (ch === '-' || ch === '=' || ch === '<')) {
|
|
265
|
+
const hit = matchEdgeOperatorAt(stmt, i)
|
|
266
|
+
if (hit && cur.trim() !== '') {
|
|
267
|
+
nodeGroups.push(cur.trim())
|
|
268
|
+
edgeOps.push(hit.edge)
|
|
269
|
+
cur = ''
|
|
270
|
+
i += hit.length
|
|
271
|
+
continue
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
cur += ch
|
|
275
|
+
i += 1
|
|
276
|
+
}
|
|
277
|
+
if (cur.trim() !== '') nodeGroups.push(cur.trim())
|
|
278
|
+
return { nodeGroups, edgeOps }
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function parseNodeToken(rawToken) {
|
|
282
|
+
let token = String(rawToken ?? '').trim()
|
|
283
|
+
if (!token) return null
|
|
284
|
+
let className = ''
|
|
285
|
+
const clsMatch = /^(.*?):::([A-Za-z0-9_-]+)\s*$/.exec(token)
|
|
286
|
+
if (clsMatch) {
|
|
287
|
+
token = clsMatch[1].trim()
|
|
288
|
+
className = clsMatch[2].trim()
|
|
289
|
+
}
|
|
290
|
+
const idMatch = /^([A-Za-z0-9_\u4E00-\u9FFF.-]+)\s*([\s\S]*)$/.exec(token)
|
|
291
|
+
if (!idMatch) return null
|
|
292
|
+
const id = idMatch[1]
|
|
293
|
+
const rest = idMatch[2].trim()
|
|
294
|
+
if (!rest) return { id, shape: null, label: null, className }
|
|
295
|
+
|
|
296
|
+
const shapeRules = [
|
|
297
|
+
{ re: /^\(\[([\s\S]*)\]\)$/, shape: 'stadium' },
|
|
298
|
+
{ re: /^\[\(([\s\S]*)\)\]$/, shape: 'cylinder' },
|
|
299
|
+
{ re: /^\[\[([\s\S]*)\]\]$/, shape: 'subroutine' },
|
|
300
|
+
{ re: /^\(\(\(([\s\S]*)\)\)\)$/, shape: 'circle' },
|
|
301
|
+
{ re: /^\(\(([\s\S]*)\)\)$/, shape: 'circle' },
|
|
302
|
+
{ re: /^\{\{([\s\S]*)\}\}$/, shape: 'hexagon' },
|
|
303
|
+
{ re: /^\{([\s\S]*)\}$/, shape: 'diamond' },
|
|
304
|
+
{ re: /^\(([\s\S]*)\)$/, shape: 'round' },
|
|
305
|
+
{ re: /^\[\/([\s\S]*)\/\]$/, shape: 'parallelogram' },
|
|
306
|
+
{ re: /^\[([\s\S]*)\]$/, shape: 'rect' },
|
|
307
|
+
]
|
|
308
|
+
for (const rule of shapeRules) {
|
|
309
|
+
const m = rule.re.exec(rest)
|
|
310
|
+
if (m) {
|
|
311
|
+
return {
|
|
312
|
+
id,
|
|
313
|
+
shape: rule.shape,
|
|
314
|
+
label: unquoteMermaidText(m[1]) || id,
|
|
315
|
+
className,
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return { id, shape: 'rect', label: unquoteMermaidText(rest) || id, className }
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function parseStyleProps(styleStr) {
|
|
323
|
+
const out = {}
|
|
324
|
+
for (const part of String(styleStr ?? '').split(',')) {
|
|
325
|
+
const kv = /^([a-zA-Z-]+)\s*:\s*(.+)$/.exec(part.trim())
|
|
326
|
+
if (!kv) continue
|
|
327
|
+
const k = kv[1].toLowerCase()
|
|
328
|
+
const v = kv[2].trim()
|
|
329
|
+
if ((k === 'fill' || k === 'stroke' || k === 'color') && /^#[0-9a-fA-F]{3,6}$/.test(v)) {
|
|
330
|
+
out[k] = v.length === 4 ? '#' + v[1] + v[1] + v[2] + v[2] + v[3] + v[3] : v.slice(0, 7).toUpperCase()
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return out
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export function parseMermaidFlowchart(slideOrText) {
|
|
337
|
+
const src = extractMermaidSource(slideOrText)
|
|
338
|
+
const statements = splitTopLevelStatements(src)
|
|
339
|
+
let direction = 'TD'
|
|
340
|
+
const nodesMap = new Map()
|
|
341
|
+
const edges = []
|
|
342
|
+
const subgraphs = []
|
|
343
|
+
const subgraphById = new Map()
|
|
344
|
+
const subgraphStack = []
|
|
345
|
+
const classDefs = new Map()
|
|
346
|
+
const nodeStyles = new Map()
|
|
347
|
+
let sgAutoIdx = 0
|
|
348
|
+
|
|
349
|
+
const upsertNode = (parsed) => {
|
|
350
|
+
if (!parsed || !parsed.id) return null
|
|
351
|
+
const activeSg = subgraphStack.length > 0 ? subgraphStack[subgraphStack.length - 1] : null
|
|
352
|
+
let existing = nodesMap.get(parsed.id)
|
|
353
|
+
if (!existing) {
|
|
354
|
+
existing = {
|
|
355
|
+
id: parsed.id,
|
|
356
|
+
label: parsed.label || parsed.id,
|
|
357
|
+
shape: parsed.shape || 'rect',
|
|
358
|
+
subgraphId: activeSg ? activeSg.id : null,
|
|
359
|
+
className: parsed.className || '',
|
|
360
|
+
order: nodesMap.size,
|
|
361
|
+
}
|
|
362
|
+
nodesMap.set(parsed.id, existing)
|
|
363
|
+
} else {
|
|
364
|
+
if (parsed.label) existing.label = parsed.label
|
|
365
|
+
if (parsed.shape) existing.shape = parsed.shape
|
|
366
|
+
if (parsed.className) existing.className = parsed.className
|
|
367
|
+
if (!existing.subgraphId && activeSg) existing.subgraphId = activeSg.id
|
|
368
|
+
}
|
|
369
|
+
if (activeSg && existing.subgraphId === activeSg.id) {
|
|
370
|
+
for (const sg of subgraphStack) {
|
|
371
|
+
if (!sg.nodeIds.includes(parsed.id)) sg.nodeIds.push(parsed.id)
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return existing
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
statements.forEach((stmt, idx) => {
|
|
378
|
+
if (idx === 0) {
|
|
379
|
+
const headMatch = /^(?:flowchart|graph)(?:\s+(TD|TB|BT|LR|RL))?\s*$/i.exec(stmt)
|
|
380
|
+
if (headMatch) {
|
|
381
|
+
const dir = (headMatch[1] || 'TD').toUpperCase()
|
|
382
|
+
direction = dir === 'TB' ? 'TD' : dir
|
|
383
|
+
return
|
|
384
|
+
}
|
|
385
|
+
const inlineHead = /^(?:flowchart|graph)\s+(TD|TB|BT|LR|RL)\s+([\s\S]+)$/i.exec(stmt)
|
|
386
|
+
if (inlineHead) {
|
|
387
|
+
const dir = inlineHead[1].toUpperCase()
|
|
388
|
+
direction = dir === 'TB' ? 'TD' : dir
|
|
389
|
+
stmt = inlineHead[2].trim()
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
if (/^direction\s+(?:TD|TB|BT|LR|RL)\s*$/i.test(stmt)) return
|
|
394
|
+
if (/^(?:linkStyle|click)\b/i.test(stmt)) return
|
|
395
|
+
|
|
396
|
+
const classDefMatch = /^classDef\s+([A-Za-z0-9_-]+)\s+(.+)$/i.exec(stmt)
|
|
397
|
+
if (classDefMatch) {
|
|
398
|
+
classDefs.set(classDefMatch[1], parseStyleProps(classDefMatch[2]))
|
|
399
|
+
return
|
|
400
|
+
}
|
|
401
|
+
const classAssignMatch = /^class\s+([^\s]+)\s+([A-Za-z0-9_-]+)\s*$/i.exec(stmt)
|
|
402
|
+
if (classAssignMatch) {
|
|
403
|
+
for (const nid of classAssignMatch[1].split(',').map((x) => x.trim()).filter(Boolean)) {
|
|
404
|
+
const n = nodesMap.get(nid)
|
|
405
|
+
if (n) n.className = classAssignMatch[2]
|
|
406
|
+
}
|
|
407
|
+
return
|
|
408
|
+
}
|
|
409
|
+
const styleMatch = /^style\s+([A-Za-z0-9_.-]+)\s+(.+)$/i.exec(stmt)
|
|
410
|
+
if (styleMatch) {
|
|
411
|
+
nodeStyles.set(styleMatch[1], parseStyleProps(styleMatch[2]))
|
|
412
|
+
return
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const sgMatch = /^subgraph\s+([\s\S]+)$/i.exec(stmt)
|
|
416
|
+
if (sgMatch) {
|
|
417
|
+
const rest = sgMatch[1].trim()
|
|
418
|
+
let sgId = ''
|
|
419
|
+
let sgTitle = ''
|
|
420
|
+
const bracketForm = /^([A-Za-z0-9_.-]+)\s*\[\s*([\s\S]+?)\s*\]\s*$/.exec(rest)
|
|
421
|
+
const quotedForm = /^"([^"]+)"\s*$/.exec(rest)
|
|
422
|
+
const twoPartForm = /^([A-Za-z0-9_.-]+)\s+([\s\S]+)$/.exec(rest)
|
|
423
|
+
if (bracketForm) {
|
|
424
|
+
sgId = bracketForm[1]
|
|
425
|
+
sgTitle = unquoteMermaidText(bracketForm[2])
|
|
426
|
+
} else if (quotedForm) {
|
|
427
|
+
sgAutoIdx += 1
|
|
428
|
+
sgId = 'sg_' + sgAutoIdx
|
|
429
|
+
sgTitle = unquoteMermaidText(quotedForm[1])
|
|
430
|
+
} else if (twoPartForm) {
|
|
431
|
+
sgId = twoPartForm[1]
|
|
432
|
+
sgTitle = unquoteMermaidText(twoPartForm[2])
|
|
433
|
+
} else {
|
|
434
|
+
sgId = rest.replace(/[^A-Za-z0-9_.-]/g, '_') || ('sg_' + (++sgAutoIdx))
|
|
435
|
+
sgTitle = unquoteMermaidText(rest)
|
|
436
|
+
}
|
|
437
|
+
let sg = subgraphById.get(sgId)
|
|
438
|
+
if (!sg) {
|
|
439
|
+
sg = {
|
|
440
|
+
id: sgId,
|
|
441
|
+
title: sgTitle || sgId,
|
|
442
|
+
parentId: subgraphStack.length > 0 ? subgraphStack[subgraphStack.length - 1].id : null,
|
|
443
|
+
nodeIds: [],
|
|
444
|
+
order: subgraphs.length,
|
|
445
|
+
}
|
|
446
|
+
subgraphs.push(sg)
|
|
447
|
+
subgraphById.set(sgId, sg)
|
|
448
|
+
}
|
|
449
|
+
subgraphStack.push(sg)
|
|
450
|
+
return
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
if (/^end\s*$/i.test(stmt)) {
|
|
454
|
+
subgraphStack.pop()
|
|
455
|
+
return
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const { nodeGroups, edgeOps } = tokenizeFlowChain(stmt)
|
|
459
|
+
if (nodeGroups.length === 0) return
|
|
460
|
+
if (edgeOps.length === 0) {
|
|
461
|
+
for (const item of splitParallelAmpersand(nodeGroups[0])) {
|
|
462
|
+
upsertNode(parseNodeToken(item))
|
|
463
|
+
}
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const resolvedGroups = nodeGroups.map((grp) =>
|
|
468
|
+
splitParallelAmpersand(grp)
|
|
469
|
+
.map((tok) => upsertNode(parseNodeToken(tok)))
|
|
470
|
+
.filter(Boolean),
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
for (let g = 0; g < edgeOps.length; g += 1) {
|
|
474
|
+
const leftNodes = resolvedGroups[g] ?? []
|
|
475
|
+
const rightNodes = resolvedGroups[g + 1] ?? []
|
|
476
|
+
const op = edgeOps[g]
|
|
477
|
+
for (const srcNode of leftNodes) {
|
|
478
|
+
for (const dstNode of rightNodes) {
|
|
479
|
+
// 若源或目标其实是一个 subgraph id,将其重定向到该子图的首/末节点
|
|
480
|
+
const actualSrc = subgraphById.has(srcNode.id) && subgraphById.get(srcNode.id).nodeIds.length > 0
|
|
481
|
+
? (nodesMap.get(subgraphById.get(srcNode.id).nodeIds[subgraphById.get(srcNode.id).nodeIds.length - 1]) || srcNode)
|
|
482
|
+
: srcNode
|
|
483
|
+
const actualDst = subgraphById.has(dstNode.id) && subgraphById.get(dstNode.id).nodeIds.length > 0
|
|
484
|
+
? (nodesMap.get(subgraphById.get(dstNode.id).nodeIds[0]) || dstNode)
|
|
485
|
+
: dstNode
|
|
486
|
+
edges.push({
|
|
487
|
+
id: 'e' + (edges.length + 1),
|
|
488
|
+
from: actualSrc.id,
|
|
489
|
+
to: actualDst.id,
|
|
490
|
+
label: op.label || '',
|
|
491
|
+
headArrow: Boolean(op.headArrow),
|
|
492
|
+
tailArrow: op.tailArrow !== false,
|
|
493
|
+
dash: op.dash || '',
|
|
494
|
+
thick: Boolean(op.thick),
|
|
495
|
+
})
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
})
|
|
500
|
+
|
|
501
|
+
// 移除误作为独立节点插入的空 subgraph 占位名
|
|
502
|
+
for (const sg of subgraphs) {
|
|
503
|
+
if (sg.nodeIds.length > 0 && nodesMap.has(sg.id)) {
|
|
504
|
+
const candidate = nodesMap.get(sg.id)
|
|
505
|
+
const usedDirectly = edges.some((e) => e.from === sg.id || e.to === sg.id)
|
|
506
|
+
if (!usedDirectly && candidate.label === sg.id) {
|
|
507
|
+
nodesMap.delete(sg.id)
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const nodes = [...nodesMap.values()].map((n) => {
|
|
513
|
+
const clsStyle = n.className && classDefs.has(n.className) ? classDefs.get(n.className) : {}
|
|
514
|
+
const directStyle = nodeStyles.get(n.id) ?? {}
|
|
515
|
+
return {
|
|
516
|
+
...n,
|
|
517
|
+
customStyle: { ...clsStyle, ...directStyle },
|
|
518
|
+
}
|
|
519
|
+
})
|
|
520
|
+
|
|
521
|
+
return {
|
|
522
|
+
mode: 'flowchart',
|
|
523
|
+
direction,
|
|
524
|
+
nodes,
|
|
525
|
+
edges,
|
|
526
|
+
subgraphs: subgraphs.filter((sg) => sg.nodeIds.some((id) => nodesMap.has(id))),
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// ---------------------------------------------------------------------------
|
|
531
|
+
// 3. Mode A:确定性 Sugiyama 分层有向图几何布局求解器
|
|
532
|
+
// ---------------------------------------------------------------------------
|
|
533
|
+
|
|
534
|
+
function wrapNodeLabelLines(label, maxEmPerLine = 12.5) {
|
|
535
|
+
const explicitLines = String(label ?? '').split('\n').map((s) => s.trim()).filter(Boolean)
|
|
536
|
+
const out = []
|
|
537
|
+
for (const line of explicitLines) {
|
|
538
|
+
const em = measureEmWidth(line, true)
|
|
539
|
+
if (em <= maxEmPerLine || line.length <= 6) {
|
|
540
|
+
out.push(line)
|
|
541
|
+
continue
|
|
542
|
+
}
|
|
543
|
+
const words = line.includes(' ') ? line.split(/\s+/) : [...line]
|
|
544
|
+
let cur = ''
|
|
545
|
+
for (const unit of words) {
|
|
546
|
+
const sep = line.includes(' ') && cur ? ' ' : ''
|
|
547
|
+
const next = cur + sep + unit
|
|
548
|
+
if (cur && measureEmWidth(next, true) > maxEmPerLine) {
|
|
549
|
+
out.push(cur)
|
|
550
|
+
cur = unit
|
|
551
|
+
} else {
|
|
552
|
+
cur = next
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (cur) out.push(cur)
|
|
556
|
+
}
|
|
557
|
+
return out.length > 0 ? out.slice(0, 3) : ['Node']
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function estimateNaturalNodeSize(node, nodeCount, isHoriz = false) {
|
|
561
|
+
const maxEmWrap = node.shape === 'diamond' ? 10.5 : nodeCount >= 9 ? 11.5 : 13.5
|
|
562
|
+
const lines = wrapNodeLabelLines(node.label, maxEmWrap)
|
|
563
|
+
const basePt = nodeCount >= 11 ? 10.5 : nodeCount >= 7 ? 11.5 : 12.5
|
|
564
|
+
const maxLineEm = Math.max(2.6, ...lines.map((l) => measureEmWidth(l, true)))
|
|
565
|
+
const textWIn = (maxLineEm * basePt) / 72
|
|
566
|
+
const textHIn = (lines.length * basePt * 1.24) / 72
|
|
567
|
+
const compactV = !isHoriz && nodeCount >= 7
|
|
568
|
+
|
|
569
|
+
if (node.shape === 'diamond') {
|
|
570
|
+
return {
|
|
571
|
+
lines,
|
|
572
|
+
basePt,
|
|
573
|
+
w: Math.min(3.30, Math.max(1.88, textWIn * 2.12 + 0.56)),
|
|
574
|
+
h: Math.min(1.34, Math.max(compactV ? 0.76 : 0.86, textHIn * 2.10 + 0.30)),
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
if (node.shape === 'circle') {
|
|
578
|
+
const d = Math.min(1.56, Math.max(compactV ? 0.72 : 0.84, Math.max(textWIn * 1.32 + 0.38, textHIn * 1.30 + 0.28)))
|
|
579
|
+
return { lines, basePt, w: d * 1.24, h: d }
|
|
580
|
+
}
|
|
581
|
+
if (node.shape === 'cylinder') {
|
|
582
|
+
return {
|
|
583
|
+
lines,
|
|
584
|
+
basePt,
|
|
585
|
+
w: Math.min(2.75, Math.max(1.56, textWIn + 0.68)),
|
|
586
|
+
h: Math.min(1.16, Math.max(compactV ? 0.68 : 0.78, textHIn + 0.36)),
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
if (node.shape === 'subroutine') {
|
|
590
|
+
return {
|
|
591
|
+
lines,
|
|
592
|
+
basePt,
|
|
593
|
+
w: Math.min(2.90, Math.max(1.66, textWIn * 1.18 + 0.76)),
|
|
594
|
+
h: Math.min(1.04, Math.max(compactV ? 0.52 : 0.60, textHIn + 0.26)),
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
if (node.shape === 'stadium') {
|
|
598
|
+
const h = Math.min(0.98, Math.max(compactV ? 0.50 : 0.56, textHIn + 0.24))
|
|
599
|
+
return {
|
|
600
|
+
lines,
|
|
601
|
+
basePt,
|
|
602
|
+
w: Math.min(2.85, Math.max(1.54, textWIn + h * 0.78 + 0.44)),
|
|
603
|
+
h,
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return {
|
|
607
|
+
lines,
|
|
608
|
+
basePt,
|
|
609
|
+
w: Math.min(2.85, Math.max(1.52, textWIn + 0.64)),
|
|
610
|
+
h: Math.min(1.04, Math.max(compactV ? 0.50 : 0.58, textHIn + 0.26)),
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function portCoordinates(nodeBox, siteIdx) {
|
|
615
|
+
const cx = nodeBox.x + nodeBox.w / 2
|
|
616
|
+
const cy = nodeBox.y + nodeBox.h / 2
|
|
617
|
+
if (siteIdx === 0) return { x: cx, y: nodeBox.y }
|
|
618
|
+
if (siteIdx === 1) return { x: nodeBox.x, y: cy }
|
|
619
|
+
if (siteIdx === 2) return { x: cx, y: nodeBox.y + nodeBox.h }
|
|
620
|
+
return { x: nodeBox.x + nodeBox.w, y: cy }
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
export function layoutMermaidFlowchart(astInput, areaBox = { x: 0.62, y: 1.86, w: 12.09, h: 4.78 }) {
|
|
624
|
+
const ast = astInput?.mode === 'flowchart' ? astInput : parseMermaidFlowchart(astInput)
|
|
625
|
+
const rawNodes = ast.nodes.length > 0
|
|
626
|
+
? ast.nodes
|
|
627
|
+
: [
|
|
628
|
+
{ id: 'Start', label: 'Start', shape: 'stadium', subgraphId: null, order: 0, customStyle: {} },
|
|
629
|
+
{ id: 'End', label: 'End', shape: 'stadium', subgraphId: null, order: 1, customStyle: {} },
|
|
630
|
+
]
|
|
631
|
+
const rawEdges = ast.nodes.length > 0
|
|
632
|
+
? ast.edges
|
|
633
|
+
: [{ id: 'e1', from: 'Start', to: 'End', label: '', headArrow: false, tailArrow: true, dash: '', thick: false }]
|
|
634
|
+
|
|
635
|
+
const nodeById = new Map(rawNodes.map((n) => [n.id, n]))
|
|
636
|
+
const nCount = rawNodes.length
|
|
637
|
+
const direction = ast.direction || 'TD'
|
|
638
|
+
const isHoriz = direction === 'LR' || direction === 'RL'
|
|
639
|
+
|
|
640
|
+
// Step 1:DFS 破环(Cycle Breaking)
|
|
641
|
+
const adjRaw = new Map(rawNodes.map((n) => [n.id, []]))
|
|
642
|
+
rawEdges.forEach((e, idx) => {
|
|
643
|
+
if (e.from !== e.to && adjRaw.has(e.from) && adjRaw.has(e.to)) {
|
|
644
|
+
adjRaw.get(e.from).push({ to: e.to, idx })
|
|
645
|
+
}
|
|
646
|
+
})
|
|
647
|
+
const visitState = new Map(rawNodes.map((n) => [n.id, 0]))
|
|
648
|
+
const reversedEdgeIdx = new Set()
|
|
649
|
+
const dfsCycle = (u) => {
|
|
650
|
+
visitState.set(u, 1)
|
|
651
|
+
for (const { to, idx } of adjRaw.get(u) ?? []) {
|
|
652
|
+
const st = visitState.get(to)
|
|
653
|
+
if (st === 1) reversedEdgeIdx.add(idx)
|
|
654
|
+
else if (st === 0) dfsCycle(to)
|
|
655
|
+
}
|
|
656
|
+
visitState.set(u, 2)
|
|
657
|
+
}
|
|
658
|
+
for (const n of rawNodes) {
|
|
659
|
+
if (visitState.get(n.id) === 0) dfsCycle(n.id)
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
const dagEdges = rawEdges
|
|
663
|
+
.map((e, idx) => {
|
|
664
|
+
if (e.from === e.to) return null
|
|
665
|
+
const rev = reversedEdgeIdx.has(idx)
|
|
666
|
+
return {
|
|
667
|
+
origIdx: idx,
|
|
668
|
+
u: rev ? e.to : e.from,
|
|
669
|
+
v: rev ? e.from : e.to,
|
|
670
|
+
reversed: rev,
|
|
671
|
+
label: e.label,
|
|
672
|
+
}
|
|
673
|
+
})
|
|
674
|
+
.filter(Boolean)
|
|
675
|
+
|
|
676
|
+
// Step 2:最长路径层级分配(Longest-Path Rank Assignment)+ 源点紧致化
|
|
677
|
+
const inDeg = new Map(rawNodes.map((n) => [n.id, 0]))
|
|
678
|
+
const outAdj = new Map(rawNodes.map((n) => [n.id, []]))
|
|
679
|
+
const inAdj = new Map(rawNodes.map((n) => [n.id, []]))
|
|
680
|
+
for (const de of dagEdges) {
|
|
681
|
+
inDeg.set(de.v, (inDeg.get(de.v) ?? 0) + 1)
|
|
682
|
+
outAdj.get(de.u).push(de.v)
|
|
683
|
+
inAdj.get(de.v).push(de.u)
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const rank = new Map(rawNodes.map((n) => [n.id, 0]))
|
|
687
|
+
const queue = rawNodes.filter((n) => (inDeg.get(n.id) ?? 0) === 0).map((n) => n.id)
|
|
688
|
+
const remIn = new Map(inDeg)
|
|
689
|
+
const topo = []
|
|
690
|
+
while (queue.length > 0) {
|
|
691
|
+
const u = queue.shift()
|
|
692
|
+
topo.push(u)
|
|
693
|
+
const ru = rank.get(u) ?? 0
|
|
694
|
+
for (const v of outAdj.get(u) ?? []) {
|
|
695
|
+
if (ru + 1 > (rank.get(v) ?? 0)) rank.set(v, ru + 1)
|
|
696
|
+
remIn.set(v, (remIn.get(v) ?? 1) - 1)
|
|
697
|
+
if (remIn.get(v) === 0) queue.push(v)
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
for (const n of rawNodes) {
|
|
701
|
+
if (!topo.includes(n.id)) topo.push(n.id)
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// 将无入边但下游最小层级 > 1 的辅助输入源拉近至 minSuccRank - 1
|
|
705
|
+
for (const n of rawNodes) {
|
|
706
|
+
if ((inAdj.get(n.id)?.length ?? 0) === 0 && (outAdj.get(n.id)?.length ?? 0) > 0) {
|
|
707
|
+
const minSucc = Math.min(...outAdj.get(n.id).map((v) => rank.get(v) ?? 1))
|
|
708
|
+
if (minSucc > 1) rank.set(n.id, minSucc - 1)
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// 同级互斥子图(Disjoint Sibling Subgraphs)单向流主轴隔离:
|
|
713
|
+
// 若子图 A 存在单向有向边指向互斥子图 B(且 B 不可达 A),将 B 的最小层级推至 maxRank(A) + 1 并向下游传播,避免兄弟子图外框相交
|
|
714
|
+
if (ast.subgraphs.length >= 2) {
|
|
715
|
+
const sgById = new Map(ast.subgraphs.map((sg) => [sg.id, sg]))
|
|
716
|
+
const sgMemberSets = new Map(ast.subgraphs.map((sg) => [sg.id, new Set(sg.nodeIds)]))
|
|
717
|
+
const isAncestorSg = (anc, desc) => {
|
|
718
|
+
let cur = sgById.get(desc)?.parentId ?? null
|
|
719
|
+
const seen = new Set()
|
|
720
|
+
while (cur && !seen.has(cur)) {
|
|
721
|
+
if (cur === anc) return true
|
|
722
|
+
seen.add(cur)
|
|
723
|
+
cur = sgById.get(cur)?.parentId ?? null
|
|
724
|
+
}
|
|
725
|
+
return false
|
|
726
|
+
}
|
|
727
|
+
const disjointPairs = []
|
|
728
|
+
for (let i = 0; i < ast.subgraphs.length; i += 1) {
|
|
729
|
+
for (let j = i + 1; j < ast.subgraphs.length; j += 1) {
|
|
730
|
+
const a = ast.subgraphs[i]
|
|
731
|
+
const b = ast.subgraphs[j]
|
|
732
|
+
if (isAncestorSg(a.id, b.id) || isAncestorSg(b.id, a.id)) continue
|
|
733
|
+
const setA = sgMemberSets.get(a.id)
|
|
734
|
+
const setB = sgMemberSets.get(b.id)
|
|
735
|
+
let shares = false
|
|
736
|
+
for (const nid of setA) {
|
|
737
|
+
if (setB.has(nid)) { shares = true; break }
|
|
738
|
+
}
|
|
739
|
+
if (!shares && setA.size > 0 && setB.size > 0) disjointPairs.push([a.id, b.id])
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
const sgDirectEdges = new Map(ast.subgraphs.map((sg) => [sg.id, new Set()]))
|
|
743
|
+
for (const de of dagEdges) {
|
|
744
|
+
for (const [idA, idB] of disjointPairs) {
|
|
745
|
+
const setA = sgMemberSets.get(idA)
|
|
746
|
+
const setB = sgMemberSets.get(idB)
|
|
747
|
+
if (setA.has(de.u) && setB.has(de.v)) sgDirectEdges.get(idA).add(idB)
|
|
748
|
+
if (setB.has(de.u) && setA.has(de.v)) sgDirectEdges.get(idB).add(idA)
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
const sgReach = (start, target) => {
|
|
752
|
+
const visited = new Set([start])
|
|
753
|
+
const st = [start]
|
|
754
|
+
while (st.length > 0) {
|
|
755
|
+
const cur = st.pop()
|
|
756
|
+
for (const nxt of sgDirectEdges.get(cur) ?? []) {
|
|
757
|
+
if (nxt === target) return true
|
|
758
|
+
if (!visited.has(nxt)) {
|
|
759
|
+
visited.add(nxt)
|
|
760
|
+
st.push(nxt)
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
return false
|
|
765
|
+
}
|
|
766
|
+
const orderedPairs = []
|
|
767
|
+
for (const [idA, idB] of disjointPairs) {
|
|
768
|
+
const aToB = sgReach(idA, idB)
|
|
769
|
+
const bToA = sgReach(idB, idA)
|
|
770
|
+
if (aToB && !bToA) orderedPairs.push([idA, idB])
|
|
771
|
+
else if (bToA && !aToB) orderedPairs.push([idB, idA])
|
|
772
|
+
}
|
|
773
|
+
for (let iter = 0; iter < orderedPairs.length + 2; iter += 1) {
|
|
774
|
+
let changed = false
|
|
775
|
+
for (const [idA, idB] of orderedPairs) {
|
|
776
|
+
const membersA = [...sgMemberSets.get(idA)]
|
|
777
|
+
const membersB = [...sgMemberSets.get(idB)]
|
|
778
|
+
const maxA = Math.max(...membersA.map((nid) => rank.get(nid) ?? 0))
|
|
779
|
+
const minB = Math.min(...membersB.map((nid) => rank.get(nid) ?? 0))
|
|
780
|
+
if (minB <= maxA) {
|
|
781
|
+
const delta = maxA + 1 - minB
|
|
782
|
+
for (const nid of membersB) {
|
|
783
|
+
rank.set(nid, (rank.get(nid) ?? 0) + delta)
|
|
784
|
+
}
|
|
785
|
+
changed = true
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
// 传播 DAG 下游层级约束(rank[v] >= rank[u] + 1)
|
|
789
|
+
for (const u of topo) {
|
|
790
|
+
const ru = rank.get(u) ?? 0
|
|
791
|
+
for (const v of outAdj.get(u) ?? []) {
|
|
792
|
+
if (ru + 1 > (rank.get(v) ?? 0)) {
|
|
793
|
+
rank.set(v, ru + 1)
|
|
794
|
+
changed = true
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
if (!changed) break
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const minR = Math.min(...rawNodes.map((n) => rank.get(n.id) ?? 0))
|
|
803
|
+
if (minR > 0) {
|
|
804
|
+
for (const n of rawNodes) rank.set(n.id, (rank.get(n.id) ?? 0) - minR)
|
|
805
|
+
}
|
|
806
|
+
const maxRank = Math.max(0, ...rawNodes.map((n) => rank.get(n.id) ?? 0))
|
|
807
|
+
const layerCount = maxRank + 1
|
|
808
|
+
|
|
809
|
+
// Step 3:构造跨层虚拟节点并执行 4 轮双向重心交叉最小化(4-Pass Barycenter Crossing Reduction)
|
|
810
|
+
const sgOrderMap = new Map(ast.subgraphs.map((sg, i) => [sg.id, i + 1]))
|
|
811
|
+
const vertices = new Map()
|
|
812
|
+
for (const n of rawNodes) {
|
|
813
|
+
const sz = estimateNaturalNodeSize(n, nCount, isHoriz)
|
|
814
|
+
vertices.set(n.id, {
|
|
815
|
+
id: n.id,
|
|
816
|
+
isDummy: false,
|
|
817
|
+
rank: rank.get(n.id) ?? 0,
|
|
818
|
+
subgraphId: n.subgraphId,
|
|
819
|
+
order: n.order,
|
|
820
|
+
w: sz.w,
|
|
821
|
+
h: sz.h,
|
|
822
|
+
lines: sz.lines,
|
|
823
|
+
basePt: sz.basePt,
|
|
824
|
+
node: n,
|
|
825
|
+
})
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
const unitPred = new Map([...vertices.keys()].map((k) => [k, []]))
|
|
829
|
+
const unitSucc = new Map([...vertices.keys()].map((k) => [k, []]))
|
|
830
|
+
let dummySeq = 0
|
|
831
|
+
for (const de of dagEdges) {
|
|
832
|
+
const ru = rank.get(de.u) ?? 0
|
|
833
|
+
const rv = rank.get(de.v) ?? 0
|
|
834
|
+
if (rv <= ru) continue
|
|
835
|
+
let prev = de.u
|
|
836
|
+
for (let r = ru + 1; r < rv; r += 1) {
|
|
837
|
+
dummySeq += 1
|
|
838
|
+
const did = '__dummy_' + dummySeq
|
|
839
|
+
vertices.set(did, {
|
|
840
|
+
id: did,
|
|
841
|
+
isDummy: true,
|
|
842
|
+
rank: r,
|
|
843
|
+
subgraphId: nodeById.get(de.u)?.subgraphId === nodeById.get(de.v)?.subgraphId ? nodeById.get(de.u)?.subgraphId : null,
|
|
844
|
+
order: 1000 + dummySeq,
|
|
845
|
+
w: isHoriz ? 0.10 : 0.14,
|
|
846
|
+
h: isHoriz ? 0.14 : 0.10,
|
|
847
|
+
lines: [],
|
|
848
|
+
basePt: 10,
|
|
849
|
+
node: null,
|
|
850
|
+
})
|
|
851
|
+
unitPred.set(did, [prev])
|
|
852
|
+
unitSucc.set(did, [])
|
|
853
|
+
unitSucc.get(prev).push(did)
|
|
854
|
+
prev = did
|
|
855
|
+
}
|
|
856
|
+
unitSucc.get(prev).push(de.v)
|
|
857
|
+
unitPred.get(de.v).push(prev)
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const layers = Array.from({ length: layerCount }, () => [])
|
|
861
|
+
for (const v of vertices.values()) {
|
|
862
|
+
layers[v.rank].push(v.id)
|
|
863
|
+
}
|
|
864
|
+
layers.forEach((layer) => {
|
|
865
|
+
layer.sort((a, b) => {
|
|
866
|
+
const va = vertices.get(a)
|
|
867
|
+
const vb = vertices.get(b)
|
|
868
|
+
const sga = sgOrderMap.get(va.subgraphId) ?? 0
|
|
869
|
+
const sgb = sgOrderMap.get(vb.subgraphId) ?? 0
|
|
870
|
+
if (sga !== sgb) return sga - sgb
|
|
871
|
+
return va.order - vb.order
|
|
872
|
+
})
|
|
873
|
+
})
|
|
874
|
+
|
|
875
|
+
const posInLayer = new Map()
|
|
876
|
+
const refreshPos = (r) => {
|
|
877
|
+
layers[r].forEach((vid, idx) => posInLayer.set(vid, idx))
|
|
878
|
+
}
|
|
879
|
+
for (let r = 0; r < layerCount; r += 1) refreshPos(r)
|
|
880
|
+
|
|
881
|
+
for (let pass = 0; pass < 4; pass += 1) {
|
|
882
|
+
// Top-Down Sweep
|
|
883
|
+
for (let r = 1; r < layerCount; r += 1) {
|
|
884
|
+
const bary = new Map()
|
|
885
|
+
layers[r].forEach((vid, idx) => {
|
|
886
|
+
const preds = unitPred.get(vid) ?? []
|
|
887
|
+
if (preds.length === 0) bary.set(vid, idx)
|
|
888
|
+
else bary.set(vid, preds.reduce((s, p) => s + (posInLayer.get(p) ?? 0), 0) / preds.length)
|
|
889
|
+
})
|
|
890
|
+
layers[r].sort((a, b) => {
|
|
891
|
+
const diff = (bary.get(a) ?? 0) - (bary.get(b) ?? 0)
|
|
892
|
+
if (Math.abs(diff) > 0.05) return diff
|
|
893
|
+
const sga = sgOrderMap.get(vertices.get(a).subgraphId) ?? 0
|
|
894
|
+
const sgb = sgOrderMap.get(vertices.get(b).subgraphId) ?? 0
|
|
895
|
+
if (sga !== sgb) return sga - sgb
|
|
896
|
+
return vertices.get(a).order - vertices.get(b).order
|
|
897
|
+
})
|
|
898
|
+
refreshPos(r)
|
|
899
|
+
}
|
|
900
|
+
// Bottom-Up Sweep
|
|
901
|
+
for (let r = layerCount - 2; r >= 0; r -= 1) {
|
|
902
|
+
const bary = new Map()
|
|
903
|
+
layers[r].forEach((vid, idx) => {
|
|
904
|
+
const succs = unitSucc.get(vid) ?? []
|
|
905
|
+
if (succs.length === 0) bary.set(vid, idx)
|
|
906
|
+
else bary.set(vid, succs.reduce((s, c) => s + (posInLayer.get(c) ?? 0), 0) / succs.length)
|
|
907
|
+
})
|
|
908
|
+
layers[r].sort((a, b) => {
|
|
909
|
+
const diff = (bary.get(a) ?? 0) - (bary.get(b) ?? 0)
|
|
910
|
+
if (Math.abs(diff) > 0.05) return diff
|
|
911
|
+
const sga = sgOrderMap.get(vertices.get(a).subgraphId) ?? 0
|
|
912
|
+
const sgb = sgOrderMap.get(vertices.get(b).subgraphId) ?? 0
|
|
913
|
+
if (sga !== sgb) return sga - sgb
|
|
914
|
+
return vertices.get(a).order - vertices.get(b).order
|
|
915
|
+
})
|
|
916
|
+
refreshPos(r)
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// 若仍有同级兄弟子图共享同一层级,强制按子图顺序分组以保证跨轴条带互不交叉
|
|
921
|
+
if (ast.subgraphs.length >= 2) {
|
|
922
|
+
const sgRankRanges = new Map()
|
|
923
|
+
for (const sg of ast.subgraphs) {
|
|
924
|
+
const rs = sg.nodeIds.map((nid) => rank.get(nid)).filter((r) => r !== undefined)
|
|
925
|
+
if (rs.length > 0) sgRankRanges.set(sg.id, [Math.min(...rs), Math.max(...rs)])
|
|
926
|
+
}
|
|
927
|
+
const overlappingSgs = new Set()
|
|
928
|
+
for (let i = 0; i < ast.subgraphs.length; i += 1) {
|
|
929
|
+
for (let j = i + 1; j < ast.subgraphs.length; j += 1) {
|
|
930
|
+
const a = ast.subgraphs[i]
|
|
931
|
+
const b = ast.subgraphs[j]
|
|
932
|
+
if (a.parentId === b.id || b.parentId === a.id) continue
|
|
933
|
+
const ra = sgRankRanges.get(a.id)
|
|
934
|
+
const rb = sgRankRanges.get(b.id)
|
|
935
|
+
if (ra && rb && ra[0] <= rb[1] && rb[0] <= ra[1]) {
|
|
936
|
+
overlappingSgs.add(a.id)
|
|
937
|
+
overlappingSgs.add(b.id)
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
if (overlappingSgs.size > 0) {
|
|
942
|
+
for (let r = 0; r < layerCount; r += 1) {
|
|
943
|
+
layers[r].sort((a, b) => {
|
|
944
|
+
const va = vertices.get(a)
|
|
945
|
+
const vb = vertices.get(b)
|
|
946
|
+
const sga = overlappingSgs.has(va.subgraphId) ? (sgOrderMap.get(va.subgraphId) ?? 0) : 0
|
|
947
|
+
const sgb = overlappingSgs.has(vb.subgraphId) ? (sgOrderMap.get(vb.subgraphId) ?? 0) : 0
|
|
948
|
+
if (sga !== sgb) return sga - sgb
|
|
949
|
+
return (posInLayer.get(a) ?? 0) - (posInLayer.get(b) ?? 0)
|
|
950
|
+
})
|
|
951
|
+
refreshPos(r)
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// Step 4:自适应盒尺寸与子图感知均衡坐标求解
|
|
957
|
+
const hasSubgraphs = ast.subgraphs.length > 0
|
|
958
|
+
const padOuterX = hasSubgraphs ? 0.18 : 0.06
|
|
959
|
+
const padOuterTop = hasSubgraphs ? (isHoriz ? 0.40 : 0.34) : 0.05
|
|
960
|
+
const padOuterBot = hasSubgraphs ? 0.14 : 0.05
|
|
961
|
+
const innerBox = {
|
|
962
|
+
x: areaBox.x + padOuterX,
|
|
963
|
+
y: areaBox.y + padOuterTop,
|
|
964
|
+
w: Math.max(2.0, areaBox.w - padOuterX * 2),
|
|
965
|
+
h: Math.max(1.6, areaBox.h - padOuterTop - padOuterBot),
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
const orderedRanks = Array.from({ length: layerCount }, (_, r) =>
|
|
969
|
+
direction === 'BT' || direction === 'RL' ? layerCount - 1 - r : r,
|
|
970
|
+
)
|
|
971
|
+
|
|
972
|
+
const realLayers = orderedRanks.map((r) =>
|
|
973
|
+
layers[r].map((vid) => vertices.get(vid)).filter((v) => !v.isDummy),
|
|
974
|
+
)
|
|
975
|
+
|
|
976
|
+
// 计算主轴(Primary Axis)各层厚度与层间间距
|
|
977
|
+
const rawLayerThickness = realLayers.map((items) =>
|
|
978
|
+
items.length > 0 ? Math.max(...items.map((v) => (isHoriz ? v.w : v.h))) : 0.50,
|
|
979
|
+
)
|
|
980
|
+
const rawLayerGaps = []
|
|
981
|
+
const layerLabelWidths = []
|
|
982
|
+
for (let i = 0; i < layerCount - 1; i += 1) {
|
|
983
|
+
const rA = orderedRanks[i]
|
|
984
|
+
const rB = orderedRanks[i + 1]
|
|
985
|
+
const labeledEdges = dagEdges.filter((de) => {
|
|
986
|
+
const ru = rank.get(de.u) ?? 0
|
|
987
|
+
const rv = rank.get(de.v) ?? 0
|
|
988
|
+
return de.label && ((ru === rA && rv === rB) || (ru === rB && rv === rA))
|
|
989
|
+
})
|
|
990
|
+
const hasLabeledEdge = labeledEdges.length > 0
|
|
991
|
+
const maxEdgeLabelW = hasLabeledEdge
|
|
992
|
+
? Math.max(...labeledEdges.map((de) => Math.min(1.65, Math.max(0.50, (measureEmWidth(de.label, true) * 10) / 72 + 0.20))))
|
|
993
|
+
: 0
|
|
994
|
+
layerLabelWidths.push(maxEdgeLabelW)
|
|
995
|
+
const sgSetA = new Set(realLayers[i].map((v) => v.subgraphId).filter(Boolean))
|
|
996
|
+
const sgSetB = new Set(realLayers[i + 1].map((v) => v.subgraphId).filter(Boolean))
|
|
997
|
+
const opensSubgraph = hasSubgraphs && [...sgSetB].some((s) => !sgSetA.has(s))
|
|
998
|
+
const closesSubgraph = hasSubgraphs && [...sgSetA].some((s) => !sgSetB.has(s))
|
|
999
|
+
let gap = isHoriz
|
|
1000
|
+
? (hasLabeledEdge ? Math.max(0.76, maxEdgeLabelW + 0.16) : 0.54)
|
|
1001
|
+
: (hasLabeledEdge ? 0.56 : 0.38)
|
|
1002
|
+
if (opensSubgraph && closesSubgraph) gap += isHoriz ? 0.36 : 0.44
|
|
1003
|
+
else if (opensSubgraph) gap += isHoriz ? 0.24 : 0.36
|
|
1004
|
+
else if (closesSubgraph) gap += isHoriz ? 0.18 : 0.22
|
|
1005
|
+
rawLayerGaps.push(gap)
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
const availPrimary = isHoriz ? innerBox.w : innerBox.h
|
|
1009
|
+
const availCross = isHoriz ? innerBox.h : innerBox.w
|
|
1010
|
+
const sumThick = rawLayerThickness.reduce((a, b) => a + b, 0)
|
|
1011
|
+
const sumGaps = rawLayerGaps.reduce((a, b) => a + b, 0)
|
|
1012
|
+
|
|
1013
|
+
let layerThickness = [...rawLayerThickness]
|
|
1014
|
+
let layerGaps = [...rawLayerGaps]
|
|
1015
|
+
let thickScale = 1
|
|
1016
|
+
if (sumThick + sumGaps > availPrimary) {
|
|
1017
|
+
const minGaps = rawLayerGaps.map((g, i) => {
|
|
1018
|
+
const sgA = new Set(realLayers[i].map((v) => v.subgraphId).filter(Boolean))
|
|
1019
|
+
const sgB = new Set(realLayers[i + 1].map((v) => v.subgraphId).filter(Boolean))
|
|
1020
|
+
const opensSg = hasSubgraphs && [...sgB].some((s) => !sgA.has(s))
|
|
1021
|
+
const closesSg = hasSubgraphs && [...sgA].some((s) => !sgB.has(s))
|
|
1022
|
+
const labelW = layerLabelWidths[i] ?? 0
|
|
1023
|
+
const labelFloor = isHoriz && labelW > 0 ? Math.min(1.08, Math.max(0.76, labelW + 0.16)) : 0
|
|
1024
|
+
const sgFloor = opensSg && closesSg ? (isHoriz ? 0.56 : 0.54) : opensSg ? (isHoriz ? 0.42 : 0.44) : 0
|
|
1025
|
+
const baseFloor = Math.min(g, (isHoriz ? 0.34 : 0.30) + (g > 0.50 ? 0.08 : 0))
|
|
1026
|
+
return Math.min(g, Math.max(baseFloor, sgFloor, labelFloor))
|
|
1027
|
+
})
|
|
1028
|
+
const minGapsTotal = minGaps.reduce((a, b) => a + b, 0)
|
|
1029
|
+
if (sumThick + minGapsTotal <= availPrimary && sumGaps > 0) {
|
|
1030
|
+
const extraAvail = availPrimary - sumThick - minGapsTotal
|
|
1031
|
+
const flexSum = rawLayerGaps.reduce((s, g, i) => s + Math.max(0, g - minGaps[i]), 0)
|
|
1032
|
+
layerGaps = rawLayerGaps.map((g, i) => minGaps[i] + (flexSum > 0 ? extraAvail * (Math.max(0, g - minGaps[i]) / flexSum) : 0))
|
|
1033
|
+
} else if (availPrimary - minGapsTotal >= sumThick * 0.62) {
|
|
1034
|
+
thickScale = (availPrimary - minGapsTotal) / Math.max(0.1, sumThick)
|
|
1035
|
+
layerThickness = rawLayerThickness.map((t) => t * thickScale)
|
|
1036
|
+
layerGaps = minGaps
|
|
1037
|
+
} else {
|
|
1038
|
+
const uniformScale = availPrimary / Math.max(0.1, sumThick + minGapsTotal)
|
|
1039
|
+
thickScale = uniformScale
|
|
1040
|
+
layerThickness = rawLayerThickness.map((t) => t * uniformScale)
|
|
1041
|
+
layerGaps = minGaps.map((g) => g * uniformScale)
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
for (const items of realLayers) {
|
|
1046
|
+
for (const v of items) {
|
|
1047
|
+
if (isHoriz) v.w *= thickScale
|
|
1048
|
+
else v.h *= thickScale
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
const totalPrimaryUsed = layerThickness.reduce((a, b) => a + b, 0) + layerGaps.reduce((a, b) => a + b, 0)
|
|
1053
|
+
let cursorPrimary = (isHoriz ? innerBox.x : innerBox.y) + Math.max(0, (availPrimary - totalPrimaryUsed) / 2)
|
|
1054
|
+
const layerPrimaryCenters = []
|
|
1055
|
+
for (let i = 0; i < layerCount; i += 1) {
|
|
1056
|
+
layerPrimaryCenters.push(cursorPrimary + layerThickness[i] / 2)
|
|
1057
|
+
cursorPrimary += layerThickness[i] + (layerGaps[i] ?? 0)
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
// 计算副轴(Cross Axis)每层节点位置(跨子图边界自动插入隔离间距)
|
|
1061
|
+
const placedBoxes = new Map()
|
|
1062
|
+
realLayers.forEach((items, layerIdx) => {
|
|
1063
|
+
if (items.length === 0) return
|
|
1064
|
+
const baseCrossGap = isHoriz ? 0.34 : 0.36
|
|
1065
|
+
const sgBoundaryExtra = hasSubgraphs ? (isHoriz ? 0.44 : 0.34) : 0
|
|
1066
|
+
const gaps = []
|
|
1067
|
+
for (let j = 0; j < items.length - 1; j += 1) {
|
|
1068
|
+
const diffSg = items[j].subgraphId !== items[j + 1].subgraphId && (items[j].subgraphId || items[j + 1].subgraphId)
|
|
1069
|
+
gaps.push(baseCrossGap + (diffSg ? sgBoundaryExtra : 0))
|
|
1070
|
+
}
|
|
1071
|
+
const rawCrossSizes = items.map((v) => (isHoriz ? v.h : v.w))
|
|
1072
|
+
const sumCross = rawCrossSizes.reduce((a, b) => a + b, 0)
|
|
1073
|
+
const sumCrossGaps = gaps.reduce((a, b) => a + b, 0)
|
|
1074
|
+
let cGapScale = 1
|
|
1075
|
+
let cSizeScale = 1
|
|
1076
|
+
if (sumCross + sumCrossGaps > availCross) {
|
|
1077
|
+
const floorGapSum = gaps.reduce((s, g) => s + Math.min(g, 0.20 + (g > baseCrossGap ? 0.18 : 0)), 0)
|
|
1078
|
+
if (sumCross + floorGapSum <= availCross && sumCrossGaps > 0) {
|
|
1079
|
+
cGapScale = (availCross - sumCross) / sumCrossGaps
|
|
1080
|
+
} else {
|
|
1081
|
+
if (sumCrossGaps > 0) cGapScale = floorGapSum / sumCrossGaps
|
|
1082
|
+
cSizeScale = Math.max(0.52, (availCross - floorGapSum) / Math.max(0.1, sumCross))
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
const effSizes = rawCrossSizes.map((s) => s * cSizeScale)
|
|
1086
|
+
const effGaps = gaps.map((g) => g * cGapScale)
|
|
1087
|
+
const usedCross = effSizes.reduce((a, b) => a + b, 0) + effGaps.reduce((a, b) => a + b, 0)
|
|
1088
|
+
let cursorCross = (isHoriz ? innerBox.y : innerBox.x) + Math.max(0, (availCross - usedCross) / 2)
|
|
1089
|
+
const pCenter = layerPrimaryCenters[layerIdx]
|
|
1090
|
+
|
|
1091
|
+
items.forEach((v, j) => {
|
|
1092
|
+
if (isHoriz) {
|
|
1093
|
+
v.h = effSizes[j]
|
|
1094
|
+
const x = pCenter - v.w / 2
|
|
1095
|
+
const y = cursorCross
|
|
1096
|
+
placedBoxes.set(v.id, { x, y, w: v.w, h: v.h, cx: x + v.w / 2, cy: y + v.h / 2 })
|
|
1097
|
+
} else {
|
|
1098
|
+
v.w = effSizes[j]
|
|
1099
|
+
const x = cursorCross
|
|
1100
|
+
const y = pCenter - v.h / 2
|
|
1101
|
+
placedBoxes.set(v.id, { x, y, w: v.w, h: v.h, cx: x + v.w / 2, cy: y + v.h / 2 })
|
|
1102
|
+
}
|
|
1103
|
+
cursorCross += effSizes[j] + (effGaps[j] ?? 0)
|
|
1104
|
+
})
|
|
1105
|
+
})
|
|
1106
|
+
|
|
1107
|
+
// 单节点层向相邻层父子重心微调对齐(使主干保持笔直直线)
|
|
1108
|
+
for (let sweep = 0; sweep < 3; sweep += 1) {
|
|
1109
|
+
for (let i = 0; i < layerCount; i += 1) {
|
|
1110
|
+
const items = realLayers[i]
|
|
1111
|
+
if (items.length !== 1) continue
|
|
1112
|
+
const v = items[0]
|
|
1113
|
+
const box = placedBoxes.get(v.id)
|
|
1114
|
+
if (!box) continue
|
|
1115
|
+
const sameSgNeighbors = [
|
|
1116
|
+
...(inAdj.get(v.id) ?? []),
|
|
1117
|
+
...(outAdj.get(v.id) ?? []),
|
|
1118
|
+
].filter((nid) => placedBoxes.has(nid) && (!hasSubgraphs || nodeById.get(nid)?.subgraphId === v.subgraphId || !v.subgraphId))
|
|
1119
|
+
const allNeighbors = [
|
|
1120
|
+
...(inAdj.get(v.id) ?? []),
|
|
1121
|
+
...(outAdj.get(v.id) ?? []),
|
|
1122
|
+
].filter((nid) => placedBoxes.has(nid))
|
|
1123
|
+
const neighbors = sameSgNeighbors.length > 0 ? sameSgNeighbors : allNeighbors
|
|
1124
|
+
if (neighbors.length === 0) continue
|
|
1125
|
+
const targetCenter = neighbors.reduce((s, nid) => {
|
|
1126
|
+
const nb = placedBoxes.get(nid)
|
|
1127
|
+
return s + (isHoriz ? nb.cy : nb.cx)
|
|
1128
|
+
}, 0) / neighbors.length
|
|
1129
|
+
if (isHoriz) {
|
|
1130
|
+
const ny = Math.max(innerBox.y, Math.min(innerBox.y + innerBox.h - box.h, targetCenter - box.h / 2))
|
|
1131
|
+
box.y = ny
|
|
1132
|
+
box.cy = ny + box.h / 2
|
|
1133
|
+
} else {
|
|
1134
|
+
const nx = Math.max(innerBox.x, Math.min(innerBox.x + innerBox.w - box.w, targetCenter - box.w / 2))
|
|
1135
|
+
box.x = nx
|
|
1136
|
+
box.cx = nx + box.w / 2
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
// 多节点层中入度为 1 的叶子节点在不碰撞相邻节点的前提下向唯一父节点对齐(消除微小错位折线)
|
|
1142
|
+
for (let i = 1; i < layerCount; i += 1) {
|
|
1143
|
+
const items = realLayers[i]
|
|
1144
|
+
if (items.length < 2) continue
|
|
1145
|
+
items.forEach((v, j) => {
|
|
1146
|
+
const preds = (inAdj.get(v.id) ?? []).filter((pid) => placedBoxes.has(pid))
|
|
1147
|
+
if (preds.length !== 1) return
|
|
1148
|
+
const box = placedBoxes.get(v.id)
|
|
1149
|
+
const pBox = placedBoxes.get(preds[0])
|
|
1150
|
+
if (!box || !pBox) return
|
|
1151
|
+
const prevGap = j > 0 && items[j].subgraphId !== items[j - 1].subgraphId && (items[j].subgraphId || items[j - 1].subgraphId)
|
|
1152
|
+
? 0.44
|
|
1153
|
+
: 0.24
|
|
1154
|
+
const nextGap = j < items.length - 1 && items[j].subgraphId !== items[j + 1].subgraphId && (items[j].subgraphId || items[j + 1].subgraphId)
|
|
1155
|
+
? 0.44
|
|
1156
|
+
: 0.24
|
|
1157
|
+
const minAllow = j === 0
|
|
1158
|
+
? (isHoriz ? innerBox.y : innerBox.x)
|
|
1159
|
+
: (isHoriz
|
|
1160
|
+
? placedBoxes.get(items[j - 1].id).y + placedBoxes.get(items[j - 1].id).h + prevGap
|
|
1161
|
+
: placedBoxes.get(items[j - 1].id).x + placedBoxes.get(items[j - 1].id).w + prevGap)
|
|
1162
|
+
const maxAllow = j === items.length - 1
|
|
1163
|
+
? (isHoriz ? innerBox.y + innerBox.h - box.h : innerBox.x + innerBox.w - box.w)
|
|
1164
|
+
: (isHoriz
|
|
1165
|
+
? placedBoxes.get(items[j + 1].id).y - box.h - nextGap
|
|
1166
|
+
: placedBoxes.get(items[j + 1].id).x - box.w - nextGap)
|
|
1167
|
+
if (minAllow > maxAllow) return
|
|
1168
|
+
if (isHoriz) {
|
|
1169
|
+
const ny = Math.max(minAllow, Math.min(maxAllow, pBox.cy - box.h / 2))
|
|
1170
|
+
box.y = ny
|
|
1171
|
+
box.cy = ny + box.h / 2
|
|
1172
|
+
} else {
|
|
1173
|
+
const nx = Math.max(minAllow, Math.min(maxAllow, pBox.cx - box.w / 2))
|
|
1174
|
+
box.x = nx
|
|
1175
|
+
box.cx = nx + box.w / 2
|
|
1176
|
+
}
|
|
1177
|
+
})
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
// 计算 Subgraph 容器外框(按嵌套深度从浅到深绘制在底层)
|
|
1181
|
+
const subgraphBoxes = ast.subgraphs
|
|
1182
|
+
.map((sg) => {
|
|
1183
|
+
const memberBoxes = sg.nodeIds.map((nid) => placedBoxes.get(nid)).filter(Boolean)
|
|
1184
|
+
if (memberBoxes.length === 0) return null
|
|
1185
|
+
const minX = Math.min(...memberBoxes.map((b) => b.x))
|
|
1186
|
+
const minY = Math.min(...memberBoxes.map((b) => b.y))
|
|
1187
|
+
const maxX = Math.max(...memberBoxes.map((b) => b.x + b.w))
|
|
1188
|
+
const maxY = Math.max(...memberBoxes.map((b) => b.y + b.h))
|
|
1189
|
+
const padL = Math.min(0.16, Math.max(0.08, 0.16 * thickScale))
|
|
1190
|
+
const padR = Math.min(0.16, Math.max(0.08, 0.16 * thickScale))
|
|
1191
|
+
const padT = 0.36
|
|
1192
|
+
const padB = Math.min(0.12, Math.max(0.08, 0.12 * thickScale))
|
|
1193
|
+
const x = Math.max(areaBox.x + 0.02, minX - padL)
|
|
1194
|
+
const y = Math.max(areaBox.y + 0.02, minY - padT)
|
|
1195
|
+
const right = Math.min(areaBox.x + areaBox.w - 0.02, maxX + padR)
|
|
1196
|
+
const bottom = Math.min(areaBox.y + areaBox.h - 0.02, maxY + padB)
|
|
1197
|
+
return {
|
|
1198
|
+
id: sg.id,
|
|
1199
|
+
title: sg.title,
|
|
1200
|
+
parentId: sg.parentId,
|
|
1201
|
+
x,
|
|
1202
|
+
y,
|
|
1203
|
+
w: Math.max(0.8, right - x),
|
|
1204
|
+
h: Math.max(0.6, bottom - y),
|
|
1205
|
+
}
|
|
1206
|
+
})
|
|
1207
|
+
.filter(Boolean)
|
|
1208
|
+
|
|
1209
|
+
// 缩放后按实际可用 fitBox 宽度重排节点文本(带防单字孤行均衡,杜绝 PowerPoint/LibreOffice 自动拆出 1 字尾行)
|
|
1210
|
+
const tokenizeForBalancedWrap = (str) => {
|
|
1211
|
+
const tokens = []
|
|
1212
|
+
let cur = ''
|
|
1213
|
+
for (const ch of str) {
|
|
1214
|
+
if (/\s/.test(ch)) {
|
|
1215
|
+
if (cur) { tokens.push(cur); cur = '' }
|
|
1216
|
+
} else if (/[\u3400-\u9fff\u3000-\u303f\uff00-\uffef]/.test(ch)) {
|
|
1217
|
+
if (cur) { tokens.push(cur); cur = '' }
|
|
1218
|
+
tokens.push(ch)
|
|
1219
|
+
} else {
|
|
1220
|
+
cur += ch
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
if (cur) tokens.push(cur)
|
|
1224
|
+
return tokens
|
|
1225
|
+
}
|
|
1226
|
+
const joinWrappedTokens = (toks) => {
|
|
1227
|
+
let s = ''
|
|
1228
|
+
for (const tok of toks) {
|
|
1229
|
+
if (!s) {
|
|
1230
|
+
s = tok
|
|
1231
|
+
} else {
|
|
1232
|
+
const prevAscii = /[A-Za-z0-9]$/.test(s)
|
|
1233
|
+
const nextAscii = /^[A-Za-z0-9]/.test(tok)
|
|
1234
|
+
const prevCjk = /[\u3400-\u9fff]$/.test(s)
|
|
1235
|
+
const nextCjk = /^[\u3400-\u9fff]/.test(tok)
|
|
1236
|
+
s += (prevAscii && nextAscii) || (prevAscii && nextCjk) || (prevCjk && nextAscii) ? ' ' + tok : tok
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
return s
|
|
1240
|
+
}
|
|
1241
|
+
const rewrapLinesForFitBox = (label, currentLines, fitBoxW, refPt = 10) => {
|
|
1242
|
+
const availEm = Math.max(2.8, (((fitBoxW - 0.08) * 72) / refPt) * 0.90)
|
|
1243
|
+
const needsRewrap = currentLines.some((ln) => measureEmWidth(ln, true) > availEm)
|
|
1244
|
+
if (!needsRewrap) return currentLines
|
|
1245
|
+
const explicit = String(label ?? '').split('\n').map((s) => s.trim()).filter(Boolean)
|
|
1246
|
+
const out = []
|
|
1247
|
+
for (const para of explicit) {
|
|
1248
|
+
if (measureEmWidth(para, true) <= availEm) {
|
|
1249
|
+
out.push(para)
|
|
1250
|
+
continue
|
|
1251
|
+
}
|
|
1252
|
+
const toks = tokenizeForBalancedWrap(para)
|
|
1253
|
+
if (toks.length <= 1) {
|
|
1254
|
+
out.push(para)
|
|
1255
|
+
continue
|
|
1256
|
+
}
|
|
1257
|
+
const lineToks = []
|
|
1258
|
+
let cur = []
|
|
1259
|
+
for (const tok of toks) {
|
|
1260
|
+
const candidate = joinWrappedTokens([...cur, tok])
|
|
1261
|
+
if (cur.length > 0 && measureEmWidth(candidate, true) > availEm) {
|
|
1262
|
+
lineToks.push(cur)
|
|
1263
|
+
cur = [tok]
|
|
1264
|
+
} else {
|
|
1265
|
+
cur.push(tok)
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
if (cur.length > 0) lineToks.push(cur)
|
|
1269
|
+
// 防单字孤行:若末行仅 1 个短字符(< 1.85 em)且上一行 >= 2 个 token,将上一行末尾 token 下移以消除单字尾行
|
|
1270
|
+
if (lineToks.length >= 2) {
|
|
1271
|
+
const last = lineToks[lineToks.length - 1]
|
|
1272
|
+
const prev = lineToks[lineToks.length - 2]
|
|
1273
|
+
const lastStr = joinWrappedTokens(last)
|
|
1274
|
+
if (last.length === 1 && measureEmWidth(lastStr, true) < 1.85 && prev.length >= 2) {
|
|
1275
|
+
const moved = prev.pop()
|
|
1276
|
+
last.unshift(moved)
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
for (const lt of lineToks) out.push(joinWrappedTokens(lt))
|
|
1280
|
+
}
|
|
1281
|
+
return out.length > 0 ? out.slice(0, 3) : currentLines
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
// 生成带精确字号拟合(>= 10pt 硬底线)的节点列表(按 ECMA-376 内缩文本框扣减 + 全节点粗体宽度测量)
|
|
1285
|
+
const positionedNodes = rawNodes.map((n) => {
|
|
1286
|
+
const b = placedBoxes.get(n.id)
|
|
1287
|
+
const v = vertices.get(n.id)
|
|
1288
|
+
const fitBox = n.shape === 'diamond'
|
|
1289
|
+
? { w: Math.max(0.55, b.w * 0.58), h: Math.max(0.32, b.h * 0.58) }
|
|
1290
|
+
: n.shape === 'stadium'
|
|
1291
|
+
? { w: Math.max(0.55, b.w - b.h * 0.50 - 0.08), h: Math.max(0.32, b.h * 0.82) }
|
|
1292
|
+
: n.shape === 'subroutine'
|
|
1293
|
+
? { w: Math.max(0.55, b.w * 0.70 - 0.08), h: Math.max(0.32, b.h * 0.82) }
|
|
1294
|
+
: n.shape === 'cylinder'
|
|
1295
|
+
? { w: Math.max(0.55, b.w * 0.82 - 0.08), h: Math.max(0.32, b.h * 0.68) }
|
|
1296
|
+
: n.shape === 'circle'
|
|
1297
|
+
? { w: Math.max(0.55, b.w * 0.72), h: Math.max(0.32, b.h * 0.72) }
|
|
1298
|
+
: { w: Math.max(0.55, b.w - 0.20), h: Math.max(0.32, b.h * 0.82) }
|
|
1299
|
+
const effectiveLines = rewrapLinesForFitBox(n.label, v.lines, fitBox.w, 10)
|
|
1300
|
+
const fit = computeTextFit(effectiveLines, fitBox, 'cardBody', {
|
|
1301
|
+
maxPt: Math.min(13.5, v.basePt + 0.5),
|
|
1302
|
+
minPt: 10,
|
|
1303
|
+
padXPt: 3,
|
|
1304
|
+
padYPt: 2,
|
|
1305
|
+
lineHeight: 1.18,
|
|
1306
|
+
spaceAfterPt: 1,
|
|
1307
|
+
bold: true,
|
|
1308
|
+
})
|
|
1309
|
+
return {
|
|
1310
|
+
id: n.id,
|
|
1311
|
+
label: n.label,
|
|
1312
|
+
lines: effectiveLines,
|
|
1313
|
+
shape: n.shape,
|
|
1314
|
+
subgraphId: n.subgraphId,
|
|
1315
|
+
customStyle: n.customStyle,
|
|
1316
|
+
rank: v.rank,
|
|
1317
|
+
isRoot: (inAdj.get(n.id)?.length ?? 0) === 0,
|
|
1318
|
+
isSink: (outAdj.get(n.id)?.length ?? 0) === 0,
|
|
1319
|
+
x: +b.x.toFixed(4),
|
|
1320
|
+
y: +b.y.toFixed(4),
|
|
1321
|
+
w: +b.w.toFixed(4),
|
|
1322
|
+
h: +b.h.toFixed(4),
|
|
1323
|
+
cx: +b.cx.toFixed(4),
|
|
1324
|
+
cy: +b.cy.toFixed(4),
|
|
1325
|
+
fontPt: Math.max(10, fit.fontPt),
|
|
1326
|
+
}
|
|
1327
|
+
})
|
|
1328
|
+
|
|
1329
|
+
const posNodeMap = new Map(positionedNodes.map((n) => [n.id, n]))
|
|
1330
|
+
|
|
1331
|
+
// 计算每条边的精确连接站点(0=top, 1=left, 2=bottom, 3=right)与路由几何
|
|
1332
|
+
const usedLabelAnchors = []
|
|
1333
|
+
const positionedEdges = rawEdges
|
|
1334
|
+
.map((e, idx) => {
|
|
1335
|
+
const src = posNodeMap.get(e.from)
|
|
1336
|
+
const dst = posNodeMap.get(e.to)
|
|
1337
|
+
if (!src || !dst) return null
|
|
1338
|
+
|
|
1339
|
+
let outIdx = 2
|
|
1340
|
+
let inIdx = 0
|
|
1341
|
+
let orientation = isHoriz ? 'horizontal' : 'vertical'
|
|
1342
|
+
|
|
1343
|
+
if (src.id === dst.id) {
|
|
1344
|
+
outIdx = 3
|
|
1345
|
+
inIdx = 0
|
|
1346
|
+
orientation = 'horizontal'
|
|
1347
|
+
} else if (!isHoriz) {
|
|
1348
|
+
if (dst.y >= src.y + src.h - 0.06) {
|
|
1349
|
+
outIdx = 2
|
|
1350
|
+
inIdx = 0
|
|
1351
|
+
orientation = 'vertical'
|
|
1352
|
+
} else if (src.y >= dst.y + dst.h - 0.06) {
|
|
1353
|
+
if (src.x + src.w + 0.08 < dst.x) {
|
|
1354
|
+
outIdx = 3
|
|
1355
|
+
inIdx = 1
|
|
1356
|
+
orientation = 'horizontal'
|
|
1357
|
+
} else if (dst.x + dst.w + 0.08 < src.x) {
|
|
1358
|
+
outIdx = 1
|
|
1359
|
+
inIdx = 3
|
|
1360
|
+
orientation = 'horizontal'
|
|
1361
|
+
} else {
|
|
1362
|
+
outIdx = 0
|
|
1363
|
+
inIdx = 2
|
|
1364
|
+
orientation = 'vertical'
|
|
1365
|
+
}
|
|
1366
|
+
} else {
|
|
1367
|
+
outIdx = dst.cx >= src.cx ? 3 : 1
|
|
1368
|
+
inIdx = dst.cx >= src.cx ? 1 : 3
|
|
1369
|
+
orientation = 'horizontal'
|
|
1370
|
+
}
|
|
1371
|
+
} else {
|
|
1372
|
+
if (dst.x >= src.x + src.w - 0.06) {
|
|
1373
|
+
outIdx = 3
|
|
1374
|
+
inIdx = 1
|
|
1375
|
+
orientation = 'horizontal'
|
|
1376
|
+
} else if (src.x >= dst.x + dst.w - 0.06) {
|
|
1377
|
+
if (src.y + src.h + 0.08 < dst.y) {
|
|
1378
|
+
outIdx = 2
|
|
1379
|
+
inIdx = 0
|
|
1380
|
+
orientation = 'vertical'
|
|
1381
|
+
} else if (dst.y + dst.h + 0.08 < src.y) {
|
|
1382
|
+
outIdx = 0
|
|
1383
|
+
inIdx = 2
|
|
1384
|
+
orientation = 'vertical'
|
|
1385
|
+
} else {
|
|
1386
|
+
outIdx = 1
|
|
1387
|
+
inIdx = 3
|
|
1388
|
+
orientation = 'horizontal'
|
|
1389
|
+
}
|
|
1390
|
+
} else {
|
|
1391
|
+
outIdx = dst.cy >= src.cy ? 2 : 0
|
|
1392
|
+
inIdx = dst.cy >= src.cy ? 0 : 2
|
|
1393
|
+
orientation = 'vertical'
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
const fromPt = portCoordinates(src, outIdx)
|
|
1398
|
+
const toPt = portCoordinates(dst, inIdx)
|
|
1399
|
+
const dx = toPt.x - fromPt.x
|
|
1400
|
+
const dy = toPt.y - fromPt.y
|
|
1401
|
+
const isCollinear = (orientation === 'vertical' && Math.abs(dx) < 0.035) ||
|
|
1402
|
+
(orientation === 'horizontal' && Math.abs(dy) < 0.035)
|
|
1403
|
+
const connectorPreset = src.id === dst.id
|
|
1404
|
+
? 'bentConnector3'
|
|
1405
|
+
: isCollinear
|
|
1406
|
+
? 'straightConnector1'
|
|
1407
|
+
: 'bentConnector3'
|
|
1408
|
+
|
|
1409
|
+
// 跨层折线避障:若 horizontal bentConnector3 默认中点折弯穿过了中间层节点,将折弯位置 adj1 移至中间节点之前/之后的净空槽道
|
|
1410
|
+
let adj1 = 50000
|
|
1411
|
+
let avoidedBlocker = null
|
|
1412
|
+
if (connectorPreset === 'bentConnector3' && orientation === 'horizontal' && Math.abs(dx) > 0.35 && Math.abs(dy) > 0.15) {
|
|
1413
|
+
const minX = Math.min(fromPt.x, toPt.x)
|
|
1414
|
+
const maxX = Math.max(fromPt.x, toPt.x)
|
|
1415
|
+
const blockersOnStartRay = positionedNodes.filter((n) =>
|
|
1416
|
+
n.id !== src.id &&
|
|
1417
|
+
n.id !== dst.id &&
|
|
1418
|
+
n.x < maxX - 0.04 &&
|
|
1419
|
+
n.x + n.w > minX + 0.04 &&
|
|
1420
|
+
fromPt.y >= n.y - 0.08 &&
|
|
1421
|
+
fromPt.y <= n.y + n.h + 0.08,
|
|
1422
|
+
)
|
|
1423
|
+
if (blockersOnStartRay.length > 0) {
|
|
1424
|
+
if (dx > 0) {
|
|
1425
|
+
const firstBlk = blockersOnStartRay.reduce((a, b) => (a.x <= b.x ? a : b))
|
|
1426
|
+
const bendX = Math.max(fromPt.x + 0.12, Math.min(firstBlk.x - 0.12, (fromPt.x + firstBlk.x) / 2))
|
|
1427
|
+
if (bendX > fromPt.x + 0.05 && bendX < toPt.x - 0.15) {
|
|
1428
|
+
adj1 = Math.max(10000, Math.min(90000, Math.round(((bendX - fromPt.x) / dx) * 100000)))
|
|
1429
|
+
avoidedBlocker = { side: 'start', bendX, blocker: firstBlk }
|
|
1430
|
+
}
|
|
1431
|
+
} else {
|
|
1432
|
+
const firstBlk = blockersOnStartRay.reduce((a, b) => (a.x + a.w >= b.x + b.w ? a : b))
|
|
1433
|
+
const bendX = Math.min(fromPt.x - 0.12, Math.max(firstBlk.x + firstBlk.w + 0.12, (fromPt.x + firstBlk.x + firstBlk.w) / 2))
|
|
1434
|
+
if (bendX < fromPt.x - 0.05 && bendX > toPt.x + 0.15) {
|
|
1435
|
+
adj1 = Math.max(10000, Math.min(90000, Math.round(((bendX - fromPt.x) / dx) * 100000)))
|
|
1436
|
+
avoidedBlocker = { side: 'start', bendX, blocker: firstBlk }
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
// 计算标签胶囊坐标并避让已有标签与节点框(短竖直直线边右移;水平净空不足时上抬至连线上方避免盖住节点文字)
|
|
1443
|
+
let labelBox = null
|
|
1444
|
+
if (e.label) {
|
|
1445
|
+
const labelFontPt = 10
|
|
1446
|
+
const lw = Math.min(2.1, Math.max(0.50, (measureEmWidth(e.label, true) * labelFontPt) / 72 + 0.20))
|
|
1447
|
+
const lh = 0.23
|
|
1448
|
+
let lx = (fromPt.x + toPt.x) / 2 - lw / 2
|
|
1449
|
+
let ly = (fromPt.y + toPt.y) / 2 - lh / 2
|
|
1450
|
+
if (avoidedBlocker && avoidedBlocker.side === 'start') {
|
|
1451
|
+
lx = (avoidedBlocker.bendX + toPt.x) / 2 - lw / 2
|
|
1452
|
+
ly = toPt.y - lh / 2
|
|
1453
|
+
} else if (connectorPreset === 'straightConnector1' && orientation === 'vertical' && Math.abs(dy) < 0.62) {
|
|
1454
|
+
lx = fromPt.x + 0.10
|
|
1455
|
+
} else if (connectorPreset === 'bentConnector3' && orientation === 'vertical' && Math.abs(dx) > 0.35) {
|
|
1456
|
+
lx = fromPt.x + dx * 0.62 - lw / 2
|
|
1457
|
+
} else if (connectorPreset === 'bentConnector3' && orientation === 'horizontal' && Math.abs(dy) > 0.35) {
|
|
1458
|
+
ly = fromPt.y + dy * 0.62 - lh / 2
|
|
1459
|
+
}
|
|
1460
|
+
const horizClearSpan = Math.abs(toPt.x - fromPt.x)
|
|
1461
|
+
if (!avoidedBlocker && orientation === 'horizontal' && horizClearSpan < lw + 0.08) {
|
|
1462
|
+
const liftedY = Math.min(fromPt.y, toPt.y) - lh - 0.06
|
|
1463
|
+
ly = liftedY >= areaBox.y + 0.02 ? liftedY : Math.max(fromPt.y, toPt.y) + 0.06
|
|
1464
|
+
}
|
|
1465
|
+
// 避免标签胶囊压到非端点节点盒
|
|
1466
|
+
for (const n of positionedNodes) {
|
|
1467
|
+
if (n.id === src.id || n.id === dst.id) continue
|
|
1468
|
+
const hitX = lx < n.x + n.w + 0.03 && lx + lw > n.x - 0.03
|
|
1469
|
+
const hitY = ly < n.y + n.h + 0.03 && ly + lh > n.y - 0.03
|
|
1470
|
+
if (hitX && hitY) {
|
|
1471
|
+
const belowY = n.y + n.h + 0.05
|
|
1472
|
+
const aboveY = n.y - lh - 0.05
|
|
1473
|
+
ly = belowY + lh <= areaBox.y + areaBox.h - 0.02 ? belowY : Math.max(areaBox.y + 0.02, aboveY)
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
for (const prev of usedLabelAnchors) {
|
|
1477
|
+
if (Math.abs(lx - prev.x) < lw * 0.78 && Math.abs(ly - prev.y) < lh * 0.92) {
|
|
1478
|
+
ly += lh + 0.04
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
lx = Math.max(areaBox.x + 0.02, Math.min(areaBox.x + areaBox.w - lw - 0.02, lx))
|
|
1482
|
+
ly = Math.max(areaBox.y + 0.02, Math.min(areaBox.y + areaBox.h - lh - 0.02, ly))
|
|
1483
|
+
usedLabelAnchors.push({ x: lx, y: ly })
|
|
1484
|
+
labelBox = { x: +lx.toFixed(4), y: +ly.toFixed(4), w: +lw.toFixed(4), h: lh, fontPt: labelFontPt }
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
return {
|
|
1488
|
+
...e,
|
|
1489
|
+
index: idx,
|
|
1490
|
+
outIdx,
|
|
1491
|
+
inIdx,
|
|
1492
|
+
orientation,
|
|
1493
|
+
connectorPreset,
|
|
1494
|
+
adj1,
|
|
1495
|
+
fromPt: { x: +fromPt.x.toFixed(4), y: +fromPt.y.toFixed(4) },
|
|
1496
|
+
toPt: { x: +toPt.x.toFixed(4), y: +toPt.y.toFixed(4) },
|
|
1497
|
+
labelBox,
|
|
1498
|
+
}
|
|
1499
|
+
})
|
|
1500
|
+
.filter(Boolean)
|
|
1501
|
+
|
|
1502
|
+
return {
|
|
1503
|
+
mode: 'flowchart',
|
|
1504
|
+
direction,
|
|
1505
|
+
areaBox,
|
|
1506
|
+
subgraphs: subgraphBoxes,
|
|
1507
|
+
nodes: positionedNodes,
|
|
1508
|
+
edges: positionedEdges,
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
// ---------------------------------------------------------------------------
|
|
1513
|
+
// 4. Mode B:Mermaid SequenceDiagram 解析器与确定性时序几何求解器
|
|
1514
|
+
// ---------------------------------------------------------------------------
|
|
1515
|
+
|
|
1516
|
+
export function parseMermaidSequence(slideOrText) {
|
|
1517
|
+
const src = extractMermaidSource(slideOrText)
|
|
1518
|
+
const rawLines = src.split('\n')
|
|
1519
|
+
const participants = []
|
|
1520
|
+
const partMap = new Map()
|
|
1521
|
+
const events = []
|
|
1522
|
+
const frames = []
|
|
1523
|
+
const frameStack = []
|
|
1524
|
+
const activeStacks = new Map()
|
|
1525
|
+
const activations = []
|
|
1526
|
+
let autonumber = false
|
|
1527
|
+
let msgCount = 0
|
|
1528
|
+
|
|
1529
|
+
const ensureActor = (rawId, explicitLabel = '', kind = 'participant') => {
|
|
1530
|
+
const id = unquoteMermaidText(rawId).replace(/\s+/g, ' ').trim()
|
|
1531
|
+
if (!id) return null
|
|
1532
|
+
let p = partMap.get(id)
|
|
1533
|
+
if (!p) {
|
|
1534
|
+
p = {
|
|
1535
|
+
id,
|
|
1536
|
+
label: explicitLabel ? unquoteMermaidText(explicitLabel) : id,
|
|
1537
|
+
kind,
|
|
1538
|
+
index: participants.length,
|
|
1539
|
+
}
|
|
1540
|
+
participants.push(p)
|
|
1541
|
+
partMap.set(id, p)
|
|
1542
|
+
} else {
|
|
1543
|
+
if (explicitLabel) p.label = unquoteMermaidText(explicitLabel)
|
|
1544
|
+
if (kind === 'actor') p.kind = 'actor'
|
|
1545
|
+
}
|
|
1546
|
+
return p
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
const pushActivation = (actorId, stepIdx) => {
|
|
1550
|
+
if (!activeStacks.has(actorId)) activeStacks.set(actorId, [])
|
|
1551
|
+
const st = activeStacks.get(actorId)
|
|
1552
|
+
st.push({ actorId, startStep: stepIdx, depth: st.length })
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
const popActivation = (actorId, stepIdx) => {
|
|
1556
|
+
const st = activeStacks.get(actorId)
|
|
1557
|
+
if (!st || st.length === 0) return
|
|
1558
|
+
const item = st.pop()
|
|
1559
|
+
activations.push({
|
|
1560
|
+
actorId,
|
|
1561
|
+
startStep: item.startStep,
|
|
1562
|
+
endStep: Math.max(item.startStep + 0.6, stepIdx),
|
|
1563
|
+
depth: item.depth,
|
|
1564
|
+
})
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
for (let i = 0; i < rawLines.length; i += 1) {
|
|
1568
|
+
const line = rawLines[i].trim()
|
|
1569
|
+
if (!line) continue
|
|
1570
|
+
if (i === 0 && /^sequenceDiagram\b/i.test(line)) continue
|
|
1571
|
+
if (/^autonumber\b/i.test(line)) {
|
|
1572
|
+
autonumber = true
|
|
1573
|
+
continue
|
|
1574
|
+
}
|
|
1575
|
+
if (/^(?:title|links|link|box)\b/i.test(line)) continue
|
|
1576
|
+
|
|
1577
|
+
const actorDecl = /^(participant|actor)\s+(.+?)(?:\s+as\s+(.+))?$/i.exec(line)
|
|
1578
|
+
if (actorDecl) {
|
|
1579
|
+
ensureActor(actorDecl[2], actorDecl[3] ?? '', actorDecl[1].toLowerCase())
|
|
1580
|
+
continue
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
const actCmd = /^(activate|deactivate)\s+(.+)$/i.exec(line)
|
|
1584
|
+
if (actCmd) {
|
|
1585
|
+
const p = ensureActor(actCmd[2])
|
|
1586
|
+
if (p) {
|
|
1587
|
+
const curStep = Math.max(0, events.length - 0.25)
|
|
1588
|
+
if (actCmd[1].toLowerCase() === 'activate') pushActivation(p.id, curStep)
|
|
1589
|
+
else popActivation(p.id, curStep)
|
|
1590
|
+
}
|
|
1591
|
+
continue
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
const noteSingle = /^Note\s+(left of|right of|over)\s+([^:]+?)\s*:\s*(.+)$/i.exec(line)
|
|
1595
|
+
if (noteSingle) {
|
|
1596
|
+
const placement = noteSingle[1].toLowerCase().startsWith('left')
|
|
1597
|
+
? 'left'
|
|
1598
|
+
: noteSingle[1].toLowerCase().startsWith('right')
|
|
1599
|
+
? 'right'
|
|
1600
|
+
: 'over'
|
|
1601
|
+
const actorTokens = noteSingle[2].split(',').map((s) => ensureActor(s.trim())).filter(Boolean)
|
|
1602
|
+
if (actorTokens.length > 0) {
|
|
1603
|
+
events.push({
|
|
1604
|
+
type: 'note',
|
|
1605
|
+
step: events.length,
|
|
1606
|
+
placement,
|
|
1607
|
+
actors: actorTokens.map((a) => a.id),
|
|
1608
|
+
text: unquoteMermaidText(noteSingle[3]),
|
|
1609
|
+
})
|
|
1610
|
+
}
|
|
1611
|
+
continue
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
const frameOpen = /^(loop|alt|opt|par|critical|break)\b\s*(.*)$/i.exec(line)
|
|
1615
|
+
if (frameOpen) {
|
|
1616
|
+
const frame = {
|
|
1617
|
+
kind: frameOpen[1].toLowerCase(),
|
|
1618
|
+
label: unquoteMermaidText(frameOpen[2]),
|
|
1619
|
+
startStep: events.length,
|
|
1620
|
+
endStep: events.length,
|
|
1621
|
+
dividers: [],
|
|
1622
|
+
depth: frameStack.length,
|
|
1623
|
+
}
|
|
1624
|
+
frames.push(frame)
|
|
1625
|
+
frameStack.push(frame)
|
|
1626
|
+
events.push({ type: 'frame-start', step: events.length, frame })
|
|
1627
|
+
continue
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
const frameDiv = /^(else|and|option)\b\s*(.*)$/i.exec(line)
|
|
1631
|
+
if (frameDiv && frameStack.length > 0) {
|
|
1632
|
+
const top = frameStack[frameStack.length - 1]
|
|
1633
|
+
const div = { kind: frameDiv[1].toLowerCase(), label: unquoteMermaidText(frameDiv[2]), step: events.length }
|
|
1634
|
+
top.dividers.push(div)
|
|
1635
|
+
events.push({ type: 'frame-divider', step: events.length, divider: div })
|
|
1636
|
+
continue
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
if (/^end\s*$/i.test(line)) {
|
|
1640
|
+
const closed = frameStack.pop()
|
|
1641
|
+
if (closed) {
|
|
1642
|
+
closed.endStep = Math.max(closed.startStep, events.length - 1)
|
|
1643
|
+
}
|
|
1644
|
+
continue
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
const msgMatch = /^([^-=:>]+?)\s*(--?>>|--?>|--?[xX]|--?\))([+-])?\s*([^:]+?)\s*:\s*(.*)$/.exec(line)
|
|
1648
|
+
if (msgMatch) {
|
|
1649
|
+
const srcActor = ensureActor(msgMatch[1])
|
|
1650
|
+
const arrowToken = msgMatch[2]
|
|
1651
|
+
const actMod = msgMatch[3] || ''
|
|
1652
|
+
const dstActor = ensureActor(msgMatch[4])
|
|
1653
|
+
if (!srcActor || !dstActor) continue
|
|
1654
|
+
msgCount += 1
|
|
1655
|
+
const rawText = unquoteMermaidText(msgMatch[5])
|
|
1656
|
+
const text = autonumber ? msgCount + '. ' + rawText : rawText
|
|
1657
|
+
const isDash = arrowToken.startsWith('--')
|
|
1658
|
+
const head = arrowToken.endsWith('>>')
|
|
1659
|
+
? 'filled'
|
|
1660
|
+
: /[xX]$/.test(arrowToken)
|
|
1661
|
+
? 'cross'
|
|
1662
|
+
: arrowToken.endsWith(')')
|
|
1663
|
+
? 'async'
|
|
1664
|
+
: 'open'
|
|
1665
|
+
const stepIdx = events.length
|
|
1666
|
+
events.push({
|
|
1667
|
+
type: 'message',
|
|
1668
|
+
step: stepIdx,
|
|
1669
|
+
from: srcActor.id,
|
|
1670
|
+
to: dstActor.id,
|
|
1671
|
+
arrow: arrowToken,
|
|
1672
|
+
dash: isDash ? 'dash' : '',
|
|
1673
|
+
head,
|
|
1674
|
+
text,
|
|
1675
|
+
})
|
|
1676
|
+
if (actMod === '+') pushActivation(dstActor.id, stepIdx)
|
|
1677
|
+
else if (actMod === '-') popActivation(srcActor.id, stepIdx)
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
const finalStep = Math.max(0, events.length - 1)
|
|
1682
|
+
while (frameStack.length > 0) {
|
|
1683
|
+
const f = frameStack.pop()
|
|
1684
|
+
f.endStep = Math.max(f.startStep, finalStep)
|
|
1685
|
+
}
|
|
1686
|
+
for (const [actorId, st] of activeStacks.entries()) {
|
|
1687
|
+
while (st.length > 0) {
|
|
1688
|
+
const item = st.pop()
|
|
1689
|
+
activations.push({
|
|
1690
|
+
actorId,
|
|
1691
|
+
startStep: item.startStep,
|
|
1692
|
+
endStep: Math.max(item.startStep + 0.6, finalStep),
|
|
1693
|
+
depth: item.depth,
|
|
1694
|
+
})
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
return {
|
|
1699
|
+
mode: 'sequence',
|
|
1700
|
+
autonumber,
|
|
1701
|
+
participants,
|
|
1702
|
+
events,
|
|
1703
|
+
frames,
|
|
1704
|
+
activations,
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
export function layoutMermaidSequence(astInput, areaBox = { x: 0.62, y: 1.86, w: 12.09, h: 4.78 }) {
|
|
1709
|
+
const ast = astInput?.mode === 'sequence' ? astInput : parseMermaidSequence(astInput)
|
|
1710
|
+
const rawParts = ast.participants.length > 0
|
|
1711
|
+
? ast.participants
|
|
1712
|
+
: [
|
|
1713
|
+
{ id: 'Client', label: 'Client', kind: 'participant', index: 0 },
|
|
1714
|
+
{ id: 'Server', label: 'Server', kind: 'participant', index: 1 },
|
|
1715
|
+
]
|
|
1716
|
+
|
|
1717
|
+
const pCount = rawParts.length
|
|
1718
|
+
const firstId = rawParts[0].id
|
|
1719
|
+
const lastId = rawParts[pCount - 1].id
|
|
1720
|
+
const hasLeftNote = ast.events.some((e) => e.type === 'note' && e.placement === 'left' && e.actors[0] === firstId)
|
|
1721
|
+
const hasRightExtra = ast.events.some(
|
|
1722
|
+
(e) =>
|
|
1723
|
+
(e.type === 'note' && e.placement === 'right' && e.actors[e.actors.length - 1] === lastId) ||
|
|
1724
|
+
(e.type === 'message' && e.from === lastId && e.to === lastId),
|
|
1725
|
+
)
|
|
1726
|
+
|
|
1727
|
+
const leftPad = hasLeftNote ? 1.55 : 0.24
|
|
1728
|
+
const rightPad = hasRightExtra ? 1.55 : 0.24
|
|
1729
|
+
const usableW = Math.max(2.4, areaBox.w - leftPad - rightPad)
|
|
1730
|
+
|
|
1731
|
+
const headH = 0.48
|
|
1732
|
+
const footH = 0.42
|
|
1733
|
+
const topY = areaBox.y + 0.02
|
|
1734
|
+
const botY = areaBox.y + areaBox.h - footH - 0.02
|
|
1735
|
+
|
|
1736
|
+
const colSpan = pCount === 1 ? usableW : usableW / pCount
|
|
1737
|
+
const boxW = Math.min(2.10, Math.max(0.96, colSpan * 0.74))
|
|
1738
|
+
const participants = rawParts.map((p, idx) => {
|
|
1739
|
+
const cx = pCount === 1
|
|
1740
|
+
? areaBox.x + leftPad + usableW / 2
|
|
1741
|
+
: areaBox.x + leftPad + boxW / 2 + idx * ((usableW - boxW) / Math.max(1, pCount - 1))
|
|
1742
|
+
const fit = computeTextFit(p.label, { w: boxW - 0.14, h: headH - 0.08 }, 'cardTitle', {
|
|
1743
|
+
maxPt: 12.5,
|
|
1744
|
+
minPt: 10,
|
|
1745
|
+
padXPt: 3,
|
|
1746
|
+
padYPt: 2,
|
|
1747
|
+
})
|
|
1748
|
+
return {
|
|
1749
|
+
...p,
|
|
1750
|
+
cx: +cx.toFixed(4),
|
|
1751
|
+
w: +boxW.toFixed(4),
|
|
1752
|
+
fontPt: Math.max(10, fit.fontPt),
|
|
1753
|
+
topBox: { x: +(cx - boxW / 2).toFixed(4), y: +topY.toFixed(4), w: +boxW.toFixed(4), h: headH },
|
|
1754
|
+
bottomBox: { x: +(cx - boxW / 2).toFixed(4), y: +botY.toFixed(4), w: +boxW.toFixed(4), h: footH },
|
|
1755
|
+
lifelineTopY: +(topY + headH).toFixed(4),
|
|
1756
|
+
lifelineBottomY: +botY.toFixed(4),
|
|
1757
|
+
}
|
|
1758
|
+
})
|
|
1759
|
+
|
|
1760
|
+
const partById = new Map(participants.map((p) => [p.id, p]))
|
|
1761
|
+
|
|
1762
|
+
// 计算每条时序事件的纵向刻度 Y
|
|
1763
|
+
const bandTop = topY + headH + 0.22
|
|
1764
|
+
const bandBottom = botY - 0.18
|
|
1765
|
+
const bandH = Math.max(0.8, bandBottom - bandTop)
|
|
1766
|
+
|
|
1767
|
+
const weights = ast.events.map((ev) => {
|
|
1768
|
+
if (ev.type === 'frame-start') return 0.78
|
|
1769
|
+
if (ev.type === 'frame-divider') return 0.64
|
|
1770
|
+
if (ev.type === 'note') return 1.32
|
|
1771
|
+
if (ev.type === 'message' && ev.from === ev.to) return 1.12
|
|
1772
|
+
return 0.88
|
|
1773
|
+
})
|
|
1774
|
+
const totalWeight = weights.reduce((a, b) => a + b, 0) || 1
|
|
1775
|
+
const unitH = Math.min(0.62, bandH / totalWeight)
|
|
1776
|
+
const usedBandH = totalWeight * unitH
|
|
1777
|
+
let cursorY = bandTop + Math.max(0, (bandH - usedBandH) * 0.28)
|
|
1778
|
+
|
|
1779
|
+
const stepYs = []
|
|
1780
|
+
ast.events.forEach((ev, idx) => {
|
|
1781
|
+
const slotH = weights[idx] * unitH
|
|
1782
|
+
stepYs.push(cursorY + slotH * 0.54)
|
|
1783
|
+
cursorY += slotH
|
|
1784
|
+
})
|
|
1785
|
+
|
|
1786
|
+
const yAtStep = (s) => {
|
|
1787
|
+
if (stepYs.length === 0) return (bandTop + bandBottom) / 2
|
|
1788
|
+
const lo = Math.max(0, Math.min(stepYs.length - 1, Math.floor(s)))
|
|
1789
|
+
const hi = Math.max(0, Math.min(stepYs.length - 1, Math.ceil(s)))
|
|
1790
|
+
const frac = s - Math.floor(s)
|
|
1791
|
+
return stepYs[lo] * (1 - frac) + stepYs[hi] * frac
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
// 布局组合片段框(loop / alt / opt / par)
|
|
1795
|
+
const positionedFrames = ast.frames.map((f, fIdx) => {
|
|
1796
|
+
const y1 = Math.max(topY + headH + 0.06, (stepYs[f.startStep] ?? bandTop) - unitH * 0.20)
|
|
1797
|
+
const y2 = Math.min(botY - 0.06, (stepYs[f.endStep] ?? bandBottom) + unitH * 0.44)
|
|
1798
|
+
const inset = f.depth * 0.14
|
|
1799
|
+
const minCx = Math.min(...participants.map((p) => p.topBox.x))
|
|
1800
|
+
const maxCx = Math.max(...participants.map((p) => p.topBox.x + p.w))
|
|
1801
|
+
const fx = Math.max(areaBox.x + 0.04, minCx - 0.18 + inset)
|
|
1802
|
+
const fw = Math.min(areaBox.x + areaBox.w - 0.04 - fx, maxCx - minCx + 0.36 - inset * 2)
|
|
1803
|
+
return {
|
|
1804
|
+
id: 'frame_' + (fIdx + 1),
|
|
1805
|
+
kind: f.kind.toUpperCase(),
|
|
1806
|
+
label: f.label,
|
|
1807
|
+
x: +fx.toFixed(4),
|
|
1808
|
+
y: +y1.toFixed(4),
|
|
1809
|
+
w: +Math.max(1.6, fw).toFixed(4),
|
|
1810
|
+
h: +Math.max(0.52, y2 - y1).toFixed(4),
|
|
1811
|
+
dividers: f.dividers.map((d) => ({
|
|
1812
|
+
kind: d.kind,
|
|
1813
|
+
label: d.label,
|
|
1814
|
+
y: +((stepYs[d.step] ?? (y1 + y2) / 2) - unitH * 0.06).toFixed(4),
|
|
1815
|
+
})),
|
|
1816
|
+
}
|
|
1817
|
+
})
|
|
1818
|
+
|
|
1819
|
+
// 布局激活条(Activation Bars)
|
|
1820
|
+
const actW = 0.15
|
|
1821
|
+
const positionedActivations = ast.activations
|
|
1822
|
+
.map((act, idx) => {
|
|
1823
|
+
const p = partById.get(act.actorId)
|
|
1824
|
+
if (!p) return null
|
|
1825
|
+
const ay1 = Math.max(topY + headH + 0.08, yAtStep(act.startStep) - 0.04)
|
|
1826
|
+
const ay2 = Math.min(botY - 0.08, Math.max(ay1 + 0.24, yAtStep(act.endStep) + 0.06))
|
|
1827
|
+
const ax = p.cx - actW / 2 + act.depth * 0.05
|
|
1828
|
+
return {
|
|
1829
|
+
id: 'act_' + (idx + 1),
|
|
1830
|
+
actorId: act.actorId,
|
|
1831
|
+
x: +ax.toFixed(4),
|
|
1832
|
+
y: +ay1.toFixed(4),
|
|
1833
|
+
w: actW,
|
|
1834
|
+
h: +(ay2 - ay1).toFixed(4),
|
|
1835
|
+
}
|
|
1836
|
+
})
|
|
1837
|
+
.filter(Boolean)
|
|
1838
|
+
|
|
1839
|
+
// 布局消息箭头与 Note 批注卡片(保障 Note 与后续消息标签之间留有安全间距)
|
|
1840
|
+
const positionedMessages = []
|
|
1841
|
+
const positionedNotes = []
|
|
1842
|
+
const msgFontPt = ast.events.filter((e) => e.type === 'message').length >= 9 ? 10 : 10.5
|
|
1843
|
+
let prevNoteBottom = -Infinity
|
|
1844
|
+
|
|
1845
|
+
ast.events.forEach((ev, idx) => {
|
|
1846
|
+
const rawY = stepYs[idx] ?? bandTop
|
|
1847
|
+
if (ev.type === 'message') {
|
|
1848
|
+
const y = Number.isFinite(prevNoteBottom)
|
|
1849
|
+
? Math.min(bandBottom - 0.04, Math.max(rawY, prevNoteBottom + 0.33))
|
|
1850
|
+
: rawY
|
|
1851
|
+
prevNoteBottom = -Infinity
|
|
1852
|
+
const src = partById.get(ev.from)
|
|
1853
|
+
const dst = partById.get(ev.to)
|
|
1854
|
+
if (!src || !dst) return
|
|
1855
|
+
const isSelf = src.id === dst.id
|
|
1856
|
+
if (isSelf) {
|
|
1857
|
+
const loopW = Math.min(0.68, Math.max(0.42, colSpan * 0.30))
|
|
1858
|
+
const loopH = Math.min(0.32, Math.max(0.20, unitH * 0.46))
|
|
1859
|
+
const startX = src.cx + 0.08
|
|
1860
|
+
const lblW = Math.min(2.4, Math.max(0.9, (measureEmWidth(ev.text, false) * msgFontPt) / 72 + 0.24))
|
|
1861
|
+
positionedMessages.push({
|
|
1862
|
+
...ev,
|
|
1863
|
+
isSelf: true,
|
|
1864
|
+
y: +y.toFixed(4),
|
|
1865
|
+
x1: +startX.toFixed(4),
|
|
1866
|
+
x2: +(startX + loopW).toFixed(4),
|
|
1867
|
+
loopH: +loopH.toFixed(4),
|
|
1868
|
+
fontPt: msgFontPt,
|
|
1869
|
+
labelBox: {
|
|
1870
|
+
x: +Math.min(areaBox.x + areaBox.w - lblW - 0.04, startX + loopW + 0.08).toFixed(4),
|
|
1871
|
+
y: +(y - loopH * 0.55).toFixed(4),
|
|
1872
|
+
w: +lblW.toFixed(4),
|
|
1873
|
+
h: 0.26,
|
|
1874
|
+
},
|
|
1875
|
+
})
|
|
1876
|
+
} else {
|
|
1877
|
+
const dirSign = dst.cx >= src.cx ? 1 : -1
|
|
1878
|
+
const x1 = src.cx + dirSign * 0.08
|
|
1879
|
+
const x2 = dst.cx - dirSign * 0.08
|
|
1880
|
+
const spanW = Math.max(0.7, Math.abs(x2 - x1) - 0.14)
|
|
1881
|
+
const textW = Math.min(spanW, Math.max(0.65, (measureEmWidth(ev.text, false) * msgFontPt) / 72 + 0.22))
|
|
1882
|
+
const midX = (x1 + x2) / 2
|
|
1883
|
+
positionedMessages.push({
|
|
1884
|
+
...ev,
|
|
1885
|
+
isSelf: false,
|
|
1886
|
+
y: +y.toFixed(4),
|
|
1887
|
+
x1: +x1.toFixed(4),
|
|
1888
|
+
x2: +x2.toFixed(4),
|
|
1889
|
+
fontPt: msgFontPt,
|
|
1890
|
+
labelBox: {
|
|
1891
|
+
x: +(midX - textW / 2).toFixed(4),
|
|
1892
|
+
y: +(y - 0.26).toFixed(4),
|
|
1893
|
+
w: +textW.toFixed(4),
|
|
1894
|
+
h: 0.23,
|
|
1895
|
+
},
|
|
1896
|
+
})
|
|
1897
|
+
}
|
|
1898
|
+
} else if (ev.type === 'note') {
|
|
1899
|
+
const y = rawY
|
|
1900
|
+
const actors = ev.actors.map((id) => partById.get(id)).filter(Boolean)
|
|
1901
|
+
if (actors.length === 0) return
|
|
1902
|
+
const minC = Math.min(...actors.map((a) => a.cx))
|
|
1903
|
+
const maxC = Math.max(...actors.map((a) => a.cx))
|
|
1904
|
+
let nw = Math.min(3.6, Math.max(1.45, (measureEmWidth(ev.text, false) * 10) / 72 + 0.42))
|
|
1905
|
+
let nx = minC - nw / 2
|
|
1906
|
+
if (ev.placement === 'left') {
|
|
1907
|
+
const availLeft = Math.max(1.35, minC - actors[0].w / 2 - 0.10 - (areaBox.x + 0.03))
|
|
1908
|
+
nw = Math.min(2.65, availLeft, nw)
|
|
1909
|
+
nx = Math.max(areaBox.x + 0.03, minC - actors[0].w / 2 - nw - 0.10)
|
|
1910
|
+
} else if (ev.placement === 'right') {
|
|
1911
|
+
const availRight = Math.max(1.35, (areaBox.x + areaBox.w - 0.03) - (maxC + actors[actors.length - 1].w / 2 + 0.10))
|
|
1912
|
+
nw = Math.min(2.65, availRight, nw)
|
|
1913
|
+
nx = Math.min(areaBox.x + areaBox.w - nw - 0.03, maxC + actors[actors.length - 1].w / 2 + 0.10)
|
|
1914
|
+
} else if (actors.length >= 2) {
|
|
1915
|
+
nw = Math.min(areaBox.w - 0.12, Math.max(nw, maxC - minC + 0.90))
|
|
1916
|
+
nx = (minC + maxC) / 2 - nw / 2
|
|
1917
|
+
} else {
|
|
1918
|
+
nw = Math.min(2.65, areaBox.w - 0.12, nw)
|
|
1919
|
+
nx = minC - nw / 2
|
|
1920
|
+
}
|
|
1921
|
+
nx = Math.max(areaBox.x + 0.03, Math.min(areaBox.x + areaBox.w - nw - 0.03, nx))
|
|
1922
|
+
const maxCharsPerLine = Math.max(8, Math.floor(((nw - 0.22) * 72) / 10.2))
|
|
1923
|
+
const noteLines = wrapNodeLabelLines(ev.text, maxCharsPerLine)
|
|
1924
|
+
const noteH = Math.min(0.56, Math.max(noteLines.length > 1 ? 0.44 : 0.34, unitH * (noteLines.length > 1 ? 0.82 : 0.68)))
|
|
1925
|
+
const noteFit = computeTextFit(noteLines, { w: Math.max(0.8, nw - 0.20), h: Math.max(0.24, noteH - 0.06) }, 'cardBody', {
|
|
1926
|
+
maxPt: 10,
|
|
1927
|
+
minPt: 8.5,
|
|
1928
|
+
padXPt: 2,
|
|
1929
|
+
padYPt: 1,
|
|
1930
|
+
lineHeight: 1.15,
|
|
1931
|
+
spaceAfterPt: 0,
|
|
1932
|
+
bold: false,
|
|
1933
|
+
})
|
|
1934
|
+
const ny = Math.max(bandTop - 0.06, Math.min(bandBottom - noteH, y - noteH / 2))
|
|
1935
|
+
prevNoteBottom = ny + noteH
|
|
1936
|
+
positionedNotes.push({
|
|
1937
|
+
...ev,
|
|
1938
|
+
lines: noteLines,
|
|
1939
|
+
x: +nx.toFixed(4),
|
|
1940
|
+
y: +ny.toFixed(4),
|
|
1941
|
+
w: +nw.toFixed(4),
|
|
1942
|
+
h: +noteH.toFixed(4),
|
|
1943
|
+
fontPt: Math.max(8.5, noteFit.fontPt),
|
|
1944
|
+
})
|
|
1945
|
+
}
|
|
1946
|
+
})
|
|
1947
|
+
|
|
1948
|
+
return {
|
|
1949
|
+
mode: 'sequence',
|
|
1950
|
+
areaBox,
|
|
1951
|
+
participants,
|
|
1952
|
+
frames: positionedFrames,
|
|
1953
|
+
activations: positionedActivations,
|
|
1954
|
+
messages: positionedMessages,
|
|
1955
|
+
notes: positionedNotes,
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
export function compileMermaidSlide(slideOrText, areaBox = { x: 0.62, y: 1.86, w: 12.09, h: 4.78 }, fallbackVariant = '') {
|
|
1960
|
+
const mode = detectMermaidMode(slideOrText, fallbackVariant || slideOrText?.variant)
|
|
1961
|
+
if (mode === 'sequence') {
|
|
1962
|
+
const ast = parseMermaidSequence(slideOrText)
|
|
1963
|
+
return layoutMermaidSequence(ast, areaBox)
|
|
1964
|
+
}
|
|
1965
|
+
const ast = parseMermaidFlowchart(slideOrText)
|
|
1966
|
+
return layoutMermaidFlowchart(ast, areaBox)
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
// ---------------------------------------------------------------------------
|
|
1970
|
+
// 5. PPTX 原生 OOXML 渲染器(100% <p:sp> 节点 + <p:cxnSp> <a:stCxn>/<a:endCxn> 连接线)
|
|
1971
|
+
// ---------------------------------------------------------------------------
|
|
1972
|
+
|
|
1973
|
+
function resolveFlowNodePreset(shape, box, chromeCfg) {
|
|
1974
|
+
if (shape === 'stadium') return { preset: 'flowChartTerminator', marginsIn: { l: 0.04, r: 0.04, t: 0.02, b: 0.02 } }
|
|
1975
|
+
if (shape === 'diamond') return { preset: 'diamond', marginsIn: { l: 0.02, r: 0.02, t: 0.02, b: 0.02 } }
|
|
1976
|
+
if (shape === 'cylinder') return { preset: 'can', adjs: { adj: 20000 }, marginsIn: { l: 0.04, r: 0.04, t: 0.02, b: 0.02 } }
|
|
1977
|
+
if (shape === 'circle') return { preset: 'ellipse', marginsIn: { l: 0.04, r: 0.04, t: 0.02, b: 0.02 } }
|
|
1978
|
+
if (shape === 'subroutine') return { preset: 'flowChartPredefinedProcess', marginsIn: { l: 0.04, r: 0.04, t: 0.02, b: 0.02 } }
|
|
1979
|
+
if (shape === 'hexagon') return { preset: 'hexagon', marginsIn: { l: 0.10, r: 0.10, t: 0.03, b: 0.03 } }
|
|
1980
|
+
if (shape === 'parallelogram') return { preset: 'parallelogram', marginsIn: { l: 0.12, r: 0.12, t: 0.03, b: 0.03 } }
|
|
1981
|
+
if (shape === 'round') {
|
|
1982
|
+
const rPx = Math.max(14, chromeCfg.cardRadiusPx || 14)
|
|
1983
|
+
return { preset: 'roundRect', adj: roundRectAdj(box.w, box.h, rPx), marginsIn: { l: 0.04, r: 0.04, t: 0.02, b: 0.02 } }
|
|
1984
|
+
}
|
|
1985
|
+
const radius = chromeCfg.cardRadiusPx > 0 ? Math.min(10, chromeCfg.cardRadiusPx) : 6
|
|
1986
|
+
return {
|
|
1987
|
+
preset: radius > 0 ? 'roundRect' : 'rect',
|
|
1988
|
+
adj: roundRectAdj(box.w, box.h, radius),
|
|
1989
|
+
marginsIn: { l: 0.04, r: 0.04, t: 0.02, b: 0.02 },
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
/**
|
|
1994
|
+
* 将逻辑四向连接点(0=top, 1=left, 2=bottom, 3=right)映射为特定 OOXML 预设几何体的精确 <cxnLst> 索引:
|
|
1995
|
+
* - rect / roundRect / diamond / flowChartTerminator / flowChartPredefinedProcess:4 站点 [0, 1, 2, 3]
|
|
1996
|
+
* - can(数据库圆柱):ECMA-376 定义 5 站点(0=顶后缘, 1=顶前缘, 2=左, 3=底, 4=右) -> [0, 2, 3, 4]
|
|
1997
|
+
* - ellipse(椭圆):ECMA-376 定义 8 站点(0=顶, 2=左, 4=底, 6=右) -> [0, 2, 4, 6]
|
|
1998
|
+
*/
|
|
1999
|
+
function resolveOoxmlConnectionSite(shape, cardinalIdx) {
|
|
2000
|
+
const idx = ((cardinalIdx % 4) + 4) % 4
|
|
2001
|
+
if (shape === 'cylinder') return [0, 2, 3, 4][idx]
|
|
2002
|
+
if (shape === 'circle') return [0, 2, 4, 6][idx]
|
|
2003
|
+
return idx
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
function resolveFlowNodePalette(node, theme) {
|
|
2007
|
+
const tk = theme.tokens
|
|
2008
|
+
const cs = node.customStyle || {}
|
|
2009
|
+
if (cs.fill) {
|
|
2010
|
+
const lum = relativeLuminance(cs.fill)
|
|
2011
|
+
return {
|
|
2012
|
+
fill: cs.fill,
|
|
2013
|
+
stroke: cs.stroke || tk.accentPrimary,
|
|
2014
|
+
textColor: cs.color || (lum < 0.38 ? '#FFFFFF' : '#0F172A'),
|
|
2015
|
+
strokePt: 1.25,
|
|
2016
|
+
bold: true,
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
if (node.shape === 'stadium' || (node.isRoot && node.shape !== 'diamond')) {
|
|
2020
|
+
return {
|
|
2021
|
+
fill: tk.accentPrimary,
|
|
2022
|
+
stroke: tk.accentPrimary,
|
|
2023
|
+
textColor: tk.inkOnAccent,
|
|
2024
|
+
strokePt: 1.25,
|
|
2025
|
+
bold: true,
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
if (node.shape === 'diamond') {
|
|
2029
|
+
return {
|
|
2030
|
+
fill: tk.accentSoft,
|
|
2031
|
+
stroke: tk.accentPrimary,
|
|
2032
|
+
textColor: tk.accentText,
|
|
2033
|
+
strokePt: 1.35,
|
|
2034
|
+
bold: true,
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
if (node.shape === 'cylinder') {
|
|
2038
|
+
return {
|
|
2039
|
+
fill: tk.surface2,
|
|
2040
|
+
stroke: tk.accentSecondary,
|
|
2041
|
+
textColor: tk.inkPrimary,
|
|
2042
|
+
strokePt: 1.15,
|
|
2043
|
+
bold: true,
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
if (node.shape === 'subroutine' || node.shape === 'circle') {
|
|
2047
|
+
return {
|
|
2048
|
+
fill: tk.accentSoft,
|
|
2049
|
+
stroke: tk.accentSecondary,
|
|
2050
|
+
textColor: tk.inkPrimary,
|
|
2051
|
+
strokePt: 1.1,
|
|
2052
|
+
bold: true,
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
if (node.isSink) {
|
|
2056
|
+
return {
|
|
2057
|
+
fill: tk.accentSoft,
|
|
2058
|
+
stroke: tk.accentPrimary,
|
|
2059
|
+
textColor: tk.inkPrimary,
|
|
2060
|
+
strokePt: 1.15,
|
|
2061
|
+
bold: true,
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
return {
|
|
2065
|
+
fill: tk.surface1,
|
|
2066
|
+
stroke: tk.hairline,
|
|
2067
|
+
textColor: tk.inkPrimary,
|
|
2068
|
+
strokePt: 1.0,
|
|
2069
|
+
bold: false,
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
function renderFlowchartPptx(model, nextIdFn, chromeCfg, theme, langAttr) {
|
|
2074
|
+
const tk = theme.tokens
|
|
2075
|
+
const shapes = []
|
|
2076
|
+
|
|
2077
|
+
// 1. Subgraph 容器簇(置于底层,带粗体簇标题)
|
|
2078
|
+
model.subgraphs.forEach((sg, idx) => {
|
|
2079
|
+
const sgFill = theme.dark
|
|
2080
|
+
? mixHex(tk.surface1, tk.accentPrimary, 0.12)
|
|
2081
|
+
: mixHex(tk.surface1, tk.accentSoft, 0.42)
|
|
2082
|
+
shapes.push(ooxmlShape(nextIdFn(), 'Mermaid Subgraph ' + sg.id, sg, {
|
|
2083
|
+
preset: 'roundRect',
|
|
2084
|
+
adj: roundRectAdj(sg.w, sg.h, Math.max(8, chromeCfg.cardRadiusPx)),
|
|
2085
|
+
fill: sgFill,
|
|
2086
|
+
stroke: idx % 2 === 0 ? tk.accentPrimary : tk.accentSecondary,
|
|
2087
|
+
strokePt: 1.0,
|
|
2088
|
+
dash: 'dash',
|
|
2089
|
+
anchor: 't',
|
|
2090
|
+
marginsIn: { l: 0.14, r: 0.14, t: 0.06, b: 0.04 },
|
|
2091
|
+
paragraphs: [
|
|
2092
|
+
ooxmlRichParagraph(sg.title, {
|
|
2093
|
+
sizePt: 10.5,
|
|
2094
|
+
color: tk.accentText,
|
|
2095
|
+
bold: true,
|
|
2096
|
+
lang: langAttr,
|
|
2097
|
+
align: 'l',
|
|
2098
|
+
font: theme.fonts.heading,
|
|
2099
|
+
lineHeight: 1.15,
|
|
2100
|
+
}),
|
|
2101
|
+
],
|
|
2102
|
+
}))
|
|
2103
|
+
})
|
|
2104
|
+
|
|
2105
|
+
// 2. 先分配确定性节点 spid,再先绘制底层边连接线或后绘制节点?
|
|
2106
|
+
// 注意:为确保连接线箭头不被节点遮挡且与节点边缘精确相接,先为每个节点分配确定性 spid,发射节点 <p:sp>,再发射绑定到真实 spid 的 <p:cxnSp>
|
|
2107
|
+
const nodeSpids = new Map()
|
|
2108
|
+
model.nodes.forEach((node) => {
|
|
2109
|
+
nodeSpids.set(node.id, nextIdFn())
|
|
2110
|
+
})
|
|
2111
|
+
|
|
2112
|
+
const nodeById = new Map(model.nodes.map((n) => [n.id, n]))
|
|
2113
|
+
model.nodes.forEach((node) => {
|
|
2114
|
+
const spid = nodeSpids.get(node.id)
|
|
2115
|
+
const geom = resolveFlowNodePreset(node.shape, node, chromeCfg)
|
|
2116
|
+
const pal = resolveFlowNodePalette(node, theme)
|
|
2117
|
+
const paras = node.lines.map((line, lIdx) =>
|
|
2118
|
+
ooxmlRichParagraph(line, {
|
|
2119
|
+
sizePt: node.fontPt,
|
|
2120
|
+
color: pal.textColor,
|
|
2121
|
+
bold: pal.bold || lIdx === 0,
|
|
2122
|
+
lang: langAttr,
|
|
2123
|
+
align: 'ctr',
|
|
2124
|
+
font: pal.bold ? theme.fonts.heading : theme.fonts.body,
|
|
2125
|
+
lineHeight: 1.16,
|
|
2126
|
+
}),
|
|
2127
|
+
)
|
|
2128
|
+
shapes.push(ooxmlShape(spid, 'Mermaid Node ' + node.id, node, {
|
|
2129
|
+
preset: geom.preset,
|
|
2130
|
+
adj: geom.adj,
|
|
2131
|
+
adjs: geom.adjs,
|
|
2132
|
+
fill: pal.fill,
|
|
2133
|
+
stroke: pal.stroke,
|
|
2134
|
+
strokePt: pal.strokePt,
|
|
2135
|
+
shadow: theme.shadow && !chromeCfg.cardBorderless,
|
|
2136
|
+
anchor: 'ctr',
|
|
2137
|
+
autofit: false,
|
|
2138
|
+
marginsIn: geom.marginsIn,
|
|
2139
|
+
paragraphs: paras,
|
|
2140
|
+
}))
|
|
2141
|
+
})
|
|
2142
|
+
|
|
2143
|
+
// 3. 原生附着连接线 <p:cxnSp>(带 <a:stCxn> / <a:endCxn>),随后在顶层统一绘制边标签胶囊 <p:sp> 以防线条穿字
|
|
2144
|
+
const labelShapes = []
|
|
2145
|
+
model.edges.forEach((edge) => {
|
|
2146
|
+
const srcSpid = nodeSpids.get(edge.from)
|
|
2147
|
+
const dstSpid = nodeSpids.get(edge.to)
|
|
2148
|
+
const srcNode = nodeById.get(edge.from)
|
|
2149
|
+
const dstNode = nodeById.get(edge.to)
|
|
2150
|
+
const outOoxmlIdx = resolveOoxmlConnectionSite(srcNode?.shape, edge.outIdx)
|
|
2151
|
+
const inOoxmlIdx = resolveOoxmlConnectionSite(dstNode?.shape, edge.inIdx)
|
|
2152
|
+
const strokeColor = edge.thick ? tk.accentPrimary : (theme.dark ? tk.inkSecondary : mixHex(tk.inkSecondary, tk.accentPrimary, 0.32))
|
|
2153
|
+
const widthPt = edge.thick ? 2.25 : 1.4
|
|
2154
|
+
|
|
2155
|
+
shapes.push(ooxmlConnector(nextIdFn(), 'Mermaid Edge ' + edge.from + '->' + edge.to, edge.fromPt, edge.toPt, {
|
|
2156
|
+
preset: edge.connectorPreset,
|
|
2157
|
+
orientation: edge.orientation,
|
|
2158
|
+
adj1: edge.adj1 ?? 50000,
|
|
2159
|
+
stCxn: { id: srcSpid, idx: outOoxmlIdx },
|
|
2160
|
+
endCxn: { id: dstSpid, idx: inOoxmlIdx },
|
|
2161
|
+
color: strokeColor,
|
|
2162
|
+
widthPt,
|
|
2163
|
+
dash: edge.dash,
|
|
2164
|
+
headArrow: edge.headArrow,
|
|
2165
|
+
tailArrow: edge.tailArrow,
|
|
2166
|
+
}))
|
|
2167
|
+
|
|
2168
|
+
if (edge.label && edge.labelBox) {
|
|
2169
|
+
labelShapes.push(ooxmlShape(nextIdFn(), 'Mermaid Edge Label ' + edge.id, edge.labelBox, {
|
|
2170
|
+
preset: 'roundRect',
|
|
2171
|
+
adj: 50000,
|
|
2172
|
+
fill: tk.canvas,
|
|
2173
|
+
stroke: tk.accentPrimary,
|
|
2174
|
+
strokePt: 0.75,
|
|
2175
|
+
anchor: 'ctr',
|
|
2176
|
+
autofit: false,
|
|
2177
|
+
marginsIn: { l: 0.04, r: 0.04, t: 0.01, b: 0.01 },
|
|
2178
|
+
paragraphs: [
|
|
2179
|
+
ooxmlRichParagraph(edge.label, {
|
|
2180
|
+
sizePt: edge.labelBox.fontPt,
|
|
2181
|
+
color: tk.accentText,
|
|
2182
|
+
bold: true,
|
|
2183
|
+
lang: langAttr,
|
|
2184
|
+
align: 'ctr',
|
|
2185
|
+
font: theme.fonts.body,
|
|
2186
|
+
lineHeight: 1.05,
|
|
2187
|
+
}),
|
|
2188
|
+
],
|
|
2189
|
+
}))
|
|
2190
|
+
}
|
|
2191
|
+
})
|
|
2192
|
+
|
|
2193
|
+
shapes.push(...labelShapes)
|
|
2194
|
+
return shapes.join('')
|
|
2195
|
+
}
|
|
2196
|
+
|
|
2197
|
+
function renderSequencePptx(model, nextIdFn, chromeCfg, theme, langAttr) {
|
|
2198
|
+
const tk = theme.tokens
|
|
2199
|
+
const shapes = []
|
|
2200
|
+
const cardPreset = chromeCfg.cardRadiusPx > 0 ? 'roundRect' : 'rect'
|
|
2201
|
+
|
|
2202
|
+
// 1. 组合片段框(loop / alt / opt / par)与 else 分隔虚线
|
|
2203
|
+
model.frames.forEach((frame) => {
|
|
2204
|
+
const frameFill = theme.dark
|
|
2205
|
+
? mixHex(tk.surface1, tk.accentPrimary, 0.10)
|
|
2206
|
+
: mixHex(tk.surface1, tk.accentSoft, 0.36)
|
|
2207
|
+
shapes.push(ooxmlShape(nextIdFn(), 'Sequence Frame ' + frame.kind, frame, {
|
|
2208
|
+
preset: 'rect',
|
|
2209
|
+
fill: frameFill,
|
|
2210
|
+
fillAlpha: 0.85,
|
|
2211
|
+
stroke: tk.accentPrimary,
|
|
2212
|
+
strokePt: 1.0,
|
|
2213
|
+
}))
|
|
2214
|
+
const tagW = Math.min(0.86, Math.max(0.56, frame.kind.length * 0.12 + 0.24))
|
|
2215
|
+
shapes.push(ooxmlShape(nextIdFn(), 'Sequence Frame Tag ' + frame.kind, { x: frame.x, y: frame.y, w: tagW, h: 0.24 }, {
|
|
2216
|
+
preset: 'homePlate',
|
|
2217
|
+
adjs: { adj: 22000 },
|
|
2218
|
+
fill: tk.accentPrimary,
|
|
2219
|
+
anchor: 'ctr',
|
|
2220
|
+
marginsIn: { l: 0.04, r: 0.08, t: 0.01, b: 0.01 },
|
|
2221
|
+
paragraphs: [
|
|
2222
|
+
ooxmlRichParagraph(frame.kind, {
|
|
2223
|
+
sizePt: 9.5,
|
|
2224
|
+
color: tk.inkOnAccent,
|
|
2225
|
+
bold: true,
|
|
2226
|
+
lang: langAttr,
|
|
2227
|
+
align: 'ctr',
|
|
2228
|
+
font: theme.fonts.heading,
|
|
2229
|
+
lineHeight: 1.0,
|
|
2230
|
+
}),
|
|
2231
|
+
],
|
|
2232
|
+
}))
|
|
2233
|
+
if (frame.label) {
|
|
2234
|
+
shapes.push(ooxmlShape(nextIdFn(), 'Sequence Frame Cond ' + frame.kind, {
|
|
2235
|
+
x: frame.x + tagW + 0.08,
|
|
2236
|
+
y: frame.y + 0.01,
|
|
2237
|
+
w: Math.max(0.6, frame.w - tagW - 0.14),
|
|
2238
|
+
h: 0.23,
|
|
2239
|
+
}, {
|
|
2240
|
+
txBox: true,
|
|
2241
|
+
anchor: 'ctr',
|
|
2242
|
+
marginsIn: { l: 0.02, r: 0.02, t: 0, b: 0 },
|
|
2243
|
+
paragraphs: [
|
|
2244
|
+
ooxmlRichParagraph('[' + frame.label + ']', {
|
|
2245
|
+
sizePt: 10,
|
|
2246
|
+
color: tk.accentText,
|
|
2247
|
+
bold: true,
|
|
2248
|
+
lang: langAttr,
|
|
2249
|
+
align: 'l',
|
|
2250
|
+
font: theme.fonts.body,
|
|
2251
|
+
lineHeight: 1.05,
|
|
2252
|
+
}),
|
|
2253
|
+
],
|
|
2254
|
+
}))
|
|
2255
|
+
}
|
|
2256
|
+
frame.dividers.forEach((div, dIdx) => {
|
|
2257
|
+
shapes.push(ooxmlLine(nextIdFn(), 'Sequence Frame Divider ' + (dIdx + 1), { x: frame.x, y: div.y }, { x: frame.x + frame.w, y: div.y }, {
|
|
2258
|
+
color: tk.accentPrimary,
|
|
2259
|
+
widthPt: 0.85,
|
|
2260
|
+
dash: 'dash',
|
|
2261
|
+
}))
|
|
2262
|
+
const divText = '[' + (div.label ? div.kind + ' ' + div.label : div.kind) + ']'
|
|
2263
|
+
shapes.push(ooxmlShape(nextIdFn(), 'Sequence Frame Else ' + (dIdx + 1), { x: frame.x + 0.10, y: div.y + 0.02, w: Math.max(0.8, frame.w - 0.20), h: 0.22 }, {
|
|
2264
|
+
txBox: true,
|
|
2265
|
+
anchor: 'ctr',
|
|
2266
|
+
marginsIn: { l: 0.02, r: 0.02, t: 0, b: 0 },
|
|
2267
|
+
paragraphs: [
|
|
2268
|
+
ooxmlRichParagraph(divText, {
|
|
2269
|
+
sizePt: 9.5,
|
|
2270
|
+
color: tk.accentText,
|
|
2271
|
+
bold: true,
|
|
2272
|
+
lang: langAttr,
|
|
2273
|
+
align: 'l',
|
|
2274
|
+
font: theme.fonts.body,
|
|
2275
|
+
lineHeight: 1.05,
|
|
2276
|
+
}),
|
|
2277
|
+
],
|
|
2278
|
+
}))
|
|
2279
|
+
})
|
|
2280
|
+
})
|
|
2281
|
+
|
|
2282
|
+
// 2. 顶/底参与者卡片 <p:sp> 与附着生命线虚线 <p:cxnSp>
|
|
2283
|
+
model.participants.forEach((p, idx) => {
|
|
2284
|
+
const topSpid = nextIdFn()
|
|
2285
|
+
const botSpid = nextIdFn()
|
|
2286
|
+
const isPrimary = idx === 0
|
|
2287
|
+
const displayLabel = p.kind === 'actor' ? '◈ ' + p.label : p.label
|
|
2288
|
+
|
|
2289
|
+
shapes.push(ooxmlShape(topSpid, 'Sequence Participant Top ' + p.id, p.topBox, {
|
|
2290
|
+
preset: cardPreset,
|
|
2291
|
+
adj: roundRectAdj(p.topBox.w, p.topBox.h, Math.min(8, chromeCfg.cardRadiusPx)),
|
|
2292
|
+
fill: isPrimary ? tk.accentPrimary : tk.surface2,
|
|
2293
|
+
stroke: tk.accentPrimary,
|
|
2294
|
+
strokePt: isPrimary ? 1.25 : 1.0,
|
|
2295
|
+
anchor: 'ctr',
|
|
2296
|
+
marginsIn: { l: 0.08, r: 0.08, t: 0.04, b: 0.04 },
|
|
2297
|
+
paragraphs: [
|
|
2298
|
+
ooxmlRichParagraph(displayLabel, {
|
|
2299
|
+
sizePt: p.fontPt,
|
|
2300
|
+
color: isPrimary ? tk.inkOnAccent : tk.inkPrimary,
|
|
2301
|
+
bold: true,
|
|
2302
|
+
lang: langAttr,
|
|
2303
|
+
align: 'ctr',
|
|
2304
|
+
font: theme.fonts.heading,
|
|
2305
|
+
lineHeight: 1.15,
|
|
2306
|
+
}),
|
|
2307
|
+
],
|
|
2308
|
+
}))
|
|
2309
|
+
|
|
2310
|
+
shapes.push(ooxmlShape(botSpid, 'Sequence Participant Bottom ' + p.id, p.bottomBox, {
|
|
2311
|
+
preset: cardPreset,
|
|
2312
|
+
adj: roundRectAdj(p.bottomBox.w, p.bottomBox.h, Math.min(8, chromeCfg.cardRadiusPx)),
|
|
2313
|
+
fill: tk.surface1,
|
|
2314
|
+
stroke: tk.hairline,
|
|
2315
|
+
strokePt: 0.85,
|
|
2316
|
+
anchor: 'ctr',
|
|
2317
|
+
marginsIn: { l: 0.08, r: 0.08, t: 0.03, b: 0.03 },
|
|
2318
|
+
paragraphs: [
|
|
2319
|
+
ooxmlRichParagraph(displayLabel, {
|
|
2320
|
+
sizePt: Math.max(10, p.fontPt - 0.5),
|
|
2321
|
+
color: tk.inkSecondary,
|
|
2322
|
+
bold: true,
|
|
2323
|
+
lang: langAttr,
|
|
2324
|
+
align: 'ctr',
|
|
2325
|
+
font: theme.fonts.heading,
|
|
2326
|
+
lineHeight: 1.1,
|
|
2327
|
+
}),
|
|
2328
|
+
],
|
|
2329
|
+
}))
|
|
2330
|
+
|
|
2331
|
+
shapes.push(ooxmlConnector(nextIdFn(), 'Sequence Lifeline ' + p.id, { x: p.cx, y: p.lifelineTopY }, { x: p.cx, y: p.lifelineBottomY }, {
|
|
2332
|
+
preset: 'straightConnector1',
|
|
2333
|
+
stCxn: { id: topSpid, idx: 2 },
|
|
2334
|
+
endCxn: { id: botSpid, idx: 0 },
|
|
2335
|
+
color: tk.inkMuted,
|
|
2336
|
+
widthPt: 1.0,
|
|
2337
|
+
dash: 'dash',
|
|
2338
|
+
tailArrow: false,
|
|
2339
|
+
}))
|
|
2340
|
+
})
|
|
2341
|
+
|
|
2342
|
+
// 3. 生命线激活条(Activation Bars)
|
|
2343
|
+
model.activations.forEach((act) => {
|
|
2344
|
+
shapes.push(ooxmlShape(nextIdFn(), 'Sequence Activation ' + act.id, act, {
|
|
2345
|
+
preset: 'rect',
|
|
2346
|
+
fill: tk.accentSoft,
|
|
2347
|
+
stroke: tk.accentPrimary,
|
|
2348
|
+
strokePt: 1.0,
|
|
2349
|
+
}))
|
|
2350
|
+
})
|
|
2351
|
+
|
|
2352
|
+
// 4. 横向/自环消息连接线 <p:cxnSp> 与上方文本胶囊
|
|
2353
|
+
model.messages.forEach((msg, idx) => {
|
|
2354
|
+
const strokeCol = msg.dash ? tk.accentSecondary : tk.accentPrimary
|
|
2355
|
+
const endType = msg.head === 'cross' ? 'oval' : msg.head === 'open' || msg.head === 'async' ? 'arrow' : 'triangle'
|
|
2356
|
+
if (msg.isSelf) {
|
|
2357
|
+
const yTop = msg.y - msg.loopH / 2
|
|
2358
|
+
const yBot = msg.y + msg.loopH / 2
|
|
2359
|
+
shapes.push(ooxmlLine(nextIdFn(), 'Sequence Self Out ' + (idx + 1), { x: msg.x1, y: yTop }, { x: msg.x2, y: yTop }, {
|
|
2360
|
+
color: strokeCol,
|
|
2361
|
+
widthPt: 1.35,
|
|
2362
|
+
dash: msg.dash,
|
|
2363
|
+
}))
|
|
2364
|
+
shapes.push(ooxmlLine(nextIdFn(), 'Sequence Self Down ' + (idx + 1), { x: msg.x2, y: yTop }, { x: msg.x2, y: yBot }, {
|
|
2365
|
+
color: strokeCol,
|
|
2366
|
+
widthPt: 1.35,
|
|
2367
|
+
dash: msg.dash,
|
|
2368
|
+
}))
|
|
2369
|
+
shapes.push(ooxmlConnector(nextIdFn(), 'Sequence Message ' + (idx + 1), { x: msg.x2, y: yBot }, { x: msg.x1, y: yBot }, {
|
|
2370
|
+
preset: 'straightConnector1',
|
|
2371
|
+
color: strokeCol,
|
|
2372
|
+
widthPt: 1.35,
|
|
2373
|
+
dash: msg.dash,
|
|
2374
|
+
tailArrow: true,
|
|
2375
|
+
tailEndType: endType,
|
|
2376
|
+
}))
|
|
2377
|
+
} else {
|
|
2378
|
+
shapes.push(ooxmlConnector(nextIdFn(), 'Sequence Message ' + (idx + 1), { x: msg.x1, y: msg.y }, { x: msg.x2, y: msg.y }, {
|
|
2379
|
+
preset: 'straightConnector1',
|
|
2380
|
+
color: strokeCol,
|
|
2381
|
+
widthPt: 1.4,
|
|
2382
|
+
dash: msg.dash,
|
|
2383
|
+
tailArrow: true,
|
|
2384
|
+
tailEndType: endType,
|
|
2385
|
+
}))
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
if (msg.text) {
|
|
2389
|
+
shapes.push(ooxmlShape(nextIdFn(), 'Sequence Label ' + (idx + 1), msg.labelBox, {
|
|
2390
|
+
preset: 'roundRect',
|
|
2391
|
+
adj: 24000,
|
|
2392
|
+
fill: tk.canvas,
|
|
2393
|
+
fillAlpha: 0.92,
|
|
2394
|
+
anchor: 'ctr',
|
|
2395
|
+
marginsIn: { l: 0.04, r: 0.04, t: 0.01, b: 0.01 },
|
|
2396
|
+
paragraphs: [
|
|
2397
|
+
ooxmlRichParagraph(msg.text, {
|
|
2398
|
+
sizePt: msg.fontPt,
|
|
2399
|
+
color: tk.inkPrimary,
|
|
2400
|
+
bold: !msg.dash,
|
|
2401
|
+
lang: langAttr,
|
|
2402
|
+
align: msg.isSelf ? 'l' : 'ctr',
|
|
2403
|
+
font: theme.fonts.body,
|
|
2404
|
+
lineHeight: 1.08,
|
|
2405
|
+
}),
|
|
2406
|
+
],
|
|
2407
|
+
}))
|
|
2408
|
+
}
|
|
2409
|
+
})
|
|
2410
|
+
|
|
2411
|
+
// 5. Note 批注卡片
|
|
2412
|
+
model.notes.forEach((note, idx) => {
|
|
2413
|
+
const noteFill = theme.dark
|
|
2414
|
+
? mixHex(tk.surface2, tk.warning, 0.18)
|
|
2415
|
+
: mixHex(tk.surface1, '#FEF3C7', 0.65)
|
|
2416
|
+
const noteLines = Array.isArray(note.lines) && note.lines.length > 0 ? note.lines : [note.text]
|
|
2417
|
+
shapes.push(ooxmlShape(nextIdFn(), 'Sequence Note ' + (idx + 1), note, {
|
|
2418
|
+
preset: 'foldedCorner',
|
|
2419
|
+
fill: noteFill,
|
|
2420
|
+
stroke: tk.accentSecondary,
|
|
2421
|
+
strokePt: 0.85,
|
|
2422
|
+
anchor: 'ctr',
|
|
2423
|
+
marginsIn: { l: 0.07, r: 0.09, t: 0.03, b: 0.03 },
|
|
2424
|
+
paragraphs: noteLines.map((ln) =>
|
|
2425
|
+
ooxmlRichParagraph(ln, {
|
|
2426
|
+
sizePt: note.fontPt,
|
|
2427
|
+
color: tk.inkPrimary,
|
|
2428
|
+
bold: false,
|
|
2429
|
+
lang: langAttr,
|
|
2430
|
+
align: 'ctr',
|
|
2431
|
+
font: theme.fonts.body,
|
|
2432
|
+
lineHeight: 1.14,
|
|
2433
|
+
}),
|
|
2434
|
+
),
|
|
2435
|
+
}))
|
|
2436
|
+
})
|
|
2437
|
+
|
|
2438
|
+
return shapes.join('')
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
export function renderMermaidPptx(slide, area, nextIdFn, chromeCfg, theme, langAttr) {
|
|
2442
|
+
const model = compileMermaidSlide(slide, area, slide.variant)
|
|
2443
|
+
if (model.mode === 'sequence') {
|
|
2444
|
+
return renderSequencePptx(model, nextIdFn, chromeCfg, theme, langAttr)
|
|
2445
|
+
}
|
|
2446
|
+
return renderFlowchartPptx(model, nextIdFn, chromeCfg, theme, langAttr)
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
// ---------------------------------------------------------------------------
|
|
2450
|
+
// 6. HTML 语义化矢量图渲染器(<svg class="deck-mermaid-svg">)
|
|
2451
|
+
// ---------------------------------------------------------------------------
|
|
2452
|
+
|
|
2453
|
+
function svgFlowShapeMarkup(node, px) {
|
|
2454
|
+
const x = px(node.x)
|
|
2455
|
+
const y = px(node.y)
|
|
2456
|
+
const w = px(node.w)
|
|
2457
|
+
const h = px(node.h)
|
|
2458
|
+
const cls = 'mm-node mm-shape-' + escapeHtml(node.shape) + (node.isRoot ? ' is-root' : node.isSink ? ' is-sink' : '')
|
|
2459
|
+
const styleAttr = node.customStyle?.fill
|
|
2460
|
+
? ' style="fill:' + escapeHtml(node.customStyle.fill) + ';stroke:' + escapeHtml(node.customStyle.stroke || 'var(--accent)') + '"'
|
|
2461
|
+
: ''
|
|
2462
|
+
|
|
2463
|
+
if (node.shape === 'diamond') {
|
|
2464
|
+
const pts = `${(x + w / 2).toFixed(1)},${y.toFixed(1)} ${(x + w).toFixed(1)},${(y + h / 2).toFixed(1)} ${(x + w / 2).toFixed(1)},${(y + h).toFixed(1)} ${x.toFixed(1)},${(y + h / 2).toFixed(1)}`
|
|
2465
|
+
return `<polygon class="${cls}" points="${pts}"${styleAttr}/>`
|
|
2466
|
+
}
|
|
2467
|
+
if (node.shape === 'circle') {
|
|
2468
|
+
return `<ellipse class="${cls}" cx="${(x + w / 2).toFixed(1)}" cy="${(y + h / 2).toFixed(1)}" rx="${(w / 2).toFixed(1)}" ry="${(h / 2).toFixed(1)}"${styleAttr}/>`
|
|
2469
|
+
}
|
|
2470
|
+
if (node.shape === 'stadium') {
|
|
2471
|
+
const r = (h / 2).toFixed(1)
|
|
2472
|
+
return `<rect class="${cls}" x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${w.toFixed(1)}" height="${h.toFixed(1)}" rx="${r}" ry="${r}"${styleAttr}/>`
|
|
2473
|
+
}
|
|
2474
|
+
if (node.shape === 'cylinder') {
|
|
2475
|
+
const ry = Math.min(11, h * 0.16)
|
|
2476
|
+
const x1 = x.toFixed(1)
|
|
2477
|
+
const x2 = (x + w).toFixed(1)
|
|
2478
|
+
const yTop = (y + ry).toFixed(1)
|
|
2479
|
+
const yBot = (y + h - ry).toFixed(1)
|
|
2480
|
+
const rx = (w / 2).toFixed(1)
|
|
2481
|
+
const ryStr = ry.toFixed(1)
|
|
2482
|
+
return (
|
|
2483
|
+
`<path class="${cls}" d="M ${x1} ${yTop} A ${rx} ${ryStr} 0 0 1 ${x2} ${yTop} L ${x2} ${yBot} A ${rx} ${ryStr} 0 0 1 ${x1} ${yBot} Z"${styleAttr}/>` +
|
|
2484
|
+
`<path class="mm-cyl-cap" d="M ${x1} ${yTop} A ${rx} ${ryStr} 0 0 0 ${x2} ${yTop}"/>`
|
|
2485
|
+
)
|
|
2486
|
+
}
|
|
2487
|
+
if (node.shape === 'subroutine') {
|
|
2488
|
+
const inset = Math.max(8, w * 0.09)
|
|
2489
|
+
return (
|
|
2490
|
+
`<rect class="${cls}" x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${w.toFixed(1)}" height="${h.toFixed(1)}" rx="6"${styleAttr}/>` +
|
|
2491
|
+
`<line class="mm-sub-rail" x1="${(x + inset).toFixed(1)}" y1="${y.toFixed(1)}" x2="${(x + inset).toFixed(1)}" y2="${(y + h).toFixed(1)}"/>` +
|
|
2492
|
+
`<line class="mm-sub-rail" x1="${(x + w - inset).toFixed(1)}" y1="${y.toFixed(1)}" x2="${(x + w - inset).toFixed(1)}" y2="${(y + h).toFixed(1)}"/>`
|
|
2493
|
+
)
|
|
2494
|
+
}
|
|
2495
|
+
const rx = node.shape === 'round' ? 14 : 8
|
|
2496
|
+
return `<rect class="${cls}" x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${w.toFixed(1)}" height="${h.toFixed(1)}" rx="${rx}"${styleAttr}/>`
|
|
2497
|
+
}
|
|
2498
|
+
|
|
2499
|
+
function buildEdgePathSvg(edge, px) {
|
|
2500
|
+
const x1 = px(edge.fromPt.x)
|
|
2501
|
+
const y1 = px(edge.fromPt.y)
|
|
2502
|
+
const x2 = px(edge.toPt.x)
|
|
2503
|
+
const y2 = px(edge.toPt.y)
|
|
2504
|
+
if (edge.connectorPreset === 'straightConnector1') {
|
|
2505
|
+
return `M ${x1.toFixed(1)} ${y1.toFixed(1)} L ${x2.toFixed(1)} ${y2.toFixed(1)}`
|
|
2506
|
+
}
|
|
2507
|
+
const r = 8
|
|
2508
|
+
const bendFrac = Math.max(0.1, Math.min(0.9, (edge.adj1 ?? 50000) / 100000))
|
|
2509
|
+
if (edge.orientation === 'vertical') {
|
|
2510
|
+
const my = y1 + (y2 - y1) * bendFrac
|
|
2511
|
+
const sx = x2 >= x1 ? 1 : -1
|
|
2512
|
+
const sy = y2 >= y1 ? 1 : -1
|
|
2513
|
+
const er = Math.min(r, Math.abs(x2 - x1) / 2, Math.abs(my - y1), Math.abs(y2 - my))
|
|
2514
|
+
if (er < 2) return `M ${x1.toFixed(1)} ${y1.toFixed(1)} L ${x1.toFixed(1)} ${my.toFixed(1)} L ${x2.toFixed(1)} ${my.toFixed(1)} L ${x2.toFixed(1)} ${y2.toFixed(1)}`
|
|
2515
|
+
return (
|
|
2516
|
+
`M ${x1.toFixed(1)} ${y1.toFixed(1)} ` +
|
|
2517
|
+
`L ${x1.toFixed(1)} ${(my - sy * er).toFixed(1)} ` +
|
|
2518
|
+
`Q ${x1.toFixed(1)} ${my.toFixed(1)} ${(x1 + sx * er).toFixed(1)} ${my.toFixed(1)} ` +
|
|
2519
|
+
`L ${(x2 - sx * er).toFixed(1)} ${my.toFixed(1)} ` +
|
|
2520
|
+
`Q ${x2.toFixed(1)} ${my.toFixed(1)} ${x2.toFixed(1)} ${(my + sy * er).toFixed(1)} ` +
|
|
2521
|
+
`L ${x2.toFixed(1)} ${y2.toFixed(1)}`
|
|
2522
|
+
)
|
|
2523
|
+
}
|
|
2524
|
+
const mx = x1 + (x2 - x1) * bendFrac
|
|
2525
|
+
const sx = x2 >= x1 ? 1 : -1
|
|
2526
|
+
const sy = y2 >= y1 ? 1 : -1
|
|
2527
|
+
const er = Math.min(r, Math.abs(mx - x1), Math.abs(x2 - mx), Math.abs(y2 - y1) / 2)
|
|
2528
|
+
if (er < 2) return `M ${x1.toFixed(1)} ${y1.toFixed(1)} L ${mx.toFixed(1)} ${y1.toFixed(1)} L ${mx.toFixed(1)} ${y2.toFixed(1)} L ${x2.toFixed(1)} ${y2.toFixed(1)}`
|
|
2529
|
+
return (
|
|
2530
|
+
`M ${x1.toFixed(1)} ${y1.toFixed(1)} ` +
|
|
2531
|
+
`L ${(mx - sx * er).toFixed(1)} ${y1.toFixed(1)} ` +
|
|
2532
|
+
`Q ${mx.toFixed(1)} ${y1.toFixed(1)} ${mx.toFixed(1)} ${(y1 + sy * er).toFixed(1)} ` +
|
|
2533
|
+
`L ${mx.toFixed(1)} ${(y2 - sy * er).toFixed(1)} ` +
|
|
2534
|
+
`Q ${mx.toFixed(1)} ${y2.toFixed(1)} ${(mx + sx * er).toFixed(1)} ${y2.toFixed(1)} ` +
|
|
2535
|
+
`L ${x2.toFixed(1)} ${y2.toFixed(1)}`
|
|
2536
|
+
)
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2539
|
+
export function renderMermaidHtml(slide, index = 0) {
|
|
2540
|
+
const area = { x: 0, y: 0, w: 12.09, h: 4.78 }
|
|
2541
|
+
const model = compileMermaidSlide(slide, area, slide.variant)
|
|
2542
|
+
const scale = 100 // 1 inch -> 100 SVG units => 1209 × 478 viewBox
|
|
2543
|
+
const px = (v) => v * scale
|
|
2544
|
+
const uid = 'mm-' + (index + 1)
|
|
2545
|
+
const ariaLabel = escapeHtml(slide.title || (model.mode === 'sequence' ? 'Sequence Diagram' : 'Flowchart'))
|
|
2546
|
+
|
|
2547
|
+
const defs = (
|
|
2548
|
+
`<defs>` +
|
|
2549
|
+
`<marker id="${uid}-arrow" viewBox="0 0 10 10" refX="8.8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M 0 1.2 L 9 5 L 0 8.8 z" fill="var(--accent)"/></marker>` +
|
|
2550
|
+
`<marker id="${uid}-arrow-muted" viewBox="0 0 10 10" refX="8.8" refY="5" markerWidth="6.5" markerHeight="6.5" orient="auto-start-reverse"><path d="M 0 1.5 L 9 5 L 0 8.5 z" fill="var(--ink-secondary)"/></marker>` +
|
|
2551
|
+
`<marker id="${uid}-cross" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M 1.5 1.5 L 8.5 8.5 M 8.5 1.5 L 1.5 8.5" stroke="var(--negative)" stroke-width="2"/></marker>` +
|
|
2552
|
+
`</defs>`
|
|
2553
|
+
)
|
|
2554
|
+
|
|
2555
|
+
if (model.mode === 'sequence') {
|
|
2556
|
+
const framesSvg = model.frames.map((f) => {
|
|
2557
|
+
const x = px(f.x).toFixed(1)
|
|
2558
|
+
const y = px(f.y).toFixed(1)
|
|
2559
|
+
const w = px(f.w).toFixed(1)
|
|
2560
|
+
const h = px(f.h).toFixed(1)
|
|
2561
|
+
const tagW = Math.max(54, f.kind.length * 11 + 22)
|
|
2562
|
+
const divs = f.dividers.map((d) =>
|
|
2563
|
+
`<line class="mm-seq-div" x1="${x}" y1="${px(d.y).toFixed(1)}" x2="${(px(f.x + f.w)).toFixed(1)}" y2="${px(d.y).toFixed(1)}"/>` +
|
|
2564
|
+
`<text class="mm-seq-cond" x="${(px(f.x) + 12).toFixed(1)}" y="${(px(d.y) + 17).toFixed(1)}">[${escapeHtml(d.label ? d.kind + ' ' + d.label : d.kind)}]</text>`,
|
|
2565
|
+
).join('')
|
|
2566
|
+
return (
|
|
2567
|
+
`<g class="mm-seq-frame">` +
|
|
2568
|
+
`<rect class="mm-frame-box" x="${x}" y="${y}" width="${w}" height="${h}" rx="6"/>` +
|
|
2569
|
+
`<polygon class="mm-frame-tag" points="${x},${y} ${(Number(x) + tagW).toFixed(1)},${y} ${(Number(x) + tagW).toFixed(1)},${(Number(y) + 15).toFixed(1)} ${(Number(x) + tagW - 9).toFixed(1)},${(Number(y) + 24).toFixed(1)} ${x},${(Number(y) + 24).toFixed(1)}"/>` +
|
|
2570
|
+
`<text class="mm-frame-tag-txt" x="${(Number(x) + (tagW - 4) / 2).toFixed(1)}" y="${(Number(y) + 16).toFixed(1)}" text-anchor="middle">${escapeHtml(f.kind)}</text>` +
|
|
2571
|
+
(f.label ? `<text class="mm-seq-cond" x="${(Number(x) + tagW + 10).toFixed(1)}" y="${(Number(y) + 17).toFixed(1)}">[${escapeHtml(f.label)}]</text>` : '') +
|
|
2572
|
+
divs +
|
|
2573
|
+
`</g>`
|
|
2574
|
+
)
|
|
2575
|
+
}).join('')
|
|
2576
|
+
|
|
2577
|
+
const partsSvg = model.participants.map((p, idx) => {
|
|
2578
|
+
const label = p.kind === 'actor' ? '◈ ' + p.label : p.label
|
|
2579
|
+
const tx = px(p.topBox.x).toFixed(1)
|
|
2580
|
+
const ty = px(p.topBox.y).toFixed(1)
|
|
2581
|
+
const tw = px(p.topBox.w).toFixed(1)
|
|
2582
|
+
const th = px(p.topBox.h).toFixed(1)
|
|
2583
|
+
const by = px(p.bottomBox.y).toFixed(1)
|
|
2584
|
+
const bh = px(p.bottomBox.h).toFixed(1)
|
|
2585
|
+
const cx = px(p.cx).toFixed(1)
|
|
2586
|
+
return (
|
|
2587
|
+
`<g class="mm-seq-participant${idx === 0 ? ' is-primary' : ''}" data-participant="${escapeHtml(p.id)}">` +
|
|
2588
|
+
`<line class="mm-lifeline" x1="${cx}" y1="${px(p.lifelineTopY).toFixed(1)}" x2="${cx}" y2="${px(p.lifelineBottomY).toFixed(1)}"/>` +
|
|
2589
|
+
`<rect class="mm-part-top${idx === 0 ? ' is-primary' : ''}" x="${tx}" y="${ty}" width="${tw}" height="${th}" rx="7"/>` +
|
|
2590
|
+
`<text class="mm-part-txt${idx === 0 ? ' is-primary' : ''}" x="${cx}" y="${(px(p.topBox.y + p.topBox.h / 2) + 5).toFixed(1)}" text-anchor="middle">${escapeHtml(label)}</text>` +
|
|
2591
|
+
`<rect class="mm-part-bot" x="${tx}" y="${by}" width="${tw}" height="${bh}" rx="7"/>` +
|
|
2592
|
+
`<text class="mm-part-bot-txt" x="${cx}" y="${(px(p.bottomBox.y + p.bottomBox.h / 2) + 4.5).toFixed(1)}" text-anchor="middle">${escapeHtml(label)}</text>` +
|
|
2593
|
+
`</g>`
|
|
2594
|
+
)
|
|
2595
|
+
}).join('')
|
|
2596
|
+
|
|
2597
|
+
const actsSvg = model.activations.map((a) =>
|
|
2598
|
+
`<rect class="mm-seq-act" x="${px(a.x).toFixed(1)}" y="${px(a.y).toFixed(1)}" width="${px(a.w).toFixed(1)}" height="${px(a.h).toFixed(1)}" rx="2"/>`,
|
|
2599
|
+
).join('')
|
|
2600
|
+
|
|
2601
|
+
const msgsSvg = model.messages.map((m) => {
|
|
2602
|
+
const markerEnd = m.head === 'cross' ? `url(#${uid}-cross)` : `url(#${uid}-arrow)`
|
|
2603
|
+
const dashClass = m.dash ? ' is-dash' : ''
|
|
2604
|
+
const lineMarkup = m.isSelf
|
|
2605
|
+
? `<path class="mm-seq-msg${dashClass}" d="M ${px(m.x1).toFixed(1)} ${px(m.y - m.loopH / 2).toFixed(1)} L ${px(m.x2).toFixed(1)} ${px(m.y - m.loopH / 2).toFixed(1)} L ${px(m.x2).toFixed(1)} ${px(m.y + m.loopH / 2).toFixed(1)} L ${px(m.x1).toFixed(1)} ${px(m.y + m.loopH / 2).toFixed(1)}" fill="none" marker-end="${markerEnd}"/>`
|
|
2606
|
+
: `<line class="mm-seq-msg${dashClass}" x1="${px(m.x1).toFixed(1)}" y1="${px(m.y).toFixed(1)}" x2="${px(m.x2).toFixed(1)}" y2="${px(m.y).toFixed(1)}" marker-end="${markerEnd}"/>`
|
|
2607
|
+
const lb = m.labelBox
|
|
2608
|
+
return (
|
|
2609
|
+
`<g class="mm-seq-msg-grp">` +
|
|
2610
|
+
lineMarkup +
|
|
2611
|
+
(m.text
|
|
2612
|
+
? `<rect class="mm-edge-pill" x="${px(lb.x).toFixed(1)}" y="${px(lb.y).toFixed(1)}" width="${px(lb.w).toFixed(1)}" height="${px(lb.h).toFixed(1)}" rx="5"/>` +
|
|
2613
|
+
`<text class="mm-seq-msg-txt" x="${px(lb.x + lb.w / 2).toFixed(1)}" y="${(px(lb.y + lb.h / 2) + 4.5).toFixed(1)}" text-anchor="middle">${escapeHtml(m.text)}</text>`
|
|
2614
|
+
: '') +
|
|
2615
|
+
`</g>`
|
|
2616
|
+
)
|
|
2617
|
+
}).join('')
|
|
2618
|
+
|
|
2619
|
+
const notesSvg = model.notes.map((n) => {
|
|
2620
|
+
const noteLines = Array.isArray(n.lines) && n.lines.length > 0 ? n.lines : [n.text]
|
|
2621
|
+
const cx = px(n.x + n.w / 2)
|
|
2622
|
+
const cy = px(n.y + n.h / 2)
|
|
2623
|
+
const maxLineEm = Math.max(1, ...noteLines.map((ln) => measureEmWidth(ln, false)))
|
|
2624
|
+
const boxInnerPx = Math.max(40, px(n.w) - 16)
|
|
2625
|
+
const fontSize = Math.max(9.5, Math.min(12, (n.fontPt || 10) * 1.16, boxInnerPx / maxLineEm))
|
|
2626
|
+
const lineStep = fontSize * 1.24
|
|
2627
|
+
const startY = cy - ((noteLines.length - 1) * lineStep) / 2 + fontSize * 0.35
|
|
2628
|
+
const tspans = noteLines.map((ln, i) =>
|
|
2629
|
+
`<tspan x="${cx.toFixed(1)}" y="${(startY + i * lineStep).toFixed(1)}">${escapeHtml(ln)}</tspan>`,
|
|
2630
|
+
).join('')
|
|
2631
|
+
return (
|
|
2632
|
+
`<g class="mm-seq-note">` +
|
|
2633
|
+
`<rect class="mm-note-box" x="${px(n.x).toFixed(1)}" y="${px(n.y).toFixed(1)}" width="${px(n.w).toFixed(1)}" height="${px(n.h).toFixed(1)}" rx="6"/>` +
|
|
2634
|
+
`<text class="mm-note-txt" font-size="${fontSize.toFixed(1)}" text-anchor="middle">${tspans}</text>` +
|
|
2635
|
+
`</g>`
|
|
2636
|
+
)
|
|
2637
|
+
}).join('')
|
|
2638
|
+
|
|
2639
|
+
return (
|
|
2640
|
+
`<div class="mermaid-board is-sequence" data-mermaid-mode="sequence">` +
|
|
2641
|
+
`<svg class="deck-mermaid-svg" viewBox="0 0 1209 478" role="img" aria-label="${ariaLabel}">` +
|
|
2642
|
+
defs + framesSvg + partsSvg + actsSvg + msgsSvg + notesSvg +
|
|
2643
|
+
`</svg></div>`
|
|
2644
|
+
)
|
|
2645
|
+
}
|
|
2646
|
+
|
|
2647
|
+
// Flowchart SVG
|
|
2648
|
+
const sgSvg = model.subgraphs.map((sg) =>
|
|
2649
|
+
`<g class="mm-subgraph" data-subgraph="${escapeHtml(sg.id)}">` +
|
|
2650
|
+
`<rect class="mm-sg-box" x="${px(sg.x).toFixed(1)}" y="${px(sg.y).toFixed(1)}" width="${px(sg.w).toFixed(1)}" height="${px(sg.h).toFixed(1)}" rx="10"/>` +
|
|
2651
|
+
`<text class="mm-sg-title" x="${(px(sg.x) + 14).toFixed(1)}" y="${(px(sg.y) + 21).toFixed(1)}">${escapeHtml(sg.title)}</text>` +
|
|
2652
|
+
`</g>`,
|
|
2653
|
+
).join('')
|
|
2654
|
+
|
|
2655
|
+
const edgesSvg = model.edges.map((e) => {
|
|
2656
|
+
const d = buildEdgePathSvg(e, px)
|
|
2657
|
+
const cls = 'mm-edge' + (e.dash ? ' is-dash' : '') + (e.thick ? ' is-thick' : '')
|
|
2658
|
+
const mStart = e.headArrow ? ` marker-start="url(#${uid}-arrow)"` : ''
|
|
2659
|
+
const mEnd = e.tailArrow ? ` marker-end="url(#${uid}-${e.thick ? 'arrow' : 'arrow-muted'})"` : ''
|
|
2660
|
+
return `<g class="mm-edge-grp" data-from="${escapeHtml(e.from)}" data-to="${escapeHtml(e.to)}"><path class="${cls}" d="${d}" fill="none"${mStart}${mEnd}/></g>`
|
|
2661
|
+
}).join('')
|
|
2662
|
+
|
|
2663
|
+
const edgeLabelsSvg = model.edges.map((e) => {
|
|
2664
|
+
const lb = e.labelBox
|
|
2665
|
+
if (!e.label || !lb) return ''
|
|
2666
|
+
return (
|
|
2667
|
+
`<g class="mm-edge-lbl">` +
|
|
2668
|
+
`<rect class="mm-edge-pill is-bordered" x="${px(lb.x).toFixed(1)}" y="${px(lb.y).toFixed(1)}" width="${px(lb.w).toFixed(1)}" height="${px(lb.h).toFixed(1)}" rx="12"/>` +
|
|
2669
|
+
`<text class="mm-edge-txt" x="${px(lb.x + lb.w / 2).toFixed(1)}" y="${(px(lb.y + lb.h / 2) + 4.5).toFixed(1)}" text-anchor="middle">${escapeHtml(e.label)}</text>` +
|
|
2670
|
+
`</g>`
|
|
2671
|
+
)
|
|
2672
|
+
}).join('')
|
|
2673
|
+
|
|
2674
|
+
const nodesSvg = model.nodes.map((n) => {
|
|
2675
|
+
const cx = px(n.cx)
|
|
2676
|
+
const cy = px(n.cy) + (n.shape === 'cylinder' ? 5 : 0)
|
|
2677
|
+
const fontSize = Math.max(12.5, n.fontPt * 1.18)
|
|
2678
|
+
const lineStep = fontSize * 1.24
|
|
2679
|
+
const startY = cy - ((n.lines.length - 1) * lineStep) / 2 + fontSize * 0.35
|
|
2680
|
+
const textCls = 'mm-node-txt' + ((n.shape === 'stadium' || (n.isRoot && n.shape !== 'diamond')) && !n.customStyle?.fill ? ' is-on-accent' : '')
|
|
2681
|
+
const tspans = n.lines.map((ln, i) =>
|
|
2682
|
+
`<tspan x="${cx.toFixed(1)}" y="${(startY + i * lineStep).toFixed(1)}">${escapeHtml(ln)}</tspan>`,
|
|
2683
|
+
).join('')
|
|
2684
|
+
return (
|
|
2685
|
+
`<g class="mm-node-grp" data-node="${escapeHtml(n.id)}">` +
|
|
2686
|
+
svgFlowShapeMarkup(n, px) +
|
|
2687
|
+
`<text class="${textCls}" font-size="${fontSize.toFixed(1)}" text-anchor="middle">${tspans}</text>` +
|
|
2688
|
+
`</g>`
|
|
2689
|
+
)
|
|
2690
|
+
}).join('')
|
|
2691
|
+
|
|
2692
|
+
return (
|
|
2693
|
+
`<div class="mermaid-board is-flowchart" data-mermaid-mode="flowchart" data-direction="${escapeHtml(model.direction)}">` +
|
|
2694
|
+
`<svg class="deck-mermaid-svg" viewBox="0 0 1209 478" role="img" aria-label="${ariaLabel}">` +
|
|
2695
|
+
defs + sgSvg + edgesSvg + nodesSvg + edgeLabelsSvg +
|
|
2696
|
+
`</svg></div>`
|
|
2697
|
+
)
|
|
2698
|
+
}
|
|
2699
|
+
|
|
2700
|
+
export const MERMAID_CSS = `
|
|
2701
|
+
.mermaid-board{width:100%;flex:1 1 0;min-height:0;height:100%;display:flex;align-items:center;justify-content:center;overflow:hidden}
|
|
2702
|
+
svg.deck-mermaid-svg{width:100%;height:100%;max-height:100%;display:block;font-family:var(--font-body)}
|
|
2703
|
+
.mm-sg-box{fill:color-mix(in srgb, var(--surface1) 62%, var(--accent-soft));stroke:var(--accent);stroke-width:1.4;stroke-dasharray:6 4}
|
|
2704
|
+
.mm-sg-title{fill:var(--accent-text);font-family:var(--font-heading);font-weight:800;font-size:13.5px;letter-spacing:.03em}
|
|
2705
|
+
.mm-node{fill:var(--surface1);stroke:var(--hairline);stroke-width:1.4}
|
|
2706
|
+
.mm-node.mm-shape-stadium,.mm-node.is-root:not(.mm-shape-diamond){fill:var(--accent);stroke:var(--accent)}
|
|
2707
|
+
.mm-node.mm-shape-diamond{fill:var(--accent-soft);stroke:var(--accent);stroke-width:1.8}
|
|
2708
|
+
.mm-node.mm-shape-cylinder{fill:var(--surface2);stroke:var(--accent2);stroke-width:1.5}
|
|
2709
|
+
.mm-node.mm-shape-subroutine,.mm-node.mm-shape-circle,.mm-node.is-sink:not(.mm-shape-stadium):not(.is-root){fill:var(--accent-soft);stroke:var(--accent);stroke-width:1.5}
|
|
2710
|
+
.mm-cyl-cap,.mm-sub-rail{fill:none;stroke:var(--accent2);stroke-width:1.3}
|
|
2711
|
+
.mm-node-txt{fill:var(--fg);font-family:var(--font-heading);font-weight:700}
|
|
2712
|
+
.mm-node-txt.is-on-accent{fill:var(--ink-on-accent)}
|
|
2713
|
+
.mm-edge{stroke:var(--ink-secondary);stroke-width:1.85;stroke-linecap:round;stroke-linejoin:round}
|
|
2714
|
+
.mm-edge.is-dash{stroke-dasharray:6 4}
|
|
2715
|
+
.mm-edge.is-thick{stroke:var(--accent);stroke-width:2.8}
|
|
2716
|
+
.mm-edge-pill{fill:var(--bg);opacity:.95}
|
|
2717
|
+
.mm-edge-pill.is-bordered{stroke:var(--accent);stroke-width:1.1}
|
|
2718
|
+
.mm-edge-txt{fill:var(--accent-text);font-size:12px;font-weight:700}
|
|
2719
|
+
.mm-frame-box{fill:color-mix(in srgb, var(--surface1) 70%, var(--accent-soft));stroke:var(--accent);stroke-width:1.3}
|
|
2720
|
+
.mm-frame-tag{fill:var(--accent)}
|
|
2721
|
+
.mm-frame-tag-txt{fill:var(--ink-on-accent);font-family:var(--font-heading);font-size:11px;font-weight:800;letter-spacing:.06em}
|
|
2722
|
+
.mm-seq-cond{fill:var(--accent-text);font-size:12px;font-weight:700}
|
|
2723
|
+
.mm-seq-div{stroke:var(--accent);stroke-width:1.15;stroke-dasharray:5 4}
|
|
2724
|
+
.mm-lifeline{stroke:var(--muted);stroke-width:1.3;stroke-dasharray:5 4}
|
|
2725
|
+
.mm-part-top{fill:var(--surface2);stroke:var(--accent);stroke-width:1.4}
|
|
2726
|
+
.mm-part-top.is-primary{fill:var(--accent);stroke:var(--accent)}
|
|
2727
|
+
.mm-part-txt{fill:var(--fg);font-family:var(--font-heading);font-size:13.5px;font-weight:800}
|
|
2728
|
+
.mm-part-txt.is-primary{fill:var(--ink-on-accent)}
|
|
2729
|
+
.mm-part-bot{fill:var(--surface1);stroke:var(--hairline);stroke-width:1.1}
|
|
2730
|
+
.mm-part-bot-txt{fill:var(--ink-secondary);font-family:var(--font-heading);font-size:12.5px;font-weight:700}
|
|
2731
|
+
.mm-seq-act{fill:var(--accent-soft);stroke:var(--accent);stroke-width:1.3}
|
|
2732
|
+
.mm-seq-msg{stroke:var(--accent);stroke-width:1.85}
|
|
2733
|
+
.mm-seq-msg.is-dash{stroke:var(--accent2);stroke-dasharray:6 4}
|
|
2734
|
+
.mm-seq-msg-txt{fill:var(--fg);font-size:12.5px;font-weight:600}
|
|
2735
|
+
.mm-note-box{fill:color-mix(in srgb, var(--surface2) 72%, var(--warning));stroke:var(--accent2);stroke-width:1.2}
|
|
2736
|
+
.mm-note-txt{fill:var(--fg);font-size:12px;font-weight:600}
|
|
2737
|
+
`
|