@easbot/tui 0.3.29 → 0.3.36

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.
package/README.en.md CHANGED
@@ -2,65 +2,317 @@
2
2
 
3
3
  # @easbot/tui
4
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.
5
+ > A fully autonomous terminal UI rendering engine — differential rendering plus synchronized output for flicker-free interactive CLI applications.
8
6
 
9
7
  ## Version
10
8
 
11
- v0.3.29
9
+ v0.3.36
10
+ ## Introduction
11
+
12
+ `@easbot/tui` is the terminal rendering foundation of EASBot, providing **differential rendering** (only repaints changed lines), **synchronized output** (atomic commit via CSI 2026), **inline images** (Kitty / iTerm2 graphics protocols), and **rich-text components** (Markdown / LaTeX / editor / fuzzy search).
13
+
14
+ Upper-layer application shells (such as [`@easbot/agent-tui`](../agent-tui/README.en.md)) assemble this package into a ready-to-use TUI.
15
+
16
+ > **Package rename note**: this package was previously named `@easbot/tui-lib` and has now been renamed to `@easbot/tui` (older npm versions of `@easbot/tui-lib` remain published, but no new versions will be released). Early 0.3.x releases of `@easbot/tui` were a **different rendering implementation** (the legacy base layer) with an incompatible API — legacy code must migrate to `TuiMainScreen` (`TUI` changed from a class to an interface); this document is the source of truth.
17
+
18
+ Every source file in the package carries **complete, standard Chinese JSDoc**, which doubles as an API reference for downstream development.
19
+
12
20
  ## Features
13
21
 
14
- - **Differential Rendering**: Three-strategy rendering system that only updates what changed
15
- - **Synchronized Output**: Uses CSI 2026 for atomic screen updates (no flicker)
16
- - **Bracketed Paste Mode**: Handles large pastes correctly with markers for >10 line pastes
17
- - **Component-based**: Simple Component interface with render() method
18
- - **Theme Support**: Components accept theme interfaces for customizable styling
19
- - **Built-in Components**: Text, TruncatedText, Input, Editor, Markdown, Loader, SelectList, SettingsList, Spacer, Image, Box, Container
20
- - **Inline Images**: Renders images in terminals that support Kitty or iTerm2 graphics protocols
21
- - **Autocomplete Support**: File paths and slash commands
22
+ - ✅ **Differential rendering**: three-strategy render system (first frame / width change / incremental update) — only repaints what changed
23
+ - ✅ **Synchronized output**: atomic screen updates via CSI 2026, eliminating flicker
24
+ - ✅ **Dual-screen modes**: `TuiMainScreen` (main screen scrolling) and `TuiAltScreen` (alternate screen with a full-screen viewport)
25
+ - ✅ **Overlays**: `showOverlay()` supports anchor / percentage / absolute positioning plus temporary hiding
26
+ - ✅ **Component library**: `Text` / `TruncatedText` / `Input` / `Editor` / `Markdown` / `Loader` / `CancellableLoader` / `SelectList` / `SettingsList` / `ScrollView` / `Image` / `Box` / `Container` / `VStack` / `HStack` / `Spacer`
27
+ - ✅ **Color system**: Oklab / OKHSL / OKLCH → sRGB conversion, with graceful degradation to 256-color and truecolor modes
28
+ - ✅ **Inline images**: Kitty and iTerm2 graphics protocols, with automatic PNG / JPEG / GIF / WebP dimension parsing
29
+ - ✅ **Keyboard protocols**: Kitty keyboard protocol parsing and key matching (`matchesKey` / `Key`)
30
+ - ✅ **Keybinding registry**: declarative override of default bindings with automatic conflict detection
31
+ - ✅ **Fuzzy search**: `fuzzyMatch` / `fuzzyFilter`, supporting multiple tokens and letter-digit transposition
32
+ - ✅ **Autocomplete**: slash commands plus file paths (`CombinedAutocompleteProvider`), with candidate grouping, an async command source, and bare-name matching
33
+ - ✅ **Native platform capabilities**: prebuilt per-platform `.node` modules ship with the package (clipboard / modifier keys / Windows virtual terminal input), degrading safely when unsupported
34
+ - ✅ **LaTeX rendering**: inline and block-level formula rendering
35
+ - ✅ **Bracketed paste**: large pastes (>10 lines) collapse into a `[paste #1 +N lines]` marker
36
+ - ✅ **Unicode width**: grapheme width computed via `Intl.Segmenter`, correctly handling CJK / emoji / combining characters
22
37
 
