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