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