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