tiny-tui 0.0.0-stage → 1.0.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.
- package/README.md +108 -2
- package/package.json +30 -4
- package/src/ansi.js +159 -0
- package/src/components/Box.js +53 -0
- package/src/components/Flex.js +123 -0
- package/src/components/Page.js +73 -0
- package/src/components/SelectList.js +38 -0
- package/src/components/index.js +5 -0
- package/src/components/renderNode.js +8 -0
- package/src/index.js +21 -0
- package/src/tui.js +128 -0
package/README.md
CHANGED
|
@@ -1,3 +1,109 @@
|
|
|
1
|
-
#
|
|
1
|
+
# tiny-tui
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A lightweight, zero-dependency, component-based Terminal User Interface (TUI) framework for Node.js. Engineered to work seamlessly in both modern terminal emulators and raw Linux virtual consoles (`TERM=linux` / TTY).
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Zero Dependencies:** Built purely on standard Node.js modules (`node:readline`).
|
|
8
|
+
- **Flicker-Free Rendering:** Full-frame buffering, line-end clearing, and batched re-renders via `setImmediate`.
|
|
9
|
+
- **Flexbox Layout Engine:** Responsive `Flex`, `Row`, and `Column` containers supporting `flex` ratios, fixed sizes, auto-sizing, and `gap`.
|
|
10
|
+
- **TTY-Safe ANSI Styling:** Chainable style builder (`ANSI.bold.bgBlue.brightWhite(...)`) compatible with the 16-color VGA TTY palette, including nested background preservation.
|
|
11
|
+
- **Page Routing & Input Isolation:** `Page` and `PageManager` components that isolate keyboard events and local hotkeys to the active view.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
Clone the repository or install it locally in your project:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install ./path/to/tiny-tui
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```javascript
|
|
24
|
+
import { App, Component, ANSI, Flex, Box, SelectList } from 'tiny-tui';
|
|
25
|
+
|
|
26
|
+
class MainScreen extends Component {
|
|
27
|
+
constructor(onExit) {
|
|
28
|
+
super();
|
|
29
|
+
this.state = { status: 'Ready' };
|
|
30
|
+
|
|
31
|
+
// Mount child components to automatically propagate state updates and key events
|
|
32
|
+
this.menu = this.mount(new SelectList({
|
|
33
|
+
items: ['Run Task', 'Check Status', 'Exit'],
|
|
34
|
+
onSelect: (item) => {
|
|
35
|
+
if (item === 'Exit') return onExit();
|
|
36
|
+
this.setState({ status: `Executed: ${ANSI.green(item)}` });
|
|
37
|
+
},
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
render(width, height) {
|
|
42
|
+
return new Flex({
|
|
43
|
+
direction: 'column',
|
|
44
|
+
width,
|
|
45
|
+
height,
|
|
46
|
+
children: [
|
|
47
|
+
new Box({
|
|
48
|
+
title: ANSI.bold.inverse.brightYellow(' SYSTEM MONITOR '),
|
|
49
|
+
children: [`Status: ${this.state.status}`],
|
|
50
|
+
}),
|
|
51
|
+
new Box({
|
|
52
|
+
title: 'ACTIONS',
|
|
53
|
+
flex: 1,
|
|
54
|
+
children: [this.menu],
|
|
55
|
+
}),
|
|
56
|
+
],
|
|
57
|
+
}).render(width, height);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const app = new App(new MainScreen(() => app.exit()));
|
|
62
|
+
app.start();
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Core API & Components
|
|
66
|
+
|
|
67
|
+
### `App` & `Component`
|
|
68
|
+
- **`new App(rootComponent)`**: Initializes alternate screen buffer, hides cursor, enables raw TTY input, handles terminal `resize` events, and restores terminal state cleanly on exit or crash.
|
|
69
|
+
- **`this.mount(child)`**: Registers a child component so its `setState()` triggers a screen re-render and keyboard events bubble down automatically.
|
|
70
|
+
- **`this.setState(partialState)`**: Merges new state and schedules a batched UI update.
|
|
71
|
+
|
|
72
|
+
### Layout (`Flex`, `Row`, `Column`)
|
|
73
|
+
Distributes available terminal space across child elements:
|
|
74
|
+
- `direction`: `'row'` | `'column'` (shorthands `Row` and `Column` are also exported).
|
|
75
|
+
- `flex`: Proportional weight for remaining space (e.g., `flex: 1`, `flex: 2`).
|
|
76
|
+
- `width` / `height`: Fixed dimensions in character cells (auto-calculated from content if omitted).
|
|
77
|
+
- `gap`: Spacing in cells/lines between child items.
|
|
78
|
+
|
|
79
|
+
### `Box`
|
|
80
|
+
Draws a bordered container around content:
|
|
81
|
+
- `title`: Header text displayed on the top border (preserves custom ANSI styles).
|
|
82
|
+
- `borderColor`: Style function applied to border characters (e.g., `ANSI.cyan`).
|
|
83
|
+
- `scrollBottom`: When `true`, automatically keeps the latest lines visible if content overflows the box height.
|
|
84
|
+
|
|
85
|
+
### `SelectList`
|
|
86
|
+
Interactive vertical menu with `Up`/`Down` arrow navigation and `Enter` selection:
|
|
87
|
+
- `items`: Array of strings to display.
|
|
88
|
+
- `onSelect(item)`: Callback triggered when `Enter` is pressed.
|
|
89
|
+
|
|
90
|
+
### `Page` & `PageManager`
|
|
91
|
+
Manages multi-screen applications with isolated hotkeys:
|
|
92
|
+
- **`Page`**: Extend this class to build custom views. Use `this.setHotkeys([{ key, label, action }])` to bind page-specific shortcuts and `this.renderHotkeys()` to render a formatted hotkey bar anywhere in your layout.
|
|
93
|
+
- **`PageManager`**: Accepts `{ pages, initialPage }` and routes `render()` and `handleKey()` calls exclusively to the active page via `manager.goTo(pageName)`.
|
|
94
|
+
|
|
95
|
+
### ANSI Utilities
|
|
96
|
+
- **`ANSI`**: Chainable color and modifier builder (`bold`, `dim`, `inverse`, `red`, `green`, `yellow`, `cyan`, `gray`, `brightWhite`, `bgBlue`, `bgYellow`, etc.) plus `ANSI.style(stylesArray, text)`.
|
|
97
|
+
- **String Helpers**: `stripAnsi(str)`, `visibleLength(str)`, `truncateAnsi(str, maxLen)`, `padRight(str, len)`, and `padLeft(str, len)`.
|
|
98
|
+
|
|
99
|
+
## Running Tests
|
|
100
|
+
|
|
101
|
+
The test suite uses the built-in Node.js test runner (`node:test`) with zero external dependencies:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
npm test
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## License
|
|
108
|
+
|
|
109
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tiny-tui",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Zero-dependency component-based TUI framework for Node.js and Linux TTY",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js",
|
|
9
|
+
"./ansi": "./src/ansi.js",
|
|
10
|
+
"./components": "./src/components/index.js"
|
|
11
|
+
},
|
|
12
|
+
"scripts": {
|
|
13
|
+
"test": "node --test"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src/",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=20.0.0"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"tui",
|
|
25
|
+
"cli",
|
|
26
|
+
"terminal",
|
|
27
|
+
"tty",
|
|
28
|
+
"components",
|
|
29
|
+
"flexbox"
|
|
30
|
+
],
|
|
31
|
+
"license": "MIT"
|
|
32
|
+
}
|
package/src/ansi.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
const ESC = '\x1b';
|
|
2
|
+
|
|
3
|
+
export const CTRL = {
|
|
4
|
+
altScreenOn: `${ESC}[?1049h`,
|
|
5
|
+
altScreenOff: `${ESC}[?1049l`,
|
|
6
|
+
cursorHide: `${ESC}[?25l`,
|
|
7
|
+
cursorShow: `${ESC}[?25h`,
|
|
8
|
+
cursorHome: `${ESC}[H`,
|
|
9
|
+
clearScreen: `${ESC}[2J${ESC}[H`,
|
|
10
|
+
clearLineEnd: `${ESC}[K`,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const CODES = {
|
|
14
|
+
// Модификаторы текста
|
|
15
|
+
bold: 1,
|
|
16
|
+
dim: 2,
|
|
17
|
+
underline: 4,
|
|
18
|
+
blink: 5,
|
|
19
|
+
inverse: 7,
|
|
20
|
+
hidden: 8,
|
|
21
|
+
|
|
22
|
+
// 8 базовых цветов текста (стандартные TTY)
|
|
23
|
+
black: 30,
|
|
24
|
+
red: 31,
|
|
25
|
+
green: 32,
|
|
26
|
+
yellow: 33,
|
|
27
|
+
blue: 34,
|
|
28
|
+
magenta: 35,
|
|
29
|
+
cyan: 36,
|
|
30
|
+
white: 37,
|
|
31
|
+
|
|
32
|
+
// 8 ярких цветов текста (VGA Bright)
|
|
33
|
+
gray: 90,
|
|
34
|
+
brightRed: 91,
|
|
35
|
+
brightGreen: 92,
|
|
36
|
+
brightYellow: 93,
|
|
37
|
+
brightBlue: 94,
|
|
38
|
+
brightMagenta: 95,
|
|
39
|
+
brightCyan: 96,
|
|
40
|
+
brightWhite: 97,
|
|
41
|
+
|
|
42
|
+
// 8 базовых цветов фона
|
|
43
|
+
bgBlack: 40,
|
|
44
|
+
bgRed: 41,
|
|
45
|
+
bgGreen: 42,
|
|
46
|
+
bgYellow: 43,
|
|
47
|
+
bgBlue: 44,
|
|
48
|
+
bgMagenta: 45,
|
|
49
|
+
bgCyan: 46,
|
|
50
|
+
bgWhite: 47,
|
|
51
|
+
|
|
52
|
+
// 8 ярких цветов фона
|
|
53
|
+
bgGray: 100,
|
|
54
|
+
bgBrightRed: 101,
|
|
55
|
+
bgBrightGreen: 102,
|
|
56
|
+
bgBrightYellow: 103,
|
|
57
|
+
bgBrightBlue: 104,
|
|
58
|
+
bgBrightMagenta: 105,
|
|
59
|
+
bgBrightCyan: 106,
|
|
60
|
+
bgBrightWhite: 107,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
function applyCodes(codes, str) {
|
|
64
|
+
const text = String(str);
|
|
65
|
+
if (!codes.length) return text;
|
|
66
|
+
const open = `${ESC}[${codes.join(';')}m`;
|
|
67
|
+
const close = `${ESC}[0m`;
|
|
68
|
+
const safeText = text.replaceAll(close, `${close}${open}`);
|
|
69
|
+
return `${open}${safeText}${close}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function createStyleBuilder(activeCodes = []) {
|
|
73
|
+
const fn = (str) => applyCodes(activeCodes, str);
|
|
74
|
+
|
|
75
|
+
return new Proxy(fn, {
|
|
76
|
+
get(target, prop) {
|
|
77
|
+
if (prop in CODES) {
|
|
78
|
+
return createStyleBuilder([...activeCodes, CODES[prop]]);
|
|
79
|
+
}
|
|
80
|
+
return target[prop];
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @typedef {(str: string | number) => string} AnsiFn
|
|
87
|
+
*
|
|
88
|
+
* @typedef {AnsiFn & {
|
|
89
|
+
* bold: AnsiChain,
|
|
90
|
+
* dim: AnsiChain,
|
|
91
|
+
* underline: AnsiChain,
|
|
92
|
+
* blink: AnsiChain,
|
|
93
|
+
* inverse: AnsiChain,
|
|
94
|
+
* hidden: AnsiChain,
|
|
95
|
+
* black: AnsiChain,
|
|
96
|
+
* red: AnsiChain,
|
|
97
|
+
* green: AnsiChain,
|
|
98
|
+
* yellow: AnsiChain,
|
|
99
|
+
* blue: AnsiChain,
|
|
100
|
+
* magenta: AnsiChain,
|
|
101
|
+
* cyan: AnsiChain,
|
|
102
|
+
* white: AnsiChain,
|
|
103
|
+
* gray: AnsiChain,
|
|
104
|
+
* brightRed: AnsiChain,
|
|
105
|
+
* brightGreen: AnsiChain,
|
|
106
|
+
* brightYellow: AnsiChain,
|
|
107
|
+
* brightBlue: AnsiChain,
|
|
108
|
+
* brightMagenta: AnsiChain,
|
|
109
|
+
* brightCyan: AnsiChain,
|
|
110
|
+
* brightWhite: AnsiChain,
|
|
111
|
+
* bgBlack: AnsiChain,
|
|
112
|
+
* bgRed: AnsiChain,
|
|
113
|
+
* bgGreen: AnsiChain,
|
|
114
|
+
* bgYellow: AnsiChain,
|
|
115
|
+
* bgBlue: AnsiChain,
|
|
116
|
+
* bgMagenta: AnsiChain,
|
|
117
|
+
* bgCyan: AnsiChain,
|
|
118
|
+
* bgWhite: AnsiChain,
|
|
119
|
+
* bgGray: AnsiChain,
|
|
120
|
+
* bgBrightRed: AnsiChain,
|
|
121
|
+
* bgBrightGreen: AnsiChain,
|
|
122
|
+
* bgBrightYellow: AnsiChain,
|
|
123
|
+
* bgBrightBlue: AnsiChain,
|
|
124
|
+
* bgBrightMagenta: AnsiChain,
|
|
125
|
+
* bgBrightCyan: AnsiChain,
|
|
126
|
+
* bgBrightWhite: AnsiChain,
|
|
127
|
+
* }} AnsiChain
|
|
128
|
+
*/
|
|
129
|
+
|
|
130
|
+
/** @type {AnsiChain & { reset: string, style: (styles: keyof typeof CODES | Array<keyof typeof CODES>, str: string | number) => string }} */
|
|
131
|
+
export const ANSI = createStyleBuilder();
|
|
132
|
+
ANSI.reset = `${ESC}[0m`;
|
|
133
|
+
ANSI.style = (styles, str) => {
|
|
134
|
+
const list = Array.isArray(styles) ? styles : [styles];
|
|
135
|
+
const codes = list.map((s) => CODES[s]).filter(Boolean);
|
|
136
|
+
return applyCodes(codes, str);
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// Утилиты для работы со строками, содержащими ANSI-коды
|
|
140
|
+
const ANSI_REGEX = /\x1b\[[0-9;]*m/g;
|
|
141
|
+
|
|
142
|
+
export const stripAnsi = (str) => String(str).replace(ANSI_REGEX, '');
|
|
143
|
+
export const visibleLength = (str) => stripAnsi(str).length;
|
|
144
|
+
|
|
145
|
+
export function truncateAnsi(str, maxLen) {
|
|
146
|
+
if (visibleLength(str) <= maxLen) return str;
|
|
147
|
+
const plain = stripAnsi(str);
|
|
148
|
+
return maxLen <= 1 ? plain.slice(0, maxLen) : plain.slice(0, maxLen - 1) + '…';
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function padRight(str, len) {
|
|
152
|
+
const vLen = visibleLength(str);
|
|
153
|
+
return vLen >= len ? str : str + ' '.repeat(len - vLen);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function padLeft(str, len) {
|
|
157
|
+
const vLen = visibleLength(str);
|
|
158
|
+
return vLen >= len ? str : ' '.repeat(len - vLen) + str;
|
|
159
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { Component } from '../tui.js';
|
|
2
|
+
import { ANSI, visibleLength, truncateAnsi, padRight } from '../ansi.js';
|
|
3
|
+
import { renderNode } from './renderNode.js';
|
|
4
|
+
|
|
5
|
+
export class Box extends Component {
|
|
6
|
+
render(availWidth = 46, availHeight) {
|
|
7
|
+
const {
|
|
8
|
+
title = '',
|
|
9
|
+
children = [],
|
|
10
|
+
width = availWidth,
|
|
11
|
+
height = availHeight,
|
|
12
|
+
scrollBottom = false,
|
|
13
|
+
borderColor = (str) => str,
|
|
14
|
+
} = this.props;
|
|
15
|
+
|
|
16
|
+
const innerWidth = Math.max(4, width - 4);
|
|
17
|
+
const cleanTitle = title ? ` ${title} ` : '';
|
|
18
|
+
const titleLen = visibleLength(cleanTitle);
|
|
19
|
+
|
|
20
|
+
// Если заголовок уже содержит ANSI-коды, не перезаписываем его стиль
|
|
21
|
+
const styledTitle = String(title).includes('\x1b[')
|
|
22
|
+
? cleanTitle
|
|
23
|
+
: ANSI.bold(cleanTitle);
|
|
24
|
+
|
|
25
|
+
const topBorder =
|
|
26
|
+
borderColor('┌─') +
|
|
27
|
+
styledTitle +
|
|
28
|
+
borderColor(`${'─'.repeat(Math.max(0, width - 3 - titleLen))}┐`);
|
|
29
|
+
|
|
30
|
+
const bottomBorder = borderColor(`└${'─'.repeat(Math.max(0, width - 2))}┘`);
|
|
31
|
+
|
|
32
|
+
const innerHeight = typeof height === 'number' ? Math.max(1, height - 2) : undefined;
|
|
33
|
+
const contentLines = children.flatMap((child) => renderNode(child, innerWidth, innerHeight));
|
|
34
|
+
|
|
35
|
+
const targetRows = innerHeight ?? contentLines.length;
|
|
36
|
+
const visibleLines = scrollBottom && contentLines.length > targetRows
|
|
37
|
+
? contentLines.slice(-targetRows)
|
|
38
|
+
: contentLines;
|
|
39
|
+
|
|
40
|
+
const leftWall = borderColor('│ ');
|
|
41
|
+
const rightWall = borderColor(' │');
|
|
42
|
+
|
|
43
|
+
const body = [];
|
|
44
|
+
for (let i = 0; i < targetRows; i++) {
|
|
45
|
+
const line = visibleLines[i] || '';
|
|
46
|
+
const clipped = truncateAnsi(line, innerWidth);
|
|
47
|
+
const padded = padRight(clipped, innerWidth);
|
|
48
|
+
body.push(`${leftWall}${padded}${rightWall}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return [topBorder, ...body, bottomBorder];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { Component } from '../tui.js';
|
|
2
|
+
import { visibleLength, truncateAnsi, padRight } from '../ansi.js';
|
|
3
|
+
import { renderNode } from './renderNode.js';
|
|
4
|
+
|
|
5
|
+
export class Flex extends Component {
|
|
6
|
+
render(availWidth, availHeight) {
|
|
7
|
+
const {
|
|
8
|
+
direction = 'row',
|
|
9
|
+
gap = 0,
|
|
10
|
+
children = [],
|
|
11
|
+
width = availWidth,
|
|
12
|
+
height = availHeight,
|
|
13
|
+
} = this.props;
|
|
14
|
+
|
|
15
|
+
const items = children.filter((c) => c !== null && c !== undefined);
|
|
16
|
+
if (!items.length) return [];
|
|
17
|
+
|
|
18
|
+
const isRow = direction === 'row';
|
|
19
|
+
const mainTotal = isRow ? (width ?? 80) : (height ?? 24);
|
|
20
|
+
const explicitCross = isRow ? height : width;
|
|
21
|
+
const totalGap = gap * Math.max(0, items.length - 1);
|
|
22
|
+
|
|
23
|
+
let fixedMain = 0;
|
|
24
|
+
let totalFlex = 0;
|
|
25
|
+
|
|
26
|
+
// 1. Замеряем фиксированные и автоматические размеры по главной оси
|
|
27
|
+
const meta = items.map((item) => {
|
|
28
|
+
const props = item?.props || {};
|
|
29
|
+
const flex = props.flex || 0;
|
|
30
|
+
const explicitSize = isRow ? props.width : props.height;
|
|
31
|
+
|
|
32
|
+
if (flex > 0) {
|
|
33
|
+
totalFlex += flex;
|
|
34
|
+
return { item, flex, size: 0 };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (typeof explicitSize === 'number') {
|
|
38
|
+
fixedMain += explicitSize;
|
|
39
|
+
return { item, flex: 0, size: explicitSize };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Передаём undefined по обеим незафиксированным осям для честного замера контента
|
|
43
|
+
const lines = renderNode(
|
|
44
|
+
item,
|
|
45
|
+
isRow ? undefined : explicitCross,
|
|
46
|
+
isRow ? explicitCross : undefined
|
|
47
|
+
);
|
|
48
|
+
const autoSize = isRow
|
|
49
|
+
? Math.max(1, ...lines.map(visibleLength))
|
|
50
|
+
: Math.max(1, lines.length);
|
|
51
|
+
|
|
52
|
+
fixedMain += autoSize;
|
|
53
|
+
return { item, flex: 0, size: autoSize };
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// 2. Распределяем оставшееся пространство между flex-элементами
|
|
57
|
+
const freeSpace = Math.max(0, mainTotal - fixedMain - totalGap);
|
|
58
|
+
let allocatedFlex = 0;
|
|
59
|
+
let flexCountSeen = 0;
|
|
60
|
+
const flexItemsCount = meta.filter((m) => m.flex > 0).length;
|
|
61
|
+
|
|
62
|
+
for (const m of meta) {
|
|
63
|
+
if (m.flex > 0) {
|
|
64
|
+
flexCountSeen++;
|
|
65
|
+
if (flexCountSeen === flexItemsCount) {
|
|
66
|
+
m.size = Math.max(1, freeSpace - allocatedFlex);
|
|
67
|
+
} else {
|
|
68
|
+
m.size = Math.max(1, Math.floor((freeSpace * m.flex) / totalFlex));
|
|
69
|
+
allocatedFlex += m.size;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 3. Рендерим каждый дочерний элемент
|
|
75
|
+
if (isRow) {
|
|
76
|
+
// Если высота ряда не задана явно (замер), считаем её по самому высокому элементу
|
|
77
|
+
const rawCols = meta.map(({ item, size }) => renderNode(item, size, explicitCross));
|
|
78
|
+
const crossTotal = explicitCross ?? Math.max(1, ...rawCols.map((c) => c.length));
|
|
79
|
+
|
|
80
|
+
const renderedCols = rawCols.map((lines, idx) => {
|
|
81
|
+
const colWidth = meta[idx].size;
|
|
82
|
+
const result = [];
|
|
83
|
+
for (let r = 0; r < crossTotal; r++) {
|
|
84
|
+
const rawLine = lines[r] || '';
|
|
85
|
+
result.push(padRight(truncateAnsi(rawLine, colWidth), colWidth));
|
|
86
|
+
}
|
|
87
|
+
return result;
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const spacer = ' '.repeat(gap);
|
|
91
|
+
const output = [];
|
|
92
|
+
for (let r = 0; r < crossTotal; r++) {
|
|
93
|
+
output.push(renderedCols.map((col) => col[r]).join(spacer));
|
|
94
|
+
}
|
|
95
|
+
return output;
|
|
96
|
+
} else {
|
|
97
|
+
const crossTotal = explicitCross ?? 80;
|
|
98
|
+
const output = [];
|
|
99
|
+
meta.forEach(({ item, size }, idx) => {
|
|
100
|
+
const lines = renderNode(item, crossTotal, size);
|
|
101
|
+
for (let r = 0; r < size; r++) {
|
|
102
|
+
output.push(lines[r] || '');
|
|
103
|
+
}
|
|
104
|
+
if (gap > 0 && idx < meta.length - 1) {
|
|
105
|
+
for (let g = 0; g < gap; g++) output.push('');
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
return output;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export class Row extends Flex {
|
|
114
|
+
constructor(props) {
|
|
115
|
+
super({ ...props, direction: 'row' });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export class Column extends Flex {
|
|
120
|
+
constructor(props) {
|
|
121
|
+
super({ ...props, direction: 'column' });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { Component } from '../tui.js';
|
|
2
|
+
import { ANSI } from '../ansi.js';
|
|
3
|
+
import { renderNode } from './renderNode.js';
|
|
4
|
+
|
|
5
|
+
export class Page extends Component {
|
|
6
|
+
constructor(props = {}) {
|
|
7
|
+
super(props);
|
|
8
|
+
this.hotkeys = props.hotkeys || [];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
setHotkeys(hotkeys) {
|
|
12
|
+
this.hotkeys = hotkeys;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
renderHotkeys(separator = ' ') {
|
|
16
|
+
if (!this.hotkeys.length) return '';
|
|
17
|
+
return ' ' + this.hotkeys
|
|
18
|
+
.map((hk) => `${ANSI.bold.bgBlue.brightWhite(` ${hk.key.toUpperCase()} `)} ${hk.label}`)
|
|
19
|
+
.join(separator);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
onKey(key) {
|
|
23
|
+
if (!key) return;
|
|
24
|
+
for (const hk of this.hotkeys) {
|
|
25
|
+
if (hk.key.toLowerCase() === key.name?.toLowerCase() && typeof hk.action === 'function') {
|
|
26
|
+
hk.action(key);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
render(width, height) {
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class PageManager extends Component {
|
|
38
|
+
constructor(props = {}) {
|
|
39
|
+
super(props);
|
|
40
|
+
const { pages = {}, initialPage = Object.keys(pages)[0] } = props;
|
|
41
|
+
this.pages = pages;
|
|
42
|
+
|
|
43
|
+
for (const page of Object.values(this.pages)) {
|
|
44
|
+
page._onUpdate = () => this._notifyUpdate();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
this.state = {
|
|
48
|
+
current: initialPage,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
goTo(pageName) {
|
|
53
|
+
if (this.pages[pageName]) {
|
|
54
|
+
this.setState({ current: pageName });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
handleKey(key) {
|
|
59
|
+
this.onKey(key);
|
|
60
|
+
const activePage = this.pages[this.state.current];
|
|
61
|
+
if (activePage) {
|
|
62
|
+
activePage.handleKey(key);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
render(width, height) {
|
|
67
|
+
const activePage = this.pages[this.state.current];
|
|
68
|
+
if (!activePage) {
|
|
69
|
+
return [ANSI.red(`Страница "${this.state.current}" не найдена`)];
|
|
70
|
+
}
|
|
71
|
+
return renderNode(activePage, width, height);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Component } from '../tui.js';
|
|
2
|
+
import { ANSI, truncateAnsi, padRight } from '../ansi.js';
|
|
3
|
+
|
|
4
|
+
export class SelectList extends Component {
|
|
5
|
+
constructor(props) {
|
|
6
|
+
super(props);
|
|
7
|
+
this.state = { selectedIndex: 0 };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
onKey(key) {
|
|
11
|
+
const { items = [], onSelect } = this.props;
|
|
12
|
+
if (!items.length) return;
|
|
13
|
+
|
|
14
|
+
if (key.name === 'up') {
|
|
15
|
+
const next = (this.state.selectedIndex - 1 + items.length) % items.length;
|
|
16
|
+
this.setState({ selectedIndex: next });
|
|
17
|
+
} else if (key.name === 'down') {
|
|
18
|
+
const next = (this.state.selectedIndex + 1) % items.length;
|
|
19
|
+
this.setState({ selectedIndex: next });
|
|
20
|
+
} else if (key.name === 'return' && onSelect) {
|
|
21
|
+
onSelect(items[this.state.selectedIndex]);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
render(availWidth = 30) {
|
|
26
|
+
const { items = [] } = this.props;
|
|
27
|
+
const textWidth = Math.max(5, availWidth - 4);
|
|
28
|
+
|
|
29
|
+
return items.map((item, idx) => {
|
|
30
|
+
const isSelected = idx === this.state.selectedIndex;
|
|
31
|
+
const prefix = isSelected ? ANSI.cyan('> ') : ' ';
|
|
32
|
+
const clipped = truncateAnsi(String(item), textWidth);
|
|
33
|
+
const padded = padRight(clipped, textWidth);
|
|
34
|
+
const label = isSelected ? ANSI.inverse(` ${padded} `) : ` ${padded} `;
|
|
35
|
+
return `${prefix}${label}`;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function renderNode(node, width, height) {
|
|
2
|
+
if (typeof node === 'string') return node.split('\n');
|
|
3
|
+
if (node && typeof node.render === 'function') {
|
|
4
|
+
const out = node.render(width, height);
|
|
5
|
+
return Array.isArray(out) ? out : String(out).split('\n');
|
|
6
|
+
}
|
|
7
|
+
return [''];
|
|
8
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export { App, Component } from './tui.js';
|
|
2
|
+
|
|
3
|
+
export {
|
|
4
|
+
ANSI, CTRL,
|
|
5
|
+
stripAnsi,
|
|
6
|
+
visibleLength,
|
|
7
|
+
truncateAnsi,
|
|
8
|
+
padRight,
|
|
9
|
+
padLeft,
|
|
10
|
+
} from './ansi.js';
|
|
11
|
+
|
|
12
|
+
export {
|
|
13
|
+
Flex,
|
|
14
|
+
Row,
|
|
15
|
+
Column,
|
|
16
|
+
Box,
|
|
17
|
+
SelectList,
|
|
18
|
+
Page,
|
|
19
|
+
PageManager,
|
|
20
|
+
renderNode,
|
|
21
|
+
} from './components/index.js';
|
package/src/tui.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import readline from 'node:readline';
|
|
2
|
+
import { CTRL } from './ansi.js';
|
|
3
|
+
|
|
4
|
+
export class Component {
|
|
5
|
+
constructor(props = {}) {
|
|
6
|
+
this.props = props;
|
|
7
|
+
this.state = {};
|
|
8
|
+
this.children = [];
|
|
9
|
+
this._onUpdate = null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
mount(child) {
|
|
13
|
+
child._onUpdate = () => this._notifyUpdate();
|
|
14
|
+
this.children.push(child);
|
|
15
|
+
return child;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
_notifyUpdate() {
|
|
19
|
+
if (this._onUpdate) this._onUpdate();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
setState(partial) {
|
|
23
|
+
this.state = { ...this.state, ...partial };
|
|
24
|
+
this._notifyUpdate();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
handleKey(key) {
|
|
28
|
+
this.onKey(key);
|
|
29
|
+
for (const child of this.children) {
|
|
30
|
+
child.handleKey(key);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
onKey(key) {}
|
|
35
|
+
render(width, height) { return []; }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class App {
|
|
39
|
+
constructor(rootComponent) {
|
|
40
|
+
this.root = rootComponent;
|
|
41
|
+
this.root._onUpdate = () => this.scheduleRender();
|
|
42
|
+
this.isExiting = false;
|
|
43
|
+
this.renderScheduled = false;
|
|
44
|
+
|
|
45
|
+
this.onKeypress = (_, key) => this.handleKey(key);
|
|
46
|
+
this.onResize = () => {
|
|
47
|
+
process.stdout.write(CTRL.clearScreen);
|
|
48
|
+
this.render();
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
start() {
|
|
53
|
+
process.stdout.write(CTRL.altScreenOn + CTRL.cursorHide + CTRL.clearScreen);
|
|
54
|
+
readline.emitKeypressEvents(process.stdin);
|
|
55
|
+
|
|
56
|
+
if (process.stdin.isTTY) {
|
|
57
|
+
process.stdin.setRawMode(true);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
process.stdin.on('keypress', this.onKeypress);
|
|
61
|
+
process.stdout.on('resize', this.onResize);
|
|
62
|
+
|
|
63
|
+
process.on('exit', () => this.cleanup());
|
|
64
|
+
process.on('SIGINT', () => this.exit());
|
|
65
|
+
process.on('SIGTERM', () => this.exit());
|
|
66
|
+
process.on('uncaughtException', (err) => this.exit(1, err));
|
|
67
|
+
process.on('unhandledRejection', (err) => this.exit(1, err));
|
|
68
|
+
|
|
69
|
+
this.render();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
handleKey(key) {
|
|
73
|
+
if (!key) return;
|
|
74
|
+
|
|
75
|
+
if (key.ctrl && key.name === 'c') {
|
|
76
|
+
return this.exit();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
this.root.handleKey(key);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
scheduleRender() {
|
|
83
|
+
if (this.renderScheduled) return;
|
|
84
|
+
this.renderScheduled = true;
|
|
85
|
+
setImmediate(() => {
|
|
86
|
+
this.renderScheduled = false;
|
|
87
|
+
this.render();
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
render() {
|
|
92
|
+
if (this.isExiting) return;
|
|
93
|
+
|
|
94
|
+
const rawCols = process.stdout.columns || 110;
|
|
95
|
+
const termWidth = Math.max(40, rawCols - 1);
|
|
96
|
+
const termHeight = Math.max(10, process.stdout.rows || 24);
|
|
97
|
+
|
|
98
|
+
const rawOutput = this.root.render(termWidth, termHeight);
|
|
99
|
+
const lines = Array.isArray(rawOutput) ? rawOutput : String(rawOutput).split('\n');
|
|
100
|
+
|
|
101
|
+
const frame =
|
|
102
|
+
CTRL.cursorHome +
|
|
103
|
+
lines.slice(0, termHeight).map((line) => line + CTRL.clearLineEnd).join('\n') +
|
|
104
|
+
CTRL.clearLineEnd;
|
|
105
|
+
|
|
106
|
+
process.stdout.write(frame);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
cleanup() {
|
|
110
|
+
if (this.isExiting) return;
|
|
111
|
+
this.isExiting = true;
|
|
112
|
+
|
|
113
|
+
process.stdout.off('resize', this.onResize);
|
|
114
|
+
process.stdin.off('keypress', this.onKeypress);
|
|
115
|
+
|
|
116
|
+
if (process.stdin.isTTY) {
|
|
117
|
+
process.stdin.setRawMode(false);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
process.stdout.write(CTRL.cursorShow + CTRL.altScreenOff);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
exit(code = 0, err = null) {
|
|
124
|
+
this.cleanup();
|
|
125
|
+
if (err) console.error(err);
|
|
126
|
+
process.exit(code);
|
|
127
|
+
}
|
|
128
|
+
}
|