23
38
  ## Quick Start
24
39
 
25
- ```typescript
26
- import { TUI, Text, Editor, ProcessTerminal } from '@easbot/tui';
40
+ ```bash
41
+ # Install dependencies at the monorepo root
42
+ pnpm install
27
43
 
28
- // Create terminal
29
- const terminal = new ProcessTerminal();
44
+ # Build this package
45
+ pnpm --filter @easbot/tui build
30
46
 
31
- // Create TUI
32
- const tui = new TUI(terminal);
47
+ # Run tests
48
+ pnpm --filter @easbot/tui test:run
33
49
 
34
- // Add components
35
- tui.addChild(new Text('Welcome to my app!'));
50
+ # Type check
51
+ pnpm --filter @easbot/tui type-check
52
+ ```
36
53
 
37
- const editor = new Editor(tui, editorTheme);
38
- editor.onSubmit = (text) => {
39
- console.log('Submitted:', text);
40
- tui.addChild(new Text(`You said: ${text}`));
41
- };
42
- tui.addChild(editor);
54
+ Minimal runnable example:
55
+
56
+ ```typescript
57
+ import { ProcessTerminal, TuiMainScreen, Text, matchesKey } from '@easbot/tui';
58
+
59
+ const tui = new TuiMainScreen(new ProcessTerminal());
60
+
61
+ tui.addChild(new Text('Welcome to EASBot!'));
62
+
63
+ // In raw mode Ctrl+C does not raise SIGINT, so intercept it to exit
64
+ tui.addInputListener((data) => {
65
+ if (matchesKey(data, 'ctrl+c')) {
66
+ tui.stop();
67
+ process.exit(0);
68
+ }
69
+ });
43
70
 
44
- // Start
45
71
  tui.start();
