termkit-ui 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 (50) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +9 -0
  3. package/README.md +153 -2
  4. package/dist/components/display/layout.d.ts +91 -0
  5. package/dist/components/display/table.d.ts +53 -0
  6. package/dist/components/progress/index.d.ts +2 -0
  7. package/dist/components/progress/progressBar.d.ts +102 -0
  8. package/dist/components/progress/spinner.d.ts +107 -0
  9. package/dist/components/prompts/base.d.ts +53 -0
  10. package/dist/components/prompts/confirm.d.ts +46 -0
  11. package/dist/components/prompts/index.d.ts +6 -0
  12. package/dist/components/prompts/input.d.ts +46 -0
  13. package/dist/components/prompts/multiselect.d.ts +100 -0
  14. package/dist/components/prompts/number.d.ts +58 -0
  15. package/dist/components/prompts/password.d.ts +45 -0
  16. package/dist/components/prompts/select.d.ts +84 -0
  17. package/dist/core/ansi/escapes.d.ts +154 -0
  18. package/dist/core/caps/detect.d.ts +74 -0
  19. package/dist/core/errors/index.d.ts +73 -0
  20. package/dist/core/styles/index.d.ts +12 -0
  21. package/dist/core/width/string-width.d.ts +42 -0
  22. package/dist/engine/guard/terminal-guard.d.ts +84 -0
  23. package/dist/engine/keyboard/parser.d.ts +79 -0
  24. package/dist/engine/renderer/coordinator.d.ts +85 -0
  25. package/dist/index.d.ts +13 -0
  26. package/dist/testing/index.d.ts +127 -0
  27. package/package.json +77 -4
  28. package/src/components/display/layout.js +224 -0
  29. package/src/components/display/table.js +179 -0
  30. package/src/components/progress/index.js +6 -0
  31. package/src/components/progress/progressBar.js +153 -0
  32. package/src/components/progress/spinner.js +195 -0
  33. package/src/components/prompts/base.js +237 -0
  34. package/src/components/prompts/confirm.js +68 -0
  35. package/src/components/prompts/index.js +10 -0
  36. package/src/components/prompts/input.js +107 -0
  37. package/src/components/prompts/multiselect.js +205 -0
  38. package/src/components/prompts/number.js +140 -0
  39. package/src/components/prompts/password.js +77 -0
  40. package/src/components/prompts/select.js +171 -0
  41. package/src/core/ansi/escapes.js +52 -0
  42. package/src/core/caps/detect.js +167 -0
  43. package/src/core/errors/index.js +106 -0
  44. package/src/core/styles/index.js +174 -0
  45. package/src/core/width/string-width.js +244 -0
  46. package/src/engine/guard/terminal-guard.js +188 -0
  47. package/src/engine/keyboard/parser.js +285 -0
  48. package/src/engine/renderer/coordinator.js +263 -0
  49. package/src/index.js +17 -0
  50. package/src/testing/index.js +250 -0
