@draht/tui 2026.3.2-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +761 -0
  2. package/dist/autocomplete.d.ts +50 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +596 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/box.d.ts +22 -0
  7. package/dist/components/box.d.ts.map +1 -0
  8. package/dist/components/box.js +104 -0
  9. package/dist/components/box.js.map +1 -0
  10. package/dist/components/cancellable-loader.d.ts +22 -0
  11. package/dist/components/cancellable-loader.d.ts.map +1 -0
  12. package/dist/components/cancellable-loader.js +35 -0
  13. package/dist/components/cancellable-loader.js.map +1 -0
  14. package/dist/components/editor.d.ts +205 -0
  15. package/dist/components/editor.d.ts.map +1 -0
  16. package/dist/components/editor.js +1679 -0
  17. package/dist/components/editor.js.map +1 -0
  18. package/dist/components/image.d.ts +28 -0
  19. package/dist/components/image.d.ts.map +1 -0
  20. package/dist/components/image.js +69 -0
  21. package/dist/components/image.js.map +1 -0
  22. package/dist/components/input.d.ts +37 -0
  23. package/dist/components/input.d.ts.map +1 -0
  24. package/dist/components/input.js +433 -0
  25. package/dist/components/input.js.map +1 -0
  26. package/dist/components/loader.d.ts +21 -0
  27. package/dist/components/loader.d.ts.map +1 -0
  28. package/dist/components/loader.js +49 -0
  29. package/dist/components/loader.js.map +1 -0
  30. package/dist/components/markdown.d.ts +95 -0
  31. package/dist/components/markdown.d.ts.map +1 -0
  32. package/dist/components/markdown.js +629 -0
  33. package/dist/components/markdown.js.map +1 -0
  34. package/dist/components/select-list.d.ts +32 -0
  35. package/dist/components/select-list.d.ts.map +1 -0
  36. package/dist/components/select-list.js +152 -0
  37. package/dist/components/select-list.js.map +1 -0
  38. package/dist/components/settings-list.d.ts +50 -0
  39. package/dist/components/settings-list.d.ts.map +1 -0
  40. package/dist/components/settings-list.js +185 -0
  41. package/dist/components/settings-list.js.map +1 -0
  42. package/dist/components/spacer.d.ts +12 -0
  43. package/dist/components/spacer.d.ts.map +1 -0
  44. package/dist/components/spacer.js +23 -0
  45. package/dist/components/spacer.js.map +1 -0
  46. package/dist/components/text.d.ts +19 -0
  47. package/dist/components/text.d.ts.map +1 -0
  48. package/dist/components/text.js +89 -0
  49. package/dist/components/text.js.map +1 -0
  50. package/dist/components/truncated-text.d.ts +13 -0
  51. package/dist/components/truncated-text.d.ts.map +1 -0
  52. package/dist/components/truncated-text.js +51 -0
  53. package/dist/components/truncated-text.js.map +1 -0
  54. package/dist/editor-component.d.ts +39 -0
  55. package/dist/editor-component.d.ts.map +1 -0
  56. package/dist/editor-component.js +2 -0
  57. package/dist/editor-component.js.map +1 -0
  58. package/dist/fuzzy.d.ts +16 -0
  59. package/dist/fuzzy.d.ts.map +1 -0
  60. package/dist/fuzzy.js +107 -0
  61. package/dist/fuzzy.js.map +1 -0
  62. package/dist/index.d.ts +23 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +32 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/keybindings.d.ts +39 -0
  67. package/dist/keybindings.d.ts.map +1 -0
  68. package/dist/keybindings.js +114 -0
  69. package/dist/keybindings.js.map +1 -0
  70. package/dist/keys.d.ts +160 -0
  71. package/dist/keys.d.ts.map +1 -0
  72. package/dist/keys.js +959 -0
  73. package/dist/keys.js.map +1 -0
  74. package/dist/kill-ring.d.ts +28 -0
  75. package/dist/kill-ring.d.ts.map +1 -0
  76. package/dist/kill-ring.js +44 -0
  77. package/dist/kill-ring.js.map +1 -0
  78. package/dist/stdin-buffer.d.ts +48 -0
  79. package/dist/stdin-buffer.d.ts.map +1 -0
  80. package/dist/stdin-buffer.js +317 -0
  81. package/dist/stdin-buffer.js.map +1 -0
  82. package/dist/terminal-image.d.ts +68 -0
  83. package/dist/terminal-image.d.ts.map +1 -0
  84. package/dist/terminal-image.js +288 -0
  85. package/dist/terminal-image.js.map +1 -0
  86. package/dist/terminal.d.ts +78 -0
  87. package/dist/terminal.d.ts.map +1 -0
  88. package/dist/terminal.js +249 -0
  89. package/dist/terminal.js.map +1 -0
  90. package/dist/tui.d.ts +210 -0
  91. package/dist/tui.d.ts.map +1 -0
  92. package/dist/tui.js +955 -0
  93. package/dist/tui.js.map +1 -0
  94. package/dist/undo-stack.d.ts +17 -0
  95. package/dist/undo-stack.d.ts.map +1 -0
  96. package/dist/undo-stack.js +25 -0
  97. package/dist/undo-stack.js.map +1 -0
  98. package/dist/utils.d.ts +78 -0
  99. package/dist/utils.d.ts.map +1 -0
  100. package/dist/utils.js +800 -0
  101. package/dist/utils.js.map +1 -0
  102. package/package.json +53 -0
