@diffra-ai/tui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +950 -2
  3. package/dist/alt-screen-search.d.ts +46 -0
  4. package/dist/alt-screen-search.d.ts.map +1 -0
  5. package/dist/alt-screen-search.js +282 -0
  6. package/dist/alt-screen-search.js.map +1 -0
  7. package/dist/autocomplete.d.ts +57 -0
  8. package/dist/autocomplete.d.ts.map +1 -0
  9. package/dist/autocomplete.js +690 -0
  10. package/dist/autocomplete.js.map +1 -0
  11. package/dist/colors.d.ts +73 -0
  12. package/dist/colors.d.ts.map +1 -0
  13. package/dist/colors.js +273 -0
  14. package/dist/colors.js.map +1 -0
  15. package/dist/components/alt-screen-flash.d.ts +13 -0
  16. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  17. package/dist/components/alt-screen-flash.js +37 -0
  18. package/dist/components/alt-screen-flash.js.map +1 -0
  19. package/dist/components/box.d.ts +24 -0
  20. package/dist/components/box.d.ts.map +1 -0
  21. package/dist/components/box.js +110 -0
  22. package/dist/components/box.js.map +1 -0
  23. package/dist/components/cancellable-loader.d.ts +22 -0
  24. package/dist/components/cancellable-loader.d.ts.map +1 -0
  25. package/dist/components/cancellable-loader.js +35 -0
  26. package/dist/components/cancellable-loader.js.map +1 -0
  27. package/dist/components/editor.d.ts +263 -0
  28. package/dist/components/editor.d.ts.map +1 -0
  29. package/dist/components/editor.js +2061 -0
  30. package/dist/components/editor.js.map +1 -0
  31. package/dist/components/h-stack.d.ts +7 -0
  32. package/dist/components/h-stack.d.ts.map +1 -0
  33. package/dist/components/h-stack.js +43 -0
  34. package/dist/components/h-stack.js.map +1 -0
  35. package/dist/components/image.d.ts +40 -0
  36. package/dist/components/image.d.ts.map +1 -0
  37. package/dist/components/image.js +123 -0
  38. package/dist/components/image.js.map +1 -0
  39. package/dist/components/input.d.ts +48 -0
  40. package/dist/components/input.d.ts.map +1 -0
  41. package/dist/components/input.js +417 -0
  42. package/dist/components/input.js.map +1 -0
  43. package/dist/components/loader.d.ts +33 -0
  44. package/dist/components/loader.d.ts.map +1 -0
  45. package/dist/components/loader.js +76 -0
  46. package/dist/components/loader.js.map +1 -0
  47. package/dist/components/markdown.d.ts +110 -0
  48. package/dist/components/markdown.d.ts.map +1 -0
  49. package/dist/components/markdown.js +941 -0
  50. package/dist/components/markdown.js.map +1 -0
  51. package/dist/components/mouse-region.d.ts +12 -0
  52. package/dist/components/mouse-region.d.ts.map +1 -0
  53. package/dist/components/mouse-region.js +21 -0
  54. package/dist/components/mouse-region.js.map +1 -0
  55. package/dist/components/scroll-view.d.ts +59 -0
  56. package/dist/components/scroll-view.d.ts.map +1 -0
  57. package/dist/components/scroll-view.js +195 -0
  58. package/dist/components/scroll-view.js.map +1 -0
  59. package/dist/components/select-list.d.ts +54 -0
  60. package/dist/components/select-list.d.ts.map +1 -0
  61. package/dist/components/select-list.js +215 -0
  62. package/dist/components/select-list.js.map +1 -0
  63. package/dist/components/settings-list.d.ts +61 -0
  64. package/dist/components/settings-list.d.ts.map +1 -0
  65. package/dist/components/settings-list.js +263 -0
  66. package/dist/components/settings-list.js.map +1 -0
  67. package/dist/components/spacer.d.ts +12 -0
  68. package/dist/components/spacer.d.ts.map +1 -0
  69. package/dist/components/spacer.js +23 -0
  70. package/dist/components/spacer.js.map +1 -0
  71. package/dist/components/stack.d.ts +32 -0
  72. package/dist/components/stack.d.ts.map +1 -0
  73. package/dist/components/stack.js +111 -0
  74. package/dist/components/stack.js.map +1 -0
  75. package/dist/components/text.d.ts +20 -0
  76. package/dist/components/text.d.ts.map +1 -0
  77. package/dist/components/text.js +98 -0
  78. package/dist/components/text.js.map +1 -0
  79. package/dist/components/truncated-text.d.ts +13 -0
  80. package/dist/components/truncated-text.d.ts.map +1 -0
  81. package/dist/components/truncated-text.js +51 -0
  82. package/dist/components/truncated-text.js.map +1 -0
  83. package/dist/components/v-stack.d.ts +8 -0
  84. package/dist/components/v-stack.d.ts.map +1 -0
  85. package/dist/components/v-stack.js +26 -0
  86. package/dist/components/v-stack.js.map +1 -0
  87. package/dist/editor-component.d.ts +39 -0
  88. package/dist/editor-component.d.ts.map +1 -0
  89. package/dist/editor-component.js +2 -0
  90. package/dist/editor-component.js.map +1 -0
  91. package/dist/fuzzy.d.ts +16 -0
  92. package/dist/fuzzy.d.ts.map +1 -0
  93. package/dist/fuzzy.js +126 -0
  94. package/dist/fuzzy.js.map +1 -0
  95. package/dist/index.d.ts +37 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +50 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/keybindings.d.ts +279 -0
  100. package/dist/keybindings.d.ts.map +1 -0
  101. package/dist/keybindings.js +248 -0
  102. package/dist/keybindings.js.map +1 -0
  103. package/dist/keys.d.ts +184 -0
  104. package/dist/keys.d.ts.map +1 -0
  105. package/dist/keys.js +1260 -0
  106. package/dist/keys.js.map +1 -0
  107. package/dist/kill-ring.d.ts +28 -0
  108. package/dist/kill-ring.d.ts.map +1 -0
  109. package/dist/kill-ring.js +44 -0
  110. package/dist/kill-ring.js.map +1 -0
  111. package/dist/latex.d.ts +10 -0
  112. package/dist/latex.d.ts.map +1 -0
  113. package/dist/latex.js +1378 -0
  114. package/dist/latex.js.map +1 -0
  115. package/dist/layout-node.d.ts +40 -0
  116. package/dist/layout-node.d.ts.map +1 -0
  117. package/dist/layout-node.js +6 -0
  118. package/dist/layout-node.js.map +1 -0
  119. package/dist/layout.d.ts +54 -0
  120. package/dist/layout.d.ts.map +1 -0
  121. package/dist/layout.js +360 -0
  122. package/dist/layout.js.map +1 -0
  123. package/dist/native-modifiers.d.ts +4 -0
  124. package/dist/native-modifiers.d.ts.map +1 -0
  125. package/dist/native-modifiers.js +13 -0
  126. package/dist/native-modifiers.js.map +1 -0
  127. package/dist/native-module-path.d.ts +7 -0
  128. package/dist/native-module-path.d.ts.map +1 -0
  129. package/dist/native-module-path.js +19 -0
  130. package/dist/native-module-path.js.map +1 -0
  131. package/dist/native-platform.d.ts +20 -0
  132. package/dist/native-platform.d.ts.map +1 -0
  133. package/dist/native-platform.js +42 -0
  134. package/dist/native-platform.js.map +1 -0
  135. package/dist/oklab.d.ts +43 -0
  136. package/dist/oklab.d.ts.map +1 -0
  137. package/dist/oklab.js +210 -0
  138. package/dist/oklab.js.map +1 -0
  139. package/dist/program-status.d.ts +23 -0
  140. package/dist/program-status.d.ts.map +1 -0
  141. package/dist/program-status.js +43 -0
  142. package/dist/program-status.js.map +1 -0
  143. package/dist/stdin-buffer.d.ts +58 -0
  144. package/dist/stdin-buffer.d.ts.map +1 -0
  145. package/dist/stdin-buffer.js +401 -0
  146. package/dist/stdin-buffer.js.map +1 -0
  147. package/dist/terminal-colors.d.ts +27 -0
  148. package/dist/terminal-colors.d.ts.map +1 -0
  149. package/dist/terminal-colors.js +64 -0
  150. package/dist/terminal-colors.js.map +1 -0
  151. package/dist/terminal-image.d.ts +142 -0
  152. package/dist/terminal-image.d.ts.map +1 -0
  153. package/dist/terminal-image.js +660 -0
  154. package/dist/terminal-image.js.map +1 -0
  155. package/dist/terminal.d.ts +149 -0
  156. package/dist/terminal.d.ts.map +1 -0
  157. package/dist/terminal.js +518 -0
  158. package/dist/terminal.js.map +1 -0
  159. package/dist/tui-alt-screen.d.ts +171 -0
  160. package/dist/tui-alt-screen.d.ts.map +1 -0
  161. package/dist/tui-alt-screen.js +1573 -0
  162. package/dist/tui-alt-screen.js.map +1 -0
  163. package/dist/tui-main-screen.d.ts +39 -0
  164. package/dist/tui-main-screen.d.ts.map +1 -0
  165. package/dist/tui-main-screen.js +598 -0
  166. package/dist/tui-main-screen.js.map +1 -0
  167. package/dist/tui.d.ts +449 -0
  168. package/dist/tui.d.ts.map +1 -0
  169. package/dist/tui.js +1218 -0
  170. package/dist/tui.js.map +1 -0
  171. package/dist/undo-stack.d.ts +17 -0
  172. package/dist/undo-stack.d.ts.map +1 -0
  173. package/dist/undo-stack.js +25 -0
  174. package/dist/undo-stack.js.map +1 -0
  175. package/dist/utils.d.ts +109 -0
  176. package/dist/utils.d.ts.map +1 -0
  177. package/dist/utils.js +1428 -0
  178. package/dist/utils.js.map +1 -0
  179. package/dist/wheel-scroll.d.ts +23 -0
  180. package/dist/wheel-scroll.d.ts.map +1 -0
  181. package/dist/wheel-scroll.js +73 -0
  182. package/dist/wheel-scroll.js.map +1 -0
  183. package/dist/word-navigation.d.ts +25 -0
  184. package/dist/word-navigation.d.ts.map +1 -0
  185. package/dist/word-navigation.js +96 -0
  186. package/dist/word-navigation.js.map +1 -0
  187. package/native/clipboard.h +208 -0
  188. package/native/darwin/README.md +22 -0
  189. package/native/darwin/build.sh +69 -0
  190. package/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  191. package/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  192. package/native/darwin/src/darwin-platform.m +132 -0
  193. package/native/linux/README.md +23 -0
  194. package/native/linux/build.sh +65 -0
  195. package/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  196. package/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  197. package/native/linux/src/clipboard-worker.h +70 -0
  198. package/native/linux/src/linux-platform-x11.c +274 -0
  199. package/native/napi.h +91 -0
  200. package/native/win32/README.md +31 -0
  201. package/native/win32/build.mjs +232 -0
  202. package/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  203. package/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  204. package/native/win32/src/win32-platform.c +241 -0
  205. package/package.json +62 -5
