@gajae-code/tui 0.1.1

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 (59) hide show
  1. package/CHANGELOG.md +818 -0
  2. package/README.md +704 -0
  3. package/dist/types/autocomplete.d.ts +76 -0
  4. package/dist/types/bracketed-paste.d.ts +26 -0
  5. package/dist/types/components/box.d.ts +15 -0
  6. package/dist/types/components/cancellable-loader.d.ts +21 -0
  7. package/dist/types/components/editor.d.ts +101 -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 +13 -0
  11. package/dist/types/components/markdown.d.ts +61 -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 +25 -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/stdin-buffer.d.ts +43 -0
  25. package/dist/types/symbols.d.ts +23 -0
  26. package/dist/types/terminal-capabilities.d.ts +75 -0
  27. package/dist/types/terminal.d.ts +61 -0
  28. package/dist/types/ttyid.d.ts +9 -0
  29. package/dist/types/tui.d.ts +161 -0
  30. package/dist/types/utils.d.ts +74 -0
  31. package/package.json +73 -0
  32. package/src/autocomplete.ts +836 -0
  33. package/src/bracketed-paste.ts +47 -0
  34. package/src/components/box.ts +144 -0
  35. package/src/components/cancellable-loader.ts +40 -0
  36. package/src/components/editor.ts +2664 -0
  37. package/src/components/image.ts +90 -0
  38. package/src/components/input.ts +465 -0
  39. package/src/components/loader.ts +86 -0
  40. package/src/components/markdown.ts +1009 -0
  41. package/src/components/select-list.ts +249 -0
  42. package/src/components/settings-list.ts +211 -0
  43. package/src/components/spacer.ts +28 -0
  44. package/src/components/tab-bar.ts +175 -0
  45. package/src/components/text.ts +110 -0
  46. package/src/components/truncated-text.ts +61 -0
  47. package/src/editor-component.ts +71 -0
  48. package/src/fuzzy.ts +143 -0
  49. package/src/index.ts +39 -0
  50. package/src/keybindings.ts +279 -0
  51. package/src/keys.ts +537 -0
  52. package/src/kill-ring.ts +46 -0
  53. package/src/stdin-buffer.ts +410 -0
  54. package/src/symbols.ts +24 -0
  55. package/src/terminal-capabilities.ts +537 -0
  56. package/src/terminal.ts +716 -0
  57. package/src/ttyid.ts +66 -0
  58. package/src/tui.ts +1481 -0
  59. package/src/utils.ts +359 -0
