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