pal-code 0.0.17 → 0.0.18
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.
- package/README.md +9 -6
- package/SYSTEM.md +17 -2
- package/package.json +10 -5
- package/packages/cli/src/agent-ui.ts +66 -0
- package/packages/cli/src/commands/ext-registry.ts +7 -0
- package/packages/cli/src/commands.ts +31 -101
- package/packages/cli/src/components/assistant-body.ts +2 -1
- package/packages/cli/src/components/message-box.ts +1 -1
- package/packages/cli/src/components/sidebar.ts +8 -2
- package/packages/cli/src/config.ts +6 -129
- package/packages/cli/src/index.ts +130 -43
- package/packages/cli/src/overlays/key-input.ts +140 -120
- package/packages/cli/src/overlays/model-picker.ts +19 -57
- package/packages/cli/src/overlays/select.ts +102 -0
- package/packages/cli/src/overlays/session-picker.ts +12 -39
- package/packages/cli/src/overlays/wizard.ts +107 -42
- package/packages/cli/src/prompt/select.ts +181 -0
- package/packages/cli/src/slash-commands.ts +105 -0
- package/packages/cli/src/state.ts +20 -74
- package/packages/cli/src/tui/render/markdown.ts +529 -0
- package/packages/cli/src/turn.ts +0 -298
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Markdown — renders CommonMark/GFM prose to styled terminal lines.
|
|
3
|
+
*
|
|
4
|
+
* pi-tui-free replacement for `Markdown` from @earendil-works/pi-tui. Same
|
|
5
|
+
* constructor signature and `Component` contract, so it drops straight into
|
|
6
|
+
* `AssistantBody`.
|
|
7
|
+
*
|
|
8
|
+
* Parsing is `marked` (already a transitive dependency via pi-tui, now declared
|
|
9
|
+
* directly); rendering is ours. Fenced code blocks go through the theme's
|
|
10
|
+
* `highlightCode` — the same function `tui/render/highlight.ts` provides — so
|
|
11
|
+
* code inside prose is styled identically to a standalone `CodeBlock`.
|
|
12
|
+
*
|
|
13
|
+
* Deliberate omissions versus pi-tui's implementation:
|
|
14
|
+
* - LaTeX math renders as plain source text, not converted to Unicode glyphs.
|
|
15
|
+
* - Images fall back to alt text; terminal image protocols are not used.
|
|
16
|
+
* Neither changes the public shape, so both can be added later.
|
|
17
|
+
*
|
|
18
|
+
* Adapted from @earendil-works/pi-tui's `dist/components/markdown.js` (MIT,
|
|
19
|
+
* © Mario Zechner, https://github.com/earendil-works/pi).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import {Marked, type Token, type Tokens} from 'marked';
|
|
23
|
+
|
|
24
|
+
import {truncateToWidth, visibleWidth, wrapTextWithAnsi} from '../tty-width.js';
|
|
25
|
+
import type {Component} from '../types.js';
|
|
26
|
+
import type {MarkdownTheme} from '../theme-types.js';
|
|
27
|
+
|
|
28
|
+
/** Base styling applied to all text unless a token overrides it. */
|
|
29
|
+
export interface DefaultTextStyle {
|
|
30
|
+
color?: (text: string) => string;
|
|
31
|
+
bgColor?: (text: string) => string;
|
|
32
|
+
bold?: boolean;
|
|
33
|
+
italic?: boolean;
|
|
34
|
+
strikethrough?: boolean;
|
|
35
|
+
underline?: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface MarkdownOptions {
|
|
39
|
+
/** Keep source list markers instead of normalizing them. */
|
|
40
|
+
preserveOrderedListMarkers?: boolean;
|
|
41
|
+
/** Keep source backslash escapes instead of normalizing them. */
|
|
42
|
+
preserveBackslashEscapes?: boolean;
|
|
43
|
+
/** Rewrite the source before parsing; receives the content width. */
|
|
44
|
+
transform?: (markdown: string, availableWidth: number) => string;
|
|
45
|
+
/** Reserved for LaTeX-to-Unicode rendering; currently ignored. */
|
|
46
|
+
renderLatex?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Shared parser — `gfm` gives tables and strikethrough, `breaks` matches pi. */
|
|
50
|
+
const parser = new Marked({gfm: true, breaks: true});
|
|
51
|
+
|
|
52
|
+
/** Default prefix applied to fenced code lines. */
|
|
53
|
+
const DEFAULT_CODE_INDENT = ' ';
|
|
54
|
+
|
|
55
|
+
export class Markdown implements Component {
|
|
56
|
+
private text: string;
|
|
57
|
+
private paddingX: number;
|
|
58
|
+
private paddingY: number;
|
|
59
|
+
private theme: MarkdownTheme;
|
|
60
|
+
private options: MarkdownOptions;
|
|
61
|
+
private defaultStylePrefix = '';
|
|
62
|
+
|
|
63
|
+
private cachedText?: string;
|
|
64
|
+
private cachedWidth?: number;
|
|
65
|
+
private cachedLines?: string[];
|
|
66
|
+
|
|
67
|
+
constructor(
|
|
68
|
+
text: string,
|
|
69
|
+
paddingX: number,
|
|
70
|
+
paddingY: number,
|
|
71
|
+
theme: MarkdownTheme,
|
|
72
|
+
defaultTextStyle?: DefaultTextStyle,
|
|
73
|
+
options: MarkdownOptions = {},
|
|
74
|
+
) {
|
|
75
|
+
this.text = text;
|
|
76
|
+
this.paddingX = paddingX;
|
|
77
|
+
this.paddingY = paddingY;
|
|
78
|
+
this.theme = theme;
|
|
79
|
+
this.options = options;
|
|
80
|
+
this.defaultStylePrefix = stylePrefix(defaultTextStyle);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
setText(text: string): void {
|
|
84
|
+
this.text = text;
|
|
85
|
+
this.invalidate();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
invalidate(): void {
|
|
89
|
+
this.cachedText = undefined;
|
|
90
|
+
this.cachedWidth = undefined;
|
|
91
|
+
this.cachedLines = undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
render(width: number): string[] {
|
|
95
|
+
if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) {
|
|
96
|
+
return this.cachedLines;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const inner = Math.max(1, width - this.paddingX * 2);
|
|
100
|
+
const source = this.options.transform ? this.options.transform(this.text, inner) : this.text;
|
|
101
|
+
|
|
102
|
+
const ctx: RenderCtx = {
|
|
103
|
+
theme: this.theme,
|
|
104
|
+
width: inner,
|
|
105
|
+
options: this.options,
|
|
106
|
+
prefix: this.defaultStylePrefix,
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
let lines: string[];
|
|
110
|
+
try {
|
|
111
|
+
lines = parser.lexer(source).flatMap((t) => renderBlock(t, ctx));
|
|
112
|
+
} catch {
|
|
113
|
+
// A malformed document must still read as text rather than blank the
|
|
114
|
+
// transcript.
|
|
115
|
+
lines = wrapTextWithAnsi(source, inner);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Trim leading/trailing blanks so a document does not open with a gap.
|
|
119
|
+
while (lines.length && lines[0].trim() === '') lines.shift();
|
|
120
|
+
while (lines.length && lines[lines.length - 1].trim() === '') lines.pop();
|
|
121
|
+
|
|
122
|
+
const margin = ' '.repeat(this.paddingX);
|
|
123
|
+
const out: string[] = [];
|
|
124
|
+
for (const line of lines) {
|
|
125
|
+
const pad = Math.max(0, inner - visibleWidth(line));
|
|
126
|
+
out.push(margin + line + ' '.repeat(pad) + margin);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const blank = ' '.repeat(width);
|
|
130
|
+
const result = [
|
|
131
|
+
...Array.from({length: this.paddingY}, () => blank),
|
|
132
|
+
...out,
|
|
133
|
+
...Array.from({length: this.paddingY}, () => blank),
|
|
134
|
+
];
|
|
135
|
+
|
|
136
|
+
this.cachedText = this.text;
|
|
137
|
+
this.cachedWidth = width;
|
|
138
|
+
this.cachedLines = result;
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
interface RenderCtx {
|
|
144
|
+
theme: MarkdownTheme;
|
|
145
|
+
width: number;
|
|
146
|
+
options: MarkdownOptions;
|
|
147
|
+
/** Style applied to plain text, composed once up front. */
|
|
148
|
+
prefix: string;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function stylePrefix(style?: DefaultTextStyle): string {
|
|
152
|
+
if (!style) return '';
|
|
153
|
+
// Background colours are applied at the padding stage, not here.
|
|
154
|
+
return [
|
|
155
|
+
style.bold ? '\x1b[1m' : '',
|
|
156
|
+
style.italic ? '\x1b[3m' : '',
|
|
157
|
+
style.strikethrough ? '\x1b[9m' : '',
|
|
158
|
+
style.underline ? '\x1b[4m' : '',
|
|
159
|
+
style.color ? style.color('') : '',
|
|
160
|
+
].join('');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ---------------------------------------------------------------------------
|
|
164
|
+
// Block level
|
|
165
|
+
// ---------------------------------------------------------------------------
|
|
166
|
+
|
|
167
|
+
function renderBlock(token: Token, ctx: RenderCtx): string[] {
|
|
168
|
+
// `marked` types every discriminated member as `X | Generic`, so the switch
|
|
169
|
+
// must cast to the concrete shape to reach fields like `depth` or `items`.
|
|
170
|
+
const t = token as Token & Record<string, unknown>;
|
|
171
|
+
switch (token.type) {
|
|
172
|
+
case 'heading':
|
|
173
|
+
return renderHeading(t as unknown as Tokens.Heading, ctx);
|
|
174
|
+
case 'paragraph':
|
|
175
|
+
return wrapTextWithAnsi(
|
|
176
|
+
renderInline((t as unknown as Tokens.Paragraph).tokens, ctx),
|
|
177
|
+
ctx.width,
|
|
178
|
+
);
|
|
179
|
+
case 'text':
|
|
180
|
+
return renderTextBlock(t as unknown as Tokens.Text, ctx);
|
|
181
|
+
case 'code':
|
|
182
|
+
return renderCode(t as unknown as Tokens.Code, ctx);
|
|
183
|
+
case 'blockquote':
|
|
184
|
+
return renderBlockquote(t as unknown as Tokens.Blockquote, ctx);
|
|
185
|
+
case 'hr':
|
|
186
|
+
return [ctx.theme.hr('─'.repeat(Math.max(1, ctx.width - 1)))];
|
|
187
|
+
case 'list':
|
|
188
|
+
return renderList(t as unknown as Tokens.List, ctx);
|
|
189
|
+
case 'table':
|
|
190
|
+
return renderTable(t as unknown as Tokens.Table, ctx);
|
|
191
|
+
case 'space':
|
|
192
|
+
return [];
|
|
193
|
+
case 'html':
|
|
194
|
+
// Raw HTML carries no terminal meaning; show the tags literally.
|
|
195
|
+
return wrapTextWithAnsi(ctx.theme.codeBlock(t.text as string), ctx.width);
|
|
196
|
+
case 'text_token':
|
|
197
|
+
return renderUnknown(token, ctx);
|
|
198
|
+
default:
|
|
199
|
+
return renderUnknown(token, ctx);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function renderHeading(token: Tokens.Heading, ctx: RenderCtx): string[] {
|
|
204
|
+
const body = renderInline(token.tokens, ctx);
|
|
205
|
+
// H1–H3 take the heading style; H4+ gets bold only so deep nesting does
|
|
206
|
+
// not shout louder than the title.
|
|
207
|
+
const styled = token.depth >= 4 ? ctx.theme.bold(body) : ctx.theme.heading(body);
|
|
208
|
+
return wrapTextWithAnsi(styled, ctx.width);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function renderTextBlock(token: Tokens.Text, ctx: RenderCtx): string[] {
|
|
212
|
+
const inner = token.tokens?.length ? renderInline(token.tokens, ctx) : ctx.prefix + token.text;
|
|
213
|
+
return inner.split('\n').flatMap((line) => wrapTextWithAnsi(line, ctx.width));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function renderCode(token: Tokens.Code, ctx: RenderCtx): string[] {
|
|
217
|
+
const highlight = ctx.theme.highlightCode;
|
|
218
|
+
if (highlight) {
|
|
219
|
+
const indent = ctx.theme.codeBlockIndent ?? DEFAULT_CODE_INDENT;
|
|
220
|
+
return highlight(token.text, token.lang || undefined).map((line) => indent + line);
|
|
221
|
+
}
|
|
222
|
+
return wrapTextWithAnsi(ctx.theme.codeBlock(token.text), ctx.width);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function renderBlockquote(token: Tokens.Blockquote, ctx: RenderCtx): string[] {
|
|
226
|
+
const nested: RenderCtx = {...ctx, width: Math.max(1, ctx.width - 2)};
|
|
227
|
+
const body = token.tokens.flatMap((child) => renderBlock(child, nested));
|
|
228
|
+
const bar = ctx.theme.quoteBorder('│');
|
|
229
|
+
return body.map((line) => `${bar} ${ctx.theme.quote(line)}`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function renderList(token: Tokens.List, ctx: RenderCtx): string[] {
|
|
233
|
+
const lines: string[] = [];
|
|
234
|
+
const start = token.start === '' ? 1 : token.start;
|
|
235
|
+
token.items.forEach((item, i) => {
|
|
236
|
+
if (i > 0) lines.push('');
|
|
237
|
+
// marked keeps `task`/`checked` on the item and also emits a leading
|
|
238
|
+
// `checkbox` token (which renderInlineToken ignores), so the marker is
|
|
239
|
+
// built here from the item fields — never from the token text.
|
|
240
|
+
const marker = token.ordered
|
|
241
|
+
? `${start + i}.`
|
|
242
|
+
: ctx.theme.listBullet(item.task ? (item.checked ? '[x]' : '[ ]') : '•');
|
|
243
|
+
lines.push(...renderListItem(item, marker, ctx));
|
|
244
|
+
});
|
|
245
|
+
return lines;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function renderListItem(item: Tokens.ListItem, marker: string, ctx: RenderCtx): string[] {
|
|
249
|
+
// The marker can carry ANSI (listBullet), so measure its painted width.
|
|
250
|
+
const gap = visibleWidth(marker) + 1;
|
|
251
|
+
const nested: RenderCtx = {...ctx, width: Math.max(1, ctx.width - gap)};
|
|
252
|
+
// A task item leads with a `checkbox` token; the marker already shows the
|
|
253
|
+
// state, so drop it and let the following `text` share the marker's row.
|
|
254
|
+
const blocks = item.task ? item.tokens.filter((b) => b.type !== 'checkbox') : item.tokens;
|
|
255
|
+
const out: string[] = [];
|
|
256
|
+
|
|
257
|
+
const first = blocks[0];
|
|
258
|
+
if (first?.type === 'text') {
|
|
259
|
+
// Tight item: the leading paragraph shares the marker's row.
|
|
260
|
+
const head = renderTextBlock(first as unknown as Tokens.Text, nested);
|
|
261
|
+
head.forEach((line, i) => {
|
|
262
|
+
out.push(i === 0 ? `${marker} ${line}` : `${' '.repeat(gap)}${line}`);
|
|
263
|
+
});
|
|
264
|
+
for (const child of blocks.slice(1)) {
|
|
265
|
+
out.push(...indentAll(renderBlock(child, nested), gap));
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
out.push(marker);
|
|
269
|
+
for (const child of blocks) {
|
|
270
|
+
out.push(...indentAll(renderBlock(child, nested), gap));
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Tight items carry no trailing blank; the caller inserts one between items.
|
|
275
|
+
if (!item.loose) {
|
|
276
|
+
while (out.length && out[out.length - 1].trim() === '') out.pop();
|
|
277
|
+
}
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Per-column alignment from a GFM delimiter row. */
|
|
282
|
+
type ColumnAlign = 'left' | 'center' | 'right' | null;
|
|
283
|
+
|
|
284
|
+
/** Longest word a column will refuse to break mid-word for. */
|
|
285
|
+
const MAX_UNBROKEN_WORD = 30;
|
|
286
|
+
|
|
287
|
+
function renderTable(token: Tokens.Table, ctx: RenderCtx): string[] {
|
|
288
|
+
const nCols = token.header.length;
|
|
289
|
+
if (nCols === 0) return [];
|
|
290
|
+
|
|
291
|
+
// Boxed layout: "│ " + n * w + (n-1) * " │ " + " │" costs 3n + 1 columns of
|
|
292
|
+
// border. That overhead is what makes a table impossible to fit once n grows,
|
|
293
|
+
// so it is charged before any cell gets a column.
|
|
294
|
+
const borderOverhead = 3 * nCols + 1;
|
|
295
|
+
const available = ctx.width - borderOverhead;
|
|
296
|
+
if (available < nCols) return renderUnfittableTable(token, ctx);
|
|
297
|
+
|
|
298
|
+
// Bold the header cells up front so the widths budget what will actually be
|
|
299
|
+
// painted. A theme whose `bold` wrapper adds visible columns (rather than
|
|
300
|
+
// ANSI-only codes) would otherwise widen every header cell after the fact and
|
|
301
|
+
// push the header row past the borders.
|
|
302
|
+
const headerText = token.header.map((c) => ctx.theme.bold(renderInline(c.tokens, ctx)));
|
|
303
|
+
const bodyText = token.rows.map((r) => r.map((c) => renderInline(c.tokens, ctx)));
|
|
304
|
+
const align = (token.align ?? []) as ColumnAlign[];
|
|
305
|
+
|
|
306
|
+
const natural: number[] = [];
|
|
307
|
+
const floor: number[] = [];
|
|
308
|
+
for (let c = 0; c < nCols; c++) {
|
|
309
|
+
const texts = [headerText[c] ?? '', ...bodyText.map((r) => r[c] ?? '')];
|
|
310
|
+
natural[c] = Math.max(...texts.map(visibleWidth));
|
|
311
|
+
// A column wider than its longest word would break that word across lines;
|
|
312
|
+
// hold it at the longest word so text wraps on spaces where it can.
|
|
313
|
+
floor[c] = Math.max(1, longestWordWidth(texts.join(' '), MAX_UNBROKEN_WORD));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const widths = fitWidths(natural, floor, available);
|
|
317
|
+
const border = (l: string, m: string, r: string): string =>
|
|
318
|
+
ctx.theme.hr(`${l}─${widths.map((w) => '─'.repeat(w)).join(`─${m}─`)}─${r}`);
|
|
319
|
+
|
|
320
|
+
// A cell wraps into as many lines as it needs; the row is as tall as its
|
|
321
|
+
// tallest cell, and every other cell is padded to match.
|
|
322
|
+
const emitRow = (cells: string[]): string[] => {
|
|
323
|
+
const wrapped = widths.map((w, c) => wrapStyledCell(cells[c] ?? '', w));
|
|
324
|
+
const height = Math.max(1, ...wrapped.map((l) => l.length));
|
|
325
|
+
const out: string[] = [];
|
|
326
|
+
for (let row = 0; row < height; row++) {
|
|
327
|
+
const parts = widths.map((w, c) =>
|
|
328
|
+
alignCell(wrapped[c]![row] ?? '', w, align[c] ?? null),
|
|
329
|
+
);
|
|
330
|
+
out.push(`│ ${parts.join(' │ ')} │`);
|
|
331
|
+
}
|
|
332
|
+
return out;
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
const separator = border('├', '┼', '┤');
|
|
336
|
+
return [
|
|
337
|
+
border('┌', '┬', '┐'),
|
|
338
|
+
...emitRow(headerText),
|
|
339
|
+
separator,
|
|
340
|
+
...bodyText.flatMap((cells, i) => [
|
|
341
|
+
...emitRow(cells),
|
|
342
|
+
...(i < bodyText.length - 1 ? [separator] : []),
|
|
343
|
+
]),
|
|
344
|
+
border('└', '┴', '┘'),
|
|
345
|
+
];
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Too narrow for even one column per cell. The bordered layout cannot express
|
|
350
|
+
* this, so fall back to the source text — the same escape pi-tui uses, and the
|
|
351
|
+
* honest answer: a table this wide does not belong on this terminal.
|
|
352
|
+
*/
|
|
353
|
+
function renderUnfittableTable(token: Tokens.Table, ctx: RenderCtx): string[] {
|
|
354
|
+
const raw = typeof token.raw === 'string' ? token.raw : '';
|
|
355
|
+
return raw ? wrapTextWithAnsi(raw, ctx.width) : [];
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Pad or ellipsize `text` to exactly `width` visible columns, honouring `align`. */
|
|
359
|
+
function alignCell(text: string, width: number, align: ColumnAlign): string {
|
|
360
|
+
const w = visibleWidth(text);
|
|
361
|
+
if (w > width) return truncateToWidth(text, width, '…');
|
|
362
|
+
const slack = width - w;
|
|
363
|
+
if (slack === 0) return text;
|
|
364
|
+
if (align === 'right') return ' '.repeat(slack) + text;
|
|
365
|
+
if (align === 'center') {
|
|
366
|
+
const left = Math.floor(slack / 2);
|
|
367
|
+
return ' '.repeat(left) + text + ' '.repeat(slack - left);
|
|
368
|
+
}
|
|
369
|
+
return text + ' '.repeat(slack);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Wrap already-styled cell text to `width`, closing styles at each line end.
|
|
374
|
+
*
|
|
375
|
+
* The text reaching here already carries the cell's own styling (a bold header,
|
|
376
|
+
* a coloured code span), and `wrapTextWithAnsi` wraps on *visible* characters
|
|
377
|
+
* only — it cannot tell a style wrapper from content. A theme that decorates
|
|
378
|
+
* with visible characters rather than escape codes therefore has its wrapper
|
|
379
|
+
* broken across lines, losing characters. Escaping the decoration first keeps
|
|
380
|
+
* the wrapper intact and the content lossless.
|
|
381
|
+
*/
|
|
382
|
+
function wrapStyledCell(text: string, width: number): string[] {
|
|
383
|
+
return wrapTextWithAnsi(escapeVisibleStyleWrappers(text), Math.max(1, width)).map(
|
|
384
|
+
(line, i, all) => (i < all.length - 1 ? `${line}\x1b[22;23;24;25;27;28;29;39m` : line),
|
|
385
|
+
);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const ANSI_SEQUENCE = /\x1b\[[0-9;]*m/g;
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Hide visible decoration added by a theme wrapper so wrapping cannot split it.
|
|
392
|
+
*
|
|
393
|
+
* Only balanced decoration is touched — a leading run that is matched by a
|
|
394
|
+
* closing run at the end — so ordinary text that merely starts with a letter or
|
|
395
|
+
* a bracket is left alone. ANSI sequences pass through untouched.
|
|
396
|
+
*/
|
|
397
|
+
function escapeVisibleStyleWrappers(text: string): string {
|
|
398
|
+
if (!text.includes('\x1b') && !/[A-Za-z]/.test(text)) return text;
|
|
399
|
+
const visible = text.replace(ANSI_SEQUENCE, '');
|
|
400
|
+
if (!/^[^\s\w]{0,4}[\w[\]{}<>/+*#-]/.test(visible)) return text;
|
|
401
|
+
|
|
402
|
+
// Only rewrite when the decoration is a repeated token at both ends.
|
|
403
|
+
const open = visible.match(/^([^\s\w]{1,4})/);
|
|
404
|
+
const close = visible.match(/([^\s\w]{1,4})$/);
|
|
405
|
+
if (!open || !close || open[1] !== close[1]) return text;
|
|
406
|
+
const wrapper = open[1];
|
|
407
|
+
if (!wrapper || /[│┌├└─]/.test(wrapper)) return text;
|
|
408
|
+
|
|
409
|
+
return text.replace(ANSI_SEQUENCE, '').split(wrapper).join(`\x1b[0m${wrapper}\x1b[0m`);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Width of the widest whitespace-delimited word in `text`, capped at `max`. */
|
|
413
|
+
function longestWordWidth(text: string, max: number): number {
|
|
414
|
+
let longest = 0;
|
|
415
|
+
for (const word of text.split(/\s+/)) {
|
|
416
|
+
if (word.length > 0) longest = Math.max(longest, visibleWidth(word));
|
|
417
|
+
}
|
|
418
|
+
return Math.min(longest, max);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Pick column widths that fit `available` (the width left after borders).
|
|
423
|
+
*
|
|
424
|
+
* Starts from each column's longest word so text wraps on spaces rather than
|
|
425
|
+
* breaking mid-word, then grows the columns towards their natural width,
|
|
426
|
+
* handing out the remaining slack round-robin so no column is starved by a
|
|
427
|
+
* neighbour that grew first.
|
|
428
|
+
*
|
|
429
|
+
* The longest-word floor is a preference, not a guarantee: one unbreakable
|
|
430
|
+
* 40-character word in a narrow table would otherwise demand more than the
|
|
431
|
+
* whole budget and push the bordered row past the content width. So the sum is
|
|
432
|
+
* clamped to `available` first, and every column is then held to at least one
|
|
433
|
+
* column — which `available >= nCols` makes possible.
|
|
434
|
+
*/
|
|
435
|
+
function fitWidths(natural: number[], floor: number[], available: number): number[] {
|
|
436
|
+
const n = natural.length;
|
|
437
|
+
const widths = natural.map((_, c) => Math.max(1, Math.min(floor[c]!, natural[c]!)));
|
|
438
|
+
|
|
439
|
+
let used = widths.reduce((a, b) => a + b, 0);
|
|
440
|
+
if (used > available) {
|
|
441
|
+
// Shrink the widest columns first until the budget is met.
|
|
442
|
+
while (used > available) {
|
|
443
|
+
let widest = 0;
|
|
444
|
+
for (let c = 1; c < n; c++) {
|
|
445
|
+
if (widths[c]! > widths[widest]!) widest = c;
|
|
446
|
+
}
|
|
447
|
+
if (widths[widest]! <= 1) break;
|
|
448
|
+
widths[widest]!--;
|
|
449
|
+
used--;
|
|
450
|
+
}
|
|
451
|
+
return widths;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
let slack = available - used;
|
|
455
|
+
let grew = true;
|
|
456
|
+
while (slack > 0 && grew) {
|
|
457
|
+
grew = false;
|
|
458
|
+
for (let c = 0; c < n && slack > 0; c++) {
|
|
459
|
+
if (widths[c]! < natural[c]!) {
|
|
460
|
+
widths[c]!++;
|
|
461
|
+
slack--;
|
|
462
|
+
grew = true;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return widths;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function renderUnknown(token: Token, ctx: RenderCtx): string[] {
|
|
470
|
+
const generic = token as {tokens?: Token[]; text?: string};
|
|
471
|
+
if (Array.isArray(generic.tokens)) {
|
|
472
|
+
return generic.tokens.flatMap((child) => renderBlock(child, ctx));
|
|
473
|
+
}
|
|
474
|
+
if (typeof generic.text === 'string' && generic.text) {
|
|
475
|
+
return wrapTextWithAnsi(generic.text, ctx.width);
|
|
476
|
+
}
|
|
477
|
+
return [];
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function indentAll(lines: string[], by: number): string[] {
|
|
481
|
+
const pad = ' '.repeat(by);
|
|
482
|
+
return lines.map((l) => (l.trim() === '' ? l : pad + l));
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// ---------------------------------------------------------------------------
|
|
486
|
+
// Inline level
|
|
487
|
+
// ---------------------------------------------------------------------------
|
|
488
|
+
|
|
489
|
+
function renderInline(tokens: Token[] | undefined, ctx: RenderCtx): string {
|
|
490
|
+
if (!tokens?.length) return '';
|
|
491
|
+
return tokens.map((t) => renderInlineToken(t, ctx)).join('');
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function renderInlineToken(token: Token, ctx: RenderCtx): string {
|
|
495
|
+
switch (token.type) {
|
|
496
|
+
case 'text':
|
|
497
|
+
return ctx.prefix + token.text;
|
|
498
|
+
case 'escape':
|
|
499
|
+
return ctx.prefix + token.text;
|
|
500
|
+
case 'strong':
|
|
501
|
+
return ctx.theme.bold(renderInline(token.tokens, ctx));
|
|
502
|
+
case 'em':
|
|
503
|
+
return ctx.theme.italic(renderInline(token.tokens, ctx));
|
|
504
|
+
case 'del':
|
|
505
|
+
return ctx.theme.strikethrough(renderInline(token.tokens, ctx));
|
|
506
|
+
case 'codespan':
|
|
507
|
+
return ctx.theme.code(token.text);
|
|
508
|
+
case 'br':
|
|
509
|
+
return '\n';
|
|
510
|
+
case 'link': {
|
|
511
|
+
const label = renderInline(token.tokens, ctx);
|
|
512
|
+
// Only show the URL when it says something the label does not.
|
|
513
|
+
const suffix =
|
|
514
|
+
token.href && token.href !== token.text ? ` (${ctx.theme.linkUrl(token.href)})` : '';
|
|
515
|
+
return `${ctx.theme.link(label)}${suffix}`;
|
|
516
|
+
}
|
|
517
|
+
case 'image':
|
|
518
|
+
// No terminal image protocol — alt text is the honest fallback.
|
|
519
|
+
return ctx.theme.italic(token.text);
|
|
520
|
+
case 'html':
|
|
521
|
+
return ctx.theme.code(token.text);
|
|
522
|
+
default: {
|
|
523
|
+
const generic = token as {tokens?: Token[]; text?: string};
|
|
524
|
+
if (Array.isArray(generic.tokens)) return renderInline(generic.tokens, ctx);
|
|
525
|
+
if (typeof generic.text === 'string') return ctx.prefix + generic.text;
|
|
526
|
+
return '';
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|