@easbot/tui 0.1.13 → 0.1.14

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