@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
package/README.md ADDED
@@ -0,0 +1,779 @@
1
+ # @elyracode/tui
2
+
3
+ Minimal terminal UI framework with differential rendering and synchronized output for flicker-free interactive CLI applications.
4
+
5
+ ## Features
6
+
7
+ - **Differential Rendering**: Three-strategy rendering system that only updates what changed
8
+ - **Synchronized Output**: Uses CSI 2026 for atomic screen updates (no flicker)
9
+ - **Bracketed Paste Mode**: Handles large pastes correctly with markers for >10 line pastes
10
+ - **Component-based**: Simple Component interface with render() method
11
+ - **Theme Support**: Components accept theme interfaces for customizable styling
12
+ - **Built-in Components**: Text, TruncatedText, Input, Editor, Markdown, Loader, SelectList, SettingsList, Spacer, Image, Box, Container
13
+ - **Inline Images**: Renders images in terminals that support Kitty or iTerm2 graphics protocols
14
+ - **Autocomplete Support**: File paths and slash commands
15
+
16
+ ## Quick Start
17
+
18
+ ```typescript
19
+ import { TUI, Text, Editor, ProcessTerminal, matchesKey } from "@elyracode/tui";
20
+
21
+ // Create terminal
22
+ const terminal = new ProcessTerminal();
23
+
24
+ // Create TUI
25
+ const tui = new TUI(terminal);
26
+
27
+ // Add components
28
+ tui.addChild(new Text("Welcome to my app!"));
29
+
30
+ import { defaultEditorTheme as editorTheme } from './test/test-themes.ts';
31
+ const editor = new Editor(tui, editorTheme);
32
+ editor.onSubmit = (text) => {
33
+ console.log("Submitted:", text);
34
+ tui.addChild(new Text(`You said: ${text}`));
35
+ };
36
+ tui.addChild(editor);
37
+
38
+ // Focus the editor so it receives keyboard input
39
+ tui.setFocus(editor);
40
+
41
+ // In raw mode Ctrl+C doesn't send SIGINT — intercept it here to allow exit
42
+ tui.addInputListener((data) => {
43
+ if (matchesKey(data, 'ctrl+c')) {
44
+ tui.stop();
45
+ process.exit(0);
46
+ }
47
+ });
48
+
49
+ // Start
50
+ tui.start();
51
+ ```
52
+
53
+ ## Core API
54
+
55
+ ### TUI
56
+
57
+ Main container that manages components and rendering.
58
+
59
+ ```typescript
60
+ const tui = new TUI(terminal);
61
+ tui.addChild(component);
62
+ tui.removeChild(component);
63
+ tui.start();
64
+ tui.stop();
65
+ tui.requestRender(); // Request a re-render
66
+
67
+ // Global debug key handler (Shift+Ctrl+D)
68
+ tui.onDebug = () => console.log("Debug triggered");
69
+ ```
70
+
71
+ ### Overlays
72
+
73
+ Overlays render components on top of existing content without replacing it. Useful for dialogs, menus, and modal UI.
74
+
75
+ ```typescript
76
+ // Show overlay with default options (centered, max 80 cols)
77
+ const handle = tui.showOverlay(component);
78
+
79
+ // Show overlay with custom positioning and sizing
80
+ // Values can be numbers (absolute) or percentage strings (e.g., "50%")
81
+ const handle = tui.showOverlay(component, {
82
+ // Sizing
83
+ width: 60, // Fixed width in columns
84
+ width: "80%", // Width as percentage of terminal
85
+ minWidth: 40, // Minimum width floor
86
+ maxHeight: 20, // Maximum height in rows
87
+ maxHeight: "50%", // Maximum height as percentage of terminal
88
+
89
+ // Anchor-based positioning (default: 'center')
90
+ anchor: 'bottom-right', // Position relative to anchor point
91
+ offsetX: 2, // Horizontal offset from anchor
92
+ offsetY: -1, // Vertical offset from anchor
93
+
94
+ // Percentage-based positioning (alternative to anchor)
95
+ row: "25%", // Vertical position (0%=top, 100%=bottom)
96
+ col: "50%", // Horizontal position (0%=left, 100%=right)
97
+
98
+ // Absolute positioning (overrides anchor/percent)
99
+ row: 5, // Exact row position
100
+ col: 10, // Exact column position
101
+
102
+ // Margin from terminal edges
103
+ margin: 2, // All sides
104
+ margin: { top: 1, right: 2, bottom: 1, left: 2 },
105
+
106
+ // Responsive visibility
107
+ visible: (termWidth, termHeight) => termWidth >= 100 // Hide on narrow terminals
108
+
109
+ // Focus behavior
110
+ nonCapturing: true // Don't auto-focus when shown
111
+ });
112
+
113
+ // OverlayHandle methods
114
+ handle.hide(); // Permanently remove the overlay
115
+ handle.setHidden(true); // Temporarily hide (can show again)
116
+ handle.setHidden(false); // Show again after hiding
117
+ handle.isHidden(); // Check if temporarily hidden
118
+ handle.focus(); // Focus and bring to visual front
119
+ handle.unfocus(); // Release focus to previous target
120
+ handle.isFocused(); // Check if overlay has focus
121
+
122
+ // Hide topmost overlay
123
+ tui.hideOverlay();
124
+
125
+ // Check if any visible overlay is active
126
+ tui.hasOverlay();
127
+ ```
128
+
129
+ **Anchor values**: `'center'`, `'top-left'`, `'top-right'`, `'bottom-left'`, `'bottom-right'`, `'top-center'`, `'bottom-center'`, `'left-center'`, `'right-center'`
130
+
131
+ **Resolution order**:
132
+ 1. `minWidth` is applied as a floor after width calculation
133
+ 2. For position: absolute `row`/`col` > percentage `row`/`col` > `anchor`
134
+ 3. `margin` clamps final position to stay within terminal bounds
135
+ 4. `visible` callback controls whether overlay renders (called each frame)
136
+
137
+ ### Component Interface
138
+
139
+ All components implement:
140
+
141
+ ```typescript
142
+ interface Component {
143
+ render(width: number): string[];
144
+ handleInput?(data: string): void;
145
+ invalidate?(): void;
146
+ }
147
+ ```
148
+
149
+ | Method | Description |
150
+ |--------|-------------|
151
+ | `render(width)` | Returns an array of strings, one per line. Each line **must not exceed `width`** or the TUI will error. Use `truncateToWidth()` or manual wrapping to ensure this. |
152
+ | `handleInput?(data)` | Called when the component has focus and receives keyboard input. The `data` string contains raw terminal input (may include ANSI escape sequences). |
153
+ | `invalidate?()` | Called to clear any cached render state. Components should re-render from scratch on the next `render()` call. |
154
+
155
+ The TUI appends a full SGR reset and OSC 8 reset at the end of each rendered line. Styles do not carry across lines. If you emit multi-line text with styling, reapply styles per line or use `wrapTextWithAnsi()` so styles are preserved for each wrapped line.
156
+
157
+ ### Focusable Interface (IME Support)
158
+
159
+ Components that display a text cursor and need IME (Input Method Editor) support should implement the `Focusable` interface:
160
+
161
+ ```typescript
162
+ import { CURSOR_MARKER, type Component, type Focusable } from "@elyracode/tui";
163
+
164
+ class MyInput implements Component, Focusable {
165
+ focused: boolean = false; // Set by TUI when focus changes
166
+
167
+ render(width: number): string[] {
168
+ const marker = this.focused ? CURSOR_MARKER : "";
169
+ // Emit marker right before the fake cursor
170
+ return [`> ${beforeCursor}${marker}\x1b[7m${atCursor}\x1b[27m${afterCursor}`];
171
+ }
172
+ }
173
+ ```
174
+
175
+ When a `Focusable` component has focus, TUI:
176
+ 1. Sets `focused = true` on the component
177
+ 2. Scans rendered output for `CURSOR_MARKER` (a zero-width APC escape sequence)
178
+ 3. Positions the hardware terminal cursor at that location
179
+ 4. Shows the hardware cursor
180
+
181
+ This enables IME candidate windows to appear at the correct position for CJK input methods. The `Editor` and `Input` built-in components already implement this interface.
182
+
183
+ **Container components with embedded inputs:** When a container component (dialog, selector, etc.) contains an `Input` or `Editor` child, the container must implement `Focusable` and propagate the focus state to the child:
184
+
185
+ ```typescript
186
+ import { Container, type Focusable, Input } from "@elyracode/tui";
187
+
188
+ class SearchDialog extends Container implements Focusable {
189
+ private searchInput: Input;
190
+
191
+ // Propagate focus to child input for IME cursor positioning
192
+ private _focused = false;
193
+ get focused(): boolean { return this._focused; }
194
+ set focused(value: boolean) {
195
+ this._focused = value;
196
+ this.searchInput.focused = value;
197
+ }
198
+
199
+ constructor() {
200
+ super();
201
+ this.searchInput = new Input();
202
+ this.addChild(this.searchInput);
203
+ }
204
+ }
205
+ ```
206
+
207
+ Without this propagation, typing with an IME (Chinese, Japanese, Korean, etc.) will show the candidate window in the wrong position.
208
+
209
+ ## Built-in Components
210
+
211
+ ### Container
212
+
213
+ Groups child components.
214
+
215
+ ```typescript
216
+ const container = new Container();
217
+ container.addChild(component);
218
+ container.removeChild(component);
219
+ ```
220
+
221
+ ### Box
222
+
223
+ Container that applies padding and background color to all children.
224
+
225
+ ```typescript
226
+ const box = new Box(
227
+ 1, // paddingX (default: 1)
228
+ 1, // paddingY (default: 1)
229
+ (text) => chalk.bgGray(text) // optional background function
230
+ );
231
+ box.addChild(new Text("Content"));
232
+ box.setBgFn((text) => chalk.bgBlue(text)); // Change background dynamically
233
+ ```
234
+
235
+ ### Text
236
+
237
+ Displays multi-line text with word wrapping and padding.
238
+
239
+ ```typescript
240
+ const text = new Text(
241
+ "Hello World", // text content
242
+ 1, // paddingX (default: 1)
243
+ 1, // paddingY (default: 1)
244
+ (text) => chalk.bgGray(text) // optional background function
245
+ );
246
+ text.setText("Updated text");
247
+ text.setCustomBgFn((text) => chalk.bgBlue(text));
248
+ ```
249
+
250
+ ### TruncatedText
251
+
252
+ Single-line text that truncates to fit viewport width. Useful for status lines and headers.
253
+
254
+ ```typescript
255
+ const truncated = new TruncatedText(
256
+ "This is a very long line that will be truncated...",
257
+ 0, // paddingX (default: 0)
258
+ 0 // paddingY (default: 0)
259
+ );
260
+ ```
261
+
262
+ ### Input
263
+
264
+ Single-line text input with horizontal scrolling.
265
+
266
+ ```typescript
267
+ const input = new Input();
268
+ input.onSubmit = (value) => console.log(value);
269
+ input.setValue("initial");
270
+ input.getValue();
271
+ ```
272
+
273
+ **Key Bindings:**
274
+ - `Enter` - Submit
275
+ - `Ctrl+A` / `Ctrl+E` - Line start/end
276
+ - `Ctrl+W` or `Alt+Backspace` - Delete word backwards
277
+ - `Ctrl+U` - Delete to start of line
278
+ - `Ctrl+K` - Delete to end of line
279
+ - `Ctrl+Left` / `Ctrl+Right` - Word navigation
280
+ - `Alt+Left` / `Alt+Right` - Word navigation
281
+ - Arrow keys, Backspace, Delete work as expected
282
+
283
+ ### Editor
284
+
285
+ Multi-line text editor with autocomplete, file completion, paste handling, and vertical scrolling when content exceeds terminal height.
286
+
287
+ ```typescript
288
+ interface EditorTheme {
289
+ borderColor: (str: string) => string;
290
+ selectList: SelectListTheme;
291
+ }
292
+
293
+ interface EditorOptions {
294
+ paddingX?: number; // Horizontal padding (default: 0)
295
+ }
296
+
297
+ const editor = new Editor(tui, theme, options?); // tui is required for height-aware scrolling
298
+ editor.onSubmit = (text) => console.log(text);
299
+ editor.onChange = (text) => console.log("Changed:", text);
300
+ editor.disableSubmit = true; // Disable submit temporarily
301
+ editor.setAutocompleteProvider(provider);
302
+ editor.borderColor = (s) => chalk.blue(s); // Change border dynamically
303
+ editor.setPaddingX(1); // Update horizontal padding dynamically
304
+ editor.getPaddingX(); // Get current padding
305
+ ```
306
+
307
+ **Features:**
308
+ - Multi-line editing with word wrap
309
+ - Slash command autocomplete (type `/`)
310
+ - File path autocomplete (press `Tab`)
311
+ - Large paste handling (>10 lines creates `[paste #1 +50 lines]` marker)
312
+ - Horizontal lines above/below editor
313
+ - Fake cursor rendering (hidden real cursor)
314
+
315
+ **Key Bindings:**
316
+ - `Enter` - Submit
317
+ - `Shift+Enter`, `Ctrl+Enter`, or `Alt+Enter` - New line (terminal-dependent, Alt+Enter most reliable)
318
+ - `Tab` - Autocomplete
319
+ - `Ctrl+K` - Delete to end of line
320
+ - `Ctrl+U` - Delete to start of line
321
+ - `Ctrl+W` or `Alt+Backspace` - Delete word backwards
322
+ - `Alt+D` or `Alt+Delete` - Delete word forwards
323
+ - `Ctrl+A` / `Ctrl+E` - Line start/end
324
+ - `Ctrl+]` - Jump forward to character (awaits next keypress, then moves cursor to first occurrence)
325
+ - `Ctrl+Alt+]` - Jump backward to character
326
+ - Arrow keys, Backspace, Delete work as expected
327
+
328
+ ### Markdown
329
+
330
+ Renders markdown with syntax highlighting and theming support.
331
+
332
+ ```typescript
333
+ interface MarkdownTheme {
334
+ heading: (text: string) => string;
335
+ link: (text: string) => string;
336
+ linkUrl: (text: string) => string;
337
+ code: (text: string) => string;
338
+ codeBlock: (text: string) => string;
339
+ codeBlockBorder: (text: string) => string;
340
+ quote: (text: string) => string;
341
+ quoteBorder: (text: string) => string;
342
+ hr: (text: string) => string;
343
+ listBullet: (text: string) => string;
344
+ bold: (text: string) => string;
345
+ italic: (text: string) => string;
346
+ strikethrough: (text: string) => string;
347
+ underline: (text: string) => string;
348
+ highlightCode?: (code: string, lang?: string) => string[];
349
+ }
350
+
351
+ interface DefaultTextStyle {
352
+ color?: (text: string) => string;
353
+ bgColor?: (text: string) => string;
354
+ bold?: boolean;
355
+ italic?: boolean;
356
+ strikethrough?: boolean;
357
+ underline?: boolean;
358
+ }
359
+
360
+ const md = new Markdown(
361
+ "# Hello\n\nSome **bold** text",
362
+ 1, // paddingX
363
+ 1, // paddingY
364
+ theme, // MarkdownTheme
365
+ defaultStyle // optional DefaultTextStyle
366
+ );
367
+ md.setText("Updated markdown");
368
+ ```
369
+
370
+ **Features:**
371
+ - Headings, bold, italic, code blocks, lists, links, blockquotes
372
+ - HTML tags rendered as plain text
373
+ - Optional syntax highlighting via `highlightCode`
374
+ - Padding support
375
+ - Render caching for performance
376
+
377
+ ### Loader
378
+
379
+ Animated loading spinner.
380
+
381
+ ```typescript
382
+ const loader = new Loader(
383
+ tui, // TUI instance for render updates
384
+ (s) => chalk.cyan(s), // spinner color function
385
+ (s) => chalk.gray(s), // message color function
386
+ "Loading..." // message (default: "Loading...")
387
+ );
388
+ loader.start();
389
+ loader.setMessage("Still loading...");
390
+ loader.stop();
391
+ ```
392
+
393
+ ### CancellableLoader
394
+
395
+ Extends Loader with Escape key handling and an AbortSignal for cancelling async operations.
396
+
397
+ ```typescript
398
+ const loader = new CancellableLoader(
399
+ tui, // TUI instance for render updates
400
+ (s) => chalk.cyan(s), // spinner color function
401
+ (s) => chalk.gray(s), // message color function
402
+ "Working..." // message
403
+ );
404
+ loader.onAbort = () => done(null); // Called when user presses Escape
405
+ doAsyncWork(loader.signal).then(done);
406
+ ```
407
+
408
+ **Properties:**
409
+ - `signal: AbortSignal` - Aborted when user presses Escape
410
+ - `aborted: boolean` - Whether the loader was aborted
411
+ - `onAbort?: () => void` - Callback when user presses Escape
412
+
413
+ ### SelectList
414
+
415
+ Interactive selection list with keyboard navigation.
416
+
417
+ ```typescript
418
+ interface SelectItem {
419
+ value: string;
420
+ label: string;
421
+ description?: string;
422
+ }
423
+
424
+ interface SelectListTheme {
425
+ selectedPrefix: (text: string) => string;
426
+ selectedText: (text: string) => string;
427
+ description: (text: string) => string;
428
+ scrollInfo: (text: string) => string;
429
+ noMatch: (text: string) => string;
430
+ }
431
+
432
+ const list = new SelectList(
433
+ [
434
+ { value: "opt1", label: "Option 1", description: "First option" },
435
+ { value: "opt2", label: "Option 2", description: "Second option" },
436
+ ],
437
+ 5, // maxVisible
438
+ theme // SelectListTheme
439
+ );
440
+
441
+ list.onSelect = (item) => console.log("Selected:", item);
442
+ list.onCancel = () => console.log("Cancelled");
443
+ list.onSelectionChange = (item) => console.log("Highlighted:", item);
444
+ list.setFilter("opt"); // Filter items
445
+ ```
446
+
447
+ **Controls:**
448
+ - Arrow keys: Navigate
449
+ - Enter: Select
450
+ - Escape: Cancel
451
+
452
+ ### SettingsList
453
+
454
+ Settings panel with value cycling and submenus.
455
+
456
+ ```typescript
457
+ interface SettingItem {
458
+ id: string;
459
+ label: string;
460
+ description?: string;
461
+ currentValue: string;
462
+ values?: string[]; // If provided, Enter/Space cycles through these
463
+ submenu?: (currentValue: string, done: (selectedValue?: string) => void) => Component;
464
+ }
465
+
466
+ interface SettingsListTheme {
467
+ label: (text: string, selected: boolean) => string;
468
+ value: (text: string, selected: boolean) => string;
469
+ description: (text: string) => string;
470
+ cursor: string;
471
+ hint: (text: string) => string;
472
+ }
473
+
474
+ const settings = new SettingsList(
475
+ [
476
+ { id: "theme", label: "Theme", currentValue: "dark", values: ["dark", "light"] },
477
+ { id: "model", label: "Model", currentValue: "gpt-4", submenu: (val, done) => modelSelector },
478
+ ],
479
+ 10, // maxVisible
480
+ theme, // SettingsListTheme
481
+ (id, newValue) => console.log(`${id} changed to ${newValue}`),
482
+ () => console.log("Cancelled")
483
+ );
484
+ settings.updateValue("theme", "light");
485
+ ```
486
+
487
+ **Controls:**
488
+ - Arrow keys: Navigate
489
+ - Enter/Space: Activate (cycle value or open submenu)
490
+ - Escape: Cancel
491
+
492
+ ### Spacer
493
+
494
+ Empty lines for vertical spacing.
495
+
496
+ ```typescript
497
+ const spacer = new Spacer(2); // 2 empty lines (default: 1)
498
+ ```
499
+
500
+ ### Image
501
+
502
+ Renders images inline for terminals that support the Kitty graphics protocol (Kitty, Ghostty, WezTerm) or iTerm2 inline images. Falls back to a text placeholder on unsupported terminals.
503
+
504
+ ```typescript
505
+ interface ImageTheme {
506
+ fallbackColor: (str: string) => string;
507
+ }
508
+
509
+ interface ImageOptions {
510
+ maxWidthCells?: number;
511
+ maxHeightCells?: number;
512
+ filename?: string;
513
+ }
514
+
515
+ const image = new Image(
516
+ base64Data, // base64-encoded image data
517
+ "image/png", // MIME type
518
+ theme, // ImageTheme
519
+ options // optional ImageOptions
520
+ );
521
+ tui.addChild(image);
522
+ ```
523
+
524
+ Supported formats: PNG, JPEG, GIF, WebP. Dimensions are parsed from the image headers automatically.
525
+
526
+ ## Autocomplete
527
+
528
+ ### CombinedAutocompleteProvider
529
+
530
+ Supports both slash commands and file paths.
531
+
532
+ ```typescript
533
+ import { CombinedAutocompleteProvider } from "@elyracode/tui";
534
+
535
+ const provider = new CombinedAutocompleteProvider(
536
+ [
537
+ { name: "help", description: "Show help" },
538
+ { name: "clear", description: "Clear screen" },
539
+ { name: "delete", description: "Delete last message" },
540
+ ],
541
+ process.cwd() // base path for file completion
542
+ );
543
+
544
+ editor.setAutocompleteProvider(provider);
545
+ ```
546
+
547
+ **Features:**
548
+ - Type `/` to see slash commands
549
+ - Press `Tab` for file path completion
550
+ - Works with `~/`, `./`, `../`, and `@` prefix
551
+ - Filters to attachable files for `@` prefix
552
+
553
+ ## Key Detection
554
+
555
+ Use `matchesKey()` with the `Key` helper for detecting keyboard input (supports Kitty keyboard protocol):
556
+
557
+ ```typescript
558
+ import { matchesKey, Key } from "@elyracode/tui";
559
+
560
+ if (matchesKey(data, Key.ctrl("c"))) {
561
+ process.exit(0);
562
+ }
563
+
564
+ if (matchesKey(data, Key.enter)) {
565
+ submit();
566
+ } else if (matchesKey(data, Key.escape)) {
567
+ cancel();
568
+ } else if (matchesKey(data, Key.up)) {
569
+ moveUp();
570
+ }
571
+ ```
572
+
573
+ **Key identifiers** (use `Key.*` for autocomplete, or string literals):
574
+ - Basic keys: `Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end`
575
+ - Arrow keys: `Key.up`, `Key.down`, `Key.left`, `Key.right`
576
+ - With modifiers: `Key.ctrl("c")`, `Key.shift("tab")`, `Key.alt("left")`, `Key.ctrlShift("p")`
577
+ - String format also works: `"enter"`, `"ctrl+c"`, `"shift+tab"`, `"ctrl+shift+p"`
578
+
579
+ ## Differential Rendering
580
+
581
+ The TUI uses three rendering strategies:
582
+
583
+ 1. **First Render**: Output all lines without clearing scrollback
584
+ 2. **Width Changed or Change Above Viewport**: Clear screen and full re-render
585
+ 3. **Normal Update**: Move cursor to first changed line, clear to end, render changed lines
586
+
587
+ All updates are wrapped in **synchronized output** (`\x1b[?2026h` ... `\x1b[?2026l`) for atomic, flicker-free rendering.
588
+
589
+ ## Terminal Interface
590
+
591
+ The TUI works with any object implementing the `Terminal` interface:
592
+
593
+ ```typescript
594
+ interface Terminal {
595
+ start(onInput: (data: string) => void, onResize: () => void): void;
596
+ stop(): void;
597
+ write(data: string): void;
598
+ get columns(): number;
599
+ get rows(): number;
600
+ moveBy(lines: number): void;
601
+ hideCursor(): void;
602
+ showCursor(): void;
603
+ clearLine(): void;
604
+ clearFromCursor(): void;
605
+ clearScreen(): void;
606
+ }
607
+ ```
608
+
609
+ **Built-in implementations:**
610
+ - `ProcessTerminal` - Uses `process.stdin/stdout`
611
+ - `VirtualTerminal` - For testing (uses `@xterm/headless`)
612
+
613
+ ## Utilities
614
+
615
+ ```typescript
616
+ import { visibleWidth, truncateToWidth, wrapTextWithAnsi } from "@elyracode/tui";
617
+
618
+ // Get visible width of string (ignoring ANSI codes)
619
+ const width = visibleWidth("\x1b[31mHello\x1b[0m"); // 5
620
+
621
+ // Truncate string to width (preserving ANSI codes, adds ellipsis)
622
+ const truncated = truncateToWidth("Hello World", 8); // "Hello..."
623
+
624
+ // Truncate without ellipsis
625
+ const truncatedNoEllipsis = truncateToWidth("Hello World", 8, ""); // "Hello Wo"
626
+
627
+ // Wrap text to width (preserving ANSI codes across line breaks)
628
+ const lines = wrapTextWithAnsi("This is a long line that needs wrapping", 20);
629
+ // ["This is a long line", "that needs wrapping"]
630
+ ```
631
+
632
+ ## Creating Custom Components
633
+
634
+ When creating custom components, **each line returned by `render()` must not exceed the `width` parameter**. The TUI will error if any line is wider than the terminal.
635
+
636
+ ### Handling Input
637
+
638
+ Use `matchesKey()` with the `Key` helper for keyboard input:
639
+
640
+ ```typescript
641
+ import { matchesKey, Key, truncateToWidth } from "@elyracode/tui";
642
+ import type { Component } from "@elyracode/tui";
643
+
644
+ class MyInteractiveComponent implements Component {
645
+ private selectedIndex = 0;
646
+ private items = ["Option 1", "Option 2", "Option 3"];
647
+
648
+ public onSelect?: (index: number) => void;
649
+ public onCancel?: () => void;
650
+
651
+ handleInput(data: string): void {
652
+ if (matchesKey(data, Key.up)) {
653
+ this.selectedIndex = Math.max(0, this.selectedIndex - 1);
654
+ } else if (matchesKey(data, Key.down)) {
655
+ this.selectedIndex = Math.min(this.items.length - 1, this.selectedIndex + 1);
656
+ } else if (matchesKey(data, Key.enter)) {
657
+ this.onSelect?.(this.selectedIndex);
658
+ } else if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
659
+ this.onCancel?.();
660
+ }
661
+ }
662
+
663
+ render(width: number): string[] {
664
+ return this.items.map((item, i) => {
665
+ const prefix = i === this.selectedIndex ? "> " : " ";
666
+ return truncateToWidth(prefix + item, width);
667
+ });
668
+ }
669
+ }
670
+ ```
671
+
672
+ ### Handling Line Width
673
+
674
+ Use the provided utilities to ensure lines fit:
675
+
676
+ ```typescript
677
+ import { visibleWidth, truncateToWidth } from "@elyracode/tui";
678
+ import type { Component } from "@elyracode/tui";
679
+
680
+ class MyComponent implements Component {
681
+ private text: string;
682
+
683
+ constructor(text: string) {
684
+ this.text = text;
685
+ }
686
+
687
+ render(width: number): string[] {
688
+ // Option 1: Truncate long lines
689
+ return [truncateToWidth(this.text, width)];
690
+
691
+ // Option 2: Check and pad to exact width
692
+ const line = this.text;
693
+ const visible = visibleWidth(line);
694
+ if (visible > width) {
695
+ return [truncateToWidth(line, width)];
696
+ }
697
+ // Pad to exact width (optional, for backgrounds)
698
+ return [line + " ".repeat(width - visible)];
699
+ }
700
+ }
701
+ ```
702
+
703
+ ### ANSI Code Considerations
704
+
705
+ Both `visibleWidth()` and `truncateToWidth()` correctly handle ANSI escape codes:
706
+
707
+ - `visibleWidth()` ignores ANSI codes when calculating width
708
+ - `truncateToWidth()` preserves ANSI codes and properly closes them when truncating
709
+
710
+ ```typescript
711
+ import chalk from "chalk";
712
+
713
+ const styled = chalk.red("Hello") + " " + chalk.blue("World");
714
+ const width = visibleWidth(styled); // 11 (not counting ANSI codes)
715
+ const truncated = truncateToWidth(styled, 8); // Red "Hello" + " W..." with proper reset
716
+ ```
717
+
718
+ ### Caching
719
+
720
+ For performance, components should cache their rendered output and only re-render when necessary:
721
+
722
+ ```typescript
723
+ class CachedComponent implements Component {
724
+ private text: string;
725
+ private cachedWidth?: number;
726
+ private cachedLines?: string[];
727
+
728
+ render(width: number): string[] {
729
+ if (this.cachedLines && this.cachedWidth === width) {
730
+ return this.cachedLines;
731
+ }
732
+
733
+ const lines = [truncateToWidth(this.text, width)];
734
+
735
+ this.cachedWidth = width;
736
+ this.cachedLines = lines;
737
+ return lines;
738
+ }
739
+
740
+ invalidate(): void {
741
+ this.cachedWidth = undefined;
742
+ this.cachedLines = undefined;
743
+ }
744
+ }
745
+ ```
746
+
747
+ ## Example
748
+
749
+ See `test/chat-simple.ts` for a complete chat interface example with:
750
+ - Markdown messages with custom background colors
751
+ - Loading spinner during responses
752
+ - Editor with autocomplete and slash commands
753
+ - Spacers between messages
754
+
755
+ Run it:
756
+ ```bash
757
+ npx tsx test/chat-simple.ts
758
+ ```
759
+
760
+ ## Development
761
+
762
+ ```bash
763
+ # Install dependencies (from monorepo root)
764
+ npm install
765
+
766
+ # Run type checking
767
+ npm run check
768
+
769
+ # Run the demo
770
+ npx tsx test/chat-simple.ts
771
+ ```
772
+
773
+ ### Debug logging
774
+
775
+ Set `ELYRA_TUI_WRITE_LOG` to capture the raw ANSI stream written to stdout.
776
+
777
+ ```bash
778
+ ELYRA_TUI_WRITE_LOG=/tmp/tui-ansi.log npx tsx test/chat-simple.ts
779
+ ```