46
72
  ```
47
73
 
74
+ > ⚠️ `TUI` is an **interface**, not a class — pick the concrete implementation by render mode:
75
+ > `TuiMainScreen` (main screen) / `TuiAltScreen` (alternate screen).
76
+
77
+ ## API / Components / Data Structures
78
+
79
+ ### Terminal abstraction
80
+
81
+ The `Terminal` interface describes terminal capabilities; `ProcessTerminal` (backed by `process.stdin/stdout`) is the built-in implementation.
82
+
83
+ ```typescript
84
+ import { ProcessTerminal, type Terminal } from '@easbot/tui';
85
+
86
+ const terminal: Terminal = new ProcessTerminal();
87
+ ```
88
+
89
+ ### Core types
90
+
91
+ | Type | Description |
92
+ | ------------- | ----------------------------------------------------------------------------------------- |
93
+ | `Component` | Component contract: `render(width): string[]`, with optional `handleInput` / `invalidate` |
94
+ | `Focusable` | Components that show a text cursor and need IME support should implement it |
95
+ | `TUI` | Renderer interface (`addChild` / `start` / `stop` / `showOverlay`, …) |
96
+ | `ViewportTUI` | Renderer interface with viewport scrolling (implemented by `TuiAltScreen`) |
97
+ | `Terminal` | Terminal capability abstraction |
98
+
99
+ ### Component reference
100
+
101
+ | Component | Constructor signature |
102
+ | ------------------- | --------------------------------------------------------------------------------------------- |
103
+ | `Text` | `(text?, paddingX?, paddingY?, customBgFn?)` |
104
+ | `TruncatedText` | `(text, paddingX?, paddingY?)` |
105
+ | `Input` | `(options?)` |
106
+ | `Editor` | `(tui, theme, options?)` |
107
+ | `Markdown` | `(text, paddingX, paddingY, theme, defaultTextStyle?, options?)` |
108
+ | `Loader` | `(ui, spinnerColorFn, messageColorFn, message?, indicator?)` |
109
+ | `CancellableLoader` | `(ui, spinnerColorFn, messageColorFn, message?)` |
110
+ | `SelectList` | `(items, maxVisible, theme, layout?)` — items may carry `group` for non-selectable title rows |
111
+ | `SettingsList` | `(items, maxVisible, theme, onChange, onCancel, options?)` |
112
+ | `ScrollView` | `(component, options?)` |
113
+ | `Image` | `(base64Data, mimeType, theme, options?, dimensions?)` |
114
+ | `Box` | `(paddingX?, paddingY?, bgFn?)` |
115
+ | `Container` | none (assembled via `addChild` / `removeChild`) |
116
+ | `VStack` / `HStack` | `(children?, options?)` |
117
+ | `Spacer` | `(lines?)` |
118
+
119
+ ### Autocomplete
120
+
121
+ ```typescript
122
+ import {
123
+ AGENT_ATTACHMENT_SYMBOL,
124
+ CombinedAutocompleteProvider,
125
+ FILE_ATTACHMENT_SYMBOL,
126
+ } from '@easbot/tui';
127
+
128
+ // Attachment symbols: `#` = file reference, `@` = agent reference
129
+ FILE_ATTACHMENT_SYMBOL; // '#'
130
+ AGENT_ATTACHMENT_SYMBOL; // '@'
131
+
132
+ const provider = new CombinedAutocompleteProvider(
133
+ [
134
+ { name: 'help', group: 'Commands' },
135
+ { name: 'foo', group: 'Skills', matchAlias: 'foo' },
136
+ ],
137
+ process.cwd(),
138
+ // Dynamic commands (skills / MCP) come from the network → async source, merged with the static list
139
+ async () => [{ name: 'server:prompt', group: 'MCP' }],
140
+ );
141
+
142
+ // Candidate grouping: `items` stays flat; `group` changes insert a non-selectable title row
143
+ const result = await provider.getSuggestions(['/'], 0, 1, { signal: new AbortController().signal });
144
+ result?.items; // [{ value: 'help', label: 'help', group: 'Commands' }, ...]
145
+ ```
146
+
147
+ **Symbol conventions:**
148
+
149
+ | Symbol | Constant | Meaning | Candidate source |
150
+ | ------ | ------------------------- | --------------- | ---------------------------------- |
151
+ | `#` | `FILE_ATTACHMENT_SYMBOL` | File reference | **Base layer** (directory scan) |
152
+ | `@` | `AGENT_ATTACHMENT_SYMBOL` | Agent reference | **Business layer** (agent list) |
153
+ | `/` | — | Slash command | Static list + async command source |
154
+
155
+ > ⚠️ The base layer **recognizes but does not own** `@`: `getSuggestions` returns `null` for an `@`
156
+ > prefix and leaves candidate production to the business layer — yet `applyCompletion` must route
157
+ > `@` prefixes to the attachment branch, otherwise the completion value lands in the wrong branch.
158
+
159
+ **Grouping conventions:**
160
+
161
+ - Candidates stay **flat** in `items`; the category is carried by `AutocompleteItem.group`
162
+ - Rendering inserts a **non-selectable** title row wherever the `group` value changes
163
+ - Slash command groups come from `SlashCommand.group` (the business layer maps the `source`
164
+ field: plain command / skill / MCP)
165
+
166
+ | Type / Constant | Description |
167
+ | ------------------------------ | ---------------------------------------------------------------------------------------------- |
168
+ | `CombinedAutocompleteProvider` | Handles slash commands, file paths, and file attachments in one provider |
169
+ | `AutocompleteItem` | A single candidate: `value` / `label` / `description?` / `group?` |
170
+ | `AutocompleteSuggestions` | One query result: `items` (flat) + `prefix` |
171
+ | `SlashCommand` | Slash command definition: `name` / `description?` / `argumentHint?` / `group?` / `matchAlias?` |
172
+ | `SlashCommandSource` | Async source of slash commands (`() => SlashCommand[] \| Promise<SlashCommand[]>`) |
173
+
174
+ ### Native platform capabilities
175
+
176
+ The bundled `native/` directory holds the native module sources (`.h` headers) used to build **optional** native capabilities:
177
+
178
+ | Capability | Platform | Description |
179
+ | ---------------------------------- | ---------------------------- | ------------------------------------------------------------ |
180
+ | Clipboard read / write | macOS / Windows / Linux(X11) | `getNativeClipboard()` returns an optional capability object |
181
+ | Modifier key state query | macOS / Windows | `isNativeModifierPressed(key)` |
182
+ | Virtual terminal input (Shift+Tab) | Windows | `enableVirtualTerminalInput()` |
183
+
184
+ ```typescript
185
+ import { getNativeClipboard, isNativeModifierPressed } from '@easbot/tui';
186
+
187
+ // When the capability is unavailable it returns `undefined` / `false` → callers degrade safely via optional chaining
188
+ const clipboard = getNativeClipboard();
189
+ const text = await clipboard?.getText?.();
190
+ const shiftPressed = isNativeModifierPressed('shift');
191
+ ```
192
+
193
+ > ⚠️ Native capabilities are an **optional enhancement**: the host must supply prebuilt `.node` modules
194
+ > (supported platforms: macOS / Windows / Linux-x64 / Linux-arm64). When absent they degrade **safely**
195
+ > to "no native capability" (`getNativeClipboard()` returns `undefined`, `isNativeModifierPressed()`
196
+ > returns `false`) without throwing. Linux requires the `DISPLAY` environment variable to
197
+ > establish an X11 connection.
198
+
199
+ **Packaging**: at build time the `onSuccess` hook in `tsup.config.ts` copies every `.node` under
200
+ `native/**` into `dist/assets/node/native/**`, **preserving the original path** — matching the bundled
201
+ resource convention of `@easbot/utils` (the layer under `assets/` is the file type; everything after
202
+ it is project-root relative). The runtime reverses the very same rules, so dev mode and the packaged
203
+ build behave identically.
204
+
205
+ ### Mock terminal (for tests)
206
+
207
+ ```typescript
208
+ import { MockTerminal } from '@easbot/tui';
209
+
210
+ const terminal = new MockTerminal(120, 40);
211
+ const tui = new TuiMainScreen(terminal);
212
+
213
+ // Assert terminal output
214
+ terminal.output();
215
+
216
+ // Simulate input / resize
217
+ terminal.feedInput('hello');
218
+ terminal.resize(100, 30);
219
+ ```
220
+
221
+ > `MockTerminal` implements every `Terminal` method and is **reusable across packages** — upper-layer shells (such as `@easbot/agent-tui`) import it directly instead of each writing their own.
222
+
223
+ ### Utilities
224
+
225
+ ```typescript
226
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@easbot/tui';
227
+
228
+ // Measure visible width, ignoring ANSI sequences
229
+ visibleWidth('\x1b[31mHello\x1b[0m'); // 5
230
+
231
+ // Truncate to a visible width (ANSI sequences preserved and correctly closed)
232
+ truncateToWidth('Hello World', 8); // 'Hello...'
233
+
234
+ // Wrap at a visible width (ANSI styling carried across line breaks)
235
+ wrapTextWithAnsi('This is a long line that needs wrapping', 20);
236
+ ```
237
+
238
+ > ⚠️ The **visible width of every line** returned by `render()` must not exceed the `width` parameter, otherwise the renderer throws.
239
+
240
+ ### Keyboard detection
241
+
242
+ ```typescript
243
+ import { Key, matchesKey } from '@easbot/tui';
244
+
245
+ if (matchesKey(data, Key.ctrl('c'))) {
246
+ process.exit(0);
247
+ }
248
+ if (matchesKey(data, Key.enter)) {
249
+ submit();
250
+ }
251
+ ```
252
+
253
+ ### Keybinding registry
254
+
255
+ ```typescript
256
+ import { KeybindingsManager, TUI_KEYBINDINGS, getKeybindings } from '@easbot/tui';
257
+
258
+ // Global manager (initialized with TUI_KEYBINDINGS on first access)
259
+ getKeybindings().getKeys('tui.editor.cursorLeft'); // ['left', 'ctrl+b']
260
+
261
+ // Custom override with conflict detection
262
+ const manager = new KeybindingsManager(TUI_KEYBINDINGS, {
263
+ 'tui.editor.cursorLeft': 'ctrl+h',
264
+ });
265
+ manager.getConflicts(); // [{ key: 'ctrl+h', keybindings: [...] }]
266
+ ```
267
+
268
+ ## Documentation Map
269
+
270
+ | Category | Path | Purpose |
271
+ | ------------- | -------------------------------------------- | ------------------------------------------------------- |
272
+ | Package guide | [`README.md`](./README.md) | Current document (Chinese) |
273
+ | English guide | [`README.en.md`](./README.en.md) | Current document (English) |
274
+ | Port notes | [`docs/tui-readme.md`](./docs/tui-readme.md) | Original upstream pi-tui README (port source reference) |
275
+ | Source API | `src/**/*.ts` | Every export carries complete Chinese JSDoc |
276
+ | Decision log | [`docs/decisions/`](../../docs/decisions/) | Repository-level architecture decisions |
277
+ | Project specs | [`spec/`](../../spec/) | Coding / naming / testing standards |
278
+ | Agent guide | [`AGENTS.md`](../../AGENTS.md) | AI Agent collaboration entry map |
279
+
48
280
  ## Development
