@nghyane/arcane-tui 0.1.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.
@@ -0,0 +1,858 @@
1
+ import { marked, type Token } from "marked";
2
+ import type { MermaidImage } from "../mermaid";
3
+ import type { SymbolTheme } from "../symbols";
4
+ import { encodeITerm2, encodeKitty, getCellDimensions, ImageProtocol, TERMINAL } from "../terminal-capabilities";
5
+ import type { Component } from "../tui";
6
+ import { applyBackgroundToLine, padding, replaceTabs, visibleWidth, wrapTextWithAnsi } from "../utils";
7
+
8
+ /**
9
+ * Default text styling for markdown content.
10
+ * Applied to all text unless overridden by markdown formatting.
11
+ */
12
+ export interface DefaultTextStyle {
13
+ /** Foreground color function */
14
+ color?: (text: string) => string;
15
+ /** Background color function */
16
+ bgColor?: (text: string) => string;
17
+ /** Bold text */
18
+ bold?: boolean;
19
+ /** Italic text */
20
+ italic?: boolean;
21
+ /** Strikethrough text */
22
+ strikethrough?: boolean;
23
+ /** Underline text */
24
+ underline?: boolean;
25
+ }
26
+
27
+ /**
28
+ * Theme functions for markdown elements.
29
+ * Each function takes text and returns styled text with ANSI codes.
30
+ */
31
+ export interface MarkdownTheme {
32
+ heading: (text: string) => string;
33
+ link: (text: string) => string;
34
+ linkUrl: (text: string) => string;
35
+ code: (text: string) => string;
36
+ codeBlock: (text: string) => string;
37
+ codeBlockBorder: (text: string) => string;
38
+ quote: (text: string) => string;
39
+ quoteBorder: (text: string) => string;
40
+ hr: (text: string) => string;
41
+ listBullet: (text: string) => string;
42
+ bold: (text: string) => string;
43
+ italic: (text: string) => string;
44
+ strikethrough: (text: string) => string;
45
+ underline: (text: string) => string;
46
+ highlightCode?: (code: string, lang?: string) => string[];
47
+ /**
48
+ * Lookup a pre-rendered mermaid image by source hash.
49
+ * Hash is computed as `Bun.hash(source.trim()).toString(16)`.
50
+ * Return null to fall back to text rendering.
51
+ */
52
+ getMermaidImage?: (sourceHash: string) => MermaidImage | null;
53
+ symbols: SymbolTheme;
54
+ }
55
+
56
+ interface InlineStyleContext {
57
+ applyText: (text: string) => string;
58
+ stylePrefix: string;
59
+ }
60
+
61
+ export class Markdown implements Component {
62
+ #text: string;
63
+ #paddingX: number; // Left/right padding
64
+ #paddingY: number; // Top/bottom padding
65
+ #defaultTextStyle?: DefaultTextStyle;
66
+ #theme: MarkdownTheme;
67
+ #defaultStylePrefix?: string;
68
+ /** Number of spaces used to indent code block content. */
69
+ #codeBlockIndent: number;
70
+
71
+ // Cache for rendered output
72
+ #cachedText?: string;
73
+ #cachedWidth?: number;
74
+ #cachedLines?: string[];
75
+
76
+ constructor(
77
+ text: string,
78
+ paddingX: number,
79
+ paddingY: number,
80
+ theme: MarkdownTheme,
81
+ defaultTextStyle?: DefaultTextStyle,
82
+ codeBlockIndent: number = 2,
83
+ ) {
84
+ this.#text = text;
85
+ this.#paddingX = paddingX;
86
+ this.#paddingY = paddingY;
87
+ this.#theme = theme;
88
+ this.#defaultTextStyle = defaultTextStyle;
89
+ this.#codeBlockIndent = Math.max(0, Math.floor(codeBlockIndent));
90
+ }
91
+
92
+ setText(text: string): void {
93
+ this.#text = text;
94
+ this.invalidate();
95
+ }
96
+
97
+ invalidate(): void {
98
+ this.#cachedText = undefined;
99
+ this.#cachedWidth = undefined;
100
+ this.#cachedLines = undefined;
101
+ }
102
+
103
+ render(width: number): string[] {
104
+ // Check cache
105
+ if (this.#cachedLines && this.#cachedText === this.#text && this.#cachedWidth === width) {
106
+ return this.#cachedLines;
107
+ }
108
+
109
+ // Calculate available width for content (subtract horizontal padding)
110
+ const contentWidth = Math.max(1, width - this.#paddingX * 2);
111
+
112
+ // Don't render anything if there's no actual text
113
+ if (!this.#text || this.#text.trim() === "") {
114
+ const result: string[] = [];
115
+ // Update cache
116
+ this.#cachedText = this.#text;
117
+ this.#cachedWidth = width;
118
+ this.#cachedLines = result;
119
+ return result;
120
+ }
121
+
122
+ // Replace tabs with 3 spaces for consistent rendering
123
+ const normalizedText = replaceTabs(this.#text);
124
+
125
+ // Parse markdown to HTML-like tokens
126
+ const tokens = marked.lexer(normalizedText);
127
+
128
+ // Convert tokens to styled terminal output
129
+ const renderedLines: string[] = [];
130
+
131
+ for (let i = 0; i < tokens.length; i++) {
132
+ const token = tokens[i];
133
+ const nextToken = tokens[i + 1];
134
+ const tokenLines = this.#renderToken(token, contentWidth, nextToken?.type);
135
+ renderedLines.push(...tokenLines);
136
+ }
137
+
138
+ // Wrap lines (NO padding, NO background yet)
139
+ const wrappedLines: string[] = [];
140
+ for (const line of renderedLines) {
141
+ // Skip wrapping for image protocol lines (would corrupt escape sequences)
142
+ if (TERMINAL.isImageLine(line)) {
143
+ wrappedLines.push(line);
144
+ } else {
145
+ wrappedLines.push(...wrapTextWithAnsi(line, contentWidth));
146
+ }
147
+ }
148
+
149
+ // Add margins and background to each wrapped line
150
+ const leftMargin = padding(this.#paddingX);
151
+ const rightMargin = padding(this.#paddingX);
152
+ const bgFn = this.#defaultTextStyle?.bgColor;
153
+ const contentLines: string[] = [];
154
+
155
+ for (const line of wrappedLines) {
156
+ // Image lines must be output raw - no margins or background
157
+ if (TERMINAL.isImageLine(line)) {
158
+ contentLines.push(line);
159
+ continue;
160
+ }
161
+
162
+ const lineWithMargins = leftMargin + line + rightMargin;
163
+
164
+ if (bgFn) {
165
+ contentLines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
166
+ } else {
167
+ // No background - just pad to width
168
+ const visibleLen = visibleWidth(lineWithMargins);
169
+ const paddingNeeded = Math.max(0, width - visibleLen);
170
+ contentLines.push(lineWithMargins + padding(paddingNeeded));
171
+ }
172
+ }
173
+
174
+ // Add top/bottom padding (empty lines)
175
+ const emptyLine = padding(width);
176
+ const emptyLines: string[] = [];
177
+ for (let i = 0; i < this.#paddingY; i++) {
178
+ const line = bgFn ? applyBackgroundToLine(emptyLine, width, bgFn) : emptyLine;
179
+ emptyLines.push(line);
180
+ }
181
+
182
+ // Combine top padding, content, and bottom padding
183
+ const result = [...emptyLines, ...contentLines, ...emptyLines];
184
+
185
+ // Update cache
186
+ this.#cachedText = this.#text;
187
+ this.#cachedWidth = width;
188
+ this.#cachedLines = result;
189
+
190
+ return result.length > 0 ? result : [""];
191
+ }
192
+
193
+ /**
194
+ * Apply default text style to a string.
195
+ * This is the base styling applied to all text content.
196
+ * NOTE: Background color is NOT applied here - it's applied at the padding stage
197
+ * to ensure it extends to the full line width.
198
+ */
199
+ #applyDefaultStyle(text: string): string {
200
+ if (!this.#defaultTextStyle) {
201
+ return text;
202
+ }
203
+
204
+ let styled = text;
205
+
206
+ // Apply foreground color (NOT background - that's applied at padding stage)
207
+ if (this.#defaultTextStyle.color) {
208
+ styled = this.#defaultTextStyle.color(styled);
209
+ }
210
+
211
+ // Apply text decorations using this.#theme
212
+ if (this.#defaultTextStyle.bold) {
213
+ styled = this.#theme.bold(styled);
214
+ }
215
+ if (this.#defaultTextStyle.italic) {
216
+ styled = this.#theme.italic(styled);
217
+ }
218
+ if (this.#defaultTextStyle.strikethrough) {
219
+ styled = this.#theme.strikethrough(styled);
220
+ }
221
+ if (this.#defaultTextStyle.underline) {
222
+ styled = this.#theme.underline(styled);
223
+ }
224
+
225
+ return styled;
226
+ }
227
+
228
+ #getDefaultStylePrefix(): string {
229
+ if (!this.#defaultTextStyle) {
230
+ return "";
231
+ }
232
+
233
+ if (this.#defaultStylePrefix !== undefined) {
234
+ return this.#defaultStylePrefix;
235
+ }
236
+
237
+ const sentinel = "\u0000";
238
+ let styled = sentinel;
239
+
240
+ if (this.#defaultTextStyle.color) {
241
+ styled = this.#defaultTextStyle.color(styled);
242
+ }
243
+
244
+ if (this.#defaultTextStyle.bold) {
245
+ styled = this.#theme.bold(styled);
246
+ }
247
+ if (this.#defaultTextStyle.italic) {
248
+ styled = this.#theme.italic(styled);
249
+ }
250
+ if (this.#defaultTextStyle.strikethrough) {
251
+ styled = this.#theme.strikethrough(styled);
252
+ }
253
+ if (this.#defaultTextStyle.underline) {
254
+ styled = this.#theme.underline(styled);
255
+ }
256
+
257
+ const sentinelIndex = styled.indexOf(sentinel);
258
+ this.#defaultStylePrefix = sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
259
+ return this.#defaultStylePrefix;
260
+ }
261
+
262
+ #getStylePrefix(styleFn: (text: string) => string): string {
263
+ const sentinel = "\u0000";
264
+ const styled = styleFn(sentinel);
265
+ const sentinelIndex = styled.indexOf(sentinel);
266
+ return sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
267
+ }
268
+
269
+ #getDefaultInlineStyleContext(): InlineStyleContext {
270
+ return {
271
+ applyText: (text: string) => this.#applyDefaultStyle(text),
272
+ stylePrefix: this.#getDefaultStylePrefix(),
273
+ };
274
+ }
275
+
276
+ #renderToken(token: Token, width: number, nextTokenType?: string): string[] {
277
+ const lines: string[] = [];
278
+
279
+ switch (token.type) {
280
+ case "heading": {
281
+ const headingLevel = token.depth;
282
+ const headingPrefix = `${"#".repeat(headingLevel)} `;
283
+ const headingText = this.#renderInlineTokens(token.tokens || []);
284
+ let styledHeading: string;
285
+ if (headingLevel === 1) {
286
+ styledHeading = this.#theme.heading(this.#theme.bold(this.#theme.underline(headingText)));
287
+ } else if (headingLevel === 2) {
288
+ styledHeading = this.#theme.heading(this.#theme.bold(headingText));
289
+ } else {
290
+ styledHeading = this.#theme.heading(this.#theme.bold(headingPrefix + headingText));
291
+ }
292
+ lines.push(styledHeading);
293
+ if (nextTokenType !== "space") {
294
+ lines.push(""); // Add spacing after headings (unless space token follows)
295
+ }
296
+ break;
297
+ }
298
+
299
+ case "paragraph": {
300
+ const paragraphText = this.#renderInlineTokens(token.tokens || []);
301
+ lines.push(paragraphText);
302
+ // Don't add spacing if next token is space or list
303
+ if (nextTokenType && nextTokenType !== "list" && nextTokenType !== "space") {
304
+ lines.push("");
305
+ }
306
+ break;
307
+ }
308
+
309
+ case "code": {
310
+ // Handle mermaid diagrams with image rendering when available
311
+ if (token.lang === "mermaid" && this.#theme.getMermaidImage) {
312
+ const hash = Bun.hash(token.text.trim()).toString(16);
313
+ const image = this.#theme.getMermaidImage(hash);
314
+
315
+ if (image && TERMINAL.imageProtocol) {
316
+ const imageLines = this.#renderMermaidImage(image, width);
317
+ if (imageLines) {
318
+ lines.push(...imageLines);
319
+ if (nextTokenType !== "space") {
320
+ lines.push("");
321
+ }
322
+ break;
323
+ }
324
+ }
325
+ }
326
+
327
+ const codeIndent = padding(this.#codeBlockIndent);
328
+ lines.push(this.#theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
329
+ if (this.#theme.highlightCode) {
330
+ const highlightedLines = this.#theme.highlightCode(token.text, token.lang);
331
+ for (const hlLine of highlightedLines) {
332
+ lines.push(`${codeIndent}${hlLine}`);
333
+ }
334
+ } else {
335
+ // Split code by newlines and style each line
336
+ const codeLines = token.text.split("\n");
337
+ for (const codeLine of codeLines) {
338
+ lines.push(`${codeIndent}${this.#theme.codeBlock(codeLine)}`);
339
+ }
340
+ }
341
+ lines.push(this.#theme.codeBlockBorder("```"));
342
+ if (nextTokenType !== "space") {
343
+ lines.push(""); // Add spacing after code blocks (unless space token follows)
344
+ }
345
+ break;
346
+ }
347
+
348
+ case "list": {
349
+ const listLines = this.#renderList(token as any, 0);
350
+ lines.push(...listLines);
351
+ // Don't add spacing after lists if a space token follows
352
+ // (the space token will handle it)
353
+ break;
354
+ }
355
+
356
+ case "table": {
357
+ const tableLines = this.#renderTable(token as any, width);
358
+ lines.push(...tableLines);
359
+ break;
360
+ }
361
+
362
+ case "blockquote": {
363
+ const quoteStyle = (text: string) => this.#theme.quote(this.#theme.italic(text));
364
+ const quoteStyleContext: InlineStyleContext = {
365
+ applyText: quoteStyle,
366
+ stylePrefix: this.#getStylePrefix(quoteStyle),
367
+ };
368
+ const quoteText = this.#renderInlineTokens(token.tokens || [], quoteStyleContext);
369
+ const quoteLines = quoteText.split("\n");
370
+
371
+ // Calculate available width for quote content (subtract border + space = 2 chars)
372
+ const quoteContentWidth = Math.max(1, width - 2);
373
+
374
+ for (const quoteLine of quoteLines) {
375
+ // Wrap the styled line, then add border to each wrapped line
376
+ const wrappedLines = wrapTextWithAnsi(quoteLine, quoteContentWidth);
377
+ for (const wrappedLine of wrappedLines) {
378
+ lines.push(this.#theme.quoteBorder(`${this.#theme.symbols.quoteBorder} `) + wrappedLine);
379
+ }
380
+ }
381
+ if (nextTokenType !== "space") {
382
+ lines.push(""); // Add spacing after blockquotes (unless space token follows)
383
+ }
384
+ break;
385
+ }
386
+
387
+ case "hr":
388
+ lines.push(this.#theme.hr(this.#theme.symbols.hrChar.repeat(Math.min(width, 80))));
389
+ if (nextTokenType !== "space") {
390
+ lines.push(""); // Add spacing after horizontal rules (unless space token follows)
391
+ }
392
+ break;
393
+
394
+ case "html":
395
+ // Render HTML as plain text (escaped for terminal)
396
+ if ("raw" in token && typeof token.raw === "string") {
397
+ lines.push(this.#applyDefaultStyle(token.raw.trim()));
398
+ }
399
+ break;
400
+
401
+ case "space":
402
+ // Space tokens represent blank lines in markdown
403
+ lines.push("");
404
+ break;
405
+
406
+ default:
407
+ // Handle any other token types as plain text
408
+ if ("text" in token && typeof token.text === "string") {
409
+ lines.push(token.text);
410
+ }
411
+ }
412
+
413
+ return lines;
414
+ }
415
+
416
+ #renderInlineTokens(tokens: Token[], styleContext?: InlineStyleContext): string {
417
+ let result = "";
418
+ const resolvedStyleContext = styleContext ?? this.#getDefaultInlineStyleContext();
419
+ const { applyText, stylePrefix } = resolvedStyleContext;
420
+ const applyTextWithNewlines = (text: string): string => {
421
+ const segments: string[] = text.split("\n");
422
+ return segments.map((segment: string) => applyText(segment)).join("\n");
423
+ };
424
+
425
+ for (const token of tokens) {
426
+ switch (token.type) {
427
+ case "text":
428
+ // Text tokens in list items can have nested tokens for inline formatting
429
+ if (token.tokens && token.tokens.length > 0) {
430
+ result += this.#renderInlineTokens(token.tokens, resolvedStyleContext);
431
+ } else {
432
+ result += applyTextWithNewlines(token.text);
433
+ }
434
+ break;
435
+
436
+ case "paragraph":
437
+ // Paragraph tokens contain nested inline tokens
438
+ result += this.#renderInlineTokens(token.tokens || [], resolvedStyleContext);
439
+ break;
440
+
441
+ case "strong": {
442
+ const boldContent = this.#renderInlineTokens(token.tokens || [], resolvedStyleContext);
443
+ result += this.#theme.bold(boldContent) + stylePrefix;
444
+ break;
445
+ }
446
+
447
+ case "em": {
448
+ const italicContent = this.#renderInlineTokens(token.tokens || [], resolvedStyleContext);
449
+ result += this.#theme.italic(italicContent) + stylePrefix;
450
+ break;
451
+ }
452
+
453
+ case "codespan":
454
+ result += this.#theme.code(token.text) + stylePrefix;
455
+ break;
456
+
457
+ case "link": {
458
+ const linkText = this.#renderInlineTokens(token.tokens || [], resolvedStyleContext);
459
+ // If link text matches href, only show the link once
460
+ // Compare raw text (token.text) not styled text (linkText) since linkText has ANSI codes
461
+ // For mailto: links, strip the prefix before comparing (autolinked emails have
462
+ // text="foo@bar.com" but href="mailto:foo@bar.com")
463
+ const hrefForComparison = token.href.startsWith("mailto:") ? token.href.slice(7) : token.href;
464
+ if (token.text === token.href || token.text === hrefForComparison) {
465
+ result += this.#theme.link(this.#theme.underline(linkText)) + stylePrefix;
466
+ } else {
467
+ result +=
468
+ this.#theme.link(this.#theme.underline(linkText)) +
469
+ this.#theme.linkUrl(` (${token.href})`) +
470
+ stylePrefix;
471
+ }
472
+ break;
473
+ }
474
+
475
+ case "br":
476
+ result += "\n";
477
+ break;
478
+
479
+ case "del": {
480
+ const delContent = this.#renderInlineTokens(token.tokens || [], resolvedStyleContext);
481
+ result += this.#theme.strikethrough(delContent) + stylePrefix;
482
+ break;
483
+ }
484
+
485
+ case "html":
486
+ // Render inline HTML as plain text
487
+ if ("raw" in token && typeof token.raw === "string") {
488
+ result += applyTextWithNewlines(token.raw);
489
+ }
490
+ break;
491
+
492
+ default:
493
+ // Handle any other inline token types as plain text
494
+ if ("text" in token && typeof token.text === "string") {
495
+ result += applyTextWithNewlines(token.text);
496
+ }
497
+ }
498
+ }
499
+
500
+ return result;
501
+ }
502
+
503
+ /**
504
+ * Render a list with proper nesting support
505
+ */
506
+ #renderList(token: Token & { items: any[]; ordered: boolean; start?: number }, depth: number): string[] {
507
+ const lines: string[] = [];
508
+ const indent = " ".repeat(depth);
509
+ // Use the list's start property (defaults to 1 for ordered lists)
510
+ const startNumber = token.start ?? 1;
511
+
512
+ for (let i = 0; i < token.items.length; i++) {
513
+ const item = token.items[i];
514
+ const bullet = token.ordered ? `${startNumber + i}. ` : "- ";
515
+
516
+ // Process item tokens to handle nested lists
517
+ const itemLines = this.#renderListItem(item.tokens || [], depth);
518
+
519
+ if (itemLines.length > 0) {
520
+ // First line - check if it's a nested list
521
+ // A nested list will start with indent (spaces) followed by cyan bullet
522
+ const firstLine = itemLines[0];
523
+ const isNestedList = /^\s+\x1b\[36m[-\d]/.test(firstLine); // starts with spaces + cyan + bullet char
524
+
525
+ if (isNestedList) {
526
+ // This is a nested list, just add it as-is (already has full indent)
527
+ lines.push(firstLine);
528
+ } else {
529
+ // Regular text content - add indent and bullet
530
+ lines.push(indent + this.#theme.listBullet(bullet) + firstLine);
531
+ }
532
+
533
+ // Rest of the lines
534
+ for (let j = 1; j < itemLines.length; j++) {
535
+ const line = itemLines[j];
536
+ const isNestedListLine = /^\s+\x1b\[36m[-\d]/.test(line); // starts with spaces + cyan + bullet char
537
+
538
+ if (isNestedListLine) {
539
+ // Nested list line - already has full indent
540
+ lines.push(line);
541
+ } else {
542
+ // Regular content - add parent indent + 2 spaces for continuation
543
+ lines.push(`${indent} ${line}`);
544
+ }
545
+ }
546
+ } else {
547
+ lines.push(indent + this.#theme.listBullet(bullet));
548
+ }
549
+ }
550
+
551
+ return lines;
552
+ }
553
+
554
+ /**
555
+ * Render list item tokens, handling nested lists
556
+ * Returns lines WITHOUT the parent indent (renderList will add it)
557
+ */
558
+ #renderListItem(tokens: Token[], parentDepth: number): string[] {
559
+ const lines: string[] = [];
560
+
561
+ for (const token of tokens) {
562
+ if (token.type === "list") {
563
+ // Nested list - render with one additional indent level
564
+ // These lines will have their own indent, so we just add them as-is
565
+ const nestedLines = this.#renderList(token as any, parentDepth + 1);
566
+ lines.push(...nestedLines);
567
+ } else if (token.type === "text") {
568
+ // Text content (may have inline tokens)
569
+ const text =
570
+ token.tokens && token.tokens.length > 0 ? this.#renderInlineTokens(token.tokens) : token.text || "";
571
+ lines.push(text);
572
+ } else if (token.type === "paragraph") {
573
+ // Paragraph in list item
574
+ const text = this.#renderInlineTokens(token.tokens || []);
575
+ lines.push(text);
576
+ } else if (token.type === "code") {
577
+ // Code block in list item
578
+ const codeIndent = padding(this.#codeBlockIndent);
579
+ lines.push(this.#theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
580
+ if (this.#theme.highlightCode) {
581
+ const highlightedLines = this.#theme.highlightCode(token.text, token.lang);
582
+ for (const hlLine of highlightedLines) {
583
+ lines.push(`${codeIndent}${hlLine}`);
584
+ }
585
+ } else {
586
+ const codeLines = token.text.split("\n");
587
+ for (const codeLine of codeLines) {
588
+ lines.push(`${codeIndent}${this.#theme.codeBlock(codeLine)}`);
589
+ }
590
+ }
591
+ lines.push(this.#theme.codeBlockBorder("```"));
592
+ } else {
593
+ // Other token types - try to render as inline
594
+ const text = this.#renderInlineTokens([token]);
595
+ if (text) {
596
+ lines.push(text);
597
+ }
598
+ }
599
+ }
600
+
601
+ return lines;
602
+ }
603
+
604
+ /**
605
+ * Get the visible width of the longest word in a string.
606
+ */
607
+ #getLongestWordWidth(text: string, maxWidth?: number): number {
608
+ const words = text.split(/\s+/).filter(word => word.length > 0);
609
+ let longest = 0;
610
+ for (const word of words) {
611
+ longest = Math.max(longest, visibleWidth(word));
612
+ }
613
+ if (maxWidth === undefined) {
614
+ return longest;
615
+ }
616
+ return Math.min(longest, maxWidth);
617
+ }
618
+
619
+ /**
620
+ * Wrap a table cell to fit into a column.
621
+ *
622
+ * Delegates to wrapTextWithAnsi() so ANSI codes + long tokens are handled
623
+ * consistently with the rest of the renderer.
624
+ */
625
+ #wrapCellText(text: string, maxWidth: number): string[] {
626
+ return wrapTextWithAnsi(text, Math.max(1, maxWidth));
627
+ }
628
+
629
+ /**
630
+ * Render a table with width-aware cell wrapping.
631
+ * Cells that don't fit are wrapped to multiple lines.
632
+ */
633
+ #renderTable(token: Token & { header: any[]; rows: any[][]; raw?: string }, availableWidth: number): string[] {
634
+ const lines: string[] = [];
635
+ const numCols = token.header.length;
636
+
637
+ if (numCols === 0) {
638
+ return lines;
639
+ }
640
+
641
+ // Calculate border overhead: "│ " + (n-1) * " │ " + " │"
642
+ // = 2 + (n-1) * 3 + 2 = 3n + 1
643
+ const borderOverhead = 3 * numCols + 1;
644
+ const availableForCells = availableWidth - borderOverhead;
645
+ if (availableForCells < numCols) {
646
+ // Too narrow to render a stable table. Fall back to raw markdown.
647
+ const fallbackLines = token.raw ? wrapTextWithAnsi(token.raw, availableWidth) : [];
648
+ fallbackLines.push("");
649
+ return fallbackLines;
650
+ }
651
+
652
+ const maxUnbrokenWordWidth = 30;
653
+
654
+ // Calculate natural column widths (what each column needs without constraints)
655
+ const naturalWidths: number[] = [];
656
+ const minWordWidths: number[] = [];
657
+ for (let i = 0; i < numCols; i++) {
658
+ const headerText = this.#renderInlineTokens(token.header[i].tokens || []);
659
+ naturalWidths[i] = visibleWidth(headerText);
660
+ minWordWidths[i] = Math.max(1, this.#getLongestWordWidth(headerText, maxUnbrokenWordWidth));
661
+ }
662
+ for (const row of token.rows) {
663
+ for (let i = 0; i < row.length; i++) {
664
+ const cellText = this.#renderInlineTokens(row[i].tokens || []);
665
+ naturalWidths[i] = Math.max(naturalWidths[i] || 0, visibleWidth(cellText));
666
+ minWordWidths[i] = Math.max(
667
+ minWordWidths[i] || 1,
668
+ this.#getLongestWordWidth(cellText, maxUnbrokenWordWidth),
669
+ );
670
+ }
671
+ }
672
+
673
+ let minColumnWidths = minWordWidths;
674
+ let minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
675
+
676
+ if (minCellsWidth > availableForCells) {
677
+ minColumnWidths = new Array(numCols).fill(1);
678
+ const remaining = availableForCells - numCols;
679
+
680
+ if (remaining > 0) {
681
+ const totalWeight = minWordWidths.reduce((total, width) => total + Math.max(0, width - 1), 0);
682
+ const growth = minWordWidths.map(width => {
683
+ const weight = Math.max(0, width - 1);
684
+ return totalWeight > 0 ? Math.floor((weight / totalWeight) * remaining) : 0;
685
+ });
686
+
687
+ for (let i = 0; i < numCols; i++) {
688
+ minColumnWidths[i] += growth[i] ?? 0;
689
+ }
690
+
691
+ const allocated = growth.reduce((total, width) => total + width, 0);
692
+ let leftover = remaining - allocated;
693
+ for (let i = 0; leftover > 0 && i < numCols; i++) {
694
+ minColumnWidths[i]++;
695
+ leftover--;
696
+ }
697
+ }
698
+
699
+ minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
700
+ }
701
+
702
+ // Calculate column widths that fit within available width
703
+ const totalNaturalWidth = naturalWidths.reduce((a, b) => a + b, 0) + borderOverhead;
704
+ let columnWidths: number[];
705
+
706
+ if (totalNaturalWidth <= availableWidth) {
707
+ // Everything fits naturally
708
+ columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index]));
709
+ } else {
710
+ // Need to shrink columns to fit
711
+ const totalGrowPotential = naturalWidths.reduce((total, width, index) => {
712
+ return total + Math.max(0, width - minColumnWidths[index]);
713
+ }, 0);
714
+ const extraWidth = Math.max(0, availableForCells - minCellsWidth);
715
+ columnWidths = minColumnWidths.map((minWidth, index) => {
716
+ const naturalWidth = naturalWidths[index];
717
+ const minWidthDelta = Math.max(0, naturalWidth - minWidth);
718
+ let grow = 0;
719
+ if (totalGrowPotential > 0) {
720
+ grow = Math.floor((minWidthDelta / totalGrowPotential) * extraWidth);
721
+ }
722
+ return minWidth + grow;
723
+ });
724
+
725
+ // Adjust for rounding errors - distribute remaining space
726
+ const allocated = columnWidths.reduce((a, b) => a + b, 0);
727
+ let remaining = availableForCells - allocated;
728
+ while (remaining > 0) {
729
+ let grew = false;
730
+ for (let i = 0; i < numCols && remaining > 0; i++) {
731
+ if (columnWidths[i] < naturalWidths[i]) {
732
+ columnWidths[i]++;
733
+ remaining--;
734
+ grew = true;
735
+ }
736
+ }
737
+ if (!grew) {
738
+ break;
739
+ }
740
+ }
741
+ }
742
+
743
+ const t = this.#theme.symbols.table;
744
+ const h = t.horizontal;
745
+ const v = t.vertical;
746
+
747
+ // Render top border
748
+ const topBorderCells = columnWidths.map(w => h.repeat(w));
749
+ lines.push(`${t.topLeft}${h}${topBorderCells.join(`${h}${t.teeDown}${h}`)}${h}${t.topRight}`);
750
+
751
+ // Render header with wrapping
752
+ const headerCellLines: string[][] = token.header.map((cell, i) => {
753
+ const text = this.#renderInlineTokens(cell.tokens || []);
754
+ return this.#wrapCellText(text, columnWidths[i]);
755
+ });
756
+ const headerLineCount = Math.max(...headerCellLines.map(c => c.length));
757
+
758
+ for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) {
759
+ const rowParts = headerCellLines.map((cellLines, colIdx) => {
760
+ const text = cellLines[lineIdx] || "";
761
+ const padded = text + padding(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
762
+ return this.#theme.bold(padded);
763
+ });
764
+ lines.push(`${v} ${rowParts.join(` ${v} `)} ${v}`);
765
+ }
766
+
767
+ // Render separator
768
+ const separatorCells = columnWidths.map(w => h.repeat(w));
769
+ const separatorLine = `${t.teeRight}${h}${separatorCells.join(`${h}${t.cross}${h}`)}${h}${t.teeLeft}`;
770
+ lines.push(separatorLine);
771
+
772
+ // Render rows with wrapping
773
+ for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
774
+ const row = token.rows[rowIndex];
775
+ const rowCellLines: string[][] = row.map((cell, i) => {
776
+ const text = this.#renderInlineTokens(cell.tokens || []);
777
+ return this.#wrapCellText(text, columnWidths[i]);
778
+ });
779
+ const rowLineCount = Math.max(...rowCellLines.map(c => c.length));
780
+
781
+ for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) {
782
+ const rowParts = rowCellLines.map((cellLines, colIdx) => {
783
+ const text = cellLines[lineIdx] || "";
784
+ return text + padding(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
785
+ });
786
+ lines.push(`${v} ${rowParts.join(` ${v} `)} ${v}`);
787
+ }
788
+
789
+ if (rowIndex < token.rows.length - 1) {
790
+ lines.push(separatorLine);
791
+ }
792
+ }
793
+
794
+ // Render bottom border
795
+ const bottomBorderCells = columnWidths.map(w => h.repeat(w));
796
+ lines.push(`${t.bottomLeft}${h}${bottomBorderCells.join(`${h}${t.teeUp}${h}`)}${h}${t.bottomRight}`);
797
+
798
+ lines.push(""); // Add spacing after table
799
+ return lines;
800
+ }
801
+
802
+ /**
803
+ * Render a mermaid image using terminal graphics protocol.
804
+ * Returns array of lines (image placeholder rows) or null if rendering fails.
805
+ */
806
+ #renderMermaidImage(image: MermaidImage, availableWidth: number): string[] | null {
807
+ if (!TERMINAL.imageProtocol) return null;
808
+
809
+ const cellDims = getCellDimensions();
810
+ const scale = 0.5; // Render at 50% of natural size
811
+
812
+ // Calculate natural size in cells (don't scale up, only down if needed)
813
+ const naturalColumns = Math.ceil((image.widthPx * scale) / cellDims.widthPx);
814
+ const naturalRows = Math.ceil((image.heightPx * scale) / cellDims.heightPx);
815
+
816
+ // Use natural size, but cap to available width
817
+ const columns = Math.min(naturalColumns, availableWidth);
818
+
819
+ // If we had to shrink width, calculate proportional height
820
+ let rows: number;
821
+ if (columns < naturalColumns) {
822
+ // Scaled down - recalculate height
823
+ const scale = columns / naturalColumns;
824
+ rows = Math.max(1, Math.ceil(naturalRows * scale));
825
+ } else {
826
+ // Natural size
827
+ rows = naturalRows;
828
+ }
829
+
830
+ let sequence: string;
831
+ switch (TERMINAL.imageProtocol) {
832
+ case ImageProtocol.Kitty:
833
+ sequence = encodeKitty(image.base64, { columns, rows });
834
+ break;
835
+ case ImageProtocol.Iterm2:
836
+ sequence = encodeITerm2(image.base64, {
837
+ width: columns,
838
+ height: "auto",
839
+ preserveAspectRatio: true,
840
+ });
841
+ break;
842
+ default:
843
+ return null;
844
+ }
845
+
846
+ // Reserve space with empty lines, then output image with cursor-up
847
+ // This ensures TUI accounts for image height in layout
848
+ const lines: string[] = [];
849
+ for (let i = 0; i < rows - 1; i++) {
850
+ lines.push("");
851
+ }
852
+ // Move cursor up to first row, then output image
853
+ const moveUp = rows > 1 ? `\x1b[${rows - 1}A` : "";
854
+ lines.push(moveUp + sequence);
855
+
856
+ return lines;
857
+ }
858
+ }