@leosdc/exploreio 0.3.0 → 0.5.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.
@@ -1,538 +1,14 @@
1
1
  /**
2
- * Native Rich Terminal Mermaid Renderer (SPEC-003)
3
- * Renderiza diagramas Mermaid (flowchart, sequence, state, class, er) em
4
- * arte Unicode/ANSI respeitando os 3 temas oficiais do Exploreio, com
5
- * adaptação automática à largura do painel e degradação segura (fail-safe).
2
+ * Native Rich Terminal Mermaid Renderer (SPEC-003 / SPEC-004)
3
+ * Delega o layout 2D (Sugiyama, redução de cruzamentos, roteamento ortogonal
4
+ * e subgraphs reais em Canvas Grid2D) para o pacote oficial `@leosdc/termaid`,
5
+ * preservando conformidade com os 3 temas do Exploreio, moldura embutida para
6
+ * blocos Markdown e degradação segura (fail-safe) para código destacado.
6
7
  */
8
+ import { renderMermaid as renderTermaid } from '@leosdc/termaid';
7
9
  import { bg, fg } from '../themes/palette.js';
8
- import { BOLD, DIM, ITALIC, RESET, stripUnsafeAnsi, truncateAnsi, visibleLength, } from '../tui/ansi.js';
10
+ import { BOLD, DIM, RESET, stripUnsafeAnsi, truncateAnsi, visibleLength } from '../tui/ansi.js';
9
11
  import { renderCodeLines } from './code.js';
