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