49
281
 
50
282
  ```bash
51
- # Install dependencies
52
- pnpm install
53
-
54
283
  # Build
55
- pnpm build
284
+ pnpm --filter @easbot/tui build
285
+
286
+ # Development mode (watch)
287
+ pnpm --filter @easbot/tui dev
288
+
289
+ # Tests (Vitest 4)
290
+ pnpm --filter @easbot/tui test:run
56
291
 
57
- # Test
58
- pnpm test
292
+ # Coverage
293
+ pnpm --filter @easbot/tui test:coverage
59
294
 
60
295
  # Type check
61
- pnpm type-check
296
+ pnpm --filter @easbot/tui type-check
297
+
298
+ # Lint (Biome 2.x)
299
+ pnpm --filter @easbot/tui lint
300
+ ```
301
+
302
+ > ⚠️ Tests **must** run from the package directory or via `--filter` — the global mocks in the package-level `tests/setup.ts` are only loaded under that package's config, so running a single file from the repository root produces a false pass.
303
+
304
+ ## Contributing
305
+
306
+ Contributions are welcome. Read [`AGENTS.md`](../../AGENTS.md) for project boundaries and collaboration conventions; coding standards live in [`spec/coding-standards.md`](../../spec/coding-standards.md) and [`rules/EASBOT_CODE_GUIDE.md`](../../rules/EASBOT_CODE_GUIDE.md).
307
+
308
+ The following must pass before submitting:
309
+
310
+ ```bash
311
+ pnpm --filter @easbot/tui type-check
312
+ pnpm --filter @easbot/tui test:run
313
+ pnpm biome-lint
62
314
  ```
63
315
 
64
316
  ## License
65
317
 
66
- MIT
318
+ MIT — see the [`LICENSE`](./LICENSE) file.