talented-args 0.2.4-beta → 0.3.0-beta

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 (70) hide show
  1. package/README.md +497 -10
  2. package/dist/clipboard.d.ts +10 -0
  3. package/dist/clipboard.js +79 -0
  4. package/dist/clipboard.js.map +1 -0
  5. package/dist/compile.d.ts +67 -0
  6. package/dist/compile.js +188 -0
  7. package/dist/compile.js.map +1 -0
  8. package/dist/descriptors.d.ts +322 -0
  9. package/dist/descriptors.js +362 -0
  10. package/dist/descriptors.js.map +1 -0
  11. package/dist/display.d.ts +31 -0
  12. package/dist/display.js +235 -0
  13. package/dist/display.js.map +1 -0
  14. package/dist/errors.d.ts +34 -17
  15. package/dist/errors.js +61 -75
  16. package/dist/errors.js.map +1 -1
  17. package/dist/index.d.ts +10 -6
  18. package/dist/index.js +8 -9
  19. package/dist/index.js.map +1 -1
  20. package/dist/options.d.ts +69 -37
  21. package/dist/options.js +198 -31
  22. package/dist/options.js.map +1 -1
  23. package/dist/parse.d.ts +70 -0
  24. package/dist/parse.js +551 -0
  25. package/dist/parse.js.map +1 -0
  26. package/dist/program.d.ts +125 -0
  27. package/dist/program.js +337 -0
  28. package/dist/program.js.map +1 -0
  29. package/dist/remember.d.ts +71 -0
  30. package/dist/remember.js +216 -0
  31. package/dist/remember.js.map +1 -0
  32. package/dist/styling.d.ts +38 -9
  33. package/dist/styling.js +155 -75
  34. package/dist/styling.js.map +1 -1
  35. package/dist/terminal.d.ts +205 -0
  36. package/dist/terminal.js +152 -0
  37. package/dist/terminal.js.map +1 -0
  38. package/dist/tools.d.ts +35 -31
  39. package/dist/tools.js +68 -140
  40. package/dist/tools.js.map +1 -1
  41. package/dist/tui.d.ts +96 -0
  42. package/dist/tui.js +397 -0
  43. package/dist/tui.js.map +1 -0
  44. package/dist/tui_layout.d.ts +152 -0
  45. package/dist/tui_layout.js +554 -0
  46. package/dist/tui_layout.js.map +1 -0
  47. package/dist/tui_model.d.ts +149 -0
  48. package/dist/tui_model.js +666 -0
  49. package/dist/tui_model.js.map +1 -0
  50. package/package.json +18 -14
  51. package/.eslintrc.js +0 -24
  52. package/.idea/codeStyles/Project.xml +0 -364
  53. package/.idea/codeStyles/codeStyleConfig.xml +0 -5
  54. package/.idea/compiler.xml +0 -7
  55. package/.idea/encodings.xml +0 -6
  56. package/.idea/inspectionProfiles/Project_Default.xml +0 -12
  57. package/.idea/jsLibraryMappings.xml +0 -6
  58. package/.idea/modules.xml +0 -8
  59. package/.idea/prettier.xml +0 -8
  60. package/.idea/talented-args.iml +0 -11
  61. package/.idea/vcs.xml +0 -6
  62. package/.prettierrc.yaml +0 -4
  63. package/dist/definitions.d.ts +0 -70
  64. package/dist/definitions.js +0 -38
  65. package/dist/definitions.js.map +0 -1
  66. package/dist/main.d.ts +0 -33
  67. package/dist/main.js +0 -313
  68. package/dist/main.js.map +0 -1
  69. package/jest.config.js +0 -4
  70. package/tsconfig.json +0 -18