@@ -0,0 +1,90 @@
1
+ import {
2
+ getImageDimensions,
3
+ type ImageDimensions,
4
+ imageFallback,
5
+ renderImage,
6
+ TERMINAL,
7
+ } from "../terminal-capabilities";
8
+ import type { Component } from "../tui";
9
+
10
+ export interface ImageTheme {
11
+ fallbackColor: (str: string) => string;
12
+ }
13
+
14
+ export interface ImageOptions {
15
+ maxWidthCells?: number;
16
+ maxHeightCells?: number;
17
+ filename?: string;
18
+ }
19
+
20
+ export class Image implements Component {
21
+ #base64Data: string;
22
+ #mimeType: string;
23
+ #dimensions: ImageDimensions;
24
+ #theme: ImageTheme;
25
+ #options: ImageOptions;
26
+
27
+ #cachedLines?: string[];
28
+ #cachedWidth?: number;
29
+
30
+ constructor(
31
+ base64Data: string,
32
+ mimeType: string,
33
+ theme: ImageTheme,
34
+ options: ImageOptions = {},
35
+ dimensions?: ImageDimensions,
36
+ ) {
37
+ this.#base64Data = base64Data;
38
+ this.#mimeType = mimeType;
39
+ this.#theme = theme;
40
+ this.#options = options;
41
+ this.#dimensions = dimensions || getImageDimensions(base64Data, mimeType) || { widthPx: 800, heightPx: 600 };
42
+ }
43
+
44
+ invalidate(): void {
45
+ this.#cachedLines = undefined;
46
+ this.#cachedWidth = undefined;
47
+ }
48
+
49
+ render(width: number): string[] {
50
+ if (this.#cachedLines && this.#cachedWidth === width) {
51
+ return this.#cachedLines;
52
+ }
53
+
54
+ const cap = this.#options.maxWidthCells;
55
+ const maxWidth = cap != null && cap > 0 ? Math.min(width - 2, cap) : width - 2;
56
+
57
+ let lines: string[];
58
+
59
+ if (TERMINAL.imageProtocol) {
60
+ const result = renderImage(this.#base64Data, this.#dimensions, {
61
+ maxWidthCells: maxWidth,
62
+ maxHeightCells: this.#options.maxHeightCells,
63
+ });
64
+
65
+ if (result) {
66
+ // Return `rows` lines so TUI accounts for image height
67
+ // First (rows-1) lines are empty (TUI clears them)
68
+ // Last line: move cursor back up, then output image sequence
69
+ lines = [];
70
+ for (let i = 0; i < result.rows - 1; i++) {
71
+ lines.push("");
72
+ }
73
+ // Move cursor up to first row, then output image
74
+ const moveUp = result.rows > 1 ? `\x1b[${result.rows - 1}A` : "";
75
+ lines.push(moveUp + result.sequence);
76
+ } else {
77
+ const fallback = imageFallback(this.#mimeType, this.#dimensions, this.#options.filename);
78
+ lines = [this.#theme.fallbackColor(fallback)];
79
+ }
80
+ } else {
81
+ const fallback = imageFallback(this.#mimeType, this.#dimensions, this.#options.filename);
82
+ lines = [this.#theme.fallbackColor(fallback)];
83
+ }
84
+
85
+ this.#cachedLines = lines;
86
+ this.#cachedWidth = width;
87
+
88
+ return lines;
89
+ }
90
+ }
@@ -0,0 +1,465 @@
1
+ import { BracketedPasteHandler } from "../bracketed-paste";
2
+ import { getKeybindings } from "../keybindings";
3
+ import { extractPrintableText } from "../keys";
4
+ import { KillRing } from "../kill-ring";
5
+ import { type Component, CURSOR_MARKER, type Focusable } from "../tui";
6
+ import {
7
+ getSegmenter,
8
+ getWordNavKind,
9
+ moveWordLeft,
10
+ moveWordRight,
11
+ padding,
12
+ replaceTabs,
13
+ sliceWithWidth,
14
+ visibleWidth,
15
+ } from "../utils";
16
+
17
+ const segmenter = getSegmenter();
18
+
19
+ interface InputState {
20
+ value: string;
21
+ cursor: number;
22
+ }
23
+ function insertTextNfcAt(value: string, cursor: number, text: string): { value: string; cursor: number } {
24
+ const before = value.slice(0, cursor);
25
+ const after = value.slice(cursor);
26
+ const beforeWithInsert = (before + text).normalize("NFC");
27
+ return {
28
+ value: (beforeWithInsert + after).normalize("NFC"),
29
+ cursor: beforeWithInsert.length,
30
+ };
31
+ }
32
+ /**
33
+ * Input component - single-line text input with horizontal scrolling
34
+ */
35
+ export class Input implements Component, Focusable {
36
+ #value: string = "";
37
+ #cursor: number = 0; // Cursor position in the value
38
+ onSubmit?: (value: string) => void;
39
+ onEscape?: () => void;
40
+
41
+ /** Focusable interface - set by TUI when focus changes */
42
+ focused: boolean = false;
43
+
44
+ // Bracketed paste mode buffering
45
+ #pasteHandler = new BracketedPasteHandler();
46
+
47
+ // Kill ring for Emacs-style kill/yank operations
48
+ #killRing = new KillRing();
49
+ #lastAction: "kill" | "yank" | "type-word" | null = null;
50
+
51
+ // Undo support
52
+ #undoStack: InputState[] = [];
53
+
54
+ getValue(): string {
55
+ return this.#value;
56
+ }
57
+
58
+ setValue(value: string): void {
59
+ const normalized = value.normalize("NFC");
60
+ this.#value = normalized;
61
+ this.#cursor = Math.min(this.#cursor, normalized.length);
62
+ }
63
+
64
+ handleInput(data: string): void {
65
+ // Handle bracketed paste mode
66
+ const paste = this.#pasteHandler.process(data);
67
+ if (paste.handled) {
68
+ if (paste.pasteContent !== undefined) {
69
+ this.#handlePaste(paste.pasteContent);
70
+ if (paste.remaining.length > 0) {
71
+ this.handleInput(paste.remaining);
72
+ }
73
+ }
74
+ return;
75
+ }
76
+
77
+ const kb = getKeybindings();
78
+
79
+ // Escape/Cancel
80
+ if (kb.matches(data, "tui.select.cancel")) {
81
+ if (this.onEscape) this.onEscape();
82
+ return;
83
+ }
84
+
85
+ // Undo
86
+ if (kb.matches(data, "tui.editor.undo")) {
87
+ this.#undo();
88
+ return;
89
+ }
90
+
91
+ // Submit
92
+ if (kb.matches(data, "tui.input.submit") || data === "\n") {
93
+ if (this.onSubmit) this.onSubmit(this.#value);
94
+ return;
95
+ }
96
+
97
+ // Deletion
98
+ if (kb.matches(data, "tui.editor.deleteCharBackward")) {
99
+ this.#handleBackspace();
100
+ return;
101
+ }
102
+
103
+ if (kb.matches(data, "tui.editor.deleteCharForward")) {
104
+ this.#handleForwardDelete();
105
+ return;
106
+ }
107
+
108
+ if (kb.matches(data, "tui.editor.deleteWordBackward")) {
109
+ this.#deleteWordBackwards();
110
+ return;
111
+ }
112
+
113
+ if (kb.matches(data, "tui.editor.deleteWordForward")) {
114
+ this.#deleteWordForward();
115
+ return;
116
+ }
117
+
118
+ if (kb.matches(data, "tui.editor.deleteToLineStart")) {
119
+ this.#deleteToLineStart();
120
+ return;
121
+ }
122
+
123
+ if (kb.matches(data, "tui.editor.deleteToLineEnd")) {
124
+ this.#deleteToLineEnd();
125
+ return;
126
+ }
127
+
128
+ // Kill ring actions
129
+ if (kb.matches(data, "tui.editor.yank")) {
130
+ this.#yank();
131
+ return;
132
+ }
133
+ if (kb.matches(data, "tui.editor.yankPop")) {
134
+ this.#yankPop();
135
+ return;
136
+ }
137
+
138
+ // Cursor movement
139
+ if (kb.matches(data, "tui.editor.cursorLeft")) {
140
+ this.#lastAction = null;
141
+ if (this.#cursor > 0) {
142
+ const beforeCursor = this.#value.slice(0, this.#cursor);
143
+ const graphemes = [...segmenter.segment(beforeCursor)];
144
+ const lastGrapheme = graphemes[graphemes.length - 1];
145
+ this.#cursor -= lastGrapheme ? lastGrapheme.segment.length : 1;
146
+ }
147
+ return;
148
+ }
149
+
150
+ if (kb.matches(data, "tui.editor.cursorRight")) {
151
+ this.#lastAction = null;
152
+ if (this.#cursor < this.#value.length) {
153
+ const afterCursor = this.#value.slice(this.#cursor);
154
+ const graphemes = [...segmenter.segment(afterCursor)];
155
+ const firstGrapheme = graphemes[0];
156
+ this.#cursor += firstGrapheme ? firstGrapheme.segment.length : 1;
157
+ }
158
+ return;
159
+ }
160
+
161
+ if (kb.matches(data, "tui.editor.cursorLineStart")) {
162
+ this.#lastAction = null;
163
+ this.#cursor = 0;
164
+ return;
165
+ }
166
+
167
+ if (kb.matches(data, "tui.editor.cursorLineEnd")) {
168
+ this.#lastAction = null;
169
+ this.#cursor = this.#value.length;
170
+ return;
171
+ }
172
+
173
+ if (kb.matches(data, "tui.editor.cursorWordLeft")) {
174
+ this.#moveWordBackwards();
175
+ return;
176
+ }
177
+
178
+ if (kb.matches(data, "tui.editor.cursorWordRight")) {
179
+ this.#moveWordForwards();
180
+ return;
181
+ }
182
+
183
+ // Regular character input, including Kitty CSI-u text-producing sequences.
184
+ const printableText = extractPrintableText(data);
185
+ if (printableText) {
186
+ this.#insertCharacter(printableText);
187
+ }
188
+ }
189
+
190
+ #insertCharacter(text: string): void {
191
+ const isWordChunk = [...segmenter.segment(text)].every(seg => getWordNavKind(seg.segment) !== "whitespace");
192
+ // Undo coalescing: consecutive word typing coalesces into one undo unit.
193
+ if (!isWordChunk || this.#lastAction !== "type-word") {
194
+ this.#pushUndo();
195
+ }
196
+ this.#lastAction = "type-word";
197
+
198
+ const inserted = insertTextNfcAt(this.#value, this.#cursor, text);
199
+ this.#value = inserted.value;
200
+ this.#cursor = inserted.cursor;
201
+ }
202
+
203
+ #handleBackspace(): void {
204
+ this.#lastAction = null;
205
+ if (this.#cursor <= 0) {
206
+ return;
207
+ }
208
+
209
+ this.#pushUndo();
210
+
211
+ const beforeCursor = this.#value.slice(0, this.#cursor);
212
+ const graphemes = [...segmenter.segment(beforeCursor)];
213
+ const lastGrapheme = graphemes[graphemes.length - 1];
214
+ const graphemeLength = lastGrapheme ? lastGrapheme.segment.length : 1;
215
+
216
+ this.#value = this.#value.slice(0, this.#cursor - graphemeLength) + this.#value.slice(this.#cursor);
217
+ this.#cursor -= graphemeLength;
218
+ }
219
+
220
+ #handleForwardDelete(): void {
221
+ this.#lastAction = null;
222
+ if (this.#cursor >= this.#value.length) {
223
+ return;
224
+ }
225
+
226
+ this.#pushUndo();
227
+
228
+ const afterCursor = this.#value.slice(this.#cursor);
229
+ const graphemes = [...segmenter.segment(afterCursor)];
230
+ const firstGrapheme = graphemes[0];
231
+ const graphemeLength = firstGrapheme ? firstGrapheme.segment.length : 1;
232
+
233
+ this.#value = this.#value.slice(0, this.#cursor) + this.#value.slice(this.#cursor + graphemeLength);
234
+ }
235
+
236
+ #deleteToLineStart(): void {
237
+ if (this.#cursor === 0) {
238
+ return;
239
+ }
240
+
241
+ this.#pushUndo();
242
+ const deletedText = this.#value.slice(0, this.#cursor);
243
+ this.#killRing.push(deletedText, { prepend: true, accumulate: this.#lastAction === "kill" });
244
+ this.#lastAction = "kill";
245
+
246
+ this.#value = this.#value.slice(this.#cursor);
247
+ this.#cursor = 0;
248
+ }
249
+
250
+ #deleteToLineEnd(): void {
251
+ if (this.#cursor >= this.#value.length) {
252
+ return;
253
+ }
254
+
255
+ this.#pushUndo();
256
+ const deletedText = this.#value.slice(this.#cursor);
257
+ this.#killRing.push(deletedText, { prepend: false, accumulate: this.#lastAction === "kill" });
258
+ this.#lastAction = "kill";
259
+
260
+ this.#value = this.#value.slice(0, this.#cursor);
261
+ }
262
+
263
+ #deleteWordBackwards(): void {
264
+ if (this.#cursor === 0) {
265
+ return;
266
+ }
267
+
268
+ // Save state before cursor movement (moveWordBackwards resets lastAction).
269
+ const wasKill = this.#lastAction === "kill";
270
+ this.#pushUndo();
271
+
272
+ const oldCursor = this.#cursor;
273
+ this.#moveWordBackwards();
274
+ const deleteFrom = this.#cursor;
275
+ this.#cursor = oldCursor;
276
+
277
+ const deletedText = this.#value.slice(deleteFrom, this.#cursor);
278
+ this.#killRing.push(deletedText, { prepend: true, accumulate: wasKill });
279
+ this.#lastAction = "kill";
280
+
281
+ this.#value = this.#value.slice(0, deleteFrom) + this.#value.slice(this.#cursor);
282
+ this.#cursor = deleteFrom;
283
+ }
284
+
285
+ #deleteWordForward(): void {
286
+ if (this.#cursor >= this.#value.length) {
287
+ return;
288
+ }
289
+
290
+ // Save state before cursor movement (moveWordForwards resets lastAction).
291
+ const wasKill = this.#lastAction === "kill";
292
+ this.#pushUndo();
293
+
294
+ const oldCursor = this.#cursor;
295
+ this.#moveWordForwards();
296
+ const deleteTo = this.#cursor;
297
+ this.#cursor = oldCursor;
298
+
299
+ const deletedText = this.#value.slice(this.#cursor, deleteTo);
300
+ this.#killRing.push(deletedText, { prepend: false, accumulate: wasKill });
301
+ this.#lastAction = "kill";
302
+
303
+ this.#value = this.#value.slice(0, this.#cursor) + this.#value.slice(deleteTo);
304
+ }
305
+
306
+ #yank(): void {
307
+ const text = this.#killRing.peek();
308
+ if (!text) {
309
+ return;
310
+ }
311
+
312
+ this.#pushUndo();
313
+ const inserted = insertTextNfcAt(this.#value, this.#cursor, text);
314
+ this.#value = inserted.value;
315
+ this.#cursor = inserted.cursor;
316
+ this.#lastAction = "yank";
317
+ }
318
+
319
+ #yankPop(): void {
320
+ if (this.#lastAction !== "yank" || this.#killRing.length <= 1) {
321
+ return;
322
+ }
323
+
324
+ this.#pushUndo();
325
+
326
+ const prevText = this.#killRing.peek() ?? "";
327
+ this.#value = this.#value.slice(0, this.#cursor - prevText.length) + this.#value.slice(this.#cursor);
328
+ this.#cursor -= prevText.length;
329
+
330
+ this.#killRing.rotate();
331
+ const text = this.#killRing.peek() ?? "";
332
+ const inserted = insertTextNfcAt(this.#value, this.#cursor, text);
333
+ this.#value = inserted.value;
334
+ this.#cursor = inserted.cursor;
335
+ this.#lastAction = "yank";
336
+ }
337
+
338
+ #pushUndo(): void {
339
+ this.#undoStack.push({ value: this.#value, cursor: this.#cursor });
340
+ }
341
+
342
+ #undo(): void {
343
+ const snapshot = this.#undoStack.pop();
344
+ if (!snapshot) {
345
+ return;
346
+ }
347
+ this.#value = snapshot.value;
348
+ this.#cursor = snapshot.cursor;
349
+ this.#lastAction = null;
350
+ }
351
+
352
+ #moveWordBackwards(): void {
353
+ if (this.#cursor === 0) {
354
+ return;
355
+ }
356
+ this.#lastAction = null;
357
+ this.#cursor = moveWordLeft(this.#value, this.#cursor);
358
+ }
359
+
360
+ #moveWordForwards(): void {
361
+ if (this.#cursor >= this.#value.length) {
362
+ return;
363
+ }
364
+ this.#lastAction = null;
365
+ this.#cursor = moveWordRight(this.#value, this.#cursor);
366
+ }
367
+
368
+ #handlePaste(pastedText: string): void {
369
+ this.#lastAction = null;
370
+ this.#pushUndo();
371
+
372
+ // Clean the pasted text — remove newlines and carriage returns, normalize
373
+ // tabs, AND normalize Unicode to NFC.
374
+ //
375
+ // NFC normalization rationale: macOS Finder drag-drops file paths in NFD
376
+ // (Conjoining Jamo, U+1100..U+11FF). `Bun.stringWidth` counts each
377
+ // conjoining jamo as a separate cell — a Korean syllable like `화` is
378
+ // 1 char and 2 cells in NFC, but 2 chars and 3 cells in NFD (ᄒ=2 cells
379
+ // + ᅪ=1 cell). The terminal renders the NFD sequence as a single
380
+ // combined syllable (2 cells visible), so the width mismatch shows up
381
+ // as cursor drift past the visible filename — N×~1.5 cells for a path
382
+ // with N Korean syllables. NFC normalization at paste time stores the
383
+ // value in the same form everything else in the codebase assumes.
384
+ const cleanText = replaceTabs(pastedText.replace(/\r\n/g, "").replace(/\r/g, "").replace(/\n/g, "")).normalize(
385
+ "NFC",
386
+ );
387
+
388
+ // Insert at cursor position
389
+ const inserted = insertTextNfcAt(this.#value, this.#cursor, cleanText);
390
+ this.#value = inserted.value;
391
+ this.#cursor = inserted.cursor;
392
+ }
393
+
394
+ invalidate(): void {
395
+ // No cached state to invalidate currently
396
+ }
397
+
398
+ render(width: number): string[] {
399
+ // Calculate visible window
400
+ const prompt = "> ";
401
+ const availableWidth = width - prompt.length;
402
+
403
+ if (availableWidth <= 0) {
404
+ return [prompt];
405
+ }
406
+
407
+ const cursorIndex = this.#cursor;
408
+ // Ensure we always have a grapheme to invert at the cursor (space at end).
409
+ const displayValue = cursorIndex >= this.#value.length ? `${this.#value} ` : this.#value;
410
+
411
+ const totalCols = visibleWidth(displayValue);
412
+ const cursorCols = visibleWidth(displayValue.slice(0, cursorIndex));
413
+
414
+ // Width of the grapheme at the cursor, for ensuring it fits in the viewport.
415
+ const cursorIter = segmenter.segment(displayValue.slice(cursorIndex))[Symbol.iterator]();
416
+ const cursorG = cursorIter.next().value?.segment ?? " ";
417
+ const cursorGWidth = visibleWidth(cursorG);
418
+
419
+ const maxStart = Math.max(0, totalCols - availableWidth);
420
+ let startCol = 0;
421
+ if (totalCols > availableWidth) {
422
+ const half = Math.floor(availableWidth / 2);
423
+ startCol = Math.max(0, Math.min(maxStart, cursorCols - half));
424
+
425
+ // Ensure the cursor grapheme is inside the viewport (and fits fully if wide).
426
+ const maxCursorRel = Math.max(0, availableWidth - cursorGWidth);
427
+ const cursorRel = cursorCols - startCol;
428
+ if (cursorRel > maxCursorRel) {
429
+ startCol = Math.max(0, Math.min(maxStart, cursorCols - maxCursorRel));
430
+ }
431
+ }
432
+
433
+ const visibleText = sliceWithWidth(displayValue, startCol, availableWidth, true).text;
434
+ const prefixText = sliceWithWidth(displayValue, startCol, Math.max(0, cursorCols - startCol), true).text;
435
+ let cursorDisplay = prefixText.length;
436
+ cursorDisplay = Math.max(0, Math.min(cursorDisplay, visibleText.length));
437
+
438
+ // Build line with fake cursor
439
+ // Insert cursor character at cursor position
440
+ const graphemes = [...segmenter.segment(visibleText.slice(cursorDisplay))];
441
+ const cursorGrapheme = graphemes[0];
442
+
443
+ const beforeCursor = visibleText.slice(0, cursorDisplay);
444
+ const atCursor = cursorGrapheme?.segment ?? " ";
445
+ const afterCursor = visibleText.slice(cursorDisplay + atCursor.length);
446
+
447
+ // Hardware cursor marker (zero-width, emitted before fake cursor for IME positioning)
448
+ const marker = this.focused ? CURSOR_MARKER : "";
449
+ // Use inverse video to show cursor
450
+ const cursorChar = `\x1b[7m${atCursor}\x1b[27m`; // ESC[7m = reverse video, ESC[27m = normal
451
+
452
+ // Clamp only the trailing text (measured in terminal cells), keeping the cursor marker intact.
453
+ const beforeWidth = visibleWidth(beforeCursor);
454
+ const cursorWidth = visibleWidth(atCursor);
455
+ const remainingAfterWidth = Math.max(0, availableWidth - beforeWidth - cursorWidth);
456
+ const clampedAfterCursor = sliceWithWidth(afterCursor, 0, remainingAfterWidth, true).text;
457
+ const renderedNoMarker = beforeCursor + cursorChar + clampedAfterCursor;
458
+ const textWithCursor = beforeCursor + marker + cursorChar + clampedAfterCursor;
459
+
460
+ const visualLength = visibleWidth(renderedNoMarker);
461
+ const pad = padding(Math.max(0, availableWidth - visualLength));
462
+ const line = prompt + textWithCursor + pad;
463
+ return [line];
464
+ }
465
+ }
@@ -0,0 +1,86 @@
1
+ import type { TUI } from "../tui";
2
+ import { sliceByColumn, visibleWidth } from "../utils";
3
+ import { Text } from "./text";
4
+
5
+ /**
6
+ * Loader component that drives display refresh at ~60fps so callers whose
7
+ * message colorizer is time-dependent (e.g. shimmer/KITT) animate smoothly.
8
+ *
9
+ * Two cadences are interleaved on a single timer:
10
+ * - **Render tick** (every `RENDER_INTERVAL_MS`) → asks the TUI to redraw.
11
+ * The TUI already throttles at 16ms (`MIN_RENDER_INTERVAL_MS`), so this
12
+ * is the natural upper bound; static messageColorFns produce identical
13
+ * output and the differ drops the no-op redraw at ~zero cost.
14
+ * - **Spinner advance** (every `SPINNER_ADVANCE_MS`) → bumps the spinner
15
+ * frame index. Decoupled from the render cadence so the spinner keeps
16
+ * its classic ~12.5fps step pace regardless of shimmer state.
17
+ */
18
+ const RENDER_INTERVAL_MS = 16;
19
+ const SPINNER_ADVANCE_MS = 80;
20
+
21
+ export class Loader extends Text {
22
+ #frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
23
+ #currentFrame = 0;
24
+ #intervalId?: NodeJS.Timeout;
25
+ #ui: TUI | null = null;
26
+ #lastSpinnerTick = 0;
27
+
28
+ constructor(
29
+ ui: TUI,
30
+ private spinnerColorFn: (str: string) => string,
31
+ private messageColorFn: (str: string) => string,
32
+ private message: string = "Loading...",
33
+ spinnerFrames?: string[],
34
+ ) {
35
+ super("", 1, 0);
36
+ this.#ui = ui;
37
+ if (spinnerFrames && spinnerFrames.length > 0) {
38
+ this.#frames = spinnerFrames;
39
+ }
40
+ this.start();
41
+ }
42
+
43
+ render(width: number): string[] {
44
+ const lines = ["", ...super.render(width)];
45
+ for (let i = 0; i < lines.length; i++) {
46
+ const line = lines[i];
47
+ if (visibleWidth(line) > width) {
48
+ lines[i] = sliceByColumn(line, 0, width, true);
49
+ }
50
+ }
51
+ return lines;
52
+ }
53
+
54
+ start() {
55
+ this.#lastSpinnerTick = performance.now();
56
+ this.#updateDisplay();
57
+ this.#intervalId = setInterval(() => {
58
+ const now = performance.now();
59
+ if (now - this.#lastSpinnerTick >= SPINNER_ADVANCE_MS) {
60
+ this.#currentFrame = (this.#currentFrame + 1) % this.#frames.length;
61
+ this.#lastSpinnerTick = now;
62
+ }
63
+ this.#updateDisplay();
64
+ }, RENDER_INTERVAL_MS);
65
+ }
66
+
67
+ stop() {
68
+ if (this.#intervalId) {
69
+ clearInterval(this.#intervalId);
70
+ this.#intervalId = undefined;
71
+ }
72
+ }
73
+
74
+ setMessage(message: string) {
75
+ this.message = message;
76
+ this.#updateDisplay();
77
+ }
78
+
79
+ #updateDisplay() {
80
+ const frame = this.#frames[this.#currentFrame];
81
+ this.setText(`${this.spinnerColorFn(frame)} ${this.messageColorFn(this.message)}`);
82
+ if (this.#ui) {
83
+ this.#ui.requestRender();
84
+ }
85
+ }
86
+ }