@openadapter/koda-tui 1.0.0-beta.3

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