@sayknow-cli/tui 0.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 (61) hide show
  1. package/CHANGELOG.md +903 -0
  2. package/README.md +704 -0
  3. package/dist/types/autocomplete.d.ts +82 -0
  4. package/dist/types/bracketed-paste.d.ts +26 -0
  5. package/dist/types/components/box.d.ts +20 -0
  6. package/dist/types/components/cancellable-loader.d.ts +21 -0
  7. package/dist/types/components/editor.d.ts +111 -0
  8. package/dist/types/components/image.d.ts +16 -0
  9. package/dist/types/components/input.d.ts +16 -0
  10. package/dist/types/components/loader.d.ts +14 -0
  11. package/dist/types/components/markdown.d.ts +64 -0
  12. package/dist/types/components/select-list.d.ts +46 -0
  13. package/dist/types/components/settings-list.d.ts +39 -0
  14. package/dist/types/components/spacer.d.ts +11 -0
  15. package/dist/types/components/tab-bar.d.ts +56 -0
  16. package/dist/types/components/text.d.ts +13 -0
  17. package/dist/types/components/truncated-text.d.ts +10 -0
  18. package/dist/types/editor-component.d.ts +36 -0
  19. package/dist/types/fuzzy.d.ts +15 -0
  20. package/dist/types/index.d.ts +26 -0
  21. package/dist/types/keybindings.d.ts +189 -0
  22. package/dist/types/keys.d.ts +208 -0
  23. package/dist/types/kill-ring.d.ts +27 -0
  24. package/dist/types/metrics.d.ts +85 -0
  25. package/dist/types/stdin-buffer.d.ts +50 -0
  26. package/dist/types/symbols.d.ts +23 -0
  27. package/dist/types/terminal-capabilities.d.ts +75 -0
  28. package/dist/types/terminal.d.ts +76 -0
  29. package/dist/types/ttyid.d.ts +9 -0
  30. package/dist/types/tui.d.ts +181 -0
  31. package/dist/types/utils.d.ts +75 -0
  32. package/package.json +74 -0
  33. package/src/autocomplete.ts +896 -0
  34. package/src/bracketed-paste.ts +47 -0
  35. package/src/components/box.ts +173 -0
  36. package/src/components/cancellable-loader.ts +40 -0
  37. package/src/components/editor.ts +2820 -0
  38. package/src/components/image.ts +90 -0
  39. package/src/components/input.ts +465 -0
  40. package/src/components/loader.ts +103 -0
  41. package/src/components/markdown.ts +1061 -0
  42. package/src/components/select-list.ts +249 -0
  43. package/src/components/settings-list.ts +211 -0
  44. package/src/components/spacer.ts +28 -0
  45. package/src/components/tab-bar.ts +175 -0
  46. package/src/components/text.ts +110 -0
  47. package/src/components/truncated-text.ts +61 -0
  48. package/src/editor-component.ts +71 -0
  49. package/src/fuzzy.ts +143 -0
  50. package/src/index.ts +41 -0
  51. package/src/keybindings.ts +279 -0
  52. package/src/keys.ts +537 -0
  53. package/src/kill-ring.ts +46 -0
  54. package/src/metrics.ts +382 -0
  55. package/src/stdin-buffer.ts +444 -0
  56. package/src/symbols.ts +24 -0
  57. package/src/terminal-capabilities.ts +537 -0
  58. package/src/terminal.ts +807 -0
  59. package/src/ttyid.ts +73 -0
  60. package/src/tui.ts +1765 -0
  61. package/src/utils.ts +389 -0