@@ -0,0 +1,666 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TuiModel = exports.TUI_BUTTONS = exports.TUI_REGIONS = void 0;
4
+ exports.splitList = splitList;
5
+ exports.shellQuote = shellQuote;
6
+ const compile_1 = require("./compile");
7
+ const descriptors_1 = require("./descriptors");
8
+ const display_1 = require("./display");
9
+ const errors_1 = require("./errors");
10
+ const parse_1 = require("./parse");
11
+ const remember_1 = require("./remember");
12
+ const tools_1 = require("./tools");
13
+ exports.TUI_REGIONS = ['commands', 'fields', 'buttons'];
14
+ exports.TUI_BUTTONS = ['run', 'copy', 'cancel'];
15
+ /** Action button explanations shown in the help area. */
16
+ const BUTTON_HELP = {
17
+ run: 'Run the command line shown below',
18
+ copy: 'Copy the command line, then leave without running it',
19
+ cancel: 'Leave without running anything',
20
+ };
21
+ const ROOT_LABEL = '(no command)';
22
+ const PAGE_SIZE = 5;
23
+ // *********************************************************************************************************************
24
+ /**
25
+ * Split a list field on whitespace, respecting single and double quotes and backslash escapes.
26
+ * Returns `null` for an unclosed quote. Does not perform shell expansion.
27
+ */
28
+ function splitList(text) {
29
+ const items = [];
30
+ let current = '';
31
+ let started = false;
32
+ let quote = null;
33
+ for (let index = 0; index < text.length; index++) {
34
+ const char = text.charAt(index);
35
+ if (quote) {
36
+ if (char === quote) {
37
+ quote = null;
38
+ }
39
+ else if (char === '\\' && quote === '"' && index + 1 < text.length) {
40
+ current += text.charAt(++index);
41
+ }
42
+ else {
43
+ current += char;
44
+ }
45
+ }
46
+ else if (char === '"' || char === "'") {
47
+ quote = char;
48
+ started = true;
49
+ }
50
+ else if (char === '\\' && index + 1 < text.length) {
51
+ current += text.charAt(++index);
52
+ started = true;
53
+ }
54
+ else if (/\s/.test(char)) {
55
+ if (started) {
56
+ items.push(current);
57
+ }
58
+ current = '';
59
+ started = false;
60
+ }
61
+ else {
62
+ current += char;
63
+ started = true;
64
+ }
65
+ }
66
+ if (quote) {
67
+ return null;
68
+ }
69
+ if (started) {
70
+ items.push(current);
71
+ }
72
+ return items;
73
+ }
74
+ /** Quote a value for a POSIX-style shell so it is read back unchanged. */
75
+ function shellQuote(value) {
76
+ if (/^[\w@%+=:,./-]+$/.test(value)) {
77
+ return value;
78
+ }
79
+ return `'${value.replace(/'/g, `'\\''`)}'`;
80
+ }
81
+ /**
82
+ * Quote a list field value for `splitList()`.
83
+ * Use double quotes when the value contains a single quote.
84
+ */
85
+ function listQuote(value) {
86
+ if (/^[\w@%+=:,./-]+$/.test(value)) {
87
+ return value;
88
+ }
89
+ return value.includes("'") ? `"${value.replace(/(["\\])/g, '\\$1')}"` : `'${value}'`;
90
+ }
91
+ /** First paragraph collapsed to one line. */
92
+ function firstParagraph(text) {
93
+ return (text.split(/\n\s*\n/)[0] ?? '').replace(/\s+/g, ' ').trim();
94
+ }
95
+ function isWrappedInQuotes(text) {
96
+ const first = text.charAt(0);
97
+ return text.length >= 2 && (first === '"' || first === "'") && text.endsWith(first);
98
+ }
99
+ /**
100
+ * Decode a scalar field by removing one pair of enclosing quotes.
101
+ * An empty field is omitted by the caller; `""` supplies an explicit empty string.
102
+ * Values containing enclosing quotes receive another pair when formatted for the field.
103
+ */
104
+ function scalarValue(text) {
105
+ return isWrappedInQuotes(text) ? text.slice(1, -1) : text;
106
+ }
107
+ /** Format a scalar value for editing, preserving empty strings and enclosing quotes. */
108
+ function scalarText(value) {
109
+ if (value === '') {
110
+ return '""';
111
+ }
112
+ return isWrappedInQuotes(value) ? `'${value}'` : value;
113
+ }
114
+ /** Build a field draft from raw parser values: a boolean, scalar text, or quoted list text. */
115
+ function draftOf(input, raws) {
116
+ const last = raws[raws.length - 1];
117
+ if (last === undefined || typeof last === 'boolean') {
118
+ return last;
119
+ }
120
+ const texts = raws.filter((raw) => typeof raw === 'string');
121
+ return input.multiple ? texts.map(listQuote).join(' ') : scalarText(last);
122
+ }
123
+ class TuiModel {
124
+ schema;
125
+ options;
126
+ entries;
127
+ /** Index of the selected command list entry. */
128
+ selected = 0;
129
+ region;
130
+ fieldIndex = 0;
131
+ button = 'run';
132
+ message = null;
133
+ drafts = new Map();
134
+ errors = new Map();
135
+ fieldsByEntry = new Map();
136
+ constructor(schema, seed, options) {
137
+ this.schema = schema;
138
+ this.options = options;
139
+ const entries = schema.commands.map(command => {
140
+ // Avoid repeating details when their first paragraph is already shown as the command summary.
141
+ const help = firstParagraph(command.details);
142
+ return {
143
+ command,
144
+ label: command.token,
145
+ summary: command.summary,
146
+ help: help === firstParagraph(command.summary) ? '' : help,
147
+ };
148
+ });
149
+ if (schema.rootRunnable) {
150
+ entries.unshift({
151
+ command: null,
152
+ label: ROOT_LABEL,
153
+ summary: schema.commands.length ? 'Run without a command' : '',
154
+ help: '',
155
+ });
156
+ }
157
+ this.entries = entries;
158
+ const recalled = options.remembered ? (0, remember_1.recall)(schema, options.remembered) : null;
159
+ const initial = !options.commandChosen && recalled && recalled.command !== undefined
160
+ ? recalled.command
161
+ : // Fall back to the command line selection, including null for running without a command.
162
+ seed.command;
163
+ this.selected = Math.max(0, entries.findIndex(entry => entry.command === initial));
164
+ if (recalled) {
165
+ let filled = this.fillDrafts('common', recalled.common);
166
+ for (const [command, given] of recalled.commands) {
167
+ filled = this.fillDrafts(command, given) || filled;
168
+ }
169
+ if (filled || this.entry.command === recalled.command) {
170
+ this.message = { kind: 'info', text: 'Filled in from the last run' };
171
+ }
172
+ }
173
+ for (const [input, raws] of seed.given) {
174
+ const draft = draftOf(input, raws);
175
+ if (draft !== undefined) {
176
+ this.draftsOf(this.entry, input).set(input, draft);
177
+ }
178
+ }
179
+ this.region =
180
+ options.commandChosen && this.fields.length
181
+ ? 'fields'
182
+ : this.availableRegions()[0] ?? 'buttons';
183
+ }
184
+ // *******************************************************************************************************************
185
+ get entry() {
186
+ const entry = this.entries[this.selected] ?? this.entries[0];
187
+ if (!entry) {
188
+ throw new TypeError('interactive mode has nothing to offer: the program has no commands and can not run without one');
189
+ }
190
+ return entry;
191
+ }
192
+ /** Fields for the selected entry, with command options before unshared common options. */
193
+ get fields() {
194
+ const { entry } = this;
195
+ return (0, tools_1.getOrCreate)(this.fieldsByEntry, entry, () => {
196
+ const active = (0, compile_1.activeScopeOf)(this.schema, entry.command);
197
+ const describe = (input, group) => {
198
+ const policy = (0, compile_1.inputPolicy)(this.schema, entry.command, input);
199
+ const defaultText = policy.hasDefault && !input.sensitive ? (0, display_1.formatDefault)(policy.defaultValue) : null;
200
+ const negatedName = [...active.negations].find(([, negated]) => negated === input)?.[0];
201
+ // Keep hints short and omit the string type, which is the default for text fields.
202
+ const hints = [];
203
+ if (input.kind === 'value') {
204
+ if (input.label !== null) {
205
+ hints.push(input.label);
206
+ }
207
+ else if (input.valueType === 'number') {
208
+ hints.push(input.multiple ? 'numbers' : 'number');
209
+ }
210
+ if (input.multiple) {
211
+ hints.push('separate with spaces');
212
+ }
213
+ }
214
+ if (defaultText !== null) {
215
+ hints.push(`default: ${defaultText}`);
216
+ }
217
+ return {
218
+ input,
219
+ name: (0, descriptors_1.inputDisplayName)(input),
220
+ kind: input.kind === 'flag' ? 'flag' : 'text',
221
+ group,
222
+ required: policy.required,
223
+ negation: negatedName !== undefined ? `--${negatedName}` : null,
224
+ hint: hints.join(' · '),
225
+ help: firstParagraph(input.description),
226
+ };
227
+ };
228
+ return [
229
+ ...active.commandInputs.map(input => describe(input, 'command')),
230
+ ...active.commonInputs.map(input => describe(input, 'common')),
231
+ ];
232
+ });
233
+ }
234
+ get focusedField() {
235
+ return this.region === 'fields' ? this.fields[this.fieldIndex] ?? null : null;
236
+ }
237
+ /** Available navigation regions in Tab order. */
238
+ availableRegions() {
239
+ return exports.TUI_REGIONS.filter(region => (region !== 'commands' || this.entries.length > 1) &&
240
+ (region !== 'fields' || this.fields.length > 0));
241
+ }
242
+ /** Populate drafts from raw values for one scope. Returns whether values were supplied. */
243
+ fillDrafts(scope, given) {
244
+ const drafts = (0, tools_1.getOrCreate)(this.drafts, scope, () => new Map());
245
+ for (const [input, raws] of given) {
246
+ const draft = draftOf(input, raws);
247
+ if (draft !== undefined) {
248
+ drafts.set(input, draft);
249
+ }
250
+ }
251
+ return given.size > 0;
252
+ }
253
+ draftsOf(entry, input) {
254
+ // Share root input drafts across commands; keep command-only drafts with their command.
255
+ const scope = entry.command && !this.schema.root.inputs.includes(input) ? entry.command : 'common';
256
+ return (0, tools_1.getOrCreate)(this.drafts, scope, () => new Map());
257
+ }
258
+ draft(field) {
259
+ return this.draftsOf(this.entry, field.input).get(field.input);
260
+ }
261
+ /** Current field text, or an empty string when no value was entered. */
262
+ text(field) {
263
+ const draft = this.draft(field);
264
+ return typeof draft === 'string' ? draft : '';
265
+ }
266
+ /** Current flag draft: `true`, `false`, or `null` when unset. */
267
+ flag(field) {
268
+ const draft = this.draft(field);
269
+ return typeof draft === 'boolean' ? draft : null;
270
+ }
271
+ error(field) {
272
+ return this.errors.get(field.input) ?? null;
273
+ }
274
+ /** Explanation for the focused command, field, or button. Empty when no extra explanation is needed. */
275
+ get help() {
276
+ switch (this.region) {
277
+ case 'commands':
278
+ return this.entry.help;
279
+ case 'fields':
280
+ return this.focusedField?.help ?? '';
281
+ case 'buttons':
282
+ return BUTTON_HELP[this.button];
283
+ }
284
+ }
285
+ /** Possible help texts for the selected entry, used to reserve a stable help area. */
286
+ get possibleHelp() {
287
+ return [
288
+ this.entry.help,
289
+ ...this.fields.map(field => field.help),
290
+ ...Object.values(BUTTON_HELP),
291
+ ];
292
+ }
293
+ // *******************************************************************************************************************
294
+ /** Update a field's draft and clear its validation error. An empty field removes the draft. */
295
+ setText(field, text) {
296
+ const drafts = this.draftsOf(this.entry, field.input);
297
+ if (text === '') {
298
+ drafts.delete(field.input);
299
+ }
300
+ else {
301
+ drafts.set(field.input, text);
302
+ }
303
+ this.errors.delete(field.input);
304
+ this.message = null;
305
+ }
306
+ toggle(field) {
307
+ const drafts = this.draftsOf(this.entry, field.input);
308
+ const current = this.flag(field);
309
+ if (current === null) {
310
+ drafts.set(field.input, true);
311
+ }
312
+ else if (current && field.negation !== null) {
313
+ // Cycle negatable flags through unset, true, and false.
314
+ drafts.set(field.input, false);
315
+ }
316
+ else {
317
+ drafts.delete(field.input);
318
+ }
319
+ this.errors.delete(field.input);
320
+ this.message = null;
321
+ }
322
+ /** Decode a text field to raw strings. Returns `null` for an unclosed list quote. */
323
+ rawValues(field) {
324
+ const text = this.text(field);
325
+ if (text === '') {
326
+ return [];
327
+ }
328
+ return field.input.multiple ? splitList(text) : [scalarValue(text)];
329
+ }
330
+ /**
331
+ * Validate a text field with its converter when focus leaves it.
332
+ * Skip empty fields until submission, when required inputs are checked.
333
+ */
334
+ validateField(field) {
335
+ if (!field || field.kind !== 'text') {
336
+ return;
337
+ }
338
+ const raws = this.rawValues(field);
339
+ if (raws === null) {
340
+ this.errors.set(field.input, 'a quote is left open');
341
+ return;
342
+ }
343
+ if (!raws.length) {
344
+ // Skip empty fields, preserving any requirement error from an earlier submission.
345
+ return;
346
+ }
347
+ for (const raw of raws) {
348
+ const outcome = (0, parse_1.convertRaw)(field.input, raw);
349
+ if (!outcome.ok) {
350
+ this.errors.set(field.input, outcome.reason);
351
+ return;
352
+ }
353
+ }
354
+ this.errors.delete(field.input);
355
+ }
356
+ /** Current command and raw argument tokens, excluding the executable. */
357
+ tokens() {
358
+ const { command } = this.entry;
359
+ return [...(command ? [command.token] : []), ...this.argTokens('raw')];
360
+ }
361
+ /** Current command line for display, with shell quoting and sensitive values masked. */
362
+ preview() {
363
+ return this.commandLine('display');
364
+ }
365
+ commandLine(style) {
366
+ const { command } = this.entry;
367
+ return [
368
+ this.options.executable,
369
+ ...(command ? [command.token] : []),
370
+ ...this.argTokens(style),
371
+ ].join(' ');
372
+ }
373
+ /** Serialize the selected entry's arguments, excluding its command token. */
374
+ argTokens(style) {
375
+ const tokens = [];
376
+ for (const field of this.fields) {
377
+ const { input } = field;
378
+ const [longName] = input.names;
379
+ const flagToken = longName !== undefined ? `--${longName}` : `-${input.aliases[0] ?? ''}`;
380
+ if (field.kind === 'flag') {
381
+ const value = this.flag(field);
382
+ if (value === true) {
383
+ tokens.push(flagToken);
384
+ }
385
+ else if (value === false && field.negation !== null) {
386
+ tokens.push(field.negation);
387
+ }
388
+ continue;
389
+ }
390
+ for (const raw of this.rawValues(field) ?? []) {
391
+ const written = style === 'raw'
392
+ ? raw
393
+ : style === 'display' && input.sensitive && raw !== ''
394
+ ? this.options.maskChar.repeat(6)
395
+ : shellQuote(raw);
396
+ if (longName !== undefined) {
397
+ // Use an inline long option value so empty strings and leading dashes are unambiguous.
398
+ tokens.push(`--${longName}=${written}`);
399
+ }
400
+ else if (raw === '' || (style !== 'raw' && !raw.startsWith('-'))) {
401
+ tokens.push(flagToken, written);
402
+ }
403
+ else {
404
+ // Attach a leading-dash value to its short option so it cannot be interpreted as another option.
405
+ tokens.push(flagToken + written);
406
+ }
407
+ }
408
+ }
409
+ return tokens;
410
+ }
411
+ /**
412
+ * Validate the current selection using normal parsing and conversion.
413
+ * On failure, mark invalid fields, focus the first one, and return `null`.
414
+ */
415
+ check() {
416
+ this.errors.clear();
417
+ this.message = null;
418
+ const issues = [];
419
+ for (const field of this.fields) {
420
+ if (field.kind === 'text' && this.rawValues(field) === null) {
421
+ issues.push({
422
+ code: 'invalid_value',
423
+ message: `Invalid value for "${field.name}": a quote is left open`,
424
+ option: field.name,
425
+ input: field.input,
426
+ });
427
+ }
428
+ }
429
+ const { command } = this.entry;
430
+ const tokens = this.argTokens('raw');
431
+ if (!issues.length) {
432
+ try {
433
+ // Bind to the selected command without rescanning for a command token.
434
+ // This preserves the selection even when a positional value matches a command name.
435
+ const resolved = (0, parse_1.resolveBinding)(this.schema, (0, parse_1.bindTarget)(this.schema, command, tokens));
436
+ if (resolved.ok) {
437
+ return { command: command ? command.token : null, tokens };
438
+ }
439
+ issues.push(...resolved.issues);
440
+ }
441
+ catch (err) {
442
+ if (!(err instanceof errors_1.UsageError)) {
443
+ throw err;
444
+ }
445
+ this.message = { kind: 'error', text: err.issues[0].message };
446
+ return null;
447
+ }
448
+ }
449
+ for (const found of issues) {
450
+ if (found.input && !this.errors.has(found.input)) {
451
+ this.errors.set(found.input, found.code === 'missing_required' ? 'required' : found.message.replace(/^[^:]*: /, ''));
452
+ }
453
+ }
454
+ const firstInvalid = this.fields.findIndex(field => this.errors.has(field.input));
455
+ if (firstInvalid >= 0) {
456
+ this.region = 'fields';
457
+ this.fieldIndex = firstInvalid;
458
+ }
459
+ this.message = { kind: 'error', text: issues[0]?.message ?? 'The command line is not valid' };
460
+ return null;
461
+ }
462
+ run() {
463
+ const line = this.check();
464
+ return line ? { kind: 'run', ...line } : 'redraw';
465
+ }
466
+ copy() {
467
+ const line = this.check();
468
+ if (!line) {
469
+ return 'redraw';
470
+ }
471
+ const masked = this.fields
472
+ .filter(field => field.input.sensitive && this.rawValues(field)?.some(raw => raw !== ''))
473
+ .map(field => field.name);
474
+ return {
475
+ kind: 'copy',
476
+ ...line,
477
+ text: this.commandLine('shell'),
478
+ shown: this.commandLine('display'),
479
+ masked,
480
+ };
481
+ }
482
+ // *******************************************************************************************************************
483
+ moveRegion(delta) {
484
+ const regions = this.availableRegions();
485
+ const index = regions.indexOf(this.region);
486
+ const next = regions[(index + delta + regions.length) % regions.length];
487
+ if (next === undefined || next === this.region) {
488
+ return 'none';
489
+ }
490
+ return this.enterRegion(next);
491
+ }
492
+ enterRegion(region) {
493
+ this.validateField(this.focusedField);
494
+ this.region = region;
495
+ this.fieldIndex = Math.min(this.fieldIndex, Math.max(0, this.fields.length - 1));
496
+ return 'redraw';
497
+ }
498
+ select(index) {
499
+ const clamped = Math.max(0, Math.min(this.entries.length - 1, index));
500
+ if (clamped === this.selected) {
501
+ return 'none';
502
+ }
503
+ this.selected = clamped;
504
+ this.fieldIndex = 0;
505
+ this.message = null;
506
+ return 'redraw';
507
+ }
508
+ moveField(delta) {
509
+ const next = this.fieldIndex + delta;
510
+ if (next < 0) {
511
+ return 'none';
512
+ }
513
+ this.validateField(this.focusedField);
514
+ if (next >= this.fields.length) {
515
+ this.region = 'buttons';
516
+ this.button = 'run';
517
+ }
518
+ else {
519
+ this.fieldIndex = next;
520
+ }
521
+ return 'redraw';
522
+ }
523
+ /** Handle a key not consumed by a field, using terminal-kit key names. */
524
+ handleKey(key, isCharacter) {
525
+ const shown = this.message;
526
+ const reaction = this.dispatchKey(key, isCharacter);
527
+ if (reaction === 'redraw' && this.message === shown) {
528
+ // Clear the previous message after a state change while retaining field error markers.
529
+ this.message = null;
530
+ }
531
+ return reaction;
532
+ }
533
+ /**
534
+ * Whether Escape cancels rather than returning to the command list.
535
+ * It cancels from the command list or when there is no command list to return to.
536
+ */
537
+ get escapeLeaves() {
538
+ return this.region === 'commands' || !this.availableRegions().includes('commands');
539
+ }
540
+ press(button) {
541
+ switch (button) {
542
+ case 'run':
543
+ return this.run();
544
+ case 'copy':
545
+ return this.copy();
546
+ case 'cancel':
547
+ return { kind: 'cancel' };
548
+ }
549
+ }
550
+ dispatchKey(key, isCharacter) {
551
+ switch (key) {
552
+ case 'ESCAPE':
553
+ return this.escapeLeaves ? { kind: 'cancel' } : this.enterRegion('commands');
554
+ case 'CTRL_C':
555
+ return { kind: 'cancel' };
556
+ case 'CTRL_R':
557
+ return this.run();
558
+ case 'CTRL_Y':
559
+ return this.copy();
560
+ case 'TAB':
561
+ return this.moveRegion(1);
562
+ case 'SHIFT_TAB':
563
+ return this.moveRegion(-1);
564
+ }
565
+ const afterCommands = () => {
566
+ this.button = 'run';
567
+ return this.enterRegion(this.fields.length ? 'fields' : 'buttons');
568
+ };
569
+ switch (this.region) {
570
+ case 'commands':
571
+ switch (key) {
572
+ case 'UP':
573
+ return this.select(this.selected - 1);
574
+ case 'DOWN':
575
+ return this.select(this.selected + 1);
576
+ case 'PAGE_UP':
577
+ return this.select(this.selected - PAGE_SIZE);
578
+ case 'PAGE_DOWN':
579
+ return this.select(this.selected + PAGE_SIZE);
580
+ case 'HOME':
581
+ return this.select(0);
582
+ case 'END':
583
+ return this.select(this.entries.length - 1);
584
+ case 'ENTER':
585
+ case 'KP_ENTER':
586
+ case 'RIGHT':
587
+ return afterCommands();
588
+ }
589
+ if (isCharacter && key.trim()) {
590
+ // Jump to the next command that starts with the typed letter
591
+ const wanted = key.toLowerCase();
592
+ for (let step = 1; step <= this.entries.length; step++) {
593
+ const index = (this.selected + step) % this.entries.length;
594
+ if (this.entries[index]?.label.toLowerCase().startsWith(wanted)) {
595
+ return this.select(index);
596
+ }
597
+ }
598
+ }
599
+ return 'none';
600
+ case 'fields': {
601
+ const field = this.focusedField;
602
+ switch (key) {
603
+ case 'UP':
604
+ return this.moveField(-1);
605
+ case 'DOWN':
606
+ case 'ENTER':
607
+ case 'KP_ENTER':
608
+ return this.moveField(1);
609
+ case 'PAGE_UP':
610
+ case 'PAGE_DOWN': {
611
+ const target = Math.max(0, Math.min(this.fields.length - 1, this.fieldIndex + (key === 'PAGE_UP' ? -PAGE_SIZE : PAGE_SIZE)));
612
+ if (target === this.fieldIndex) {
613
+ return 'none';
614
+ }
615
+ this.validateField(field);
616
+ this.fieldIndex = target;
617
+ return 'redraw';
618
+ }
619
+ case ' ':
620
+ if (field?.kind === 'flag') {
621
+ this.toggle(field);
622
+ return 'redraw';
623
+ }
624
+ return 'none';
625
+ case 'CTRL_U':
626
+ if (field?.kind === 'text' && this.text(field) !== '') {
627
+ this.setText(field, '');
628
+ return 'redraw';
629
+ }
630
+ return 'none';
631
+ }
632
+ return 'none';
633
+ }
634
+ case 'buttons':
635
+ switch (key) {
636
+ case 'LEFT':
637
+ case 'RIGHT': {
638
+ const next = exports.TUI_BUTTONS[exports.TUI_BUTTONS.indexOf(this.button) + (key === 'LEFT' ? -1 : 1)];
639
+ if (next === undefined) {
640
+ return 'none';
641
+ }
642
+ this.button = next;
643
+ return 'redraw';
644
+ }
645
+ case 'UP': {
646
+ const regions = this.availableRegions();
647
+ const previous = regions[regions.indexOf('buttons') - 1];
648
+ if (previous === undefined) {
649
+ return 'none';
650
+ }
651
+ if (previous === 'fields') {
652
+ this.fieldIndex = this.fields.length - 1;
653
+ }
654
+ return this.enterRegion(previous);
655
+ }
656
+ case 'ENTER':
657
+ case 'KP_ENTER':
658
+ case ' ':
659
+ return this.press(this.button);
660
+ }
661
+ return 'none';
662
+ }
663
+ }
664
+ }
665
+ exports.TuiModel = TuiModel;
666
+ //# sourceMappingURL=tui_model.js.map