package/README.md CHANGED
@@ -1,3 +1,951 @@
1
- # Temporary Holding Version
1
+ # @diffra-ai/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
+ - **Interchangeable Renderers**: Shared `TUI` interface with main-screen and alternate-screen implementations
8
+ - **Differential Rendering**: Updates only changed lines or viewport rows
9
+ - **Application-owned Scrolling**: Alternate-screen viewport supports mouse, trackpad, and keyboard navigation
10
+ - **Synchronized Output**: Uses CSI 2026 for atomic screen updates (no flicker)
11
+ - **Bracketed Paste Mode**: Handles large pastes correctly with markers for >10 line pastes
12
+ - **Component-based**: Simple Component interface with render() method
13
+ - **Theme Support**: Components accept theme interfaces for customizable styling
14
+ - **Built-in Components**: Text, TruncatedText, Input, Editor, Markdown, Loader, SelectList, SettingsList, MouseRegion, Spacer, Image, Box, Container, VStack, HStack, ScrollView
15
+ - **Inline Images**: Renders images in terminals that support Kitty or iTerm2 graphics protocols
16
+ - **Autocomplete Support**: File paths and slash commands
17
+
18
+ ## Quick Start
19
+
20
+ ```typescript
21
+ import { type TUI, Text, Editor, ProcessTerminal, TuiMainScreen, matchesKey } from "@diffra-ai/tui";
22
+
23
+ // Create terminal
24
+ const terminal = new ProcessTerminal();
25
+
26
+ // Create the default main-screen renderer through the shared TUI interface
27
+ const tui: TUI = new TuiMainScreen(terminal);
28
+
29
+ // Add components
30
+ tui.addChild(new Text("Welcome to my app!"));
31
+
32
+ import { defaultEditorTheme as editorTheme } from './test/test-themes.ts';
33
+ const editor = new Editor(tui, editorTheme);
34
+ editor.onSubmit = (text) => {
35
+ console.log("Submitted:", text);
36
+ tui.addChild(new Text(`You said: ${text}`));
37
+ };
38
+ tui.addChild(editor);
39
+
40
+ // Focus the editor so it receives keyboard input
41
+ tui.setFocus(editor);
42
+
43
+ // In raw mode Ctrl+C doesn't send SIGINT — intercept it here to allow exit
44
+ tui.addInputListener((data) => {
45
+ if (matchesKey(data, 'ctrl+c')) {
46
+ tui.stop();
47
+ process.exit(0);
48
+ }
49
+ });
50
+
51
+ // Start
52
+ tui.start();
53
+ ```
54
+
55
+ ## Core API
56
+
57
+ ### TUI interface and renderers
58
+
59
+ `TUI` is the shared interface for component management, focus, overlays, input, lifecycle, terminal queries, and rendering. Choose a concrete renderer only when constructing the application:
60
+
61
+ - `TuiMainScreen` renders into the main terminal buffer and preserves terminal scrollback.
62
+ - `TuiAltScreen` renders a fixed-height viewport in the alternate terminal buffer with application-owned scrolling. When stopped, it restores the main buffer and prints the complete final document.
63
+
64
+ ```typescript
65
+ import { type TUI, TuiAltScreen, TuiMainScreen } from "@diffra-ai/tui";
66
+
67
+ const tui: TUI = new TuiMainScreen(terminal);
68
+ // To use an application-owned viewport in the alternate terminal buffer instead:
69
+ // const tui: TUI = new TuiAltScreen(terminal);
70
+
71
+ tui.addChild(component);
72
+ tui.removeChild(component);
73
+ tui.start();
74
+ tui.stop();
75
+ tui.requestRender(); // Request a re-render
76
+
77
+ // Global debug key handler (Shift+Ctrl+D)
78
+ tui.onDebug = () => console.log("Debug triggered");
79
+ ```
80
+
81
+ ### Colors and terminal styles
82
+
83
+ Colors are values that can be converted or mixed before terminal rendering:
84
+
85
+ ```typescript
86
+ import {
87
+ colorToRgb,
88
+ foregroundAnsi,
89
+ getTerminalColorMode,
90
+ mixColors,
91
+ parseColor,
92
+ rgbColor,
93
+ styleText,
94
+ } from "@diffra-ai/tui";
95
+
96
+ const accent = parseColor("oklch(70% 0.12 220)");
97
+ const background = parseColor("#20242a");
98
+ const foreground = mixColors(accent, background, 0.2);
99
+
100
+ const text = styleText(
101
+ "Ready",
102
+ { fg: foreground, bg: background, bold: true },
103
+ getTerminalColorMode(),
104
+ );
105
+ ```
106
+
107
+ `Color` is an indexed ANSI color, an sRGB color, or an OKLCH color. Every color converts to sRGB, so color math such as `mixColors()` always works. Indices 0-15 follow the user's terminal palette, so their sRGB values are approximations. `styleText()` converts colors to truecolor or 256-color output based on the requested terminal mode.
108
+
109
+ `parseColor()` also accepts OKHSL, as in `okhsl(250 60% 55%)`; `okhslColor()` builds it in code and `colorToOkhsl()` reads any color's OKHSL channels. OKHSL saturation is relative to the most the sRGB gamut allows at the hue and lightness, so every value is in gamut and equal saturation looks equally colorful across hues. OKHSL colors are converted to sRGB when created.
110
+
111
+ Conversions are not cached. OKLCH colors, especially ones outside the sRGB gamut, are more expensive to convert than sRGB or indexed colors. For colors used on every render, convert once and reuse the result:
112
+
113
+ ```typescript
114
+ const { r, g, b } = colorToRgb(mixColors(accent, background, 0.2));
115
+ const foreground = rgbColor(r, g, b); // cheap to render repeatedly
116
+ const foregroundCode = foregroundAnsi(foreground, getTerminalColorMode());
117
+ ```
118
+
119
+ ### Alternate-screen viewport layouts
120
+
121
+ `TuiAltScreen` can render an explicit terminal-height layout. `VStack` and `HStack` allocate constrained regions, while `ScrollView` owns scrolling for one region. These semantics are intentionally unavailable on `TuiMainScreen`, where the terminal owns scrollback.
122
+
123
+ ```typescript
124
+ import {
125
+ Container,
126
+ isViewportTUI,
127
+ ScrollView,
128
+ Text,
129
+ VStack,
130
+ } from "@diffra-ai/tui";
131
+
132
+ const transcript = new Container();
133
+ transcript.addChild(new Text("History"));
134
+
135
+ const editorAndFooter = new VStack([
136
+ editor,
137
+ new Text("status"),
138
+ ]);
139
+
140
+ if (isViewportTUI(tui)) {
141
+ tui.setLayoutRoot(new VStack([
142
+ {
143
+ component: new ScrollView(transcript, {
144
+ follow: "end",
145
+ primary: true,
146
+ overscroll: "chain",
147
+ }),
148
+ basis: 0,
149
+ grow: 1,
150
+ minSize: 1,
151
+ },
152
+ {
153
+ component: editorAndFooter,
154
+ basis: "auto",
155
+ shrink: 1,
156
+ minSize: 1,
157
+ },
158
+ ]));
159
+ }
160
+ ```
161
+
162
+ Stack entries support `basis`, `grow`, `shrink`, `minSize`, `maxSize`, and responsive `visible` callbacks. Mouse-wheel input targets the scroll view under the pointer and unused delta chains to outer scroll views by default. The primary scroll view receives the alternate-screen keyboard navigation actions and wheel input over non-scrollable regions. It can also jump between OSC 133 semantic prompt markers, matching common terminal prompt-navigation shortcuts. Press `Ctrl+Shift+F` to open or close its bordered search panel. The panel shows the configured previous/next shortcuts and provides clickable arrow controls; by default, `Enter`/`Ctrl+G` and `Shift+Enter`/`Ctrl+Shift+G` move between matches, and `Escape` also closes search. `TuiAltScreenOptions.searchMatchStyle` and `searchCurrentMatchStyle` customize match highlighting, while `searchNavigationButtonStyle` styles each arrow button and receives its hover state. `TuiAltScreenOptions.scrollToEndIndicator` renders a clickable label centered on the last row of a `follow: "end"` primary scroll view while it is scrolled away from the end; clicking it resumes end-following.
163
+
164
+ Layout geometry is rebuilt for each requested frame. Stateful components are retained, and their existing rendered-line caches remain effective. Calling `render(width)` directly on these layout components produces an unbounded document, which is also used when alt mode restores the main screen.
165
+
166
+ ### Overlays
167
+
168
+ Overlays render components on top of existing content without replacing it. Useful for dialogs, menus, and modal UI.
169
+
170
+ ```typescript
171
+ // Show overlay with default options (centered, max 80 cols)
172
+ const handle = tui.showOverlay(component);
173
+
174
+ // Show overlay with custom positioning and sizing
175
+ // Values can be numbers (absolute) or percentage strings (e.g., "50%")
176
+ const handle = tui.showOverlay(component, {
177
+ // Sizing
178
+ width: 60, // Fixed width in columns
179
+ width: "80%", // Width as percentage of terminal
180
+ minWidth: 40, // Minimum width floor
181
+ maxHeight: 20, // Maximum height in rows
182
+ maxHeight: "50%", // Maximum height as percentage of terminal
183
+
184
+ // Anchor-based positioning (default: 'center')
185
+ anchor: 'bottom-right', // Position relative to anchor point
186
+ offsetX: 2, // Horizontal offset from anchor
187
+ offsetY: -1, // Vertical offset from anchor
188
+
189
+ // Percentage-based positioning (alternative to anchor)
190
+ row: "25%", // Vertical position (0%=top, 100%=bottom)
191
+ col: "50%", // Horizontal position (0%=left, 100%=right)
192
+
193
+ // Absolute positioning (overrides anchor/percent)
194
+ row: 5, // Exact row position
195
+ col: 10, // Exact column position
196
+
197
+ // Margin from terminal edges
198
+ margin: 2, // All sides
199
+ margin: { top: 1, right: 2, bottom: 1, left: 2 },
200
+
201
+ // Responsive visibility
202
+ visible: (termWidth, termHeight) => termWidth >= 100 // Hide on narrow terminals
203
+
204
+ // Focus behavior
205
+ nonCapturing: true // Don't auto-focus when shown
206
+ });
207
+
208
+ // OverlayHandle methods
209
+ handle.hide(); // Permanently remove the overlay
210
+ handle.setHidden(true); // Temporarily hide (can show again)
211
+ handle.setHidden(false); // Show again after hiding
212
+ handle.isHidden(); // Check if temporarily hidden
213
+ handle.focus(); // Focus and bring to visual front
214
+ handle.unfocus(); // Release focus to normal fallback
215
+ handle.unfocus({ target: baseComponent }); // Release this overlay to a specific component
216
+ handle.unfocus({ target: null }); // Release this overlay and leave focus empty
217
+ handle.isFocused(); // Check if overlay has focus
218
+ handle.getBounds(); // Get last rendered terminal-relative bounds
219
+
220
+ handle.unfocus();
221
+ // Overlay loses focus; TUI falls back to another visible capturing overlay or the previous focus target.
222
+
223
+ handle.unfocus({ target: null });
224
+ // Overlay loses focus; no component receives input until focus is set again.
225
+
226
+ // A focused visible overlay reclaims keyboard input after temporary replacement UI
227
+ // releases focus. If you want a specific component to receive input while overlays remain
228
+ // visible, call handle.unfocus({ target: component }).
229
+
230
+ // Hide topmost overlay
231
+ tui.hideOverlay();
232
+
233
+ // Check if any visible overlay is active
234
+ tui.hasOverlay();
235
+ ```
236
+
237
+ **Anchor values**: `'center'`, `'top-left'`, `'top-right'`, `'bottom-left'`, `'bottom-right'`, `'top-center'`, `'bottom-center'`, `'left-center'`, `'right-center'`
238
+
239
+ **Resolution order**:
240
+ 1. `minWidth` is applied as a floor after width calculation
241
+ 2. For position: absolute `row`/`col` > percentage `row`/`col` > `anchor`
242
+ 3. `margin` clamps final position to stay within terminal bounds
243
+ 4. `visible` callback controls whether overlay renders (called each frame)
244
+
245
+ ### Component Interface
246
+
247
+ All components implement:
248
+
249
+ ```typescript
250
+ interface Component {
251
+ render(width: number): readonly string[];
252
+ handleInput?(data: string): void;
253
+ handleMouse?(event: TuiMouseEvent): TuiMouseEventResult | undefined;
254
+ capturesViewportInput?: boolean;
255
+ invalidate(): void;
256
+ }
257
+ ```
258
+
259
+ | Method | Description |
260
+ |--------|-------------|
261
+ | `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. The result is read-only: components, including `Container`, `Box`, `Text`, and `Markdown`, return the same cached array while nothing changed. Copy it before modifying it, for example `[...super.render(width)]`. |
262
+ | `handleInput?(data)` | Called when the component has focus and receives keyboard input. The `data` string contains raw terminal input (may include ANSI escape sequences). |
263
+ | `handleMouse?(event)` | Called by `TuiAltScreen` for normalized pointer input targeted at the component. |
264
+ | `capturesViewportInput?` | If true while the component has focus, `TuiAltScreen` passes its viewport scrolling and prompt-jump keys (`tui.altScreen.*` except search) to it instead of scrolling the viewport, as it does for a focused overlay. Set by `SelectList`, `SettingsList`, and `Editor` while autocomplete is open, so PageUp/PageDown move the selection. Only the focused component is checked: a wrapper that forwards input to a list must expose the list's value itself. Use `getSelectPageIndex(keybindings, data, selectedIndex, itemCount, pageSize)` to compute the new selection. |
265
+ | `invalidate()` | Required. Clear any cached render state so the next `render()` starts from scratch. Components without cached render state can use an empty implementation. |
266
+
267
+ 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.
268
+
269
+ ### Mouse Input
270
+
271
+ `TuiAltScreen` normalizes SGR mouse input and hit-tests components and overlays. Events contain component-local `x`/`y`, absolute `screenX`/`screenY`, bounds, button, modifiers, click count, and wheel delta. `TuiMainScreen` does not capture mouse input because the terminal owns its scrollback.
272
+
273
+ ```typescript
274
+ import type { TuiMouseEvent, TuiMouseEventResult } from "@diffra-ai/tui";
275
+
276
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
277
+ if (event.type === "click" && event.button === "left") {
278
+ this.expanded = !this.expanded;
279
+ return { handled: true };
280
+ }
281
+ if (event.type === "press" && event.button === "left") {
282
+ return { handled: true, capture: true, focus: true };
283
+ }
284
+ if (event.type === "drag") {
285
+ this.updateFromPointer(event.x, event.y);
286
+ return { handled: true, render: true };
287
+ }
288
+ return undefined;
289
+ }
290
+ ```
291
+
292
+ Returning `handled` suppresses renderer-level fallback behavior. `capture` keeps subsequent drag and release events routed to the same component. `focus` requests keyboard focus. The optional `render` flag controls repainting: press, click, drag, and wheel default to rendering; move and release do not. Set `render: true` for a hover state that visibly changed, or `render: false` for a handled no-op. Render requests are coalesced and terminal output remains differential.
293
+
294
+ Unhandled gestures retain alternate-screen defaults: wheel input scrolls the nearest `ScrollView` and chains unused delta, primary-button drags select text, OSC 8 links open before parent click handlers, and unhandled right-click preserves configured paste behavior. A click is emitted only when press/release completes without a drag.
295
+
296
+ Use `MouseRegion` to add mouse behavior without changing a component's rendering:
297
+
298
+ ```typescript
299
+ const collapsible = new MouseRegion(content, (event) => {
300
+ if (event.type !== "click" || event.button !== "left") return undefined;
301
+ expanded = !expanded;
302
+ return { handled: true };
303
+ });
304
+ ```
305
+
306
+ `Container` and `Box` route events to nested children using geometry recorded by the last rendered frame, so pointer motion does not rerender children merely to hit-test them. Explicit `VStack`, `HStack`, and `ScrollView` layouts use the alternate-screen layout frame directly.
307
+
308
+ ### Focusable Interface (IME Support)
309
+
310
+ Components that display a text cursor and need IME (Input Method Editor) support should implement the `Focusable` interface:
311
+
312
+ ```typescript
313
+ import { CURSOR_MARKER, type Component, type Focusable, renderFakeCursor } from "@diffra-ai/tui";
314
+
315
+ class MyInput implements Component, Focusable {
316
+ focused: boolean = false; // Set by TUI when focus changes
317
+
318
+ render(width: number): string[] {
319
+ const marker = this.focused ? CURSOR_MARKER : "";
320
+ // Emit marker right before the fake cursor
321
+ return [`> ${beforeCursor}${marker}${renderFakeCursor(atCursor)}${afterCursor}`];
322
+ }
323
+
324
+ invalidate(): void {}
325
+ }
326
+ ```
327
+
328
+ When a `Focusable` component has focus, TUI:
329
+ 1. Sets `focused = true` on the component
330
+ 2. Scans rendered output for `CURSOR_MARKER` (a zero-width APC escape sequence)
331
+ 3. Positions the hardware terminal cursor at that location
332
+ 4. Shows the hardware cursor only when `showHardwareCursor` is enabled
333
+
334
+ `renderFakeCursor()` wraps the cursor cell in zero-width markers. TUI renders them as reverse video. When `showHardwareCursor` is enabled, TUI removes the fake cursor that directly follows `CURSOR_MARKER`, so the focused component shows only the terminal cursor. Fake cursors without a preceding `CURSOR_MARKER` stay visible.
335
+
336
+ The hardware 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 renderer constructor's `showHardwareCursor` argument or `setShowHardwareCursor(true)`. The `Editor` and `Input` built-in components already implement this interface.
337
+
338
+ **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:
339
+
340
+ ```typescript
341
+ import { Container, type Focusable, Input } from "@diffra-ai/tui";
342
+
343
+ class SearchDialog extends Container implements Focusable {
344
+ private searchInput: Input;
345
+
346
+ // Propagate focus to child input for IME cursor positioning
347
+ private _focused = false;
348
+ get focused(): boolean { return this._focused; }
349
+ set focused(value: boolean) {
350
+ this._focused = value;
351
+ this.searchInput.focused = value;
352
+ }
353
+
354
+ constructor() {
355
+ super();
356
+ this.searchInput = new Input();
357
+ this.addChild(this.searchInput);
358
+ }
359
+ }
360
+ ```
361
+
362
+ Without this propagation, typing with an IME (Chinese, Japanese, Korean, etc.) will show the candidate window in the wrong position.
363
+
364
+ ## Built-in Components
365
+
366
+ ### Container
367
+
368
+ Groups child components.
369
+
370
+ ```typescript
371
+ const container = new Container();
372
+ container.addChild(component);
373
+ container.removeChild(component);
374
+ ```
375
+
376
+ ### Box
377
+
378
+ Container that applies padding and background color to all children.
379
+
380
+ ```typescript
381
+ const box = new Box(
382
+ 1, // paddingX (default: 1)
383
+ 1, // paddingY (default: 1)
384
+ (text) => chalk.bgGray(text) // optional background function
385
+ );
386
+ box.addChild(new Text("Content"));
387
+ box.setBgFn((text) => chalk.bgBlue(text)); // Change background dynamically
388
+ ```
389
+
390
+ ### Text
391
+
392
+ Displays multi-line text with word wrapping and padding.
393
+
394
+ ```typescript
395
+ const text = new Text(
396
+ "Hello World", // text content
397
+ 1, // paddingX (default: 1)
398
+ 1, // paddingY (default: 1)
399
+ (text) => chalk.bgGray(text) // optional background function
400
+ );
401
+ text.setText("Updated text");
402
+ text.setCustomBgFn((text) => chalk.bgBlue(text));
403
+ ```
404
+
405
+ ### TruncatedText
406
+
407
+ Single-line text that truncates to fit viewport width. Useful for status lines and headers.
408
+
409
+ ```typescript
410
+ const truncated = new TruncatedText(
411
+ "This is a very long line that will be truncated...",
412
+ 0, // paddingX (default: 0)
413
+ 0 // paddingY (default: 0)
414
+ );
415
+ ```
416
+
417
+ ### Input
418
+
419
+ Single-line text input with horizontal scrolling.
420
+
421
+ ```typescript
422
+ const input = new Input();
423
+ input.onSubmit = (value) => console.log(value);
424
+ input.setValue("initial");
425
+ input.getValue();
426
+ ```
427
+
428
+ Clicking positions the cursor and gives the input keyboard focus in alternate-screen mode.
429
+
430
+ **Key Bindings:**
431
+ - `Enter` - Submit
432
+ - `Ctrl+A` / `Ctrl+E` - Line start/end
433
+ - `Ctrl+W` or `Alt+Backspace` - Delete word backwards
434
+ - `Ctrl+U` - Delete to start of line
435
+ - `Ctrl+K` - Delete to end of line
436
+ - `Ctrl+Left` / `Ctrl+Right` - Word navigation
437
+ - `Alt+Left` / `Alt+Right` - Word navigation
438
+ - Arrow keys, Backspace, Delete work as expected
439
+
440
+ ### Editor
441
+
442
+ Multi-line text editor with autocomplete, file completion, paste handling, and vertical scrolling when content exceeds terminal height.
443
+
444
+ ```typescript
445
+ interface EditorTheme {
446
+ borderColor: (str: string) => string;
447
+ selectList: SelectListTheme;
448
+ }
449
+
450
+ interface EditorOptions {
451
+ paddingX?: number; // Horizontal padding (default: 0)
452
+ }
453
+
454
+ const editor = new Editor(tui, theme, options?); // tui is required for height-aware scrolling
455
+ editor.onSubmit = (text) => console.log(text);
456
+ editor.onChange = (text) => console.log("Changed:", text);
457
+ editor.disableSubmit = true; // Disable submit temporarily
458
+ editor.setAutocompleteProvider(provider);
459
+ editor.borderColor = (s) => chalk.blue(s); // Change border dynamically
460
+ editor.setPaddingX(1); // Update horizontal padding dynamically
461
+ editor.getPaddingX(); // Get current padding
462
+ ```
463
+
464
+ **Features:**
465
+ - Click-to-position cursor and clickable autocomplete rows in alternate-screen mode
466
+ - Multi-line editing with word wrap
467
+ - Slash command autocomplete (type `/`)
468
+ - File path autocomplete (press `Tab`)
469
+ - Large paste handling (>10 lines creates `[paste #1 +50 lines]` marker)
470
+ - Horizontal lines above/below editor
471
+ - Fake cursor rendering (hidden real cursor)
472
+
473
+ **Key Bindings:**
474
+ - `Enter` - Submit
475
+ - `Shift+Enter`, `Ctrl+Enter`, or `Alt+Enter` - New line (terminal-dependent, Alt+Enter most reliable)
476
+ - `Tab` - Autocomplete
477
+ - `Ctrl+K` - Delete to end of line
478
+ - `Ctrl+U` - Delete to start of line
479
+ - `Ctrl+W` or `Alt+Backspace` - Delete word backwards
480
+ - `Alt+D` or `Alt+Delete` - Delete word forwards
481
+ - `Ctrl+A` / `Ctrl+E` - Line start/end
482
+ - `Ctrl+]` - Jump forward to character (awaits next keypress, then moves cursor to first occurrence)
483
+ - `Ctrl+Alt+]` - Jump backward to character
484
+ - Arrow keys, Backspace, Delete work as expected
485
+
486
+ ### Markdown
487
+
488
+ Renders markdown with syntax highlighting and theming support.
489
+
490
+ ```typescript
491
+ interface MarkdownTheme {
492
+ heading: (text: string) => string;
493
+ link: (text: string) => string;
494
+ linkUrl: (text: string) => string;
495
+ code: (text: string) => string;
496
+ codeBlock: (text: string) => string;
497
+ codeBlockBorder: (text: string) => string;
498
+ quote: (text: string) => string;
499
+ quoteBorder: (text: string) => string;
500
+ hr: (text: string) => string;
501
+ listBullet: (text: string) => string;
502
+ bold: (text: string) => string;
503
+ italic: (text: string) => string;
504
+ strikethrough: (text: string) => string;
505
+ underline: (text: string) => string;
506
+ highlightCode?: (code: string, lang?: string) => string[];
507
+ }
508
+
509
+ interface DefaultTextStyle {
510
+ color?: (text: string) => string;
511
+ bgColor?: (text: string) => string;
512
+ bold?: boolean;
513
+ italic?: boolean;
514
+ strikethrough?: boolean;
515
+ underline?: boolean;
516
+ }
517
+
518
+ const md = new Markdown(
519
+ "# Hello\n\nSome **bold** text",
520
+ 1, // paddingX
521
+ 1, // paddingY
522
+ theme, // MarkdownTheme
523
+ defaultStyle // optional DefaultTextStyle
524
+ );
525
+ md.setText("Updated markdown");
526
+ ```
527
+
528
+ **Features:**
529
+ - Headings, bold, italic, code blocks, lists, links, blockquotes
530
+ - HTML tags rendered as plain text
531
+ - Optional syntax highlighting via `highlightCode`
532
+ - Padding support
533
+ - Render caching for performance
534
+
535
+ ### Loader
536
+
537
+ Animated loading spinner.
538
+
539
+ ```typescript
540
+ const loader = new Loader(
541
+ tui, // TUI instance for render updates
542
+ (s) => chalk.cyan(s), // spinner color function
543
+ (s) => chalk.gray(s), // message color function
544
+ "Loading..." // message (default: "Loading...")
545
+ );
546
+ loader.start();
547
+ loader.setMessage("Still loading...");
548
+ loader.stop();
549
+ ```
550
+
551
+ ### CancellableLoader
552
+
553
+ Extends Loader with Escape key handling and an AbortSignal for cancelling async operations.
554
+
555
+ ```typescript
556
+ const loader = new CancellableLoader(
557
+ tui, // TUI instance for render updates
558
+ (s) => chalk.cyan(s), // spinner color function
559
+ (s) => chalk.gray(s), // message color function
560
+ "Working..." // message
561
+ );
562
+ loader.onAbort = () => done(null); // Called when user presses Escape
563
+ doAsyncWork(loader.signal).then(done);
564
+ ```
565
+
566
+ **Properties:**
567
+ - `signal: AbortSignal` - Aborted when user presses Escape
568
+ - `aborted: boolean` - Whether the loader was aborted
569
+ - `onAbort?: () => void` - Callback when user presses Escape
570
+
571
+ ### SelectList
572
+
573
+ Interactive selection list with keyboard navigation.
574
+
575
+ ```typescript
576
+ interface SelectItem {
577
+ value: string;
578
+ label: string;
579
+ description?: string;
580
+ }
581
+
582
+ interface SelectListTheme {
583
+ selectedPrefix: (text: string) => string;
584
+ selectedText: (text: string) => string;
585
+ description: (text: string) => string;
586
+ scrollInfo: (text: string) => string;
587
+ noMatch: (text: string) => string;
588
+ }
589
+
590
+ const list = new SelectList(
591
+ [
592
+ { value: "opt1", label: "Option 1", description: "First option" },
593
+ { value: "opt2", label: "Option 2", description: "Second option" },
594
+ ],
595
+ 5, // maxVisible
596
+ theme // SelectListTheme
597
+ );
598
+
599
+ list.onSelect = (item) => console.log("Selected:", item);
600
+ list.onCancel = () => console.log("Cancelled");
601
+ list.onSelectionChange = (item) => console.log("Highlighted:", item);
602
+ list.setFilter("opt"); // Filter items
603
+ ```
604
+
605
+ **Controls:**
606
+ - Mouse move/wheel: Highlight rows in alternate-screen mode
607
+ - Click: Select a row
608
+ - Arrow keys: Navigate
609
+ - Enter: Select
610
+ - Escape: Cancel
611
+
612
+ ### SettingsList
613
+
614
+ Settings panel with value cycling and submenus.
615
+
616
+ ```typescript
617
+ interface SettingItem {
618
+ id: string;
619
+ label: string;
620
+ description?: string;
621
+ currentValue: string;
622
+ values?: string[]; // If provided, Enter/Space cycles through these
623
+ submenu?: (currentValue: string, done: (selectedValue?: string) => void) => Component;
624
+ }
625
+
626
+ interface SettingsListTheme {
627
+ label: (text: string, selected: boolean) => string;
628
+ value: (text: string, selected: boolean) => string;
629
+ description: (text: string) => string;
630
+ cursor: string;
631
+ hint: (text: string) => string;
632
+ }
633
+
634
+ const settings = new SettingsList(
635
+ [
636
+ { id: "theme", label: "Theme", currentValue: "dark", values: ["dark", "light"] },
637
+ { id: "model", label: "Model", currentValue: "gpt-4", submenu: (val, done) => modelSelector },
638
+ ],
639
+ 10, // maxVisible
640
+ theme, // SettingsListTheme
641
+ (id, newValue) => console.log(`${id} changed to ${newValue}`),
642
+ () => console.log("Cancelled")
643
+ );
644
+ settings.updateValue("theme", "light");
645
+ ```
646
+
647
+ **Controls:**
648
+ - Mouse move/wheel: Highlight rows in alternate-screen mode
649
+ - Click: Activate a row
650
+ - Arrow keys: Navigate
651
+ - Enter/Space: Activate (cycle value or open submenu)
652
+ - Escape: Cancel
653
+
654
+ ### Spacer
655
+
656
+ Empty lines for vertical spacing.
657
+
658
+ ```typescript
659
+ const spacer = new Spacer(2); // 2 empty lines (default: 1)
660
+ ```
661
+
662
+ ### Image
663
+
664
+ 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.
665
+
666
+ ```typescript
667
+ interface ImageTheme {
668
+ fallbackColor: (str: string) => string;
669
+ }
670
+
671
+ interface ImageOptions {
672
+ maxWidthCells?: number;
673
+ maxHeightCells?: number;
674
+ filename?: string;
675
+ }
676
+
677
+ const image = new Image(
678
+ base64Data, // base64-encoded image data
679
+ "image/png", // MIME type
680
+ theme, // ImageTheme
681
+ options // optional ImageOptions
682
+ );
683
+ tui.addChild(image);
684
+ ```
685
+
686
+ Supported formats: PNG, JPEG, GIF, WebP. Dimensions are parsed from the image headers automatically.
687
+
688
+ #### Alternate-screen image compatibility
689
+
690
+ `TuiAltScreen` supports inline images and partial viewport cropping in terminals that implement the Kitty graphics protocol, including Kitty and Ghostty. iTerm2's inline-image protocol does not provide operations to delete an existing placement or crop its source while scrolling. To prevent stale images from remaining over repainted content, `TuiAltScreen` renders image components as text placeholders in iTerm2. `TuiMainScreen` continues to render iTerm2 inline images normally.
691
+
692
+ ## Autocomplete
693
+
694
+ ### CombinedAutocompleteProvider
695
+
696
+ Supports both slash commands and file paths.
697
+
698
+ ```typescript
699
+ import { CombinedAutocompleteProvider } from "@diffra-ai/tui";
700
+
701
+ const provider = new CombinedAutocompleteProvider(
702
+ [
703
+ { name: "help", description: "Show help" },
704
+ { name: "clear", description: "Clear screen" },
705
+ { name: "delete", description: "Delete last message" },
706
+ ],
707
+ process.cwd() // base path for file completion
708
+ );
709
+
710
+ editor.setAutocompleteProvider(provider);
711
+ ```
712
+
713
+ **Features:**
714
+ - Type `/` to see slash commands
715
+ - Press `Tab` for file path completion
716
+ - Works with `~/`, `./`, `../`, and `@` prefix
717
+ - Filters to attachable files for `@` prefix
718
+
719
+ ## Key Detection
720
+
721
+ Use `matchesKey()` with the `Key` helper for detecting keyboard input (supports Kitty keyboard protocol):
722
+
723
+ ```typescript
724
+ import { matchesKey, Key } from "@diffra-ai/tui";
725
+
726
+ if (matchesKey(data, Key.ctrl("c"))) {
727
+ process.exit(0);
728
+ }
729
+
730
+ if (matchesKey(data, Key.enter)) {
731
+ submit();
732
+ } else if (matchesKey(data, Key.escape)) {
733
+ cancel();
734
+ } else if (matchesKey(data, Key.up)) {
735
+ moveUp();
736
+ }
737
+ ```
738
+
739
+ **Key identifiers** (use `Key.*` for autocomplete, or string literals):
740
+ - Basic keys: `Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end`
741
+ - Arrow keys: `Key.up`, `Key.down`, `Key.left`, `Key.right`
742
+ - With modifiers: `Key.ctrl("c")`, `Key.shift("tab")`, `Key.alt("left")`, `Key.ctrlShift("p")`
743
+ - String format also works: `"enter"`, `"ctrl+c"`, `"shift+tab"`, `"ctrl+shift+p"`
744
+
745
+ ## Rendering modes
746
+
747
+ `TuiMainScreen` uses three rendering strategies:
748
+
749
+ 1. **First Render**: Output all lines without clearing scrollback
750
+ 2. **Width Changed or Change Above Viewport**: Clear screen and fully re-render
751
+ 3. **Normal Update**: Move the cursor to the first changed line, clear to the end, and render changed lines
752
+
753
+ `TuiAltScreen` owns a terminal-height viewport. Without an explicit layout root it preserves the legacy single-document scrolling behavior. With `setLayoutRoot()`, `VStack`, `HStack`, and nested `ScrollView` components can reserve fixed regions and independently scroll constrained regions. It updates changed viewport rows in place, follows streaming output while at the bottom, and preserves a manually selected scroll position while content grows. Mouse-wheel and configurable keyboard navigation scroll without modifying terminal scrollback, including jumps between OSC 133 semantic prompt markers. Scrollbars support hover expansion, thumb dragging, and track-click jumping. Clicking an OSC 8 hyperlink opens it with the configured URL handler. Dragging with the primary mouse button selects text and, unless `TuiAltScreenOptions.copyOnSelect` is `false`, copies it to the clipboard with OSC 52; holding the drag at a scroll view's top or bottom edge auto-scrolls and extends the selection into off-screen content. Kitty images support vertical viewport cropping; iTerm2 inline images fall back to text because the iTerm2 protocol cannot delete or crop placements during viewport repainting.
754
+
755
+ Both renderers wrap updates in **synchronized output** (`\x1b[?2026h` ... `\x1b[?2026l`) for atomic, flicker-free rendering.
756
+
757
+ ## Terminal Interface
758
+
759
+ The TUI works with any object implementing the `Terminal` interface:
760
+
761
+ ```typescript
762
+ interface Terminal {
763
+ start(onInput: (data: string) => void, onResize: () => void): void;
764
+ stop(): void;
765
+ write(data: string): void;
766
+ get columns(): number;
767
+ get rows(): number;
768
+ moveBy(lines: number): void;
769
+ hideCursor(): void;
770
+ showCursor(): void;
771
+ clearLine(): void;
772
+ clearFromCursor(): void;
773
+ clearScreen(): void;
774
+ }
775
+ ```
776
+
777
+ **Built-in implementations:**
778
+ - `ProcessTerminal` - Uses `process.stdin/stdout`
779
+ - `VirtualTerminal` - For testing (uses `@xterm/headless`)
780
+
781
+ ## Utilities
782
+
783
+ ```typescript
784
+ import { visibleWidth, truncateToWidth, wrapTextWithAnsi } from "@diffra-ai/tui";
785
+
786
+ // Get visible width of string (ignoring ANSI codes)
787
+ const width = visibleWidth("\x1b[31mHello\x1b[0m"); // 5
788
+
789
+ // Truncate string to width (preserving ANSI codes, adds ellipsis)
790
+ const truncated = truncateToWidth("Hello World", 8); // "Hello..."
791
+
792
+ // Truncate without ellipsis
793
+ const truncatedNoEllipsis = truncateToWidth("Hello World", 8, ""); // "Hello Wo"
794
+
795
+ // Wrap text to width (preserving ANSI codes across line breaks)
796
+ const lines = wrapTextWithAnsi("This is a long line that needs wrapping", 20);
797
+ // ["This is a long line", "that needs wrapping"]
798
+ ```
799
+
800
+ ## Creating Custom Components
801
+
802
+ 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.
803
+
804
+ ### Handling Input
805
+
806
+ Use `matchesKey()` with the `Key` helper for keyboard input:
807
+
808
+ ```typescript
809
+ import { matchesKey, Key, truncateToWidth } from "@diffra-ai/tui";
810
+ import type { Component } from "@diffra-ai/tui";
811
+
812
+ class MyInteractiveComponent implements Component {
813
+ private selectedIndex = 0;
814
+ private items = ["Option 1", "Option 2", "Option 3"];
815
+
816
+ public onSelect?: (index: number) => void;
817
+ public onCancel?: () => void;
818
+
819
+ handleInput(data: string): void {
820
+ if (matchesKey(data, Key.up)) {
821
+ this.selectedIndex = Math.max(0, this.selectedIndex - 1);
822
+ } else if (matchesKey(data, Key.down)) {
823
+ this.selectedIndex = Math.min(this.items.length - 1, this.selectedIndex + 1);
824
+ } else if (matchesKey(data, Key.enter)) {
825
+ this.onSelect?.(this.selectedIndex);
826
+ } else if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
827
+ this.onCancel?.();
828
+ }
829
+ }
830
+
831
+ render(width: number): string[] {
832
+ return this.items.map((item, i) => {
833
+ const prefix = i === this.selectedIndex ? "> " : " ";
834
+ return truncateToWidth(prefix + item, width);
835
+ });
836
+ }
837
+
838
+ invalidate(): void {}
839
+ }
840
+ ```
841
+
842
+ ### Handling Line Width
843
+
844
+ Use the provided utilities to ensure lines fit:
845
+
846
+ ```typescript
847
+ import { visibleWidth, truncateToWidth } from "@diffra-ai/tui";
848
+ import type { Component } from "@diffra-ai/tui";
849
+
850
+ class MyComponent implements Component {
851
+ private text: string;
852
+
853
+ constructor(text: string) {
854
+ this.text = text;
855
+ }
856
+
857
+ render(width: number): string[] {
858
+ // Option 1: Truncate long lines
859
+ return [truncateToWidth(this.text, width)];
860
+
861
+ // Option 2: Check and pad to exact width
862
+ const line = this.text;
863
+ const visible = visibleWidth(line);
864
+ if (visible > width) {
865
+ return [truncateToWidth(line, width)];
866
+ }
867
+ // Pad to exact width (optional, for backgrounds)
868
+ return [line + " ".repeat(width - visible)];
869
+ }
870
+
871
+ invalidate(): void {}
872
+ }
873
+ ```
874
+
875
+ ### ANSI Code Considerations
876
+
877
+ Both `visibleWidth()` and `truncateToWidth()` correctly handle ANSI escape codes:
878
+
879
+ - `visibleWidth()` ignores ANSI codes when calculating width
880
+ - `truncateToWidth()` preserves ANSI codes and properly closes them when truncating
881
+
882
+ ```typescript
883
+ import chalk from "chalk";
884
+
885
+ const styled = chalk.red("Hello") + " " + chalk.blue("World");
886
+ const width = visibleWidth(styled); // 11 (not counting ANSI codes)
887
+ const truncated = truncateToWidth(styled, 8); // Red "Hello" + " W..." with proper reset
888
+ ```
889
+
890
+ ### Caching
891
+
892
+ For performance, components should cache their rendered output and only re-render when necessary:
893
+
894
+ ```typescript
895
+ class CachedComponent implements Component {
896
+ private text: string;
897
+ private cachedWidth?: number;
898
+ private cachedLines?: string[];
899
+
900
+ render(width: number): string[] {
901
+ if (this.cachedLines && this.cachedWidth === width) {
902
+ return this.cachedLines;
903
+ }
904
+
905
+ const lines = [truncateToWidth(this.text, width)];
906
+
907
+ this.cachedWidth = width;
908
+ this.cachedLines = lines;
909
+ return lines;
910
+ }
911
+
912
+ invalidate(): void {
913
+ this.cachedWidth = undefined;
914
+ this.cachedLines = undefined;
915
+ }
916
+ }
917
+ ```
918
+
919
+ ## Example
920
+
921
+ See `test/chat-simple.ts` for a complete chat interface example with:
922
+ - Markdown messages with custom background colors
923
+ - Loading spinner during responses
924
+ - Editor with autocomplete and slash commands
925
+ - Spacers between messages
926
+
927
+ Run it:
928
+ ```bash
929
+ node test/chat-simple.ts
930
+ ```
931
+
932
+ ## Development
933
+
934
+ ```bash
935
+ # Install dependencies (from monorepo root)
936
+ npm install
937
+
938
+ # Run type checking
939
+ npm run check
940
+
941
+ # Run the demo
942
+ node test/chat-simple.ts
943
+ ```
944
+
945
+ ### Debug logging
946
+
947
+ Set `DIFFRA_TUI_WRITE_LOG` to capture the raw ANSI stream written to stdout.
948
+
949
+ ```bash
950
+ DIFFRA_TUI_WRITE_LOG=/tmp/tui-ansi.log node test/chat-simple.ts
951
+ ```