@@ -0,0 +1,444 @@
1
+ /**
2
+ * StdinBuffer buffers input and emits complete sequences.
3
+ *
4
+ * This is necessary because stdin data events can arrive in partial chunks,
5
+ * especially for escape sequences like mouse events. Without buffering,
6
+ * partial sequences can be misinterpreted as regular keypresses.
7
+ *
8
+ * For example, the mouse SGR sequence `\x1b[<35;20;5m` might arrive as:
9
+ * - Event 1: `\x1b`
10
+ * - Event 2: `[<35`
11
+ * - Event 3: `;20;5m`
12
+ *
13
+ * The buffer accumulates these until a complete sequence is detected.
14
+ * Call the `process()` method to feed input data.
15
+ *
16
+ * Based on code from OpenTUI (https://github.com/anomalyco/opentui)
17
+ * MIT License - Copyright (c) 2025 opentui
18
+ */
19
+
20
+ import { StringDecoder } from "node:string_decoder";
21
+ import { EventEmitter } from "events";
22
+
23
+ const ESC = "\x1b";
24
+ const BRACKETED_PASTE_START = "\x1b[200~";
25
+ const BRACKETED_PASTE_END = "\x1b[201~";
26
+
27
+ /**
28
+ * Check if a string is a complete escape sequence or needs more data
29
+ */
30
+ function isCompleteSequence(data: string): "complete" | "incomplete" | "not-escape" {
31
+ if (!data.startsWith(ESC)) {
32
+ return "not-escape";
33
+ }
34
+
35
+ if (data.length === 1) {
36
+ return "incomplete";
37
+ }
38
+
39
+ const afterEsc = data.slice(1);
40
+
41
+ // CSI sequences: ESC [
42
+ if (afterEsc.startsWith("[")) {
43
+ // Check for old-style mouse sequence: ESC[M + 3 bytes
44
+ if (afterEsc.startsWith("[M")) {
45
+ // Old-style mouse needs ESC[M + 3 bytes = 6 total
46
+ return data.length >= 6 ? "complete" : "incomplete";
47
+ }
48
+ return isCompleteCsiSequence(data);
49
+ }
50
+
51
+ // OSC sequences: ESC ]
52
+ if (afterEsc.startsWith("]")) {
53
+ return isCompleteOscSequence(data);
54
+ }
55
+
56
+ // DCS sequences: ESC P ... ESC \ (includes XTVersion responses)
57
+ if (afterEsc.startsWith("P")) {
58
+ return isCompleteDcsSequence(data);
59
+ }
60
+
61
+ // APC sequences: ESC _ ... ESC \ (includes Kitty graphics responses)
62
+ if (afterEsc.startsWith("_")) {
63
+ return isCompleteApcSequence(data);
64
+ }
65
+
66
+ // SS3 sequences: ESC O
67
+ if (afterEsc.startsWith("O")) {
68
+ // ESC O followed by a single character
69
+ return afterEsc.length >= 2 ? "complete" : "incomplete";
70
+ }
71
+
72
+ // Meta key sequences: ESC followed by a single character
73
+ if (afterEsc.length === 1) {
74
+ return "complete";
75
+ }
76
+
77
+ // Unknown escape sequence - treat as complete
78
+ return "complete";
79
+ }
80
+
81
+ /**
82
+ * Check if CSI sequence is complete
83
+ * CSI sequences: ESC [ ... followed by a final byte (0x40-0x7E)
84
+ */
85
+ function isCompleteCsiSequence(data: string): "complete" | "incomplete" {
86
+ if (!data.startsWith(`${ESC}[`)) {
87
+ return "complete";
88
+ }
89
+
90
+ // Need at least ESC [ and one more character
91
+ if (data.length < 3) {
92
+ return "incomplete";
93
+ }
94
+
95
+ const payload = data.slice(2);
96
+
97
+ // CSI sequences end with a byte in the range 0x40-0x7E (@-~)
98
+ // This includes all letters and several special characters
99
+ const lastChar = payload[payload.length - 1];
100
+ const lastCharCode = lastChar.charCodeAt(0);
101
+
102
+ if (lastCharCode >= 0x40 && lastCharCode <= 0x7e) {
103
+ // Special handling for SGR mouse sequences
104
+ // Format: ESC[<B;X;Ym or ESC[<B;X;YM
105
+ if (payload.startsWith("<")) {
106
+ // Must have format: <digits;digits;digits[Mm]
107
+ const mouseMatch = /^<\d+;\d+;\d+[Mm]$/.test(payload);
108
+ if (mouseMatch) {
109
+ return "complete";
110
+ }
111
+ // If it ends with M or m but doesn't match the pattern, still incomplete
112
+ if (lastChar === "M" || lastChar === "m") {
113
+ // Check if we have the right structure
114
+ const parts = payload.slice(1, -1).split(";");
115
+ if (parts.length === 3 && parts.every(p => /^\d+$/.test(p))) {
116
+ return "complete";
117
+ }
118
+ }
119
+
120
+ return "incomplete";
121
+ }
122
+
123
+ return "complete";
124
+ }
125
+
126
+ return "incomplete";
127
+ }
128
+
129
+ /**
130
+ * Check if OSC sequence is complete
131
+ * OSC sequences: ESC ] ... ST (where ST is ESC \ or BEL)
132
+ */
133
+ function isCompleteOscSequence(data: string): "complete" | "incomplete" {
134
+ if (!data.startsWith(`${ESC}]`)) {
135
+ return "complete";
136
+ }
137
+
138
+ // OSC sequences end with ST (ESC \) or BEL (\x07)
139
+ if (data.endsWith(`${ESC}\\`) || data.endsWith("\x07")) {
140
+ return "complete";
141
+ }
142
+
143
+ return "incomplete";
144
+ }
145
+
146
+ /**
147
+ * Check if DCS (Device Control String) sequence is complete
148
+ * DCS sequences: ESC P ... ST (where ST is ESC \)
149
+ * Used for XTVersion responses like ESC P >| ... ESC \
150
+ */
151
+ function isCompleteDcsSequence(data: string): "complete" | "incomplete" {
152
+ if (!data.startsWith(`${ESC}P`)) {
153
+ return "complete";
154
+ }
155
+
156
+ // DCS sequences end with ST (ESC \)
157
+ if (data.endsWith(`${ESC}\\`)) {
158
+ return "complete";
159
+ }
160
+
161
+ return "incomplete";
162
+ }
163
+
164
+ /**
165
+ * Check if APC (Application Program Command) sequence is complete
166
+ * APC sequences: ESC _ ... ST (where ST is ESC \)
167
+ * Used for Kitty graphics responses like ESC _ G ... ESC \
168
+ */
169
+ function isCompleteApcSequence(data: string): "complete" | "incomplete" {
170
+ if (!data.startsWith(`${ESC}_`)) {
171
+ return "complete";
172
+ }
173
+
174
+ // APC sequences end with ST (ESC \)
175
+ if (data.endsWith(`${ESC}\\`)) {
176
+ return "complete";
177
+ }
178
+
179
+ return "incomplete";
180
+ }
181
+
182
+ /**
183
+ * Split accumulated buffer into complete sequences
184
+ */
185
+ function parseUnmodifiedKittyPrintableCodepoint(sequence: string): number | undefined {
186
+ const match = sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);
187
+ if (!match) return undefined;
188
+
189
+ const codepoint = parseInt(match[1]!, 10);
190
+ return codepoint >= 32 ? codepoint : undefined;
191
+ }
192
+
193
+ function extractCompleteSequences(buffer: string): { sequences: string[]; remainder: string } {
194
+ const sequences: string[] = [];
195
+ let pos = 0;
196
+
197
+ while (pos < buffer.length) {
198
+ const remaining = buffer.slice(pos);
199
+
200
+ // Try to extract a sequence starting at this position
201
+ if (remaining.startsWith(ESC)) {
202
+ // Find the end of this escape sequence
203
+ let seqEnd = 1;
204
+ while (seqEnd <= remaining.length) {
205
+ const candidate = remaining.slice(0, seqEnd);
206
+ const status = isCompleteSequence(candidate);
207
+
208
+ if (status === "complete") {
209
+ sequences.push(candidate);
210
+ pos += seqEnd;
211
+ break;
212
+ } else if (status === "incomplete") {
213
+ seqEnd++;
214
+ } else {
215
+ // Should not happen when starting with ESC
216
+ sequences.push(candidate);
217
+ pos += seqEnd;
218
+ break;
219
+ }
220
+ }
221
+
222
+ if (seqEnd > remaining.length) {
223
+ return { sequences, remainder: remaining };
224
+ }
225
+ } else {
226
+ // Not an escape sequence - take a single character
227
+ sequences.push(remaining[0]!);
228
+ pos++;
229
+ }
230
+ }
231
+
232
+ return { sequences, remainder: "" };
233
+ }
234
+
235
+ export type StdinBufferOptions = {
236
+ /**
237
+ * Maximum time to wait for sequence completion (default: 10ms)
238
+ * After this time, the buffer is flushed even if incomplete
239
+ */
240
+ timeout?: number;
241
+ };
242
+
243
+ export type StdinBufferEventMap = {
244
+ data: [string];
245
+ paste: [string];
246
+ };
247
+
248
+ /**
249
+ * Buffers stdin input and emits complete sequences via the 'data' event.
250
+ * Handles partial escape sequences that arrive across multiple chunks.
251
+ *
252
+ * StdinBuffer is the single raw-stdin decoding boundary: raw terminal bytes
253
+ * enter via `process()` and decoded string events leave via the 'data' and
254
+ * 'paste' events. UTF-8 is decoded exactly once here (using a persistent
255
+ * StringDecoder) so multi-byte characters split across chunk boundaries are
256
+ * reassembled rather than corrupted into U+FFFD. All downstream parsing
257
+ * (escape sequences, bracketed paste, Kitty/CSI, OSC/DA1) operates on strings.
258
+ */
259
+ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
260
+ #buffer: string = "";
261
+ #timeout?: NodeJS.Timeout;
262
+ readonly #timeoutMs: number;
263
+ #pasteMode: boolean = false;
264
+ #pasteBuffer: string = "";
265
+ #pendingKittyPrintableCodepoint: number | undefined;
266
+ // Persistent UTF-8 decoder. Holds an incomplete trailing multi-byte
267
+ // sequence between chunks so split reads (e.g. a 3-byte Korean syllable
268
+ // split across two stdin events) reassemble correctly instead of emitting
269
+ // U+FFFD. Reset on clear()/destroy(); never finalized on normal flush.
270
+ #decoder = new StringDecoder("utf8");
271
+
272
+ constructor(options: StdinBufferOptions = {}) {
273
+ super();
274
+ this.#timeoutMs = options.timeout ?? 10;
275
+ }
276
+
277
+ process(data: string | Buffer): void {
278
+ // Clear any pending timeout
279
+ if (this.#timeout) {
280
+ clearTimeout(this.#timeout);
281
+ this.#timeout = undefined;
282
+ }
283
+
284
+ // Decode raw bytes into a string. Buffers come from raw stdin; strings
285
+ // come from tests or non-terminal callers and are already decoded.
286
+ let str: string;
287
+ let decodedFromBuffer = false;
288
+ if (Buffer.isBuffer(data)) {
289
+ // Legacy 8-bit meta: an isolated high byte (0x80-0xFF) is treated
290
+ // as ESC + (byte - 128) for Alt/meta compatibility, BEFORE UTF-8
291
+ // decoding. This is the one documented exception to UTF-8 boundary
292
+ // decoding — a lone high byte that is also a valid UTF-8 lead byte
293
+ // is still read as meta — so such a byte is never fed to the decoder.
294
+ if (data.length === 1 && data[0]! > 127) {
295
+ const byte = data[0]! - 128;
296
+ str = `\x1b${String.fromCharCode(byte)}`;
297
+ } else {
298
+ // Decode through the persistent StringDecoder so a multi-byte
299
+ // sequence split across chunks (e.g. a 3-byte Korean syllable)
300
+ // is reassembled instead of emitting U+FFFD.
301
+ str = this.#decoder.write(data);
302
+ decodedFromBuffer = true;
303
+ }
304
+ } else {
305
+ str = data;
306
+ }
307
+
308
+ if (str.length === 0 && this.#buffer.length === 0) {
309
+ // A Buffer that decoded to nothing means the decoder is holding an
310
+ // incomplete UTF-8 prefix; emit nothing and wait for the completing
311
+ // bytes. Preserve the historical empty 'data' event for explicit
312
+ // empty-string input only.
313
+ if (!decodedFromBuffer) {
314
+ this.#emitDataSequence("");
315
+ }
316
+ return;
317
+ }
318
+
319
+ this.#buffer += str;
320
+
321
+ if (this.#pasteMode) {
322
+ this.#pasteBuffer += this.#buffer;
323
+ this.#buffer = "";
324
+
325
+ const endIndex = this.#pasteBuffer.indexOf(BRACKETED_PASTE_END);
326
+ if (endIndex !== -1) {
327
+ const pastedContent = this.#pasteBuffer.slice(0, endIndex);
328
+ const remaining = this.#pasteBuffer.slice(endIndex + BRACKETED_PASTE_END.length);
329
+
330
+ this.#pasteMode = false;
331
+ this.#pasteBuffer = "";
332
+ this.#pendingKittyPrintableCodepoint = undefined;
333
+
334
+ this.emit("paste", pastedContent);
335
+
336
+ if (remaining.length > 0) {
337
+ this.process(remaining);
338
+ }
339
+ }
340
+ return;
341
+ }
342
+
343
+ const startIndex = this.#buffer.indexOf(BRACKETED_PASTE_START);
344
+ if (startIndex !== -1) {
345
+ if (startIndex > 0) {
346
+ const beforePaste = this.#buffer.slice(0, startIndex);
347
+ const result = extractCompleteSequences(beforePaste);
348
+ for (const sequence of result.sequences) {
349
+ this.#emitDataSequence(sequence);
350
+ }
351
+ }
352
+
353
+ this.#pendingKittyPrintableCodepoint = undefined;
354
+ this.#buffer = this.#buffer.slice(startIndex + BRACKETED_PASTE_START.length);
355
+ this.#pasteMode = true;
356
+ this.#pasteBuffer = this.#buffer;
357
+ this.#buffer = "";
358
+
359
+ const endIndex = this.#pasteBuffer.indexOf(BRACKETED_PASTE_END);
360
+ if (endIndex !== -1) {
361
+ const pastedContent = this.#pasteBuffer.slice(0, endIndex);
362
+ const remaining = this.#pasteBuffer.slice(endIndex + BRACKETED_PASTE_END.length);
363
+
364
+ this.#pasteMode = false;
365
+ this.#pasteBuffer = "";
366
+ this.#pendingKittyPrintableCodepoint = undefined;
367
+
368
+ this.emit("paste", pastedContent);
369
+
370
+ if (remaining.length > 0) {
371
+ this.process(remaining);
372
+ }
373
+ }
374
+ return;
375
+ }
376
+
377
+ const result = extractCompleteSequences(this.#buffer);
378
+ this.#buffer = result.remainder;
379
+
380
+ for (const sequence of result.sequences) {
381
+ this.#emitDataSequence(sequence);
382
+ }
383
+
384
+ if (this.#buffer.length > 0) {
385
+ this.#timeout = setTimeout(() => {
386
+ const flushed = this.flush();
387
+
388
+ for (const sequence of flushed) {
389
+ this.#emitDataSequence(sequence);
390
+ }
391
+ }, this.#timeoutMs);
392
+ }
393
+ }
394
+
395
+ #emitDataSequence(sequence: string): void {
396
+ const rawCodepoint = sequence.length === 1 ? sequence.codePointAt(0) : undefined;
397
+ if (rawCodepoint !== undefined && rawCodepoint === this.#pendingKittyPrintableCodepoint) {
398
+ this.#pendingKittyPrintableCodepoint = undefined;
399
+ return;
400
+ }
401
+
402
+ this.#pendingKittyPrintableCodepoint = parseUnmodifiedKittyPrintableCodepoint(sequence);
403
+ this.emit("data", sequence);
404
+ }
405
+
406
+ flush(): string[] {
407
+ if (this.#timeout) {
408
+ clearTimeout(this.#timeout);
409
+ this.#timeout = undefined;
410
+ }
411
+
412
+ if (this.#buffer.length === 0) {
413
+ return [];
414
+ }
415
+
416
+ const sequences = [this.#buffer];
417
+ this.#buffer = "";
418
+ this.#pendingKittyPrintableCodepoint = undefined;
419
+ return sequences;
420
+ }
421
+
422
+ clear(): void {
423
+ if (this.#timeout) {
424
+ clearTimeout(this.#timeout);
425
+ this.#timeout = undefined;
426
+ }
427
+ this.#buffer = "";
428
+ this.#pasteMode = false;
429
+ this.#pasteBuffer = "";
430
+ this.#pendingKittyPrintableCodepoint = undefined;
431
+ // Drop any incomplete multi-byte sequence the decoder is holding so a
432
+ // stale partial prefix cannot combine with future input. destroy()
433
+ // resets the decoder by calling clear().
434
+ this.#decoder = new StringDecoder("utf8");
435
+ }
436
+
437
+ getBuffer(): string {
438
+ return this.#buffer;
439
+ }
440
+
441
+ destroy(): void {
442
+ this.clear();
443
+ }
444
+ }
package/src/symbols.ts ADDED
@@ -0,0 +1,24 @@
1
+ export interface BoxSymbols {
2
+ topLeft: string;
3
+ topRight: string;
4
+ bottomLeft: string;
5
+ bottomRight: string;
6
+ horizontal: string;
7
+ vertical: string;
8
+ teeDown: string;
9
+ teeUp: string;
10
+ teeLeft: string;
11
+ teeRight: string;
12
+ cross: string;
13
+ }
14
+
15
+ export interface SymbolTheme {
16
+ cursor: string;
17
+ inputCursor: string;
18
+ boxRound: Omit<BoxSymbols, "teeDown" | "teeUp" | "teeLeft" | "teeRight" | "cross">;
19
+ boxSharp: BoxSymbols;
20
+ table: BoxSymbols;
21
+ quoteBorder: string;
22
+ hrChar: string;
23
+ spinnerFrames: string[];
24
+ }