@@ -0,0 +1,629 @@
1
+ import { marked } from "marked";
2
+ import { isImageLine } from "../terminal-image.js";
3
+ import { applyBackgroundToLine, visibleWidth, wrapTextWithAnsi } from "../utils.js";
4
+ export class Markdown {
5
+ text;
6
+ paddingX; // Left/right padding
7
+ paddingY; // Top/bottom padding
8
+ defaultTextStyle;
9
+ theme;
10
+ defaultStylePrefix;
11
+ // Cache for rendered output
12
+ cachedText;
13
+ cachedWidth;
14
+ cachedLines;
15
+ constructor(text, paddingX, paddingY, theme, defaultTextStyle) {
16
+ this.text = text;
17
+ this.paddingX = paddingX;
18
+ this.paddingY = paddingY;
19
+ this.theme = theme;
20
+ this.defaultTextStyle = defaultTextStyle;
21
+ }
22
+ setText(text) {
23
+ this.text = text;
24
+ this.invalidate();
25
+ }
26
+ invalidate() {
27
+ this.cachedText = undefined;
28
+ this.cachedWidth = undefined;
29
+ this.cachedLines = undefined;
30
+ }
31
+ render(width) {
32
+ // Check cache
33
+ if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) {
34
+ return this.cachedLines;
35
+ }
36
+ // Calculate available width for content (subtract horizontal padding)
37
+ const contentWidth = Math.max(1, width - this.paddingX * 2);
38
+ // Don't render anything if there's no actual text
39
+ if (!this.text || this.text.trim() === "") {
40
+ const result = [];
41
+ // Update cache
42
+ this.cachedText = this.text;
43
+ this.cachedWidth = width;
44
+ this.cachedLines = result;
45
+ return result;
46
+ }
47
+ // Replace tabs with 3 spaces for consistent rendering
48
+ const normalizedText = this.text.replace(/\t/g, " ");
49
+ // Parse markdown to HTML-like tokens
50
+ const tokens = marked.lexer(normalizedText);
51
+ // Convert tokens to styled terminal output
52
+ const renderedLines = [];
53
+ for (let i = 0; i < tokens.length; i++) {
54
+ const token = tokens[i];
55
+ const nextToken = tokens[i + 1];
56
+ const tokenLines = this.renderToken(token, contentWidth, nextToken?.type);
57
+ renderedLines.push(...tokenLines);
58
+ }
59
+ // Wrap lines (NO padding, NO background yet)
60
+ const wrappedLines = [];
61
+ for (const line of renderedLines) {
62
+ if (isImageLine(line)) {
63
+ wrappedLines.push(line);
64
+ }
65
+ else {
66
+ wrappedLines.push(...wrapTextWithAnsi(line, contentWidth));
67
+ }
68
+ }
69
+ // Add margins and background to each wrapped line
70
+ const leftMargin = " ".repeat(this.paddingX);
71
+ const rightMargin = " ".repeat(this.paddingX);
72
+ const bgFn = this.defaultTextStyle?.bgColor;
73
+ const contentLines = [];
74
+ for (const line of wrappedLines) {
75
+ if (isImageLine(line)) {
76
+ contentLines.push(line);
77
+ continue;
78
+ }
79
+ const lineWithMargins = leftMargin + line + rightMargin;
80
+ if (bgFn) {
81
+ contentLines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
82
+ }
83
+ else {
84
+ // No background - just pad to width
85
+ const visibleLen = visibleWidth(lineWithMargins);
86
+ const paddingNeeded = Math.max(0, width - visibleLen);
87
+ contentLines.push(lineWithMargins + " ".repeat(paddingNeeded));
88
+ }
89
+ }
90
+ // Add top/bottom padding (empty lines)
91
+ const emptyLine = " ".repeat(width);
92
+ const emptyLines = [];
93
+ for (let i = 0; i < this.paddingY; i++) {
94
+ const line = bgFn ? applyBackgroundToLine(emptyLine, width, bgFn) : emptyLine;
95
+ emptyLines.push(line);
96
+ }
97
+ // Combine top padding, content, and bottom padding
98
+ const result = [...emptyLines, ...contentLines, ...emptyLines];
99
+ // Update cache
100
+ this.cachedText = this.text;
101
+ this.cachedWidth = width;
102
+ this.cachedLines = result;
103
+ return result.length > 0 ? result : [""];
104
+ }
105
+ /**
106
+ * Apply default text style to a string.
107
+ * This is the base styling applied to all text content.
108
+ * NOTE: Background color is NOT applied here - it's applied at the padding stage
109
+ * to ensure it extends to the full line width.
110
+ */
111
+ applyDefaultStyle(text) {
112
+ if (!this.defaultTextStyle) {
113
+ return text;
114
+ }
115
+ let styled = text;
116
+ // Apply foreground color (NOT background - that's applied at padding stage)
117
+ if (this.defaultTextStyle.color) {
118
+ styled = this.defaultTextStyle.color(styled);
119
+ }
120
+ // Apply text decorations using this.theme
121
+ if (this.defaultTextStyle.bold) {
122
+ styled = this.theme.bold(styled);
123
+ }
124
+ if (this.defaultTextStyle.italic) {
125
+ styled = this.theme.italic(styled);
126
+ }
127
+ if (this.defaultTextStyle.strikethrough) {
128
+ styled = this.theme.strikethrough(styled);
129
+ }
130
+ if (this.defaultTextStyle.underline) {
131
+ styled = this.theme.underline(styled);
132
+ }
133
+ return styled;
134
+ }
135
+ getDefaultStylePrefix() {
136
+ if (!this.defaultTextStyle) {
137
+ return "";
138
+ }
139
+ if (this.defaultStylePrefix !== undefined) {
140
+ return this.defaultStylePrefix;
141
+ }
142
+ const sentinel = "\u0000";
143
+ let styled = sentinel;
144
+ if (this.defaultTextStyle.color) {
145
+ styled = this.defaultTextStyle.color(styled);
146
+ }
147
+ if (this.defaultTextStyle.bold) {
148
+ styled = this.theme.bold(styled);
149
+ }
150
+ if (this.defaultTextStyle.italic) {
151
+ styled = this.theme.italic(styled);
152
+ }
153
+ if (this.defaultTextStyle.strikethrough) {
154
+ styled = this.theme.strikethrough(styled);
155
+ }
156
+ if (this.defaultTextStyle.underline) {
157
+ styled = this.theme.underline(styled);
158
+ }
159
+ const sentinelIndex = styled.indexOf(sentinel);
160
+ this.defaultStylePrefix = sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
161
+ return this.defaultStylePrefix;
162
+ }
163
+ getStylePrefix(styleFn) {
164
+ const sentinel = "\u0000";
165
+ const styled = styleFn(sentinel);
166
+ const sentinelIndex = styled.indexOf(sentinel);
167
+ return sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
168
+ }
169
+ getDefaultInlineStyleContext() {
170
+ return {
171
+ applyText: (text) => this.applyDefaultStyle(text),
172
+ stylePrefix: this.getDefaultStylePrefix(),
173
+ };
174
+ }
175
+ renderToken(token, width, nextTokenType) {
176
+ const lines = [];
177
+ switch (token.type) {
178
+ case "heading": {
179
+ const headingLevel = token.depth;
180
+ const headingPrefix = `${"#".repeat(headingLevel)} `;
181
+ const headingText = this.renderInlineTokens(token.tokens || []);
182
+ let styledHeading;
183
+ if (headingLevel === 1) {
184
+ styledHeading = this.theme.heading(this.theme.bold(this.theme.underline(headingText)));
185
+ }
186
+ else if (headingLevel === 2) {
187
+ styledHeading = this.theme.heading(this.theme.bold(headingText));
188
+ }
189
+ else {
190
+ styledHeading = this.theme.heading(this.theme.bold(headingPrefix + headingText));
191
+ }
192
+ lines.push(styledHeading);
193
+ if (nextTokenType !== "space") {
194
+ lines.push(""); // Add spacing after headings (unless space token follows)
195
+ }
196
+ break;
197
+ }
198
+ case "paragraph": {
199
+ const paragraphText = this.renderInlineTokens(token.tokens || []);
200
+ lines.push(paragraphText);
201
+ // Don't add spacing if next token is space or list
202
+ if (nextTokenType && nextTokenType !== "list" && nextTokenType !== "space") {
203
+ lines.push("");
204
+ }
205
+ break;
206
+ }
207
+ case "code": {
208
+ const indent = this.theme.codeBlockIndent ?? " ";
209
+ lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
210
+ if (this.theme.highlightCode) {
211
+ const highlightedLines = this.theme.highlightCode(token.text, token.lang);
212
+ for (const hlLine of highlightedLines) {
213
+ lines.push(`${indent}${hlLine}`);
214
+ }
215
+ }
216
+ else {
217
+ // Split code by newlines and style each line
218
+ const codeLines = token.text.split("\n");
219
+ for (const codeLine of codeLines) {
220
+ lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
221
+ }
222
+ }
223
+ lines.push(this.theme.codeBlockBorder("```"));
224
+ if (nextTokenType !== "space") {
225
+ lines.push(""); // Add spacing after code blocks (unless space token follows)
226
+ }
227
+ break;
228
+ }
229
+ case "list": {
230
+ const listLines = this.renderList(token, 0);
231
+ lines.push(...listLines);
232
+ // Don't add spacing after lists if a space token follows
233
+ // (the space token will handle it)
234
+ break;
235
+ }
236
+ case "table": {
237
+ const tableLines = this.renderTable(token, width);
238
+ lines.push(...tableLines);
239
+ break;
240
+ }
241
+ case "blockquote": {
242
+ const quoteStyle = (text) => this.theme.quote(this.theme.italic(text));
243
+ const quoteStyleContext = {
244
+ applyText: quoteStyle,
245
+ stylePrefix: this.getStylePrefix(quoteStyle),
246
+ };
247
+ const quoteText = this.renderInlineTokens(token.tokens || [], quoteStyleContext);
248
+ const quoteLines = quoteText.split("\n");
249
+ // Calculate available width for quote content (subtract border "│ " = 2 chars)
250
+ const quoteContentWidth = Math.max(1, width - 2);
251
+ for (const quoteLine of quoteLines) {
252
+ // Wrap the styled line, then add border to each wrapped line
253
+ const wrappedLines = wrapTextWithAnsi(quoteLine, quoteContentWidth);
254
+ for (const wrappedLine of wrappedLines) {
255
+ lines.push(this.theme.quoteBorder("│ ") + wrappedLine);
256
+ }
257
+ }
258
+ if (nextTokenType !== "space") {
259
+ lines.push(""); // Add spacing after blockquotes (unless space token follows)
260
+ }
261
+ break;
262
+ }
263
+ case "hr":
264
+ lines.push(this.theme.hr("─".repeat(Math.min(width, 80))));
265
+ if (nextTokenType !== "space") {
266
+ lines.push(""); // Add spacing after horizontal rules (unless space token follows)
267
+ }
268
+ break;
269
+ case "html":
270
+ // Render HTML as plain text (escaped for terminal)
271
+ if ("raw" in token && typeof token.raw === "string") {
272
+ lines.push(this.applyDefaultStyle(token.raw.trim()));
273
+ }
274
+ break;
275
+ case "space":
276
+ // Space tokens represent blank lines in markdown
277
+ lines.push("");
278
+ break;
279
+ default:
280
+ // Handle any other token types as plain text
281
+ if ("text" in token && typeof token.text === "string") {
282
+ lines.push(token.text);
283
+ }
284
+ }
285
+ return lines;
286
+ }
287
+ renderInlineTokens(tokens, styleContext) {
288
+ let result = "";
289
+ const resolvedStyleContext = styleContext ?? this.getDefaultInlineStyleContext();
290
+ const { applyText, stylePrefix } = resolvedStyleContext;
291
+ const applyTextWithNewlines = (text) => {
292
+ const segments = text.split("\n");
293
+ return segments.map((segment) => applyText(segment)).join("\n");
294
+ };
295
+ for (const token of tokens) {
296
+ switch (token.type) {
297
+ case "text":
298
+ // Text tokens in list items can have nested tokens for inline formatting
299
+ if (token.tokens && token.tokens.length > 0) {
300
+ result += this.renderInlineTokens(token.tokens, resolvedStyleContext);
301
+ }
302
+ else {
303
+ result += applyTextWithNewlines(token.text);
304
+ }
305
+ break;
306
+ case "paragraph":
307
+ // Paragraph tokens contain nested inline tokens
308
+ result += this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
309
+ break;
310
+ case "strong": {
311
+ const boldContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
312
+ result += this.theme.bold(boldContent) + stylePrefix;
313
+ break;
314
+ }
315
+ case "em": {
316
+ const italicContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
317
+ result += this.theme.italic(italicContent) + stylePrefix;
318
+ break;
319
+ }
320
+ case "codespan":
321
+ result += this.theme.code(token.text) + stylePrefix;
322
+ break;
323
+ case "link": {
324
+ const linkText = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
325
+ // If link text matches href, only show the link once
326
+ // Compare raw text (token.text) not styled text (linkText) since linkText has ANSI codes
327
+ // For mailto: links, strip the prefix before comparing (autolinked emails have
328
+ // text="foo@bar.com" but href="mailto:foo@bar.com")
329
+ const hrefForComparison = token.href.startsWith("mailto:") ? token.href.slice(7) : token.href;
330
+ if (token.text === token.href || token.text === hrefForComparison) {
331
+ result += this.theme.link(this.theme.underline(linkText)) + stylePrefix;
332
+ }
333
+ else {
334
+ result +=
335
+ this.theme.link(this.theme.underline(linkText)) +
336
+ this.theme.linkUrl(` (${token.href})`) +
337
+ stylePrefix;
338
+ }
339
+ break;
340
+ }
341
+ case "br":
342
+ result += "\n";
343
+ break;
344
+ case "del": {
345
+ const delContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
346
+ result += this.theme.strikethrough(delContent) + stylePrefix;
347
+ break;
348
+ }
349
+ case "html":
350
+ // Render inline HTML as plain text
351
+ if ("raw" in token && typeof token.raw === "string") {
352
+ result += applyTextWithNewlines(token.raw);
353
+ }
354
+ break;
355
+ default:
356
+ // Handle any other inline token types as plain text
357
+ if ("text" in token && typeof token.text === "string") {
358
+ result += applyTextWithNewlines(token.text);
359
+ }
360
+ }
361
+ }
362
+ return result;
363
+ }
364
+ /**
365
+ * Render a list with proper nesting support
366
+ */
367
+ renderList(token, depth) {
368
+ const lines = [];
369
+ const indent = " ".repeat(depth);
370
+ // Use the list's start property (defaults to 1 for ordered lists)
371
+ const startNumber = token.start ?? 1;
372
+ for (let i = 0; i < token.items.length; i++) {
373
+ const item = token.items[i];
374
+ const bullet = token.ordered ? `${startNumber + i}. ` : "- ";
375
+ // Process item tokens to handle nested lists
376
+ const itemLines = this.renderListItem(item.tokens || [], depth);
377
+ if (itemLines.length > 0) {
378
+ // First line - check if it's a nested list
379
+ // A nested list will start with indent (spaces) followed by cyan bullet
380
+ const firstLine = itemLines[0];
381
+ const isNestedList = /^\s+\x1b\[36m[-\d]/.test(firstLine); // starts with spaces + cyan + bullet char
382
+ if (isNestedList) {
383
+ // This is a nested list, just add it as-is (already has full indent)
384
+ lines.push(firstLine);
385
+ }
386
+ else {
387
+ // Regular text content - add indent and bullet
388
+ lines.push(indent + this.theme.listBullet(bullet) + firstLine);
389
+ }
390
+ // Rest of the lines
391
+ for (let j = 1; j < itemLines.length; j++) {
392
+ const line = itemLines[j];
393
+ const isNestedListLine = /^\s+\x1b\[36m[-\d]/.test(line); // starts with spaces + cyan + bullet char
394
+ if (isNestedListLine) {
395
+ // Nested list line - already has full indent
396
+ lines.push(line);
397
+ }
398
+ else {
399
+ // Regular content - add parent indent + 2 spaces for continuation
400
+ lines.push(`${indent} ${line}`);
401
+ }
402
+ }
403
+ }
404
+ else {
405
+ lines.push(indent + this.theme.listBullet(bullet));
406
+ }
407
+ }
408
+ return lines;
409
+ }
410
+ /**
411
+ * Render list item tokens, handling nested lists
412
+ * Returns lines WITHOUT the parent indent (renderList will add it)
413
+ */
414
+ renderListItem(tokens, parentDepth) {
415
+ const lines = [];
416
+ for (const token of tokens) {
417
+ if (token.type === "list") {
418
+ // Nested list - render with one additional indent level
419
+ // These lines will have their own indent, so we just add them as-is
420
+ const nestedLines = this.renderList(token, parentDepth + 1);
421
+ lines.push(...nestedLines);
422
+ }
423
+ else if (token.type === "text") {
424
+ // Text content (may have inline tokens)
425
+ const text = token.tokens && token.tokens.length > 0 ? this.renderInlineTokens(token.tokens) : token.text || "";
426
+ lines.push(text);
427
+ }
428
+ else if (token.type === "paragraph") {
429
+ // Paragraph in list item
430
+ const text = this.renderInlineTokens(token.tokens || []);
431
+ lines.push(text);
432
+ }
433
+ else if (token.type === "code") {
434
+ // Code block in list item
435
+ const indent = this.theme.codeBlockIndent ?? " ";
436
+ lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
437
+ if (this.theme.highlightCode) {
438
+ const highlightedLines = this.theme.highlightCode(token.text, token.lang);
439
+ for (const hlLine of highlightedLines) {
440
+ lines.push(`${indent}${hlLine}`);
441
+ }
442
+ }
443
+ else {
444
+ const codeLines = token.text.split("\n");
445
+ for (const codeLine of codeLines) {
446
+ lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
447
+ }
448
+ }
449
+ lines.push(this.theme.codeBlockBorder("```"));
450
+ }
451
+ else {
452
+ // Other token types - try to render as inline
453
+ const text = this.renderInlineTokens([token]);
454
+ if (text) {
455
+ lines.push(text);
456
+ }
457
+ }
458
+ }
459
+ return lines;
460
+ }
461
+ /**
462
+ * Get the visible width of the longest word in a string.
463
+ */
464
+ getLongestWordWidth(text, maxWidth) {
465
+ const words = text.split(/\s+/).filter((word) => word.length > 0);
466
+ let longest = 0;
467
+ for (const word of words) {
468
+ longest = Math.max(longest, visibleWidth(word));
469
+ }
470
+ if (maxWidth === undefined) {
471
+ return longest;
472
+ }
473
+ return Math.min(longest, maxWidth);
474
+ }
475
+ /**
476
+ * Wrap a table cell to fit into a column.
477
+ *
478
+ * Delegates to wrapTextWithAnsi() so ANSI codes + long tokens are handled
479
+ * consistently with the rest of the renderer.
480
+ */
481
+ wrapCellText(text, maxWidth) {
482
+ return wrapTextWithAnsi(text, Math.max(1, maxWidth));
483
+ }
484
+ /**
485
+ * Render a table with width-aware cell wrapping.
486
+ * Cells that don't fit are wrapped to multiple lines.
487
+ */
488
+ renderTable(token, availableWidth) {
489
+ const lines = [];
490
+ const numCols = token.header.length;
491
+ if (numCols === 0) {
492
+ return lines;
493
+ }
494
+ // Calculate border overhead: "│ " + (n-1) * " │ " + " │"
495
+ // = 2 + (n-1) * 3 + 2 = 3n + 1
496
+ const borderOverhead = 3 * numCols + 1;
497
+ const availableForCells = availableWidth - borderOverhead;
498
+ if (availableForCells < numCols) {
499
+ // Too narrow to render a stable table. Fall back to raw markdown.
500
+ const fallbackLines = token.raw ? wrapTextWithAnsi(token.raw, availableWidth) : [];
501
+ fallbackLines.push("");
502
+ return fallbackLines;
503
+ }
504
+ const maxUnbrokenWordWidth = 30;
505
+ // Calculate natural column widths (what each column needs without constraints)
506
+ const naturalWidths = [];
507
+ const minWordWidths = [];
508
+ for (let i = 0; i < numCols; i++) {
509
+ const headerText = this.renderInlineTokens(token.header[i].tokens || []);
510
+ naturalWidths[i] = visibleWidth(headerText);
511
+ minWordWidths[i] = Math.max(1, this.getLongestWordWidth(headerText, maxUnbrokenWordWidth));
512
+ }
513
+ for (const row of token.rows) {
514
+ for (let i = 0; i < row.length; i++) {
515
+ const cellText = this.renderInlineTokens(row[i].tokens || []);
516
+ naturalWidths[i] = Math.max(naturalWidths[i] || 0, visibleWidth(cellText));
517
+ minWordWidths[i] = Math.max(minWordWidths[i] || 1, this.getLongestWordWidth(cellText, maxUnbrokenWordWidth));
518
+ }
519
+ }
520
+ let minColumnWidths = minWordWidths;
521
+ let minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
522
+ if (minCellsWidth > availableForCells) {
523
+ minColumnWidths = new Array(numCols).fill(1);
524
+ const remaining = availableForCells - numCols;
525
+ if (remaining > 0) {
526
+ const totalWeight = minWordWidths.reduce((total, width) => total + Math.max(0, width - 1), 0);
527
+ const growth = minWordWidths.map((width) => {
528
+ const weight = Math.max(0, width - 1);
529
+ return totalWeight > 0 ? Math.floor((weight / totalWeight) * remaining) : 0;
530
+ });
531
+ for (let i = 0; i < numCols; i++) {
532
+ minColumnWidths[i] += growth[i] ?? 0;
533
+ }
534
+ const allocated = growth.reduce((total, width) => total + width, 0);
535
+ let leftover = remaining - allocated;
536
+ for (let i = 0; leftover > 0 && i < numCols; i++) {
537
+ minColumnWidths[i]++;
538
+ leftover--;
539
+ }
540
+ }
541
+ minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
542
+ }
543
+ // Calculate column widths that fit within available width
544
+ const totalNaturalWidth = naturalWidths.reduce((a, b) => a + b, 0) + borderOverhead;
545
+ let columnWidths;
546
+ if (totalNaturalWidth <= availableWidth) {
547
+ // Everything fits naturally
548
+ columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index]));
549
+ }
550
+ else {
551
+ // Need to shrink columns to fit
552
+ const totalGrowPotential = naturalWidths.reduce((total, width, index) => {
553
+ return total + Math.max(0, width - minColumnWidths[index]);
554
+ }, 0);
555
+ const extraWidth = Math.max(0, availableForCells - minCellsWidth);
556
+ columnWidths = minColumnWidths.map((minWidth, index) => {
557
+ const naturalWidth = naturalWidths[index];
558
+ const minWidthDelta = Math.max(0, naturalWidth - minWidth);
559
+ let grow = 0;
560
+ if (totalGrowPotential > 0) {
561
+ grow = Math.floor((minWidthDelta / totalGrowPotential) * extraWidth);
562
+ }
563
+ return minWidth + grow;
564
+ });
565
+ // Adjust for rounding errors - distribute remaining space
566
+ const allocated = columnWidths.reduce((a, b) => a + b, 0);
567
+ let remaining = availableForCells - allocated;
568
+ while (remaining > 0) {
569
+ let grew = false;
570
+ for (let i = 0; i < numCols && remaining > 0; i++) {
571
+ if (columnWidths[i] < naturalWidths[i]) {
572
+ columnWidths[i]++;
573
+ remaining--;
574
+ grew = true;
575
+ }
576
+ }
577
+ if (!grew) {
578
+ break;
579
+ }
580
+ }
581
+ }
582
+ // Render top border
583
+ const topBorderCells = columnWidths.map((w) => "─".repeat(w));
584
+ lines.push(`┌─${topBorderCells.join("─┬─")}─┐`);
585
+ // Render header with wrapping
586
+ const headerCellLines = token.header.map((cell, i) => {
587
+ const text = this.renderInlineTokens(cell.tokens || []);
588
+ return this.wrapCellText(text, columnWidths[i]);
589
+ });
590
+ const headerLineCount = Math.max(...headerCellLines.map((c) => c.length));
591
+ for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) {
592
+ const rowParts = headerCellLines.map((cellLines, colIdx) => {
593
+ const text = cellLines[lineIdx] || "";
594
+ const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
595
+ return this.theme.bold(padded);
596
+ });
597
+ lines.push(`│ ${rowParts.join(" │ ")} │`);
598
+ }
599
+ // Render separator
600
+ const separatorCells = columnWidths.map((w) => "─".repeat(w));
601
+ const separatorLine = `├─${separatorCells.join("─┼─")}─┤`;
602
+ lines.push(separatorLine);
603
+ // Render rows with wrapping
604
+ for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
605
+ const row = token.rows[rowIndex];
606
+ const rowCellLines = row.map((cell, i) => {
607
+ const text = this.renderInlineTokens(cell.tokens || []);
608
+ return this.wrapCellText(text, columnWidths[i]);
609
+ });
610
+ const rowLineCount = Math.max(...rowCellLines.map((c) => c.length));
611
+ for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) {
612
+ const rowParts = rowCellLines.map((cellLines, colIdx) => {
613
+ const text = cellLines[lineIdx] || "";
614
+ return text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
615
+ });
616
+ lines.push(`│ ${rowParts.join(" │ ")} │`);
617
+ }
618
+ if (rowIndex < token.rows.length - 1) {
619
+ lines.push(separatorLine);
620
+ }
621
+ }
622
+ // Render bottom border
623
+ const bottomBorderCells = columnWidths.map((w) => "─".repeat(w));
624
+ lines.push(`└─${bottomBorderCells.join("─┴─")}─┘`);
625
+ lines.push(""); // Add spacing after table
626
+ return lines;
627
+ }
628
+ }
629
+ //# sourceMappingURL=markdown.js.map