@intellectual-frontiers/terminal 0.0.0-stage → 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.
package/dist/vt.js ADDED
@@ -0,0 +1,486 @@
1
+ // Spec: 0001-terminal FR-005
2
+ /**
3
+ * A small terminal emulator for snapshot tests (commons 0006-signals FR-025): a screen a given number of columns wide, either growing as it
4
+ * is written to (no height) or a given number of rows high and scrolling, that is fed what a program writes and shows what a person would
5
+ * see after it: the text, each cell's style kept apart from it, and the cursor.
6
+ *
7
+ * What it understands, as xterm does:
8
+ * - printable text by grapheme and display width (`width.ts`): a wide character or emoji takes two cells (the second a continuation), a
9
+ * combining mark or another zero-width grapheme joins the cell before; a character that does not fit in the last column wraps to the next
10
+ * line (autowrap with the wrap deferred until the next character, so a line exactly as wide as the screen does not add an empty one), and a
11
+ * wide character that would cross the right edge wraps whole, leaving the last cell empty;
12
+ * - CR, LF (also VT and FF), BS and TAB (stops every eight columns); LF also returns the carriage by default (`newline: "crlf"`, as a
13
+ * terminal's line discipline turns a program's "\n" into CR LF), or only moves down (`newline: "lf"`);
14
+ * - CSI cursor up, down, forward and back (A, B, C, D), next and previous line (E, F), column (G), row (d), position (H, f), save and
15
+ * restore (s, u, and ESC 7, ESC 8), erase in line (K 0, 1, 2) and in display (J 0, 1, 2, 3), and SGR (m: bold, dim, italic, underline,
16
+ * blink, inverse, hidden, strike, their resets, the 8, 16, 256 and 24-bit colours of text and background);
17
+ * - cursor shown and hidden (CSI ? 25 h and l), kept in `cursor().visible`;
18
+ * - every other control sequence, other private mode, OSC, DCS, APC, PM and SOS string, other escape and other control character: read
19
+ * and ignored. A sequence may be split across writes; bytes are decoded as UTF-8 across writes too.
20
+ *
21
+ * Erased cells take no style. A grapheme split across two writes is seen as two (the second joins the first cell, without changing its
22
+ * width).
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { createScreen } from "./vt.ts";
27
+ * const s = createScreen({ width: 20 });
28
+ * s.write("building\n\u001b[32m✅\u001b[0m done");
29
+ * s.write("\u001b[1A\r\u001b[2Kbuilt");
30
+ * s.text(); // "built\n✅ done"
31
+ * s.cell(1, 0)?.style.fg; // { kind: "indexed", index: 2 }
32
+ * ```
33
+ *
34
+ * @module
35
+ */
36
+ import { absurd } from "@intellectual-frontiers/core";
37
+ import { graphemes, graphemeWidth } from "./width.js";
38
+ const DEFAULT = { kind: "default" };
39
+ /** The style of a cell nothing styled: every attribute off, default colours. */
40
+ export const PLAIN = {
41
+ bold: false,
42
+ dim: false,
43
+ italic: false,
44
+ underline: false,
45
+ blink: false,
46
+ inverse: false,
47
+ hidden: false,
48
+ strike: false,
49
+ fg: DEFAULT,
50
+ bg: DEFAULT,
51
+ };
52
+ const colourName = (c) => {
53
+ switch (c.kind) {
54
+ case "default":
55
+ return "default";
56
+ case "indexed":
57
+ return String(c.index);
58
+ case "rgb":
59
+ return `#${[c.r, c.g, c.b].map((n) => n.toString(16).padStart(2, "0")).join("")}`;
60
+ default:
61
+ return absurd(c);
62
+ }
63
+ };
64
+ /** A style in words, for a snapshot: the attributes on, then `fg=` and `bg=` where not the default; "" for `PLAIN`. */
65
+ export function describeStyle(style) {
66
+ const words = [];
67
+ for (const a of ["bold", "dim", "italic", "underline", "blink", "inverse", "hidden", "strike"])
68
+ if (style[a])
69
+ words.push(a);
70
+ if (style.fg.kind !== "default")
71
+ words.push(`fg=${colourName(style.fg)}`);
72
+ if (style.bg.kind !== "default")
73
+ words.push(`bg=${colourName(style.bg)}`);
74
+ return words.join(" ");
75
+ }
76
+ /** Whether two styles draw the same. */
77
+ export function sameStyle(a, b) {
78
+ return describeStyle(a) === describeStyle(b);
79
+ }
80
+ const BLANK = { text: " ", width: 1, style: PLAIN };
81
+ const CONTINUATION = (style) => ({ text: "", width: 0, style });
82
+ /** A new, empty screen with the cursor at the top left, shown. */
83
+ export function createScreen(options) {
84
+ const width = Math.max(1, Math.floor(options.width));
85
+ const height = options.height === undefined ? undefined : Math.max(1, Math.floor(options.height));
86
+ const crlf = (options.newline ?? "crlf") === "crlf";
87
+ const rows = [];
88
+ const decoder = new TextDecoder();
89
+ let row = 0;
90
+ let col = 0;
91
+ let pending = false;
92
+ let visible = true;
93
+ let style = PLAIN;
94
+ let saved = { row: 0, col: 0, style: PLAIN };
95
+ let state = "ground";
96
+ let seq = "";
97
+ let text = "";
98
+ const blankRow = () => Array.from({ length: width }, () => BLANK);
99
+ const line = (r) => {
100
+ while (rows.length <= r)
101
+ rows.push(blankRow());
102
+ return rows[r] ?? blankRow();
103
+ };
104
+ const maxRow = () => (height === undefined ? Number.MAX_SAFE_INTEGER : height - 1);
105
+ const clampCol = (c) => Math.min(width - 1, Math.max(0, c));
106
+ const clampRow = (r) => Math.min(maxRow(), Math.max(0, r));
107
+ const linefeed = () => {
108
+ if (height !== undefined && row === height - 1) {
109
+ line(height - 1);
110
+ rows.shift();
111
+ rows.push(blankRow());
112
+ }
113
+ else {
114
+ row++;
115
+ }
116
+ };
117
+ /** Blanks columns `from` to `to` (inclusive) of a row, with the halves of wide characters cut by the edges. */
118
+ const blank = (r, from, to) => {
119
+ const l = line(r);
120
+ let a = Math.max(0, from);
121
+ let b = Math.min(width - 1, to);
122
+ if (a > b)
123
+ return;
124
+ if (l[a]?.width === 0 && a > 0)
125
+ a--;
126
+ if (l[b]?.width === 2 && b < width - 1)
127
+ b++;
128
+ for (let c = a; c <= b; c++)
129
+ l[c] = BLANK;
130
+ };
131
+ const put = (g, w) => {
132
+ const l = line(row);
133
+ blank(row, col, col + w - 1);
134
+ l[col] = { text: g, width: w, style };
135
+ if (w === 2 && col + 1 < width)
136
+ l[col + 1] = CONTINUATION(style);
137
+ };
138
+ const print = (chunk) => {
139
+ for (const g of graphemes(chunk)) {
140
+ const w = graphemeWidth(g);
141
+ if (w === 0) {
142
+ const cp = g.codePointAt(0) ?? 0;
143
+ if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0))
144
+ continue;
145
+ let c = pending ? col : col - 1;
146
+ const l = line(row);
147
+ if (l[c]?.width === 0)
148
+ c--;
149
+ const cell = l[c];
150
+ if (c >= 0 && cell !== undefined)
151
+ l[c] = { ...cell, text: cell.text + g };
152
+ continue;
153
+ }
154
+ if (pending) {
155
+ col = 0;
156
+ linefeed();
157
+ pending = false;
158
+ }
159
+ if (col + w > width && col > 0) {
160
+ col = 0;
161
+ linefeed();
162
+ }
163
+ put(g, w > width ? 1 : w);
164
+ col += Math.min(w, width);
165
+ if (col >= width) {
166
+ col = width - 1;
167
+ pending = true;
168
+ }
169
+ }
170
+ };
171
+ const flush = () => {
172
+ if (text !== "")
173
+ print(text);
174
+ text = "";
175
+ };
176
+ const sgr = (params) => {
177
+ const ps = params.length === 0 ? [0] : params;
178
+ const extended = (i) => {
179
+ if (ps[i + 1] === 5)
180
+ return { colour: { kind: "indexed", index: (ps[i + 2] ?? 0) & 0xff }, used: 2 };
181
+ if (ps[i + 1] === 2) {
182
+ const at = (k) => (ps[i + k] ?? 0) & 0xff;
183
+ return { colour: { kind: "rgb", r: at(2), g: at(3), b: at(4) }, used: 4 };
184
+ }
185
+ return { colour: DEFAULT, used: 0 };
186
+ };
187
+ for (let i = 0; i < ps.length; i++) {
188
+ const p = ps[i] ?? 0;
189
+ if (p === 0)
190
+ style = PLAIN;
191
+ else if (p === 1)
192
+ style = { ...style, bold: true };
193
+ else if (p === 2)
194
+ style = { ...style, dim: true };
195
+ else if (p === 3)
196
+ style = { ...style, italic: true };
197
+ else if (p === 4)
198
+ style = { ...style, underline: true };
199
+ else if (p === 5 || p === 6)
200
+ style = { ...style, blink: true };
201
+ else if (p === 7)
202
+ style = { ...style, inverse: true };
203
+ else if (p === 8)
204
+ style = { ...style, hidden: true };
205
+ else if (p === 9)
206
+ style = { ...style, strike: true };
207
+ else if (p === 21 || p === 24)
208
+ style = { ...style, underline: false };
209
+ else if (p === 22)
210
+ style = { ...style, bold: false, dim: false };
211
+ else if (p === 23)
212
+ style = { ...style, italic: false };
213
+ else if (p === 25)
214
+ style = { ...style, blink: false };
215
+ else if (p === 27)
216
+ style = { ...style, inverse: false };
217
+ else if (p === 28)
218
+ style = { ...style, hidden: false };
219
+ else if (p === 29)
220
+ style = { ...style, strike: false };
221
+ else if (p >= 30 && p <= 37)
222
+ style = { ...style, fg: { kind: "indexed", index: p - 30 } };
223
+ else if (p === 39)
224
+ style = { ...style, fg: DEFAULT };
225
+ else if (p >= 40 && p <= 47)
226
+ style = { ...style, bg: { kind: "indexed", index: p - 40 } };
227
+ else if (p === 49)
228
+ style = { ...style, bg: DEFAULT };
229
+ else if (p >= 90 && p <= 97)
230
+ style = { ...style, fg: { kind: "indexed", index: p - 90 + 8 } };
231
+ else if (p >= 100 && p <= 107)
232
+ style = { ...style, bg: { kind: "indexed", index: p - 100 + 8 } };
233
+ else if (p === 38 || p === 48) {
234
+ const { colour, used } = extended(i);
235
+ style = p === 38 ? { ...style, fg: colour } : { ...style, bg: colour };
236
+ i += used;
237
+ }
238
+ else if (p === 58)
239
+ i += extended(i).used;
240
+ }
241
+ };
242
+ const csi = (body, final) => {
243
+ const priv = /^[<=>?]/.test(body);
244
+ const raw = (priv ? body.slice(1) : body).replace(/[ -/]+$/, "");
245
+ const params = raw === "" ? [] : raw.split(/[;:]/).map((p) => (p === "" ? 0 : Number.parseInt(p, 10) || 0));
246
+ if (priv) {
247
+ if (body.startsWith("?") && params.includes(25) && (final === "h" || final === "l"))
248
+ visible = final === "h";
249
+ return;
250
+ }
251
+ if (/[ -/]$/.test(body))
252
+ return; // a sequence with intermediates is none of these
253
+ const n = Math.max(1, params[0] ?? 1);
254
+ switch (final) {
255
+ case "A":
256
+ row = clampRow(row - n);
257
+ break;
258
+ case "B":
259
+ row = clampRow(row + n);
260
+ break;
261
+ case "C":
262
+ col = clampCol(col + n);
263
+ break;
264
+ case "D":
265
+ col = clampCol(col - n);
266
+ break;
267
+ case "E":
268
+ row = clampRow(row + n);
269
+ col = 0;
270
+ break;
271
+ case "F":
272
+ row = clampRow(row - n);
273
+ col = 0;
274
+ break;
275
+ case "G":
276
+ case "`":
277
+ col = clampCol(n - 1);
278
+ break;
279
+ case "d":
280
+ row = clampRow(n - 1);
281
+ break;
282
+ case "H":
283
+ case "f":
284
+ row = clampRow(n - 1);
285
+ col = clampCol(Math.max(1, params[1] ?? 1) - 1);
286
+ break;
287
+ case "K": {
288
+ const mode = params[0] ?? 0;
289
+ if (mode === 0)
290
+ blank(row, col, width - 1);
291
+ else if (mode === 1)
292
+ blank(row, 0, col);
293
+ else if (mode === 2)
294
+ blank(row, 0, width - 1);
295
+ break;
296
+ }
297
+ case "J": {
298
+ const mode = params[0] ?? 0;
299
+ if (mode === 0) {
300
+ blank(row, col, width - 1);
301
+ if (height === undefined)
302
+ rows.length = Math.min(rows.length, row + 1);
303
+ else
304
+ for (let r = row + 1; r < height; r++)
305
+ blank(r, 0, width - 1);
306
+ }
307
+ else if (mode === 1) {
308
+ for (let r = 0; r < row; r++)
309
+ blank(r, 0, width - 1);
310
+ blank(row, 0, col);
311
+ }
312
+ else if (mode === 2 || mode === 3) {
313
+ if (height === undefined)
314
+ rows.length = 0;
315
+ else
316
+ for (let r = 0; r < height; r++)
317
+ blank(r, 0, width - 1);
318
+ }
319
+ break;
320
+ }
321
+ case "m":
322
+ sgr(params);
323
+ return; // SGR leaves a deferred wrap as it is
324
+ case "s":
325
+ saved = { row, col, style };
326
+ break;
327
+ case "u":
328
+ ({ row, col, style } = saved);
329
+ break;
330
+ default:
331
+ return; // unknown: ignored, and the cursor untouched
332
+ }
333
+ pending = false;
334
+ };
335
+ const control = (code) => {
336
+ switch (code) {
337
+ case 0x0d:
338
+ col = 0;
339
+ pending = false;
340
+ return;
341
+ case 0x0a:
342
+ case 0x0b:
343
+ case 0x0c:
344
+ linefeed();
345
+ if (crlf)
346
+ col = 0;
347
+ pending = false;
348
+ return;
349
+ case 0x08:
350
+ col = Math.max(0, col - 1);
351
+ pending = false;
352
+ return;
353
+ case 0x09:
354
+ col = Math.min(width - 1, (Math.floor(col / 8) + 1) * 8);
355
+ pending = false;
356
+ return;
357
+ default:
358
+ return; // BEL and the other controls show nothing
359
+ }
360
+ };
361
+ const feed = (data) => {
362
+ for (let i = 0; i < data.length; i++) {
363
+ const ch = data.charAt(i);
364
+ const code = data.charCodeAt(i);
365
+ switch (state) {
366
+ case "ground":
367
+ if (code === 0x1b) {
368
+ flush();
369
+ state = "escape";
370
+ }
371
+ else if (code < 0x20 || code === 0x7f) {
372
+ flush();
373
+ control(code);
374
+ }
375
+ else
376
+ text += ch;
377
+ break;
378
+ case "escape":
379
+ if (code === 0x5b) {
380
+ state = "csi";
381
+ seq = "";
382
+ }
383
+ else if (ch === "]" || ch === "P" || ch === "X" || ch === "^" || ch === "_")
384
+ state = "string";
385
+ else if (code >= 0x20 && code <= 0x2f)
386
+ seq += ch;
387
+ else if (code >= 0x30 && code <= 0x7e) {
388
+ if (seq === "" && ch === "7")
389
+ saved = { row, col, style };
390
+ else if (seq === "" && ch === "8")
391
+ ({ row, col, style } = saved);
392
+ seq = "";
393
+ state = "ground";
394
+ }
395
+ else if (code !== 0x1b) {
396
+ seq = "";
397
+ state = "ground";
398
+ i--;
399
+ }
400
+ break;
401
+ case "csi":
402
+ if (code >= 0x20 && code <= 0x3f)
403
+ seq += ch;
404
+ else if (code >= 0x40 && code <= 0x7e) {
405
+ csi(seq, ch);
406
+ seq = "";
407
+ state = "ground";
408
+ }
409
+ else if (code === 0x1b) {
410
+ seq = "";
411
+ state = "escape";
412
+ }
413
+ else {
414
+ seq = "";
415
+ state = "ground";
416
+ if (code !== 0x18 && code !== 0x1a)
417
+ i--;
418
+ }
419
+ break;
420
+ case "string":
421
+ if (code === 0x07)
422
+ state = "ground";
423
+ else if (code === 0x1b)
424
+ state = "string-escape";
425
+ break;
426
+ case "string-escape":
427
+ seq = "";
428
+ state = code === 0x5c ? "ground" : "escape";
429
+ if (code !== 0x5c)
430
+ i--;
431
+ break;
432
+ default:
433
+ absurd(state);
434
+ }
435
+ }
436
+ flush();
437
+ };
438
+ const visibleCells = (l) => l.filter((c) => c.width !== 0);
439
+ const dropTrailingEmpty = (ls, empty) => {
440
+ let end = ls.length;
441
+ for (let last = ls[end - 1]; last !== undefined && empty(last); last = ls[end - 1])
442
+ end--;
443
+ return ls.slice(0, end);
444
+ };
445
+ const lines = () => dropTrailingEmpty(rows.map((l) => visibleCells(l)
446
+ .map((c) => c.text)
447
+ .join("")
448
+ .replace(/ +$/, "")), (l) => l === "");
449
+ return {
450
+ width,
451
+ height,
452
+ write(data) {
453
+ feed(typeof data === "string" ? data : decoder.decode(data, { stream: true }));
454
+ },
455
+ lines,
456
+ text() {
457
+ return lines().join("\n");
458
+ },
459
+ styled() {
460
+ const out = rows.map((l) => {
461
+ const cells = visibleCells(l);
462
+ let end = cells.length;
463
+ while (end > 0 && cells[end - 1]?.text === " " && sameStyle(cells[end - 1]?.style ?? PLAIN, PLAIN))
464
+ end--;
465
+ const runs = [];
466
+ for (const c of cells.slice(0, end)) {
467
+ const last = runs[runs.length - 1];
468
+ if (last !== undefined && sameStyle(last.style, c.style))
469
+ runs[runs.length - 1] = { text: last.text + c.text, style: last.style };
470
+ else
471
+ runs.push({ text: c.text, style: c.style });
472
+ }
473
+ return runs;
474
+ });
475
+ return dropTrailingEmpty(out, (l) => l.length === 0);
476
+ },
477
+ cell(r, c) {
478
+ if (r < 0 || c < 0 || c >= width || (height !== undefined && r >= height))
479
+ return undefined;
480
+ return rows[r]?.[c] ?? BLANK;
481
+ },
482
+ cursor() {
483
+ return { row, col, visible };
484
+ },
485
+ };
486
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Display width: how many columns of a terminal a text takes, and a text cut to a number of columns (commons 0006-signals FR-023). An
3
+ * escape sequence takes none and is never split; a grapheme (what a person sees as one character, found with `Intl.Segmenter`) is never
4
+ * split either; a wide character or an emoji takes two columns.
5
+ *
6
+ * The width of a grapheme is an approximation of what terminals do (as `wcwidth` and the `string-width` package approximate it):
7
+ * - a control character, a combining mark, a format character (such as the zero-width joiner) or a variation selector alone: 0;
8
+ * - an emoji: 2 when it is shown as an emoji, which is when its first code point has the `Emoji_Presentation` property (✅ ❌ 👉), when
9
+ * it carries the emoji variation selector U+FE0F (⏭️ ⏹️ ⚠️, keycaps such as 1️⃣), or when it is a zero-width-joiner sequence (one glyph
10
+ * of two columns, however many code points it joins); the text variation selector U+FE0E makes it 1;
11
+ * - an East Asian Wide or Fullwidth character (CJK ideographs, kana, Hangul syllables, fullwidth forms): 2, by the ranges in `WIDE`,
12
+ * which follow Unicode's `EastAsianWidth.txt` in blocks rather than code point by code point (JavaScript has no property escape for it);
13
+ * - anything else: 1. Ambiguous-width characters (Greek, box drawing) count 1, as a terminal in a Western locale shows them.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { cutToWidth, displayWidth } from "./width.js";
18
+ * displayWidth("✅ 测试"); // 7
19
+ * cutToWidth("✅ 测试", 6); // "✅ 测"
20
+ * cutToWidth("\u001b[31mfailed badly\u001b[0m", 7, "…"); // "\u001b[31mfailed…\u001b[0m"
21
+ * ```
22
+ *
23
+ * @module
24
+ */
25
+ /** A piece of a text: an escape sequence, or a run of text between them. */
26
+ export type Token = {
27
+ readonly kind: "escape";
28
+ readonly text: string;
29
+ } | {
30
+ readonly kind: "text";
31
+ readonly text: string;
32
+ };
33
+ /** A text split into its escape sequences and the runs of text between them, in order; joined, the pieces are the text again. */
34
+ export declare function tokens(text: string): readonly Token[];
35
+ /** The graphemes of a text with no escape sequence, in order (extended grapheme clusters, by `Intl.Segmenter`). */
36
+ export declare function graphemes(text: string): readonly string[];
37
+ /** The columns one grapheme takes: 0, 1 or 2 (see the module's rules). */
38
+ export declare function graphemeWidth(grapheme: string): 0 | 1 | 2;
39
+ /** The columns a text takes on a terminal: its graphemes' widths summed; escape sequences take none. */
40
+ export declare function displayWidth(text: string): number;
41
+ /** A text split in two at a number of columns. */
42
+ export type Split = {
43
+ /** The longest beginning that takes at most the columns asked for, with every escape sequence before the cut. */
44
+ readonly head: string;
45
+ /** The rest: `head + tail` is the text. */
46
+ readonly tail: string;
47
+ };
48
+ /**
49
+ * A text split where it reaches `width` columns, between two graphemes or escape sequences, never inside one: a wide character that would
50
+ * cross the edge goes to the tail. Escape sequences up to the first grapheme that does not fit stay in the head.
51
+ */
52
+ export declare function splitAtWidth(text: string, width: number): Split;
53
+ /** The parameters of an SGR sequence (`ESC [ ... m`), or undefined for another sequence. */
54
+ export declare function sgrParams(escape: string): readonly number[] | undefined;
55
+ /** The SGR sequence that turns every style off. */
56
+ export declare const RESET: string;
57
+ /**
58
+ * A text cut to at most `width` columns. A text that fits is returned as it is. Otherwise it is cut between graphemes so that it and the
59
+ * `ellipsis` (none by default; "…" is the usual one) fit; the escape sequences before the cut are kept, those after are dropped, and where a
60
+ * colour or another style was still on at the cut, the result ends with a reset so that the style does not run on. An ellipsis wider than
61
+ * `width` is left out.
62
+ */
63
+ export declare function cutToWidth(text: string, width: number, ellipsis?: string): string;