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,179 @@
1
+ /**
2
+ * @fileoverview Tabular data presentation component.
3
+ */
4
+
5
+ import { detectCapabilities } from '../../core/caps/detect.js';
6
+ import { style } from '../../core/styles/index.js';
7
+ import { stringWidth, truncate } from '../../core/width/string-width.js';
8
+
9
+ const TABLE_BORDERS = {
10
+ single: {
11
+ top: '┌─┬┐',
12
+ mid: '├─┼┤',
13
+ bottom: '└─┴┘',
14
+ v: '│',
15
+ h: '─'
16
+ },
17
+ rounded: {
18
+ top: '╭─┬╮',
19
+ mid: '├─┼┤',
20
+ bottom: '╰─┴╯',
21
+ v: '│',
22
+ h: '─'
23
+ },
24
+ ascii: {
25
+ top: '+-++',
26
+ mid: '+-++',
27
+ bottom: '+-++',
28
+ v: '|',
29
+ h: '-'
30
+ }
31
+ };
32
+
33
+ /**
34
+ * @typedef {Object} TableColumn
35
+ * @property {string} key - Object key or column id
36
+ * @property {string} header - Display header title
37
+ * @property {'left' | 'center' | 'right'} [align='left']
38
+ * @property {number} [width] - Fixed width
39
+ */
40
+
41
+ /**
42
+ * @typedef {Object} TableOptions
43
+ * @property {Array<TableColumn | string>} [columns] - Explicit column definitions
44
+ * @property {'single' | 'rounded' | 'ascii'} [borderStyle='rounded']
45
+ * @property {boolean} [compact=false]
46
+ * @property {number} [width] - Constrain total table width to this many columns
47
+ * @property {Partial<import('../../core/caps/detect.js').TerminalCapabilities>} [capabilities] - Override detected capabilities (testing only)
48
+ */
49
+
50
+ /**
51
+ * Format tabular rows into an aligned visual table.
52
+ * @param {Array<Record<string, any> | any[]>} rows
53
+ * @param {TableOptions} [options={}]
54
+ * @returns {string}
55
+ */
56
+ export function table(rows, options = {}) {
57
+ if (!rows || rows.length === 0) return '';
58
+
59
+ const caps = options.capabilities || detectCapabilities();
60
+ const borderName = !caps.unicode ? 'ascii' : (options.borderStyle || 'rounded');
61
+ const b = TABLE_BORDERS[borderName] || TABLE_BORDERS.single;
62
+
63
+ // 1. Normalize Column Definitions
64
+ /** @type {TableColumn[]} */
65
+ let columns = [];
66
+
67
+ if (options.columns) {
68
+ columns = options.columns.map((col) => {
69
+ if (typeof col === 'string') {
70
+ return { key: col, header: col, align: 'left' };
71
+ }
72
+ return { align: 'left', ...col };
73
+ });
74
+ } else if (!Array.isArray(rows[0])) {
75
+ // Infer from object keys of first row
76
+ columns = Object.keys(rows[0]).map((key) => ({
77
+ key,
78
+ header: key.toUpperCase(),
79
+ align: 'left'
80
+ }));
81
+ } else {
82
+ // 2D Array without explicit columns: derive 1..N columns
83
+ const maxCols = Math.max(...rows.map((r) => (Array.isArray(r) ? r.length : 0)));
84
+ columns = Array.from({ length: maxCols }, (_, i) => ({
85
+ key: String(i),
86
+ header: `COL ${i + 1}`,
87
+ align: 'left'
88
+ }));
89
+ }
90
+
91
+ // 2. Measure Column Widths
92
+ const colWidths = columns.map((col) => col.width || stringWidth(col.header));
93
+
94
+ for (const row of rows) {
95
+ columns.forEach((col, idx) => {
96
+ let cellVal = '';
97
+ if (Array.isArray(row)) {
98
+ cellVal = row[idx] !== undefined ? String(row[idx]) : '';
99
+ } else {
100
+ cellVal = row[col.key] !== undefined ? String(row[col.key]) : '';
101
+ }
102
+ colWidths[idx] = Math.max(colWidths[idx], stringWidth(cellVal));
103
+ });
104
+ }
105
+
106
+ // If options.width is provided, ensure total width does not exceed options.width
107
+ if (options.width && options.width > 0) {
108
+ const fixedBorderOverhead = columns.length * 3 + 1;
109
+ const availForContent = Math.max(columns.length, options.width - fixedBorderOverhead);
110
+ const totalContentWidth = colWidths.reduce((a, b) => a + b, 0);
111
+ if (totalContentWidth > availForContent) {
112
+ let remaining = availForContent;
113
+ for (let i = 0; i < colWidths.length; i++) {
114
+ if (i === colWidths.length - 1) {
115
+ colWidths[i] = Math.max(1, remaining);
116
+ } else {
117
+ const share = Math.max(1, Math.floor((colWidths[i] / totalContentWidth) * availForContent));
118
+ colWidths[i] = share;
119
+ remaining -= share;
120
+ }
121
+ }
122
+ }
123
+ }
124
+
125
+ // 3. Format Cell Helper
126
+ /**
127
+ * @param {string} text
128
+ * @param {number} width
129
+ * @param {'left' | 'center' | 'right'} [align='left']
130
+ */
131
+ function formatCell(text, width, align = 'left') {
132
+ const ellipsis = caps.unicode ? '…' : '...';
133
+ const safeText = stringWidth(text) > width ? truncate(text, width, ellipsis) : text;
134
+ const textW = stringWidth(safeText);
135
+ const space = Math.max(0, width - textW);
136
+ if (align === 'right') {
137
+ return ' '.repeat(space) + safeText;
138
+ }
139
+ if (align === 'center') {
140
+ const left = Math.floor(space / 2);
141
+ return ' '.repeat(left) + safeText + ' '.repeat(space - left);
142
+ }
143
+ return safeText + ' '.repeat(space);
144
+ }
145
+
146
+ const lines = [];
147
+
148
+ // Top Border: ╭─────┬─────╮
149
+ const topSegments = colWidths.map((w) => b.h.repeat(w + 2));
150
+ lines.push(style.dim(b.top[0] + topSegments.join(b.top[2]) + b.top[3]));
151
+
152
+ // Header Row: │ COL 1 │ COL 2 │
153
+ const headerCells = columns.map((col, idx) => ` ${style.bold(formatCell(col.header, colWidths[idx], col.align))} `);
154
+ lines.push(`${style.dim(b.v)}${headerCells.join(style.dim(b.v))}${style.dim(b.v)}`);
155
+
156
+ // Header Separator: ├─────┼─────┤
157
+ const midSegments = colWidths.map((w) => b.h.repeat(w + 2));
158
+ lines.push(style.dim(b.mid[0] + midSegments.join(b.mid[2]) + b.mid[3]));
159
+
160
+ // Data Rows
161
+ for (const row of rows) {
162
+ const rowCells = columns.map((col, idx) => {
163
+ let cellVal = '';
164
+ if (Array.isArray(row)) {
165
+ cellVal = row[idx] !== undefined ? String(row[idx]) : '';
166
+ } else {
167
+ cellVal = row[col.key] !== undefined ? String(row[col.key]) : '';
168
+ }
169
+ return ` ${formatCell(cellVal, colWidths[idx], col.align)} `;
170
+ });
171
+ lines.push(`${style.dim(b.v)}${rowCells.join(style.dim(b.v))}${style.dim(b.v)}`);
172
+ }
173
+
174
+ // Bottom Border: ╰─────┴─────╯
175
+ const bottomSegments = colWidths.map((w) => b.h.repeat(w + 2));
176
+ lines.push(style.dim(b.bottom[0] + bottomSegments.join(b.bottom[2]) + b.bottom[3]));
177
+
178
+ return lines.join('\n');
179
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @fileoverview Export progress indicators.
3
+ */
4
+
5
+ export * from './spinner.js';
6
+ export * from './progressBar.js';
@@ -0,0 +1,153 @@
1
+ /**
2
+ * @fileoverview Terminal progress bar component.
3
+ * Displays percentage, visual bar, elapsed time, and ETA.
4
+ */
5
+
6
+ import { detectCapabilities } from '../../core/caps/detect.js';
7
+ import { style } from '../../core/styles/index.js';
8
+ import { OutputCoordinator, defaultCoordinator } from '../../engine/renderer/coordinator.js';
9
+ import { terminalGuard } from '../../engine/guard/terminal-guard.js';
10
+
11
+ /**
12
+ * @typedef {Object} ProgressBarOptions
13
+ * @property {number} total - Total ticks / units
14
+ * @property {string} [message=''] - Label text
15
+ * @property {number} [width=30] - Width of the bar in columns
16
+ * @property {NodeJS.WritableStream} [stream] - Defaults to process.stderr
17
+ * @property {boolean} [showEta=true] - Display ETA calculation
18
+ * @property {boolean} [showPercentage=true] - Display percentage
19
+ * @property {boolean} [accessible] - Force accessible milestone mode
20
+ */
21
+
22
+ export class ProgressBar {
23
+ /**
24
+ * @param {ProgressBarOptions} options
25
+ */
26
+ constructor(options) {
27
+ /** @type {number} */
28
+ this.total = Math.max(1, options.total);
29
+ /** @type {number} */
30
+ this.current = 0;
31
+ /** @type {string} */
32
+ this.message = options.message || '';
33
+ /** @type {number} */
34
+ this.barWidth = options.width || 30;
35
+ /** @type {NodeJS.WritableStream} */
36
+ this.stream = options.stream || process.stderr;
37
+ /** @type {boolean} */
38
+ this.showEta = options.showEta !== undefined ? options.showEta : true;
39
+ /** @type {boolean} */
40
+ this.showPercentage = options.showPercentage !== undefined ? options.showPercentage : true;
41
+
42
+ const caps = detectCapabilities({ stream: this.stream });
43
+ /** @type {boolean} */
44
+ this.isAccessible = Boolean(options.accessible || caps.reducedMotion || caps.isDumb || !caps.isTTY || caps.isCI);
45
+ /** @type {boolean} */
46
+ this.useUnicode = caps.unicode;
47
+
48
+ /** @type {number} */
49
+ this.startTime = Date.now();
50
+ /** @type {number} */
51
+ this._lastMilestone = 0;
52
+
53
+ /** @type {OutputCoordinator} */
54
+ this.coordinator = this.stream === process.stderr ? defaultCoordinator : new OutputCoordinator(this.stream);
55
+ /** @type {import('../../engine/renderer/coordinator.js').LiveRegion | null} */
56
+ this._region = null;
57
+ /** @type {boolean} */
58
+ this._active = false;
59
+ }
60
+
61
+ /**
62
+ * Start or update progress.
63
+ * @param {number} current
64
+ * @param {string} [message]
65
+ */
66
+ update(current, message) {
67
+ this.current = Math.min(this.total, Math.max(0, current));
68
+ if (message !== undefined) this.message = message;
69
+
70
+ const fraction = this.current / this.total;
71
+ const percentage = Math.floor(fraction * 100);
72
+
73
+ // Accessible / Non-TTY: Emit discrete milestone lines at 25%, 50%, 75%, 100%
74
+ if (this.isAccessible) {
75
+ const isComplete = this.current >= this.total;
76
+ if ((percentage >= this._lastMilestone + 25 || isComplete) && this._lastMilestone < 100) {
77
+ this._lastMilestone = isComplete ? 100 : percentage;
78
+ try {
79
+ this.stream.write(`[PROGRESS] ${this.message} ${percentage}% (${this.current}/${this.total})\n`);
80
+ } catch {
81
+ // Ignore
82
+ }
83
+ }
84
+ return;
85
+ }
86
+
87
+ if (!this._active) {
88
+ this._active = true;
89
+ terminalGuard.hideCursor(this.stream);
90
+ this._region = this.coordinator.createLiveRegion();
91
+ }
92
+
93
+ const filledCols = Math.round(fraction * this.barWidth);
94
+ const emptyCols = Math.max(0, this.barWidth - filledCols);
95
+
96
+ const filledChar = this.useUnicode ? '█' : '=';
97
+ const emptyChar = this.useUnicode ? '░' : '-';
98
+
99
+ const bar = style.cyan(filledChar.repeat(filledCols)) + style.dim(emptyChar.repeat(emptyCols));
100
+ const pctText = this.showPercentage ? ` ${percentage}%` : '';
101
+
102
+ let etaText = '';
103
+ if (this.showEta && fraction > 0) {
104
+ const elapsedSec = (Date.now() - this.startTime) / 1000;
105
+ const totalSec = elapsedSec / fraction;
106
+ const remainingSec = Math.max(0, Math.round(totalSec - elapsedSec));
107
+ etaText = ` ${style.dim(`(ETA: ${remainingSec}s)`)}`;
108
+ }
109
+
110
+ const line = `${this.message ? `${this.message} ` : ''}[${bar}]${pctText}${etaText}`;
111
+ this._region?.render([line]);
112
+ }
113
+
114
+ /**
115
+ * Increment progress by amount.
116
+ * @param {number} [amount=1]
117
+ * @param {string} [message]
118
+ */
119
+ increment(amount = 1, message) {
120
+ this.update(this.current + amount, message);
121
+ }
122
+
123
+ /**
124
+ * Complete the progress bar.
125
+ * @param {string} [message]
126
+ */
127
+ complete(message) {
128
+ this.update(this.total, message);
129
+ this.stop();
130
+ }
131
+
132
+ /**
133
+ * Stop and unmount the progress bar.
134
+ */
135
+ stop() {
136
+ if (!this._active) return;
137
+ this._active = false;
138
+ if (this._region) {
139
+ this._region.unmount();
140
+ this._region = null;
141
+ }
142
+ terminalGuard.showCursor(this.stream);
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Factory to create a progress bar.
148
+ * @param {ProgressBarOptions} options
149
+ * @returns {ProgressBar}
150
+ */
151
+ export function progressBar(options) {
152
+ return new ProgressBar(options);
153
+ }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * @fileoverview Terminal animated spinner component.
3
+ * Coordinated with OutputCoordinator to prevent line collisions during concurrent logging.
4
+ */
5
+
6
+ import { detectCapabilities } from '../../core/caps/detect.js';
7
+ import { style } from '../../core/styles/index.js';
8
+ import { OutputCoordinator, defaultCoordinator } from '../../engine/renderer/coordinator.js';
9
+ import { terminalGuard } from '../../engine/guard/terminal-guard.js';
10
+
11
+ const BRAILLE_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
12
+ const ASCII_FRAMES = ['-', '\\', '|', '/'];
13
+
14
+ /**
15
+ * @typedef {Object} SpinnerOptions
16
+ * @property {string} [message=''] - Initial loading text
17
+ * @property {NodeJS.WritableStream} [stream] - Defaults to process.stderr
18
+ * @property {string} [color='cyan'] - Color of the spinner glyph
19
+ * @property {boolean} [accessible] - Force accessible static mode
20
+ */
21
+
22
+ export class Spinner {
23
+ /**
24
+ * @param {SpinnerOptions | string} [options='']
25
+ */
26
+ constructor(options = '') {
27
+ const opts = typeof options === 'string' ? { message: options } : options;
28
+ /** @type {string} */
29
+ this.message = opts.message || '';
30
+ /** @type {NodeJS.WritableStream} */
31
+ this.stream = opts.stream || process.stderr;
32
+ /** @type {string} */
33
+ this.color = opts.color || 'cyan';
34
+ /** @type {boolean} */
35
+ this.isSpinning = false;
36
+
37
+ const caps = detectCapabilities({ stream: this.stream });
38
+ /** @type {boolean} */
39
+ this.isAccessible = Boolean(opts.accessible || caps.reducedMotion || caps.isDumb || !caps.isTTY || caps.isCI);
40
+ /** @type {string[]} */
41
+ this.frames = caps.unicode ? BRAILLE_FRAMES : ASCII_FRAMES;
42
+ /** @type {number} */
43
+ this._frameIndex = 0;
44
+ /** @type {NodeJS.Timeout | null} */
45
+ this._timer = null;
46
+
47
+ /** @type {OutputCoordinator} */
48
+ this.coordinator = this.stream === process.stderr ? defaultCoordinator : new OutputCoordinator(this.stream);
49
+ /** @type {import('../../engine/renderer/coordinator.js').LiveRegion | null} */
50
+ this._region = null;
51
+ /** @type {(() => void) | null} */
52
+ this._unregisterGuard = null;
53
+ }
54
+
55
+ /**
56
+ * Start the spinner.
57
+ * @param {string} [message]
58
+ * @returns {Spinner}
59
+ */
60
+ start(message) {
61
+ if (this.isSpinning) return this;
62
+ if (message !== undefined) this.message = message;
63
+ this.isSpinning = true;
64
+
65
+ if (this.isAccessible) {
66
+ // Non-animated milestone
67
+ try {
68
+ this.stream.write(`[BUSY] ${this.message}\n`);
69
+ } catch {
70
+ // Ignore stream error
71
+ }
72
+ return this;
73
+ }
74
+
75
+ terminalGuard.hideCursor(this.stream);
76
+ this._region = this.coordinator.createLiveRegion();
77
+
78
+ // Register emergency cleanup
79
+ this._unregisterGuard = terminalGuard.register(() => {
80
+ this.stop();
81
+ });
82
+
83
+ this._renderFrame();
84
+ this._timer = setInterval(() => {
85
+ this._frameIndex = (this._frameIndex + 1) % this.frames.length;
86
+ this._renderFrame();
87
+ }, 80);
88
+
89
+ return this;
90
+ }
91
+
92
+ /**
93
+ * @private
94
+ */
95
+ _renderFrame() {
96
+ if (!this._region || !this.isSpinning) return;
97
+ const glyph = style.cyan(this.frames[this._frameIndex]);
98
+ this._region.render([`${glyph} ${this.message}`]);
99
+ }
100
+
101
+ /**
102
+ * Update the spinner message while running.
103
+ * @param {string} message
104
+ * @returns {Spinner}
105
+ */
106
+ update(message) {
107
+ this.message = message;
108
+ if (!this.isAccessible && this.isSpinning) {
109
+ this._renderFrame();
110
+ }
111
+ return this;
112
+ }
113
+
114
+ /**
115
+ * Stop the spinner and clear active line.
116
+ */
117
+ stop() {
118
+ if (!this.isSpinning) return;
119
+ this.isSpinning = false;
120
+ if (this._timer) {
121
+ clearInterval(this._timer);
122
+ this._timer = null;
123
+ }
124
+ if (this._region) {
125
+ this._region.clear();
126
+ this._region.unmount();
127
+ this._region = null;
128
+ }
129
+ terminalGuard.showCursor(this.stream);
130
+ if (this._unregisterGuard) {
131
+ this._unregisterGuard();
132
+ this._unregisterGuard = null;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Complete with success state.
138
+ * @param {string} [message]
139
+ */
140
+ succeed(message) {
141
+ this._finish(message, '[OK]', style.green('✔'));
142
+ }
143
+
144
+ /**
145
+ * Complete with failure state.
146
+ * @param {string} [message]
147
+ */
148
+ fail(message) {
149
+ this._finish(message, '[FAIL]', style.red('✖'));
150
+ }
151
+
152
+ /**
153
+ * Complete with warning state.
154
+ * @param {string} [message]
155
+ */
156
+ warn(message) {
157
+ this._finish(message, '[WARN]', style.yellow('▲'));
158
+ }
159
+
160
+ /**
161
+ * Complete with info state.
162
+ * @param {string} [message]
163
+ */
164
+ info(message) {
165
+ this._finish(message, '[INFO]', style.blue('ℹ'));
166
+ }
167
+
168
+ /**
169
+ * @private
170
+ * @param {string | undefined} message
171
+ * @param {string} textPrefix
172
+ * @param {string} symbolPrefix
173
+ */
174
+ _finish(message, textPrefix, symbolPrefix) {
175
+ if (!this.isSpinning && !this.isAccessible) return;
176
+ const text = message !== undefined ? message : this.message;
177
+ this.stop();
178
+
179
+ const prefix = this.isAccessible ? textPrefix : symbolPrefix;
180
+ try {
181
+ this.stream.write(`${prefix} ${text}\n`);
182
+ } catch {
183
+ // Ignore
184
+ }
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Factory to create a spinner.
190
+ * @param {SpinnerOptions | string} [options]
191
+ * @returns {Spinner}
192
+ */
193
+ export function spinner(options) {
194
+ return new Spinner(options);
195
+ }