10
- import { parseMermaid, } from './mermaidParser.js';
11
- function shapeColor(shape, theme) {
12
- switch (shape) {
13
- case 'diamond':
14
- return theme.warning;
15
- case 'stadium':
16
- return theme.success;
17
- case 'cylinder':
18
- return theme.syntaxType;
19
- case 'round':
20
- return theme.accentAlt;
21
- case 'circle':
22
- return theme.dir;
23
- case 'rect':
24
- default:
25
- return theme.accent;
26
- }
27
- }
28
- function renderFlowBox(node, maxBoxWidth, theme) {
29
- const color = shapeColor(node.shape, theme);
30
- const safeMax = Math.max(10, maxBoxWidth);
31
- const innerLimit = Math.max(4, safeMax - 4);
32
- const label = truncateAnsi(stripUnsafeAnsi(node.label), innerLimit);
33
- const innerW = Math.max(4, visibleLength(label) + 2);
34
- const padTotal = innerW - visibleLength(label);
35
- const padLeft = Math.floor(padTotal / 2);
36
- const padRight = padTotal - padLeft;
37
- const centered = `${' '.repeat(padLeft)}${fg(theme.text)}${BOLD}${label}${RESET}${' '.repeat(padRight)}`;
38
- const c = (s) => `${fg(color)}${s}${RESET}`;
39
- const bar = '─'.repeat(innerW);
40
- let top = c(`┌${bar}┐`);
41
- let mid = `${c('│')}${centered}${c('│')}`;
42
- let bot = c(`└${bar}┘`);
43
- if (node.shape === 'round') {
44
- top = c(`╭${bar}╮`);
45
- bot = c(`╰${bar}╯`);
46
- }
47
- else if (node.shape === 'stadium') {
48
- top = c(`╭${bar}╮`);
49
- mid = `${c('(')}${centered}${c(')')}`;
50
- bot = c(`╰${bar}╯`);
51
- }
52
- else if (node.shape === 'cylinder') {
53
- top = c(`╭${bar}╮`);
54
- mid = `${c('╞')}${centered}${c('╡')}`;
55
- bot = c(`╰${bar}╯`);
56
- }
57
- else if (node.shape === 'diamond') {
58
- top = c(`╭${bar}╮`);
59
- mid = `${c('◇')}${centered}${c('◇')}`;
60
- bot = c(`╰${bar}╯`);
61
- }
62
- else if (node.shape === 'circle') {
63
- top = c(`╭${bar}╮`);
64
- mid = `${c('◉')}${centered}${c('◉')}`;
65
- bot = c(`╰${bar}╯`);
66
- }
67
- return { width: innerW + 2, lines: [top, mid, bot] };
68
- }
69
- function computeFlowLayers(ast) {
70
- const nodeById = new Map(ast.nodes.map((n) => [n.id, n]));
71
- const adj = new Map();
72
- const inDegree = new Map();
73
- for (const n of ast.nodes) {
74
- adj.set(n.id, []);
75
- inDegree.set(n.id, 0);
76
- }
77
- // Detecta back-edges via DFS iterativo/recursivo com marcação de pilha (O(V+E), ciclo-seguro)
78
- const backEdgeSet = new Set();
79
- const visited = new Set();
80
- const inStack = new Set();
81
- const outgoingEdges = new Map();
82
- for (const e of ast.edges) {
83
- const list = outgoingEdges.get(e.from) ?? [];
84
- list.push(e);
85
- outgoingEdges.set(e.from, list);
86
- }
87
- const dfs = (id) => {
88
- visited.add(id);
89
- inStack.add(id);
90
- for (const edge of outgoingEdges.get(id) ?? []) {
91
- if (edge.from === edge.to || inStack.has(edge.to)) {
92
- backEdgeSet.add(edge);
93
- }
94
- else if (!visited.has(edge.to) && nodeById.has(edge.to)) {
95
- dfs(edge.to);
96
- }
97
- }
98
- inStack.delete(id);
99
- };
100
- for (const n of ast.nodes) {
101
- if (!visited.has(n.id))
102
- dfs(n.id);
103
- }
104
- for (const edge of ast.edges) {
105
- if (backEdgeSet.has(edge))
106
- continue;
107
- if (!nodeById.has(edge.from) || !nodeById.has(edge.to))
108
- continue;
109
- adj.get(edge.from)?.push(edge.to);
110
- inDegree.set(edge.to, (inDegree.get(edge.to) ?? 0) + 1);
111
- }
112
- // Atribuição de camadas por ordem topológica (Kahn)
113
- const nodeLayer = new Map();
114
- const queue = [];
115
- for (const n of ast.nodes) {
116
- if ((inDegree.get(n.id) ?? 0) === 0) {
117
- nodeLayer.set(n.id, 0);
118
- queue.push(n.id);
119
- }
120
- }
121
- let head = 0;
122
- while (head < queue.length) {
123
- const cur = queue[head++] ?? '';
124
- const curLayer = nodeLayer.get(cur) ?? 0;
125
- for (const next of adj.get(cur) ?? []) {
126
- const prevLayer = nodeLayer.get(next) ?? 0;
127
- nodeLayer.set(next, Math.max(prevLayer, curLayer + 1));
128
- const nextDeg = (inDegree.get(next) ?? 1) - 1;
129
- inDegree.set(next, nextDeg);
130
- if (nextDeg === 0)
131
- queue.push(next);
132
- }
133
- }
134
- for (const n of ast.nodes) {
135
- if (!nodeLayer.has(n.id))
136
- nodeLayer.set(n.id, 0);
137
- }
138
- const maxLayer = Math.max(0, ...nodeLayer.values());
139
- const layers = Array.from({ length: maxLayer + 1 }, () => []);
140
- for (const n of ast.nodes) {
141
- const idx = nodeLayer.get(n.id) ?? 0;
142
- layers[idx]?.push(n);
143
- }
144
- const orderedLayers = ast.direction === 'BT' || ast.direction === 'RL' ? [...layers].reverse() : layers;
145
- return { layers: orderedLayers, nodeLayer, backEdges: Array.from(backEdgeSet) };
146
- }
147
- function edgeArrowGlyph(style, horizontal, reversed = false) {
148
- if (horizontal) {
149
- if (style === 'bidirectional')
150
- return '◀──▶';
151
- if (style === 'line')
152
- return '────';
153
- if (style === 'dotted')
154
- return reversed ? '◀╌╌╌' : '╌╌╌▶';
155
- if (style === 'thick')
156
- return reversed ? '◀═══' : '═══▶';
157
- return reversed ? '◀───' : '───▶';
158
- }
159
- if (style === 'dotted')
160
- return '┆';
161
- if (style === 'thick')
162
- return '║';
163
- return '│';
164
- }
165
- function tryRenderHorizontalChain(ast, layers, width, theme) {
166
- if (layers.some((layer) => layer.length !== 1))
167
- return null;
168
- const chain = layers.map((l) => l[0]).filter((n) => Boolean(n));
169
- if (chain.length < 2)
170
- return null;
171
- const reversed = ast.direction === 'RL';
172
- const maxBoxW = Math.max(12, Math.floor((width - (chain.length - 1) * 8) / chain.length));
173
- const boxes = chain.map((n) => renderFlowBox(n, maxBoxW, theme));
174
- const connectors = [];
175
- for (let i = 0; i < chain.length - 1; i++) {
176
- const a = chain[i];
177
- const b = chain[i + 1];
178
- const edge = ast.edges.find((e) => (e.from === a?.id && e.to === b?.id) || (reversed && e.from === b?.id && e.to === a?.id));
179
- const arrow = edgeArrowGlyph(edge?.style ?? 'solid', true, reversed);
180
- const labelText = edge?.label ? truncateAnsi(edge.label, 14) : '';
181
- const connW = Math.max(arrow.length + 2, visibleLength(labelText) + 2);
182
- const topPad = Math.max(0, connW - visibleLength(labelText));
183
- const topLeft = Math.floor(topPad / 2);
184
- const topLine = labelText
185
- ? `${' '.repeat(topLeft)}${fg(theme.syntaxString)}${DIM}${labelText}${RESET}${' '.repeat(topPad - topLeft)}`
186
- : ' '.repeat(connW);
187
- const arrowPad = Math.max(0, connW - arrow.length);
188
- const aLeft = Math.floor(arrowPad / 2);
189
- const fillCh = edge?.style === 'dotted' ? '╌' : edge?.style === 'thick' ? '═' : '─';
190
- const midLine = `${fg(theme.border)}${fillCh.repeat(aLeft)}${fg(theme.accentAlt)}${arrow}${fg(theme.border)}${fillCh.repeat(arrowPad - aLeft)}${RESET}`;
191
- connectors.push({ width: connW, top: topLine, mid: midLine, bot: ' '.repeat(connW) });
192
- }
193
- const totalWidth = boxes.reduce((sum, b) => sum + b.width, 0) +
194
- connectors.reduce((sum, c) => sum + c.width, 0);
195
- if (totalWidth > width)
196
- return null;
197
- const row0 = [];
198
- const row1 = [];
199
- const row2 = [];
200
- boxes.forEach((box, idx) => {
201
- row0.push(box.lines[0]);
202
- row1.push(box.lines[1]);
203
- row2.push(box.lines[2]);
204
- const conn = connectors[idx];
205
- if (conn) {
206
- row0.push(conn.top);
207
- row1.push(conn.mid);
208
- row2.push(conn.bot);
209
- }
210
- });
211
- return [row0.join(''), row1.join(''), row2.join('')];
212
- }
213
- function renderFlowchart(ast, width, theme) {
214
- const safeWidth = Math.max(28, width);
215
- const { layers, backEdges } = computeFlowLayers(ast);
216
- const out = [];
217
- if (ast.subgraphs.length > 0) {
218
- const summary = ast.subgraphs
219
- .map((sg) => `${fg(theme.accentAlt)}[${sg.title}]${RESET}`)
220
- .join(` ${fg(theme.muted)}·${RESET} `);
221
- out.push(`${fg(theme.muted)}${DIM}Subgraphs:${RESET} ${summary}`);
222
- }
223
- if (ast.direction === 'LR' || ast.direction === 'RL') {
224
- const horizontal = tryRenderHorizontalChain(ast, layers, safeWidth, theme);
225
- if (horizontal) {
226
- out.push(...horizontal);
227
- if (backEdges.length > 0) {
228
- out.push('');
229
- for (const be of backEdges) {
230
- const lbl = be.label ? ` ${fg(theme.syntaxString)}[${be.label}]${RESET}` : '';
231
- out.push(`${fg(theme.warning)}↩${RESET} ${fg(theme.text)}${be.from}${RESET} ${fg(theme.border)}──▶${RESET} ${fg(theme.text)}${be.to}${RESET}${lbl}`);
232
- }
233
- }
234
- return out;
235
- }
236
- }
237
- const nodeLabelById = new Map(ast.nodes.map((n) => [n.id, n.label]));
238
- layers.forEach((layer, layerIdx) => {
239
- const gap = 2;
240
- const perBoxMax = Math.max(12, Math.floor((safeWidth - Math.max(0, layer.length - 1) * gap) / Math.max(1, layer.length)));
241
- const boxes = layer.map((n) => renderFlowBox(n, Math.min(34, perBoxMax), theme));
242
- // Agrupa caixas em linhas horizontais caso haja muitos nós na mesma camada
243
- let cursor = 0;
244
- while (cursor < boxes.length) {
245
- const rowBoxes = [];
246
- let rowW = 0;
247
- while (cursor < boxes.length) {
248
- const next = boxes[cursor];
249
- if (!next)
250
- break;
251
- const needed = rowBoxes.length === 0 ? next.width : gap + next.width;
252
- if (rowBoxes.length > 0 && rowW + needed > safeWidth)
253
- break;
254
- rowBoxes.push(next);
255
- rowW += needed;
256
- cursor++;
257
- }
258
- const sep = ' '.repeat(gap);
259
- out.push(rowBoxes.map((b) => b.lines[0]).join(sep));
260
- out.push(rowBoxes.map((b) => b.lines[1]).join(sep));
261
- out.push(rowBoxes.map((b) => b.lines[2]).join(sep));
262
- }
263
- // Conectores para a próxima camada
264
- const nextLayer = layers[layerIdx + 1];
265
- if (nextLayer) {
266
- const nextIds = new Set(nextLayer.map((n) => n.id));
267
- const layerIds = new Set(layer.map((n) => n.id));
268
- const directEdges = ast.edges.filter((e) => ast.direction === 'BT' || ast.direction === 'RL'
269
- ? nextIds.has(e.from) && layerIds.has(e.to)
270
- : layerIds.has(e.from) && nextIds.has(e.to));
271
- if (directEdges.length === 1 && layer.length === 1 && nextLayer.length === 1) {
272
- const e = directEdges[0];
273
- const stem = edgeArrowGlyph(e?.style ?? 'solid', false);
274
- const pad = ' '.repeat(Math.max(2, Math.floor((boxes[0]?.width ?? 8) / 2)));
275
- const lbl = e?.label ? ` ${fg(theme.syntaxString)}${DIM}${truncateAnsi(e.label, safeWidth - 10)}${RESET}` : '';
276
- out.push(`${pad}${fg(theme.border)}${stem}${RESET}${lbl}`);
277
- out.push(`${pad}${fg(theme.accentAlt)}▼${RESET}`);
278
- }
279
- else if (directEdges.length > 0) {
280
- for (const e of directEdges.slice(0, 6)) {
281
- const arrow = edgeArrowGlyph(e.style, true);
282
- const fromLbl = truncateAnsi(nodeLabelById.get(e.from) ?? e.from, 18);
283
- const toLbl = truncateAnsi(nodeLabelById.get(e.to) ?? e.to, 18);
284
- const edgeLbl = e.label ? ` ${fg(theme.syntaxString)}[${truncateAnsi(e.label, 18)}]${RESET}` : '';
285
- out.push(` ${fg(theme.border)}└─${RESET} ${fg(theme.muted)}${fromLbl}${RESET} ${fg(theme.accentAlt)}${arrow}${RESET} ${fg(theme.text)}${toLbl}${RESET}${edgeLbl}`);
286
- }
287
- if (directEdges.length > 6) {
288
- out.push(` ${fg(theme.muted)}${DIM}… (+${directEdges.length - 6} conexões)${RESET}`);
289
- }
290
- }
291
- else {
292
- out.push(` ${fg(theme.border)}│${RESET}`);
293
- out.push(` ${fg(theme.accentAlt)}▼${RESET}`);
294
- }
295
- }
296
- });
297
- if (backEdges.length > 0) {
298
- out.push('');
299
- for (const be of backEdges) {
300
- const fromLbl = truncateAnsi(nodeLabelById.get(be.from) ?? be.from, 20);
301
- const toLbl = truncateAnsi(nodeLabelById.get(be.to) ?? be.to, 20);
302
- const lbl = be.label ? ` ${fg(theme.syntaxString)}[${truncateAnsi(be.label, 20)}]${RESET}` : '';
303
- out.push(`${fg(theme.warning)}↩${RESET} ${fg(theme.text)}${fromLbl}${RESET} ${fg(theme.border)}──▶${RESET} ${fg(theme.text)}${toLbl}${RESET}${lbl}`);
304
- }
305
- }
306
- return out;
307
- }
308
- function renderSequenceCompact(ast, width, theme) {
309
- const out = [];
310
- const labelMap = new Map(ast.participants.map((p) => [p.id, p.label]));
311
- const headerNames = ast.participants
312
- .map((p) => `${fg(p.isActor ? theme.accentAlt : theme.accent)}${BOLD}${p.label}${RESET}`)
313
- .join(` ${fg(theme.muted)}·${RESET} `);
314
- out.push(truncateAnsi(`${fg(theme.muted)}Participantes:${RESET} ${headerNames}`, width));
315
- out.push(`${fg(theme.border)}${'─'.repeat(Math.min(width, 48))}${RESET}`);
316
- let indent = 0;
317
- for (const item of ast.items) {
318
- if (item.kind === 'block') {
319
- if (item.keyword === 'end') {
320
- indent = Math.max(0, indent - 1);
321
- out.push(`${' '.repeat(indent)}${fg(theme.accentAlt)}└─ end${RESET}`);
322
- }
323
- else if (item.keyword === 'else') {
324
- out.push(`${' '.repeat(Math.max(0, indent - 1))}${fg(theme.accentAlt)}├─ else${item.label ? ` ${item.label}` : ''}${RESET}`);
325
- }
326
- else {
327
- out.push(`${' '.repeat(indent)}${fg(theme.accentAlt)}${BOLD}┌─ [${item.keyword}]${RESET} ${fg(theme.text)}${item.label}${RESET}`);
328
- indent++;
329
- }
330
- }
331
- else if (item.kind === 'note') {
332
- out.push(`${' '.repeat(indent)}${fg(theme.warning)}✎ Note (${item.targets.join(', ')}):${RESET} ${fg(theme.text)}${ITALIC}${item.text}${RESET}`);
333
- }
334
- else {
335
- const from = labelMap.get(item.from) ?? item.from;
336
- const to = labelMap.get(item.to) ?? item.to;
337
- const arrow = item.dashed ? '╌╌▶' : '──▶';
338
- const pad = ' '.repeat(indent);
339
- const header = `${pad}${fg(theme.accent)}${from}${RESET} ${fg(theme.accentAlt)}${arrow}${RESET} ${fg(theme.accent)}${to}${RESET}`;
340
- const single = `${header}: ${fg(theme.text)}${item.label}${RESET}`;
341
- if (visibleLength(single) <= width) {
342
- out.push(single);
343
- }
344
- else {
345
- out.push(truncateAnsi(header, width));
346
- if (item.label) {
347
- out.push(truncateAnsi(`${pad} ${fg(theme.muted)}↳${RESET} ${fg(theme.text)}${item.label}${RESET}`, width));
348
- }
349
- }
350
- }
351
- }
352
- return out;
353
- }
354
- function renderSequenceDiagram(ast, width, theme) {
355
- const safeWidth = Math.max(28, width);
356
- const count = ast.participants.length;
357
- const colWidth = Math.floor(safeWidth / Math.max(1, count));
358
- // Se o painel for estreito demais para as lifelines lado a lado, usa layout compacto
359
- if (count > 5 || colWidth < 16) {
360
- return renderSequenceCompact(ast, safeWidth, theme);
361
- }
362
- const centers = ast.participants.map((_, idx) => idx * colWidth + Math.floor(colWidth / 2));
363
- const indexById = new Map(ast.participants.map((p, idx) => [p.id, idx]));
364
- const out = [];
365
- // Cabeçalho dos participantes em caixas Unicode
366
- const topParts = [];
367
- const midParts = [];
368
- const botParts = [];
369
- for (const p of ast.participants) {
370
- const innerW = Math.max(4, Math.min(colWidth - 4, visibleLength(p.label) + 2));
371
- const txt = truncateAnsi(p.label, innerW - 2);
372
- const pad = Math.max(0, innerW - visibleLength(txt));
373
- const pl = Math.floor(pad / 2);
374
- const pr = pad - pl;
375
- const boxW = innerW + 2;
376
- const outerPad = Math.max(0, colWidth - boxW);
377
- const ol = Math.floor(outerPad / 2);
378
- const or = outerPad - ol;
379
- const color = p.isActor ? theme.accentAlt : theme.accent;
380
- topParts.push(`${' '.repeat(ol)}${fg(color)}╭${'─'.repeat(innerW)}╮${RESET}${' '.repeat(or)}`);
381
- midParts.push(`${' '.repeat(ol)}${fg(color)}│${RESET}${' '.repeat(pl)}${fg(theme.text)}${BOLD}${txt}${RESET}${' '.repeat(pr)}${fg(color)}│${RESET}${' '.repeat(or)}`);
382
- botParts.push(`${' '.repeat(ol)}${fg(color)}╰${'─'.repeat(innerW)}╯${RESET}${' '.repeat(or)}`);
383
- }
384
- out.push(topParts.join(''), midParts.join(''), botParts.join(''));
385
- const renderLifelineRow = () => {
386
- const chars = Array.from({ length: count * colWidth }, () => ' ');
387
- for (const c of centers) {
388
- if (c >= 0 && c < chars.length)
389
- chars[c] = '│';
390
- }
391
- return `${fg(theme.border)}${chars.join('').trimEnd()}${RESET}`;
392
- };
393
- for (const item of ast.items) {
394
- if (item.kind === 'block') {
395
- if (item.keyword === 'end') {
396
- out.push(`${fg(theme.accentAlt)}└─ end ${'─'.repeat(Math.max(4, safeWidth - 10))}${RESET}`);
397
- }
398
- else if (item.keyword === 'else') {
399
- out.push(`${fg(theme.accentAlt)}├─ else${item.label ? `: ${item.label}` : ''} ${'╌'.repeat(Math.max(4, safeWidth - 16 - visibleLength(item.label)))}${RESET}`);
400
- }
401
- else {
402
- out.push(`${fg(theme.accentAlt)}${BOLD}┌─[${item.keyword}]${RESET} ${fg(theme.text)}${truncateAnsi(item.label, safeWidth - 14)}${RESET}`);
403
- }
404
- continue;
405
- }
406
- if (item.kind === 'note') {
407
- const noteText = truncateAnsi(item.text, safeWidth - 14);
408
- out.push(`${fg(theme.warning)}╭─ NOTE (${item.targets.join(', ')}) ─╮${RESET}`);
409
- out.push(`${fg(theme.warning)}│${RESET} ${fg(theme.text)}${ITALIC}${noteText}${RESET}`);
410
- out.push(`${fg(theme.warning)}╰${'─'.repeat(Math.min(safeWidth - 2, Math.max(12, visibleLength(noteText) + 2)))}╯${RESET}`);
411
- continue;
412
- }
413
- const fromIdx = indexById.get(item.from) ?? 0;
414
- const toIdx = indexById.get(item.to) ?? 0;
415
- const fromX = centers[fromIdx] ?? 0;
416
- const toX = centers[toIdx] ?? 0;
417
- if (fromIdx === toIdx) {
418
- const prefix = ' '.repeat(fromX);
419
- out.push(`${prefix}${fg(theme.accentAlt)}├─▶${RESET} ${fg(theme.text)}${truncateAnsi(item.label, safeWidth - fromX - 5)}${RESET}`);
420
- continue;
421
- }
422
- const leftX = Math.min(fromX, toX);
423
- const rightX = Math.max(fromX, toX);
424
- const span = Math.max(2, rightX - leftX - 1);
425
- const goingRight = toX > fromX;
426
- // Linha do rótulo acima da seta
427
- const labelText = truncateAnsi(item.label, Math.max(6, span + 6));
428
- const labelStart = Math.max(0, Math.min(safeWidth - visibleLength(labelText), leftX + Math.floor((span - visibleLength(labelText)) / 2) + 1));
429
- const labelChars = Array.from({ length: Math.max(count * colWidth, labelStart + visibleLength(labelText)) }, () => ' ');
430
- for (const c of centers) {
431
- if (c >= 0 && c < labelChars.length)
432
- labelChars[c] = '│';
433
- }
434
- const prefixPlain = labelChars.slice(0, labelStart).join('');
435
- out.push(`${fg(theme.border)}${prefixPlain}${RESET}${fg(theme.text)}${labelText}${RESET}`);
436
- // Linha da seta entre lifelines
437
- const fillCh = item.dashed ? '╌' : '─';
438
- const arrowBody = goingRight
439
- ? `${fillCh.repeat(Math.max(1, span - 1))}▶`
440
- : `◀${fillCh.repeat(Math.max(1, span - 1))}`;
441
- let row = '';
442
- for (let pos = 0; pos < count * colWidth; pos++) {
443
- if (pos === leftX) {
444
- row += `${fg(theme.accentAlt)}${goingRight ? '├' : '┤'}${RESET}`;
445
- }
446
- else if (pos > leftX && pos < rightX) {
447
- if (pos === leftX + 1) {
448
- row += `${fg(theme.accentAlt)}${arrowBody}${RESET}`;
449
- }
450
- }
451
- else if (pos === rightX) {
452
- row += `${fg(theme.accentAlt)}${goingRight ? '┤' : '├'}${RESET}`;
453
- }
454
- else if (centers.includes(pos)) {
455
- row += `${fg(theme.border)}│${RESET}`;
456
- }
457
- else {
458
- row += ' ';
459
- }
460
- }
461
- out.push(row.trimEnd());
462
- }
463
- out.push(renderLifelineRow());
464
- return out;
465
- }
466
- function renderStateDiagram(ast, width, theme) {
467
- const safeWidth = Math.max(28, width);
468
- const out = [];
469
- const formatState = (id, isTarget) => {
470
- if (id === '[*]') {
471
- return isTarget ? `${fg(theme.danger)}${BOLD}◉ FIM${RESET}` : `${fg(theme.success)}${BOLD}● INÍCIO${RESET}`;
472
- }
473
- const label = ast.labels[id] ? `${id}: ${ast.labels[id]}` : id;
474
- return `${fg(theme.accent)}╭─${RESET} ${fg(theme.text)}${BOLD}${truncateAnsi(label, 24)}${RESET} ${fg(theme.accent)}─╮${RESET}`;
475
- };
476
- for (const t of ast.transitions) {
477
- const fromStr = formatState(t.from, false);
478
- const toStr = formatState(t.to, true);
479
- const lbl = t.label ? ` ${fg(theme.syntaxString)}[${truncateAnsi(t.label, 22)}]${RESET}` : '';
480
- const line = `${fromStr} ${fg(theme.accentAlt)}──▶${RESET} ${toStr}${lbl}`;
481
- out.push(truncateAnsi(line, safeWidth));
482
- }
483
- if (out.length === 0) {
484
- for (const [id, desc] of Object.entries(ast.labels)) {
485
- out.push(`${fg(theme.accent)}▸ ${id}${RESET}: ${fg(theme.text)}${desc}${RESET}`);
486
- }
487
- }
488
- return out;
489
- }
490
- function formatRelationOp(op) {
491
- if (op.includes('|>'))
492
- return '──▷';
493
- if (op.includes('<|'))
494
- return '◁──';
495
- if (op.includes('*'))
496
- return '◆──';
497
- if (op.includes('o--') || op.includes('--o'))
498
- return '◇──';
499
- if (op.includes('..'))
500
- return '╌╌▶';
501
- if (op.includes('{') || op.includes('}'))
502
- return ` ${op} `;
503
- return '──▶';
504
- }
505
- function renderClassOrErDiagram(ast, width, theme) {
506
- const safeWidth = Math.max(28, width);
507
- const out = [];
508
- const boxMaxW = Math.min(44, safeWidth - 2);
509
- for (const entity of ast.entities) {
510
- const title = truncateAnsi(entity.name, boxMaxW - 4);
511
- const memberLines = entity.members.map((m) => truncateAnsi(m, boxMaxW - 4));
512
- const innerW = Math.max(visibleLength(title) + 2, ...memberLines.map((m) => visibleLength(m) + 2), 12);
513
- const b = (s) => `${fg(ast.type === 'er' ? theme.syntaxType : theme.accent)}${s}${RESET}`;
514
- out.push(b(`┌${'─'.repeat(innerW)}┐`));
515
- const tPad = Math.max(0, innerW - visibleLength(title) - 1);
516
- out.push(`${b('│')} ${fg(theme.text)}${BOLD}${title}${RESET}${' '.repeat(tPad)}${b('│')}`);
517
- if (memberLines.length > 0) {
518
- out.push(b(`├${'─'.repeat(innerW)}┤`));
519
- for (const m of memberLines) {
520
- const mPad = Math.max(0, innerW - visibleLength(m) - 1);
521
- out.push(`${b('│')} ${fg(theme.muted)}${m}${RESET}${' '.repeat(mPad)}${b('│')}`);
522
- }
523
- }
524
- out.push(b(`└${'─'.repeat(innerW)}┘`));
525
- }
526
- if (ast.relations.length > 0) {
527
- out.push(`${fg(theme.muted)}${DIM}Relacionamentos:${RESET}`);
528
- for (const rel of ast.relations) {
529
- const op = formatRelationOp(rel.operator);
530
- const lbl = rel.label ? ` ${fg(theme.syntaxString)}: ${truncateAnsi(rel.label, 24)}${RESET}` : '';
531
- out.push(truncateAnsi(` ${fg(theme.accent)}${rel.from}${RESET} ${fg(theme.accentAlt)}${op}${RESET} ${fg(theme.accent)}${rel.to}${RESET}${lbl}`, safeWidth));
532
- }
533
- }
534
- return out;
535
- }
536
12
  function wrapEmbeddedFrame(headerLabel, bodyLines, width, theme) {
537
13
  const safeWidth = Math.max(28, width);
538
14
  const badge = ` ◈ ${stripUnsafeAnsi(headerLabel)} `;
@@ -556,9 +32,13 @@ export function renderMermaid(source, options) {
556
32
  showLineNumbers: true,
557
33
  });