@@ -0,0 +1,285 @@
1
+ /**
2
+ * @fileoverview High-performance keyboard sequence parser and event dispatcher.
3
+ * Decodes ANSI escape sequences, arrow keys, function keys, and bracketed paste chunks.
4
+ */
5
+
6
+ import { EventEmitter } from 'node:events';
7
+
8
+ /**
9
+ * @typedef {Object} KeyEvent
10
+ * @property {string} name - Normalized key name (e.g. 'up', 'down', 'return', 'escape', 'backspace', 'a')
11
+ * @property {string} sequence - Raw byte or character sequence
12
+ * @property {boolean} ctrl - Whether Ctrl key was pressed
13
+ * @property {boolean} meta - Whether Meta/Alt key was pressed
14
+ * @property {boolean} shift - Whether Shift key was pressed
15
+ * @property {boolean} [isPaste] - Whether this event represents a pasted block of text
16
+ * @property {string} [pasteText] - Text content of the paste if isPaste is true
17
+ */
18
+
19
+ export class KeyboardParser extends EventEmitter {
20
+ /**
21
+ * @param {NodeJS.ReadableStream} [stream] - Defaults to process.stdin
22
+ */
23
+ constructor(stream = process.stdin) {
24
+ super();
25
+ /** @type {NodeJS.ReadableStream} */
26
+ this.stream = stream;
27
+ /** @type {string} */
28
+ this._buffer = '';
29
+ /** @type {boolean} */
30
+ this._isPasting = false;
31
+ /** @type {string} */
32
+ this._pasteBuffer = '';
33
+ /** @type {(chunk: Buffer | string) => void} */
34
+ this._onData = this._handleData.bind(this);
35
+ /** @type {boolean} */
36
+ this._attached = false;
37
+ }
38
+
39
+ /**
40
+ * Attach parser to stream.
41
+ */
42
+ attach() {
43
+ if (this._attached) return;
44
+ this._attached = true;
45
+ this.stream.on('data', this._onData);
46
+ }
47
+
48
+ /**
49
+ * Detach parser from stream.
50
+ */
51
+ detach() {
52
+ if (!this._attached) return;
53
+ this._attached = false;
54
+ this.stream.removeListener('data', this._onData);
55
+ this._buffer = '';
56
+ this._isPasting = false;
57
+ this._pasteBuffer = '';
58
+ }
59
+
60
+ /**
61
+ * Process raw input chunk.
62
+ * @private
63
+ * @param {Buffer | string} chunk
64
+ */
65
+ _handleData(chunk) {
66
+ const str = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
67
+
68
+ // Handle Bracketed Paste Mode (\x1b[200~ ... \x1b[201~)
69
+ if (this._isPasting) {
70
+ if (str.includes('\x1b[201~')) {
71
+ const parts = str.split('\x1b[201~');
72
+ this._pasteBuffer += parts[0];
73
+ this._isPasting = false;
74
+ this.emit('keypress', {
75
+ name: 'paste',
76
+ sequence: '',
77
+ ctrl: false,
78
+ meta: false,
79
+ shift: false,
80
+ isPaste: true,
81
+ pasteText: this._pasteBuffer
82
+ });
83
+ this._pasteBuffer = '';
84
+ if (parts[1]) {
85
+ this._handleData(parts[1]);
86
+ }
87
+ } else {
88
+ this._pasteBuffer += str;
89
+ }
90
+ return;
91
+ }
92
+
93
+ if (str.includes('\x1b[200~')) {
94
+ const parts = str.split('\x1b[200~');
95
+ if (parts[0]) {
96
+ this._parseNormal(parts[0]);
97
+ }
98
+ this._isPasting = true;
99
+ this._pasteBuffer = '';
100
+ if (parts[1]) {
101
+ this._handleData(parts[1]);
102
+ }
103
+ return;
104
+ }
105
+
106
+ this._parseNormal(str);
107
+ }
108
+
109
+ /**
110
+ * Parse normal character stream.
111
+ * @private
112
+ * @param {string} str
113
+ */
114
+ _parseNormal(str) {
115
+ let i = 0;
116
+ while (i < str.length) {
117
+ // 1. Enter / Return
118
+ if (str[i] === '\r' || str[i] === '\n') {
119
+ this.emit('keypress', {
120
+ name: 'return',
121
+ sequence: str[i],
122
+ ctrl: false,
123
+ meta: false,
124
+ shift: false
125
+ });
126
+ i++;
127
+ continue;
128
+ }
129
+
130
+ // 2. Tab
131
+ if (str[i] === '\t') {
132
+ this.emit('keypress', {
133
+ name: 'tab',
134
+ sequence: '\t',
135
+ ctrl: false,
136
+ meta: false,
137
+ shift: false
138
+ });
139
+ i++;
140
+ continue;
141
+ }
142
+
143
+ // 3. Backspace
144
+ if (str[i] === '\x7f' || str[i] === '\b') {
145
+ this.emit('keypress', {
146
+ name: 'backspace',
147
+ sequence: str[i],
148
+ ctrl: false,
149
+ meta: false,
150
+ shift: false
151
+ });
152
+ i++;
153
+ continue;
154
+ }
155
+
156
+ // 4. Space
157
+ if (str[i] === ' ') {
158
+ this.emit('keypress', {
159
+ name: 'space',
160
+ sequence: ' ',
161
+ ctrl: false,
162
+ meta: false,
163
+ shift: false
164
+ });
165
+ i++;
166
+ continue;
167
+ }
168
+
169
+ // 5. Control Characters (Ctrl+A to Ctrl+Z)
170
+ const code = str.charCodeAt(i);
171
+ if (code >= 1 && code <= 26 && code !== 9 && code !== 10 && code !== 13) {
172
+ const charName = String.fromCharCode(code + 96);
173
+ this.emit('keypress', {
174
+ name: charName,
175
+ sequence: str[i],
176
+ ctrl: true,
177
+ meta: false,
178
+ shift: false
179
+ });
180
+ i++;
181
+ continue;
182
+ }
183
+
184
+ // 6. Escape Sequences (ANSI / VT100 / Windows)
185
+ if (str[i] === '\x1b') {
186
+ // Standalone Escape
187
+ if (i + 1 >= str.length) {
188
+ this.emit('keypress', {
189
+ name: 'escape',
190
+ sequence: '\x1b',
191
+ ctrl: false,
192
+ meta: false,
193
+ shift: false
194
+ });
195
+ i++;
196
+ continue;
197
+ }
198
+
199
+ // CSI Sequences: \x1b[ ... or SS3 \x1bO ...
200
+ if (str[i + 1] === '[' || str[i + 1] === 'O') {
201
+ const prefix = str.slice(i, i + 3);
202
+ // Standard arrows
203
+ if (prefix === '\x1b[A' || prefix === '\x1bOA') {
204
+ this.emit('keypress', { name: 'up', sequence: prefix, ctrl: false, meta: false, shift: false });
205
+ i += 3;
206
+ continue;
207
+ }
208
+ if (prefix === '\x1b[B' || prefix === '\x1bOB') {
209
+ this.emit('keypress', { name: 'down', sequence: prefix, ctrl: false, meta: false, shift: false });
210
+ i += 3;
211
+ continue;
212
+ }
213
+ if (prefix === '\x1b[C' || prefix === '\x1bOC') {
214
+ this.emit('keypress', { name: 'right', sequence: prefix, ctrl: false, meta: false, shift: false });
215
+ i += 3;
216
+ continue;
217
+ }
218
+ if (prefix === '\x1b[D' || prefix === '\x1bOD') {
219
+ this.emit('keypress', { name: 'left', sequence: prefix, ctrl: false, meta: false, shift: false });
220
+ i += 3;
221
+ continue;
222
+ }
223
+ if (prefix === '\x1b[H' || prefix === '\x1bOH') {
224
+ this.emit('keypress', { name: 'home', sequence: prefix, ctrl: false, meta: false, shift: false });
225
+ i += 3;
226
+ continue;
227
+ }
228
+ if (prefix === '\x1b[F' || prefix === '\x1bOF') {
229
+ this.emit('keypress', { name: 'end', sequence: prefix, ctrl: false, meta: false, shift: false });
230
+ i += 3;
231
+ continue;
232
+ }
233
+
234
+ // Extended codes: \x1b[3~ (delete), \x1b[5~ (pageup), \x1b[6~ (pagedown)
235
+ if (str.slice(i, i + 4) === '\x1b[3~') {
236
+ this.emit('keypress', { name: 'delete', sequence: '\x1b[3~', ctrl: false, meta: false, shift: false });
237
+ i += 4;
238
+ continue;
239
+ }
240
+ if (str.slice(i, i + 4) === '\x1b[5~') {
241
+ this.emit('keypress', { name: 'pageup', sequence: '\x1b[5~', ctrl: false, meta: false, shift: false });
242
+ i += 4;
243
+ continue;
244
+ }
245
+ if (str.slice(i, i + 4) === '\x1b[6~') {
246
+ this.emit('keypress', { name: 'pagedown', sequence: '\x1b[6~', ctrl: false, meta: false, shift: false });
247
+ i += 4;
248
+ continue;
249
+ }
250
+
251
+ // Skip unrecognized escape sequence
252
+ let endIdx = i + 2;
253
+ while (endIdx < str.length && !/[a-zA-Z~]/.test(str[endIdx])) {
254
+ endIdx++;
255
+ }
256
+ i = endIdx + 1;
257
+ continue;
258
+ }
259
+
260
+ // Alt/Meta + Key: \x1b + char
261
+ const nextChar = str[i + 1];
262
+ this.emit('keypress', {
263
+ name: nextChar.toLowerCase(),
264
+ sequence: str.slice(i, i + 2),
265
+ ctrl: false,
266
+ meta: true,
267
+ shift: nextChar >= 'A' && nextChar <= 'Z'
268
+ });
269
+ i += 2;
270
+ continue;
271
+ }
272
+
273
+ // 7. Regular Character Input
274
+ const char = str[i];
275
+ this.emit('keypress', {
276
+ name: char,
277
+ sequence: char,
278
+ ctrl: false,
279
+ meta: false,
280
+ shift: char >= 'A' && char <= 'Z'
281
+ });
282
+ i++;
283
+ }
284
+ }
285
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * @fileoverview Central Output Coordinator and Virtual Screen Renderer.
3
+ * Manages active live regions, diffed line repaints, and safe concurrent logging.
4
+ */
5
+
6
+ import { terminalGuard } from '../guard/terminal-guard.js';
7
+
8
+ export class LiveRegion {
9
+ /**
10
+ * @param {OutputCoordinator} coordinator
11
+ * @param {NodeJS.WritableStream} stream
12
+ */
13
+ constructor(coordinator, stream) {
14
+ /** @type {OutputCoordinator} */
15
+ this.coordinator = coordinator;
16
+ /** @type {NodeJS.WritableStream} */
17
+ this.stream = stream;
18
+ /** @type {string[]} */
19
+ this._lines = [];
20
+ /** @type {boolean} */
21
+ this._active = true;
22
+ }
23
+
24
+ /**
25
+ * Update the live region with new line contents or via a render callback.
26
+ * @param {string[] | string | (() => string[] | string)} lines
27
+ */
28
+ render(lines) {
29
+ if (!this._active) return;
30
+ let resolved;
31
+ try {
32
+ resolved = typeof lines === 'function' ? lines() : lines;
33
+ } catch (err) {
34
+ terminalGuard.restore();
35
+ throw err;
36
+ }
37
+ const formattedLines = Array.isArray(resolved) ? resolved : resolved.split('\n');
38
+ this.coordinator.updateRegion(this, formattedLines);
39
+ this._lines = formattedLines;
40
+ }
41
+
42
+ /**
43
+ * Get current rendered lines.
44
+ * @returns {string[]}
45
+ */
46
+ getLines() {
47
+ return this._lines;
48
+ }
49
+
50
+ /**
51
+ * Erase the live region from the terminal without completing it.
52
+ */
53
+ clear() {
54
+ if (!this._active) return;
55
+ this.coordinator.clearRegion(this);
56
+ this._lines = [];
57
+ }
58
+
59
+ /**
60
+ * Permanently unmount the live region.
61
+ * @param {string[] | string} [finalLines]
62
+ */
63
+ unmount(finalLines) {
64
+ if (!this._active) return;
65
+ if (finalLines !== undefined) {
66
+ this.render(finalLines);
67
+ // Advance cursor below final lines
68
+ try {
69
+ this.stream.write('\n');
70
+ } catch {
71
+ // Ignore write errors
72
+ }
73
+ } else {
74
+ this.clear();
75
+ }
76
+ this._active = false;
77
+ this.coordinator.removeRegion(this);
78
+ }
79
+ }
80
+
81
+ export class OutputCoordinator {
82
+ /**
83
+ * @param {NodeJS.WritableStream} [stream] - Defaults to process.stderr
84
+ */
85
+ constructor(stream = process.stderr) {
86
+ /** @type {NodeJS.WritableStream} */
87
+ this.stream = stream;
88
+ /** @type {LiveRegion | null} */
89
+ this._activeRegion = null;
90
+ /** @type {string[]} */
91
+ this._renderedLines = [];
92
+
93
+ // Register emergency terminal restore
94
+ this._unregisterGuard = terminalGuard.register(() => {
95
+ this.emergencyClear();
96
+ });
97
+
98
+ // Handle stream EPIPE errors gracefully
99
+ if (typeof this.stream.on === 'function') {
100
+ /** @param {any} err */
101
+ this._onStreamError = (err) => {
102
+ if (err && (err.code === 'EPIPE' || err.code === 'ERR_STREAM_DESTROYED')) {
103
+ // Swallow broken pipe error to prevent unhandled crash
104
+ }
105
+ };
106
+ this.stream.on('error', this._onStreamError);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Mount a new live region on this stream.
112
+ * @returns {LiveRegion}
113
+ */
114
+ createLiveRegion() {
115
+ if (this._activeRegion) {
116
+ this._activeRegion.unmount();
117
+ }
118
+ const region = new LiveRegion(this, this.stream);
119
+ this._activeRegion = region;
120
+ this._renderedLines = [];
121
+ return region;
122
+ }
123
+
124
+ /**
125
+ * Update active region lines using diffed redrawing.
126
+ * @param {LiveRegion} region
127
+ * @param {string[]} nextLines
128
+ */
129
+ updateRegion(region, nextLines) {
130
+ if (this._activeRegion !== region) return;
131
+
132
+ const prevCount = this._renderedLines.length;
133
+ const nextCount = nextLines.length;
134
+ let out = '';
135
+
136
+ // If we previously had lines, move cursor back up to first line
137
+ if (prevCount > 0) {
138
+ // Move up prevCount - 1 lines, then carriage return
139
+ if (prevCount > 1) {
140
+ out += `\x1b[${prevCount - 1}A`;
141
+ }
142
+ out += '\r';
143
+ }
144
+
145
+ // Print each next line, clearing the existing row
146
+ for (let i = 0; i < nextCount; i++) {
147
+ out += `\x1b[2K${nextLines[i]}`;
148
+ if (i < nextCount - 1) {
149
+ out += '\n';
150
+ }
151
+ }
152
+
153
+ // If previous rendering had more lines than current, clear trailing lines
154
+ if (prevCount > nextCount) {
155
+ for (let i = nextCount; i < prevCount; i++) {
156
+ out += '\n\x1b[2K';
157
+ }
158
+ // Return cursor to end of new lines
159
+ out += `\x1b[${prevCount - nextCount}A`;
160
+ }
161
+
162
+ this._renderedLines = nextLines;
163
+ try {
164
+ this.stream.write(out);
165
+ } catch {
166
+ // Stream error handled gracefully
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Clear active region lines completely.
172
+ * @param {LiveRegion} region
173
+ */
174
+ clearRegion(region) {
175
+ if (this._activeRegion !== region) return;
176
+ const count = this._renderedLines.length;
177
+ if (count === 0) return;
178
+
179
+ let out = '';
180
+ if (count > 1) {
181
+ out += `\x1b[${count - 1}A`;
182
+ }
183
+ out += '\r';
184
+ for (let i = 0; i < count; i++) {
185
+ out += '\x1b[2K';
186
+ if (i < count - 1) {
187
+ out += '\n';
188
+ }
189
+ }
190
+ if (count > 1) {
191
+ out += `\x1b[${count - 1}A`;
192
+ }
193
+ out += '\r';
194
+
195
+ this._renderedLines = [];
196
+ try {
197
+ this.stream.write(out);
198
+ } catch {
199
+ // Ignore stream errors
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Safe concurrent logging: prints log content ABOVE any active live region.
205
+ * @param {string} message
206
+ */
207
+ log(message) {
208
+ if (!this._activeRegion || this._renderedLines.length === 0) {
209
+ try {
210
+ this.stream.write(`${message}\n`);
211
+ } catch {
212
+ // Ignore
213
+ }
214
+ return;
215
+ }
216
+
217
+ // 1. Clear active live region lines
218
+ const savedLines = [...this._renderedLines];
219
+ this.clearRegion(this._activeRegion);
220
+
221
+ // 2. Write log message cleanly followed by newline
222
+ try {
223
+ this.stream.write(`${message}\n`);
224
+ } catch {
225
+ // Ignore
226
+ }
227
+
228
+ // 3. Redraw active live region underneath
229
+ this.updateRegion(this._activeRegion, savedLines);
230
+ }
231
+
232
+ /**
233
+ * Remove active region.
234
+ * @param {LiveRegion} region
235
+ */
236
+ removeRegion(region) {
237
+ if (this._activeRegion === region) {
238
+ this._activeRegion = null;
239
+ this._renderedLines = [];
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Emergency clear on abnormal process exit.
245
+ */
246
+ emergencyClear() {
247
+ if (this._activeRegion) {
248
+ this.clearRegion(this._activeRegion);
249
+ this._activeRegion = null;
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Dispose coordinator.
255
+ */
256
+ dispose() {
257
+ this.emergencyClear();
258
+ this._unregisterGuard();
259
+ }
260
+ }
261
+
262
+ /** Default shared coordinator for process.stderr */
263
+ export const defaultCoordinator = new OutputCoordinator(process.stderr);
package/src/index.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @fileoverview TermKit primary entry point.
3
+ */
4
+
5
+ export * from './core/errors/index.js';
6
+ export * from './core/caps/detect.js';
7
+ export * from './core/ansi/escapes.js';
8
+ export * from './core/width/string-width.js';
9
+ export * from './core/styles/index.js';
10
+ export * from './engine/guard/terminal-guard.js';
11
+ export * from './engine/renderer/coordinator.js';
12
+ export * from './engine/keyboard/parser.js';
13
+ export * from './components/prompts/index.js';
14
+ export * from './components/progress/index.js';
15
+ export * from './components/display/layout.js';
16
+ export * from './components/display/table.js';
17
+ export * from './testing/index.js';