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,237 @@
1
+ /**
2
+ * @fileoverview Base execution wrapper and lifecycle manager for interactive prompts.
3
+ */
4
+
5
+ import { detectCapabilities } from '../../core/caps/detect.js';
6
+ import { CancelError, NonInteractiveError, ValidationError } from '../../core/errors/index.js';
7
+ import { createStyleEngine, style } from '../../core/styles/index.js';
8
+ import { KeyboardParser } from '../../engine/keyboard/parser.js';
9
+ import { OutputCoordinator } from '../../engine/renderer/coordinator.js';
10
+ import { terminalGuard } from '../../engine/guard/terminal-guard.js';
11
+
12
+ /**
13
+ * @template T
14
+ * @typedef {Object} PromptContext
15
+ * @property {string} message - Prompt label
16
+ * @property {T} [default] - Fallback value
17
+ * @property {(val: T) => boolean | string | Promise<boolean | string>} [validate]
18
+ * @property {NodeJS.ReadableStream} [input]
19
+ * @property {NodeJS.WritableStream} [output]
20
+ * @property {AbortSignal} [signal]
21
+ * @property {boolean} [accessible]
22
+ * @property {'throw' | 'return-null'} [onCancel]
23
+ * @property {Partial<import('../../core/caps/detect.js').TerminalCapabilities>} [capabilities]
24
+ */
25
+
26
+ /**
27
+ * Run an interactive prompt with guaranteed terminal restoration and non-interactive fallbacks.
28
+ *
29
+ * @template T
30
+ * @param {Object} options
31
+ * @param {string} options.name - Prompt identifier (e.g. 'confirm', 'input')
32
+ * @param {PromptContext<T>} options.context - User supplied options
33
+ * @param {(state: any, caps: any) => string[]} options.renderView - View generator returning virtual lines
34
+ * @param {(key: import('../../engine/keyboard/parser.js').KeyEvent, state: any) => 'submit' | 'cancel' | 'update' | void} options.onKey - Key handler
35
+ * @param {any} options.initialState - Initial component state
36
+ * @param {(state: any) => T} options.getValue - Function extracting current value from state
37
+ * @param {(value: T, state: any) => string} [options.formatSubmitted] - Function formatting final submitted line
38
+ * @returns {Promise<T | null>}
39
+ */
40
+ export async function runPrompt({
41
+ name,
42
+ context,
43
+ renderView,
44
+ onKey,
45
+ initialState,
46
+ getValue,
47
+ formatSubmitted
48
+ }) {
49
+ const input = context.input || process.stdin;
50
+ const output = context.output || process.stderr;
51
+ const caps = context.capabilities || detectCapabilities({ stream: output });
52
+ const promptStyle = createStyleEngine({ colorLevel: caps.colorLevel });
53
+ const isAccessible = context.accessible || caps.reducedMotion || caps.isDumb;
54
+ const chevron = caps.unicode ? '›' : '>';
55
+
56
+ // 1. Non-Interactive Environment Handling (ADR-004)
57
+ const isInputTTY = Boolean(/** @type {any} */ (input).isTTY);
58
+ const isOutputTTY = Boolean(/** @type {any} */ (output).isTTY);
59
+
60
+ if (!isInputTTY || (caps.isCI && !isInputTTY)) {
61
+ if (context.default !== undefined) {
62
+ // Auto-accept default
63
+ try {
64
+ const textVal = String(context.default);
65
+ const prefix = isAccessible ? '[?]' : (caps.unicode ? promptStyle.cyan('?') : promptStyle.cyan('[?]'));
66
+ const autoHint = promptStyle.dim('(auto)');
67
+ output.write(`${prefix} ${context.message} ${chevron} ${textVal} ${autoHint}\n`);
68
+ } catch {
69
+ // Ignore write error
70
+ }
71
+ return context.default;
72
+ }
73
+ throw new NonInteractiveError(name);
74
+ }
75
+
76
+ // 2. Interactive Terminal Setup
77
+ const coordinator = new OutputCoordinator(output);
78
+ const region = coordinator.createLiveRegion();
79
+ const keyboard = new KeyboardParser(input);
80
+ const state = { ...initialState, error: null };
81
+
82
+ terminalGuard.hideCursor(output);
83
+ terminalGuard.enableRawMode(input);
84
+
85
+ // Return promise driven by keyboard events
86
+ return new Promise((resolve, reject) => {
87
+ let settled = false;
88
+ let validationId = 0;
89
+
90
+ // Handle AbortSignal if provided
91
+ /** @type {(() => void) | null} */
92
+ let abortListener = null;
93
+ if (context.signal) {
94
+ abortListener = () => {
95
+ handleCancellation('abort');
96
+ };
97
+ context.signal.addEventListener('abort', abortListener, { once: true });
98
+ }
99
+
100
+ // Handle input stream close (EOF / destroy) per ADR-003
101
+ /** @type {(() => void) | null} */
102
+ let onStreamEnd = null;
103
+ const inputStream = /** @type {any} */ (input);
104
+ if (typeof inputStream.on === 'function') {
105
+ onStreamEnd = () => {
106
+ handleCancellation('stream-closed');
107
+ };
108
+ inputStream.on('end', onStreamEnd);
109
+ inputStream.on('close', onStreamEnd);
110
+ }
111
+
112
+ /**
113
+ * Unconditional terminal cleanup invariant.
114
+ */
115
+ function cleanup() {
116
+ if (onStreamEnd && typeof inputStream.removeListener === 'function') {
117
+ inputStream.removeListener('end', onStreamEnd);
118
+ inputStream.removeListener('close', onStreamEnd);
119
+ }
120
+ if (abortListener && context.signal) {
121
+ context.signal.removeEventListener('abort', abortListener);
122
+ }
123
+ keyboard.detach();
124
+ coordinator.dispose();
125
+ terminalGuard.showCursor(output);
126
+ terminalGuard.disableRawMode();
127
+ }
128
+
129
+ /**
130
+ * Handle prompt cancellation.
131
+ * @param {'ctrl-c' | 'escape' | 'abort' | 'stream-closed'} reason
132
+ */
133
+ function handleCancellation(reason) {
134
+ if (settled) return;
135
+ settled = true;
136
+ region.clear();
137
+ cleanup();
138
+
139
+ if (context.onCancel === 'return-null') {
140
+ resolve(null);
141
+ } else {
142
+ reject(new CancelError(undefined, reason));
143
+ }
144
+ }
145
+
146
+ // Attach Keypress Handler
147
+ keyboard.on('keypress', async (key) => {
148
+ if (settled) return;
149
+
150
+ // Clear previous error on fresh keypress (unless pressing return)
151
+ if (key.name !== 'return') {
152
+ state.error = null;
153
+ validationId++;
154
+ }
155
+
156
+ // Ctrl+C cancellation
157
+ if (key.ctrl && key.name === 'c') {
158
+ handleCancellation('ctrl-c');
159
+ return;
160
+ }
161
+
162
+ // Escape cancellation
163
+ if (key.name === 'escape') {
164
+ handleCancellation('escape');
165
+ return;
166
+ }
167
+
168
+ const action = onKey(key, state);
169
+
170
+ if (action === 'cancel') {
171
+ handleCancellation('escape');
172
+ return;
173
+ }
174
+
175
+ if (action === 'submit') {
176
+ const val = getValue(state);
177
+
178
+ // Validation Hook
179
+ if (typeof context.validate === 'function') {
180
+ const currentValidationId = ++validationId;
181
+ try {
182
+ const valid = await context.validate(val);
183
+ if (settled || validationId !== currentValidationId) {
184
+ return;
185
+ }
186
+ if (typeof valid === 'string' || valid === false) {
187
+ state.error = typeof valid === 'string' ? valid : 'Invalid input.';
188
+ region.render(renderView(state, caps));
189
+ return;
190
+ }
191
+ } catch (e) {
192
+ if (settled || validationId !== currentValidationId) {
193
+ return;
194
+ }
195
+ state.error = e instanceof Error ? e.message : 'Validation error.';
196
+ region.render(renderView(state, caps));
197
+ return;
198
+ }
199
+ }
200
+
201
+ settled = true;
202
+ // Format final permanent submitted line
203
+ const formatted = formatSubmitted
204
+ ? formatSubmitted(val, state)
205
+ : String(val);
206
+ const prefix = isAccessible ? '[OK]' : (caps.unicode ? promptStyle.green('✔') : promptStyle.green('[OK]'));
207
+ const finalLine = `${prefix} ${context.message} ${chevron} ${promptStyle.cyan(formatted)}`;
208
+
209
+ region.unmount([finalLine]);
210
+ cleanup();
211
+ resolve(val);
212
+ return;
213
+ }
214
+
215
+ // Default: redraw updated state
216
+ try {
217
+ region.render(renderView(state, caps));
218
+ } catch (err) {
219
+ settled = true;
220
+ cleanup();
221
+ reject(err);
222
+ return;
223
+ }
224
+ });
225
+
226
+ // Render initial view and attach keyboard
227
+ try {
228
+ region.render(renderView(state, caps));
229
+ } catch (err) {
230
+ settled = true;
231
+ cleanup();
232
+ reject(err);
233
+ return;
234
+ }
235
+ keyboard.attach();
236
+ });
237
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @fileoverview Confirm (Yes/No) prompt component.
3
+ */
4
+
5
+ import { style } from '../../core/styles/index.js';
6
+ import { runPrompt } from './base.js';
7
+
8
+ /**
9
+ * @typedef {Object} ConfirmOptions
10
+ * @property {string} message - Prompt label
11
+ * @property {boolean} [default=true] - Default value
12
+ * @property {string} [activeText='Yes'] - Label for true
13
+ * @property {string} [inactiveText='No'] - Label for false
14
+ * @property {NodeJS.ReadableStream} [input]
15
+ * @property {NodeJS.WritableStream} [output]
16
+ * @property {AbortSignal} [signal]
17
+ * @property {boolean} [accessible]
18
+ * @property {'throw' | 'return-null'} [onCancel]
19
+ * @property {Partial<import('../../core/caps/detect.js').TerminalCapabilities>} [capabilities]
20
+ */
21
+
22
+ /**
23
+ * Ask for a boolean confirmation (Y/n).
24
+ * @template {'throw' | 'return-null'} [TCancel='throw']
25
+ * @param {ConfirmOptions & { onCancel?: TCancel }} options
26
+ * @returns {Promise<TCancel extends 'return-null' ? boolean | null : boolean>}
27
+ */
28
+ export async function confirm(options) {
29
+ const initialValue = options.default !== undefined ? options.default : true;
30
+ const activeLabel = options.activeText || 'Yes';
31
+ const inactiveLabel = options.inactiveText || 'No';
32
+
33
+ const res = await runPrompt({
34
+ name: 'confirm',
35
+ context: { ...options, default: initialValue },
36
+ initialState: { value: initialValue },
37
+ getValue: (state) => state.value,
38
+ formatSubmitted: (val) => (val ? activeLabel : inactiveLabel),
39
+ renderView: (state, caps) => {
40
+ const isAccessible = caps.reducedMotion || caps.isDumb;
41
+ const chevron = caps.unicode ? '›' : '>';
42
+ const prefix = isAccessible ? '[?]' : style.cyan('?');
43
+ const yesStyled = state.value ? style.bold.cyan(activeLabel) : style.dim(activeLabel);
44
+ const noStyled = !state.value ? style.bold.cyan(inactiveLabel) : style.dim(inactiveLabel);
45
+ const hint = style.dim(`(${activeLabel[0].toUpperCase()}/${inactiveLabel[0].toLowerCase()})`);
46
+
47
+ return [`${prefix} ${options.message} ${hint} ${chevron} ${yesStyled} / ${noStyled}`];
48
+ },
49
+ onKey: (key, state) => {
50
+ if (key.name === 'return') {
51
+ return 'submit';
52
+ }
53
+ if (key.name === 'y') {
54
+ state.value = true;
55
+ return 'submit';
56
+ }
57
+ if (key.name === 'n') {
58
+ state.value = false;
59
+ return 'submit';
60
+ }
61
+ if (key.name === 'left' || key.name === 'right' || key.name === 'up' || key.name === 'down' || key.name === 'tab') {
62
+ state.value = !state.value;
63
+ return 'update';
64
+ }
65
+ }
66
+ });
67
+ return /** @type {any} */ (res);
68
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @fileoverview Export all interactive prompts.
3
+ */
4
+
5
+ export * from './confirm.js';
6
+ export * from './input.js';
7
+ export * from './password.js';
8
+ export * from './number.js';
9
+ export * from './select.js';
10
+ export * from './multiselect.js';
@@ -0,0 +1,107 @@
1
+ /**
2
+ * @fileoverview Text input prompt component.
3
+ */
4
+
5
+ import { style } from '../../core/styles/index.js';
6
+ import { runPrompt } from './base.js';
7
+
8
+ /**
9
+ * @typedef {Object} InputOptions
10
+ * @property {string} message - Prompt label
11
+ * @property {string} [default] - Fallback value
12
+ * @property {string} [placeholder] - Placeholder text
13
+ * @property {string} [initial] - Initial input buffer
14
+ * @property {(value: string) => boolean | string | Promise<boolean | string>} [validate]
15
+ * @property {NodeJS.ReadableStream} [input]
16
+ * @property {NodeJS.WritableStream} [output]
17
+ * @property {AbortSignal} [signal]
18
+ * @property {boolean} [accessible]
19
+ * @property {'throw' | 'return-null'} [onCancel]
20
+ */
21
+
22
+ /**
23
+ * Prompt user for a text string.
24
+ * @template {'throw' | 'return-null'} [TCancel='throw']
25
+ * @param {InputOptions & { onCancel?: TCancel }} options
26
+ * @returns {Promise<TCancel extends 'return-null' ? string | null : string>}
27
+ */
28
+ export async function input(options) {
29
+ const initialBuffer = options.initial || '';
30
+
31
+ const res = await runPrompt({
32
+ name: 'input',
33
+ context: options,
34
+ initialState: {
35
+ buffer: initialBuffer,
36
+ cursor: initialBuffer.length
37
+ },
38
+ getValue: (state) => (state.buffer.length > 0 ? state.buffer : options.default || ''),
39
+ formatSubmitted: (val) => val,
40
+ renderView: (state, caps) => {
41
+ const isAccessible = caps.reducedMotion || caps.isDumb;
42
+ const chevron = caps.unicode ? '›' : '>';
43
+ const prefix = isAccessible ? '[?]' : style.cyan('?');
44
+ let displayInput = state.buffer;
45
+
46
+ if (displayInput.length === 0 && options.default) {
47
+ displayInput = style.dim(`(${options.default})`);
48
+ } else if (displayInput.length === 0 && options.placeholder) {
49
+ displayInput = style.dim(options.placeholder);
50
+ }
51
+
52
+ const lines = [`${prefix} ${options.message} ${chevron} ${displayInput}`];
53
+ if (state.error) {
54
+ const errPrefix = isAccessible ? '[ERROR]' : style.red('✖');
55
+ lines.push(` ${errPrefix} ${style.red(state.error)}`);
56
+ }
57
+ return lines;
58
+ },
59
+ onKey: (key, state) => {
60
+ if (key.name === 'return') {
61
+ return 'submit';
62
+ }
63
+ if (key.isPaste && key.pasteText) {
64
+ state.buffer = state.buffer.slice(0, state.cursor) + key.pasteText + state.buffer.slice(state.cursor);
65
+ state.cursor += key.pasteText.length;
66
+ return 'update';
67
+ }
68
+ if (key.name === 'backspace') {
69
+ if (state.cursor > 0) {
70
+ state.buffer = state.buffer.slice(0, state.cursor - 1) + state.buffer.slice(state.cursor);
71
+ state.cursor--;
72
+ }
73
+ return 'update';
74
+ }
75
+ if (key.name === 'delete') {
76
+ if (state.cursor < state.buffer.length) {
77
+ state.buffer = state.buffer.slice(0, state.cursor) + state.buffer.slice(state.cursor + 1);
78
+ }
79
+ return 'update';
80
+ }
81
+ if (key.name === 'left') {
82
+ if (state.cursor > 0) state.cursor--;
83
+ return 'update';
84
+ }
85
+ if (key.name === 'right') {
86
+ if (state.cursor < state.buffer.length) state.cursor++;
87
+ return 'update';
88
+ }
89
+ if (key.name === 'home') {
90
+ state.cursor = 0;
91
+ return 'update';
92
+ }
93
+ if (key.name === 'end') {
94
+ state.cursor = state.buffer.length;
95
+ return 'update';
96
+ }
97
+
98
+ // Printable character
99
+ if (!key.ctrl && !key.meta && key.name.length === 1) {
100
+ state.buffer = state.buffer.slice(0, state.cursor) + key.name + state.buffer.slice(state.cursor);
101
+ state.cursor++;
102
+ return 'update';
103
+ }
104
+ }
105
+ });
106
+ return /** @type {any} */ (res);
107
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * @fileoverview MultiSelect checkbox choice prompt component.
3
+ */
4
+
5
+ import { style } from '../../core/styles/index.js';
6
+ import { runPrompt } from './base.js';
7
+
8
+ /**
9
+ * @template [T=any]
10
+ * @typedef {Object} MultiSelectItem
11
+ * @property {string} label - Display label
12
+ * @property {T} value - Selected value
13
+ * @property {string} [hint] - Optional muted hint
14
+ * @property {boolean | string} [disabled] - Whether item is disabled
15
+ * @property {boolean} [selected] - Initially selected
16
+ */
17
+
18
+ /**
19
+ * @template [T=any]
20
+ * @typedef {Object} MultiSelectOptions
21
+ * @property {string} message - Prompt label
22
+ * @property {readonly MultiSelectItem<T>[] | readonly { readonly label: string; readonly value: T; readonly hint?: string; readonly disabled?: boolean | string; readonly selected?: boolean }[]} items - List of choices
23
+ * @property {T[]} [default] - Default selected values
24
+ * @property {number} [pageSize=7] - Number of items displayed at once
25
+ * @property {boolean} [required=false] - At least one item required
26
+ * @property {number} [min] - Minimum selection count
27
+ * @property {number} [max] - Maximum selection count
28
+ * @property {NodeJS.ReadableStream} [input]
29
+ * @property {NodeJS.WritableStream} [output]
30
+ * @property {AbortSignal} [signal]
31
+ * @property {boolean} [accessible]
32
+ * @property {'throw' | 'return-null'} [onCancel]
33
+ * @property {Partial<import('../../core/caps/detect.js').TerminalCapabilities>} [capabilities]
34
+ */
35
+
36
+ /**
37
+ * Multiple item checkbox select prompt.
38
+ * @template T
39
+ * @template {'throw' | 'return-null'} [TCancel='throw']
40
+ * @param {MultiSelectOptions<T> & { onCancel?: TCancel }} options
41
+ * @returns {Promise<TCancel extends 'return-null' ? T[] | null : T[]>}
42
+ */
43
+ export async function multiselect(options) {
44
+ const items = options.items || [];
45
+ const pageSize = options.pageSize || 7;
46
+
47
+ /** @type {Set<number>} */
48
+ const selectedIndices = new Set();
49
+
50
+ // Populate initial selections
51
+ if (options.default) {
52
+ items.forEach((it, idx) => {
53
+ if (options.default?.includes(it.value) && !it.disabled) {
54
+ selectedIndices.add(idx);
55
+ }
56
+ });
57
+ } else {
58
+ items.forEach((it, idx) => {
59
+ if (it.selected && !it.disabled) {
60
+ selectedIndices.add(idx);
61
+ }
62
+ });
63
+ }
64
+
65
+ const res = await runPrompt({
66
+ name: 'multiselect',
67
+ context: options,
68
+ initialState: {
69
+ cursor: 0,
70
+ selected: selectedIndices
71
+ },
72
+ getValue: (state) => Array.from(state.selected).map((idx) => items[idx].value),
73
+ formatSubmitted: (val, state) =>
74
+ Array.from(state.selected)
75
+ .map((idx) => items[idx].label)
76
+ .join(', ') || 'none',
77
+ renderView: (state, caps) => {
78
+ const isAccessible = caps.reducedMotion || caps.isDumb;
79
+ const prefix = isAccessible ? '[?]' : style.cyan('?');
80
+ const navHint = style.dim('(Space to select, a to toggle all, Enter to submit)');
81
+ const lines = [`${prefix} ${options.message} ${navHint}`];
82
+
83
+ // Window pagination
84
+ const total = items.length;
85
+ let start = Math.max(0, state.cursor - Math.floor(pageSize / 2));
86
+ let end = Math.min(total, start + pageSize);
87
+ if (end - start < pageSize) {
88
+ start = Math.max(0, end - pageSize);
89
+ }
90
+
91
+ for (let i = start; i < end; i++) {
92
+ const item = items[i];
93
+ const isCurrent = i === state.cursor;
94
+ const isChecked = state.selected.has(i);
95
+ const isDisabled = Boolean(item.disabled);
96
+
97
+ let pointer = ' ';
98
+ if (isCurrent) {
99
+ pointer = style.cyan(caps.unicode ? '❯' : '>');
100
+ }
101
+
102
+ let box = isChecked
103
+ ? style.green(caps.unicode ? '☑' : '[X]')
104
+ : (caps.unicode ? '☐' : '[ ]');
105
+ if (isAccessible) {
106
+ box = isChecked ? '[X]' : '[ ]';
107
+ }
108
+
109
+ let itemText = item.label;
110
+ if (isDisabled) {
111
+ const reason = typeof item.disabled === 'string' ? ` (${item.disabled})` : ' (disabled)';
112
+ itemText = style.dim(`${item.label}${reason}`);
113
+ } else if (isCurrent) {
114
+ itemText = style.bold.cyan(item.label);
115
+ }
116
+
117
+ const hintText = item.hint ? ` ${style.dim(`- ${item.hint}`)}` : '';
118
+ lines.push(` ${pointer} ${box} ${itemText}${hintText}`);
119
+ }
120
+
121
+ if (state.error) {
122
+ const errPrefix = isAccessible ? '[ERROR]' : style.red('✖');
123
+ lines.push(` ${errPrefix} ${style.red(state.error)}`);
124
+ }
125
+
126
+ return lines;
127
+ },
128
+ onKey: (key, state) => {
129
+ if (key.name === 'return') {
130
+ const count = state.selected.size;
131
+ if (options.required && count === 0) {
132
+ state.error = 'At least one item must be selected.';
133
+ return 'update';
134
+ }
135
+ if (options.min !== undefined && count < options.min) {
136
+ state.error = `At least ${options.min} items must be selected.`;
137
+ return 'update';
138
+ }
139
+ if (options.max !== undefined && count > options.max) {
140
+ state.error = `At most ${options.max} items can be selected.`;
141
+ return 'update';
142
+ }
143
+ return 'submit';
144
+ }
145
+
146
+ if (key.name === 'space') {
147
+ const curItem = items[state.cursor];
148
+ if (curItem && !curItem.disabled) {
149
+ if (state.selected.has(state.cursor)) {
150
+ state.selected.delete(state.cursor);
151
+ } else {
152
+ if (options.max !== undefined && state.selected.size >= options.max) {
153
+ state.error = `Maximum ${options.max} selections allowed.`;
154
+ return 'update';
155
+ }
156
+ state.selected.add(state.cursor);
157
+ }
158
+ }
159
+ return 'update';
160
+ }
161
+
162
+ if (key.name === 'a') {
163
+ // Toggle all non-disabled
164
+ const allSelected = items.every((it, idx) => it.disabled || state.selected.has(idx));
165
+ if (allSelected) {
166
+ state.selected.clear();
167
+ } else {
168
+ items.forEach((it, idx) => {
169
+ if (!it.disabled) state.selected.add(idx);
170
+ });
171
+ }
172
+ return 'update';
173
+ }
174
+
175
+ if (key.name === 'i') {
176
+ // Invert selection
177
+ items.forEach((it, idx) => {
178
+ if (!it.disabled) {
179
+ if (state.selected.has(idx)) {
180
+ state.selected.delete(idx);
181
+ } else {
182
+ state.selected.add(idx);
183
+ }
184
+ }
185
+ });
186
+ return 'update';
187
+ }
188
+
189
+ if (key.name === 'down' || key.name === 'j') {
190
+ let next = state.cursor + 1;
191
+ while (next < items.length && items[next].disabled) next++;
192
+ if (next < items.length) state.cursor = next;
193
+ return 'update';
194
+ }
195
+
196
+ if (key.name === 'up' || key.name === 'k') {
197
+ let prev = state.cursor - 1;
198
+ while (prev >= 0 && items[prev].disabled) prev--;
199
+ if (prev >= 0) state.cursor = prev;
200
+ return 'update';
201
+ }
202
+ }
203
+ });
204
+ return /** @type {any} */ (res);
205
+ }