558
34
  }
559
- const parsed = parseMermaid(source);
560
- if (!parsed.ok || !parsed.ast) {
561
- const safeReason = stripUnsafeAnsi(parsed.error ?? 'Diagrama não suportado.');
35
+ const contentWidth = embedded ? Math.max(24, safeWidth - 4) : safeWidth;
36
+ const result = renderTermaid(source, {
37
+ theme: theme.name,
38
+ maxWidth: contentWidth,
39
+ });
40
+ if (!result.ok) {
41
+ const safeReason = stripUnsafeAnsi(result.error ?? 'Diagrama não suportado.');
562
42
  const fallbackBody = [
563
43
  `${fg(theme.warning)}${BOLD}▲ ${safeReason}${RESET}`,
564
44
  ...renderCodeLines(source, {
@@ -568,44 +48,20 @@ export function renderMermaid(source, options) {
568
48
  }),
569
49
  ];
570
50
  return embedded
571
- ? wrapEmbeddedFrame(parsed.headerLabel, fallbackBody, safeWidth, theme)
51
+ ? wrapEmbeddedFrame(result.headerLabel, fallbackBody, safeWidth, theme)
572
52
  : [
573
- `${fg(theme.warning)}${BOLD}◈ ${stripUnsafeAnsi(parsed.headerLabel)}${RESET} ${fg(theme.muted)}${DIM}(${safeReason})${RESET}`,
53
+ `${fg(theme.warning)}${BOLD}◈ ${stripUnsafeAnsi(result.headerLabel)}${RESET} ${fg(theme.muted)}${DIM}(${safeReason})${RESET}`,
574
54
  ...renderCodeLines(source, { language: 'plain', theme, showLineNumbers: true }),
575
55
  ];
576
56
  }
577
- const contentWidth = embedded ? Math.max(24, safeWidth - 4) : safeWidth;
578
- let diagramLines;
579
- switch (parsed.ast.type) {
580
- case 'flowchart':
581
- diagramLines = renderFlowchart(parsed.ast, contentWidth, theme);
582
- break;
583
- case 'sequence':
584
- diagramLines = renderSequenceDiagram(parsed.ast, contentWidth, theme);
585
- break;
586
- case 'state':
587
- diagramLines = renderStateDiagram(parsed.ast, contentWidth, theme);
588
- break;
589
- case 'class':
590
- case 'er':
591
- diagramLines = renderClassOrErDiagram(parsed.ast, contentWidth, theme);
592
- break;
593
- }
594
57
  if (embedded) {
595
- return wrapEmbeddedFrame(parsed.headerLabel, diagramLines, safeWidth, theme);
58
+ return wrapEmbeddedFrame(result.headerLabel, result.lines, safeWidth, theme);
596
59
  }
597
- const meta = parsed.ast.type === 'flowchart'
598
- ? `${parsed.ast.nodes.length} nó(s) · ${parsed.ast.edges.length} aresta(s)`
599
- : parsed.ast.type === 'sequence'
600
- ? `${parsed.ast.participants.length} participante(s) · ${parsed.ast.items.length} evento(s)`
601
- : parsed.ast.type === 'state'
602
- ? `${parsed.ast.transitions.length} transição(ões)`
603
- : `${parsed.ast.entities.length} entidade(s) · ${parsed.ast.relations.length} relação(ões)`;
604
60
  return [
605
- `${fg(theme.accent)}${BOLD}◈ ${stripUnsafeAnsi(parsed.headerLabel)}${RESET} ${fg(theme.muted)}${DIM}· ${meta}${RESET}`,
61
+ `${fg(theme.accent)}${BOLD}◈ ${stripUnsafeAnsi(result.headerLabel)}${RESET} ${fg(theme.muted)}${DIM}· ${result.width}×${result.height} · @leosdc/termaid${RESET}`,
606
62
  `${fg(theme.border)}${'─'.repeat(Math.min(safeWidth, 56))}${RESET}`,
607
63
  '',
608
- ...diagramLines,
64
+ ...result.lines,
609
65
  ];
610
66
  }
611
67
  //# sourceMappingURL=mermaid.js.map