From e585a9b9587a6c38b0a4b72036ba643940fcc0ae Mon Sep 17 00:00:00 2001 From: "@StringerBell69" Date: Thu, 15 Oct 2026 15:28:22 +0200 Subject: [PATCH 1/3] feat(prompts): add back navigation to `group` (#39) Pressing Shift+Tab during a grouped prompt returns to the previous step, discarding its answer and re-running the previous prompt. - @clack/core: add a `back` action (unbound by default, so standalone prompts are unchanged), a `BACK_SYMBOL`/`isBack()` pair mirroring `CANCEL_SYMBOL`/`isCancel()`, and a `'back'` prompt state. - @clack/prompts: rework `group()` into a navigable loop. Back is on by default (disable with `navigate: false`) and exposes `onBack`. Closes #39 --- .changeset/group-back-navigation.md | 17 +++ packages/core/src/index.ts | 2 + packages/core/src/prompts/prompt.ts | 33 +++- packages/core/src/types.ts | 10 +- packages/core/src/utils/index.ts | 6 + packages/core/src/utils/settings.ts | 2 +- packages/prompts/src/common.ts | 4 + packages/prompts/src/group.ts | 104 ++++++++++--- packages/prompts/src/index.ts | 9 +- packages/prompts/test/group.test.ts | 227 ++++++++++++++++++++++++++++ 10 files changed, 389 insertions(+), 25 deletions(-) create mode 100644 .changeset/group-back-navigation.md create mode 100644 packages/prompts/test/group.test.ts diff --git a/.changeset/group-back-navigation.md b/.changeset/group-back-navigation.md new file mode 100644 index 00000000..a79ec43d --- /dev/null +++ b/.changeset/group-back-navigation.md @@ -0,0 +1,17 @@ +--- +'@clack/core': minor +'@clack/prompts': minor +--- + +Add back navigation to `group` + +The `group` utility can now return to a previous step. Pressing `Shift+Tab` +during a prompt returns to the previous one. Answers are kept, and each step +receives its previous answer as `previous`, so passing it to the prompt's +`initialValue` restores what the user had entered. It is on by default and can +be turned off with `group(prompts, { navigate: false })`; an +`onBack({ from, to, results })` callback is also available. + +Under the hood this adds a `back` action to `@clack/core` (unbound by default, so +standalone prompts are unchanged), a `BACK_SYMBOL`/`isBack()` pair mirroring +`CANCEL_SYMBOL`/`isCancel()`, and a `'back'` prompt state. Closes #39. diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 1ce83777..705b1b68 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -22,10 +22,12 @@ export type { TextOptions } from './prompts/text.js'; export { default as TextPrompt } from './prompts/text.js'; export type { ClackState as State } from './types.js'; export { + BACK_SYMBOL, block, CANCEL_SYMBOL, getColumns, getRows, + isBack, isCancel, wrapTextWithPrefix, } from './utils/index.js'; diff --git a/packages/core/src/prompts/prompt.ts b/packages/core/src/prompts/prompt.ts index 4b45612c..8a3e704c 100644 --- a/packages/core/src/prompts/prompt.ts +++ b/packages/core/src/prompts/prompt.ts @@ -6,6 +6,7 @@ import { cursor, erase } from 'sisteransi'; import type { ClackEvents, ClackState } from '../types.js'; import type { Action } from '../utils/index.js'; import { + BACK_SYMBOL, CANCEL_SYMBOL, diffLines, getColumns, @@ -146,7 +147,8 @@ export default class Prompt { } public prompt() { - return new Promise((resolve) => { + type Resolution = TValue | typeof CANCEL_SYMBOL | typeof BACK_SYMBOL | undefined; + return new Promise((resolve) => { if (this._abortSignal) { if (this._abortSignal.aborted) { this.state = 'cancel'; @@ -196,6 +198,12 @@ export default class Prompt { setRawMode(this.input, false); resolve(CANCEL_SYMBOL); }); + this.once('back', () => { + this.output.write(cursor.show); + this.output.off('resize', this.render); + setRawMode(this.input, false); + resolve(BACK_SYMBOL); + }); // No answer can arrive once the input has ended (e.g. stdin is // `/dev/null` or a pipe that ran out), so cancel instead of hanging. @@ -300,12 +308,20 @@ export default class Prompt { if (isActionKey([char, key?.name, key?.sequence], 'cancel')) { this.state = 'cancel'; } + // `back` lets a caller (e.g. the `group` utility) return to a previous + // step. It is unbound by default, so standalone prompts are unaffected. + if (this.state !== 'cancel' && isActionKey([char, key?.name, key?.sequence], 'back')) { + this.state = 'back'; + } - if (this.state === 'submit' || this.state === 'cancel') { + if (this.state === 'submit' || this.state === 'cancel' || this.state === 'back') { this.emit('finalize'); } - this.render(); - if (this.state === 'submit' || this.state === 'cancel') { + // `back` leaves no frame behind (see close()), so skip its render. + if (this.state !== 'back') { + this.render(); + } + if (this.state === 'submit' || this.state === 'cancel' || this.state === 'back') { this.close(); } } @@ -314,7 +330,14 @@ export default class Prompt { this.input.unpipe(); this.input.removeListener('keypress', this.onKeypress); this.input.removeListener('end', this.onInputEnd); - this.output.write('\n'); + if (this.state === 'back') { + // Going back: erase this step's output so navigation stays clean, + // rather than leaving a finalized frame behind like submit/cancel do. + this.restoreCursor(); + this.output.write(erase.down()); + } else { + this.output.write('\n'); + } setRawMode(this.input, false); this.rl?.close(); this.rl = undefined; diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 14c34567..ea824fba 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -4,7 +4,14 @@ import type { Action } from './utils/settings.js'; /** * The state of the prompt */ -export type ClackState = 'initial' | 'active' | 'cancel' | 'submit' | 'error' | 'validating'; +export type ClackState = + | 'initial' + | 'active' + | 'cancel' + | 'back' + | 'submit' + | 'error' + | 'validating'; /** * Typed event emitter for clack @@ -13,6 +20,7 @@ export interface ClackEvents { initial: (value?: any) => void; active: (value?: any) => void; cancel: (value?: any) => void; + back: (value?: any) => void; submit: (value?: any) => void; error: (value?: any) => void; validating: (value?: any) => void; diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index 9c688be0..8ce2f342 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -19,6 +19,12 @@ export function isCancel(value: unknown): value is typeof CANCEL_SYMBOL { return value === CANCEL_SYMBOL; } +export const BACK_SYMBOL = Symbol('clack:back'); + +export function isBack(value: unknown): value is typeof BACK_SYMBOL { + return value === BACK_SYMBOL; +} + export function setRawMode(input: Readable, value: boolean) { const i = input as typeof stdin; diff --git a/packages/core/src/utils/settings.ts b/packages/core/src/utils/settings.ts index b3d008cf..51bb5dae 100644 --- a/packages/core/src/utils/settings.ts +++ b/packages/core/src/utils/settings.ts @@ -1,4 +1,4 @@ -const actions = ['up', 'down', 'left', 'right', 'space', 'enter', 'cancel'] as const; +const actions = ['up', 'down', 'left', 'right', 'space', 'enter', 'cancel', 'back'] as const; export type Action = (typeof actions)[number]; const DEFAULT_MONTH_NAMES = [ diff --git a/packages/prompts/src/common.ts b/packages/prompts/src/common.ts index e5f791fd..1dca1332 100644 --- a/packages/prompts/src/common.ts +++ b/packages/prompts/src/common.ts @@ -53,6 +53,8 @@ export const symbol = (state: State) => { return styleText('green', S_STEP_SUBMIT); case 'validating': return styleText('dim', S_STEP_ACTIVE); + case 'back': + return styleText('dim', S_STEP_ACTIVE); } }; @@ -67,6 +69,8 @@ export const symbolBar = (state: State) => { return styleText('yellow', S_BAR); case 'submit': return styleText('green', S_BAR); + case 'back': + return styleText('dim', S_BAR); } }; diff --git a/packages/prompts/src/group.ts b/packages/prompts/src/group.ts index 0e4b9246..9b33de28 100644 --- a/packages/prompts/src/group.ts +++ b/packages/prompts/src/group.ts @@ -1,4 +1,7 @@ -import { isCancel } from '@clack/core'; +import { isBack, isCancel, settings } from '@clack/core'; + +/** Shift+Tab. Bound to the `back` action while a navigable group is running. */ +const SHIFT_TAB_SEQUENCE = '\x1b[Z'; type Prettify = { [P in keyof T]: T[P]; @@ -20,6 +23,26 @@ export interface PromptGroupOptions { * Called when any one of the prompts is canceled. */ onCancel?: (opts: { results: Prettify>> }) => void; + + /** + * Enable back navigation. When `true` (the default), pressing `Shift+Tab` + * during a prompt returns to the previous step. Answers are kept, and each + * step receives its previous answer as `previous` so it can be restored. Set + * to `false` to keep the group strictly forward-only. + * + * @default true + */ + navigate?: boolean; + + /** + * Called when the user returns to a previous step, with the name of the step + * being left and the step being returned to. + */ + onBack?: (opts: { + from: keyof T; + to: keyof T; + results: Prettify>>; + }) => void; } /** @@ -29,6 +52,12 @@ export interface PromptGroupOptions { export type PromptGroup = { [P in keyof T]: (opts: { results: Prettify>>>; + /** + * This step's previously-submitted answer, if the user has visited it + * before (e.g. after going back). Pass it to the prompt's `initialValue` + * to restore what they had entered. + */ + previous?: PromptGroupAwaitedReturn[P]; }) => undefined | Promise; }; @@ -44,11 +73,14 @@ export type PromptGroup = { * import { group, text, password } from '@clack/prompts'; * * const account = await group({ - * email: () => text({ + * // `Shift+Tab` goes back; pass `previous` to `initialValue` to restore it. + * email: ({ previous }) => text({ * message: 'What is your email address?', + * initialValue: previous, * }), - * username: ({ results }) => text({ + * username: ({ results, previous }) => text({ * message: 'What is your username?', + * initialValue: previous, * placeholder: results.email?.replace(/@.+$/, '').toLowerCase() ?? '', * }), * password: () => password({ @@ -63,23 +95,61 @@ export const group = async ( ): Promise>> => { const results = {} as any; const promptNames = Object.keys(prompts); + const navigate = opts?.navigate !== false; - for (const name of promptNames) { - const prompt = prompts[name as keyof T]; - const result = await prompt({ results })?.catch((e) => { - throw e; - }); + // We bind Shift+Tab -> `back` only while a step that *can* go back is showing, + // and restore the previous alias state afterwards so we never clobber a user's + // own binding. We only manage the alias when the user hasn't bound it already. + const manageAlias = navigate && !settings.aliases.has(SHIFT_TAB_SEQUENCE); + const setBackEnabled = (enabled: boolean) => { + if (!manageAlias) return; + if (enabled) settings.aliases.set(SHIFT_TAB_SEQUENCE, 'back'); + else settings.aliases.delete(SHIFT_TAB_SEQUENCE); + }; - // Pass the results to the onCancel function - // so the user can decide what to do with the results - // TODO: Switch to callback within core to avoid isCancel Fn - if (typeof opts?.onCancel === 'function' && isCancel(result)) { - results[name] = 'canceled'; - opts.onCancel({ results }); - continue; - } + try { + let index = 0; + while (index < promptNames.length) { + // There is nowhere to go back to from the first step, so `back` is + // disabled there (Shift+Tab does nothing); enabled from the second on. + setBackEnabled(index > 0); + + // Safe: the loop condition guarantees `index` is in range. + const name = promptNames[index] as string; + const prompt = prompts[name as keyof T]; + // `previous` lets a revisited step restore what the user had entered. + const result = await prompt({ results, previous: results[name] })?.catch((e) => { + throw e; + }); - results[name] = result; + // `back`: return to the previous step. Answers are kept (not discarded), + // so each step can offer them back via `previous`. Guarded against the + // first step in case a caller forces `back` there programmatically. + if (navigate && isBack(result)) { + if (index > 0) { + const from = name as keyof T; + index--; + const to = promptNames[index] as keyof T; + opts?.onBack?.({ from, to, results }); + } + continue; + } + + // Pass the results to the onCancel function + // so the user can decide what to do with the results + // TODO: Switch to callback within core to avoid isCancel Fn + if (typeof opts?.onCancel === 'function' && isCancel(result)) { + results[name] = 'canceled'; + opts.onCancel({ results }); + index++; + continue; + } + + results[name] = result; + index++; + } + } finally { + setBackEnabled(false); } return results; diff --git a/packages/prompts/src/index.ts b/packages/prompts/src/index.ts index 766b0897..07151f93 100644 --- a/packages/prompts/src/index.ts +++ b/packages/prompts/src/index.ts @@ -1,5 +1,12 @@ export type { ClackSettings } from '@clack/core'; -export { CANCEL_SYMBOL, isCancel, settings, updateSettings } from '@clack/core'; +export { + BACK_SYMBOL, + CANCEL_SYMBOL, + isBack, + isCancel, + settings, + updateSettings, +} from '@clack/core'; export * from './autocomplete.js'; export * from './box.js'; diff --git a/packages/prompts/test/group.test.ts b/packages/prompts/test/group.test.ts new file mode 100644 index 00000000..ea29891a --- /dev/null +++ b/packages/prompts/test/group.test.ts @@ -0,0 +1,227 @@ +import { BACK_SYMBOL, CANCEL_SYMBOL, isBack, settings } from '@clack/core'; +import { afterEach, describe, expect, test, vi } from 'vitest'; +import * as prompts from '../src/index.js'; +import { MockReadable, MockWritable } from './test-utils.js'; + +const SHIFT_TAB = '\x1b[Z'; + +describe('group', () => { + afterEach(() => { + settings.aliases.delete(SHIFT_TAB); + vi.restoreAllMocks(); + }); + + test('collects each prompt result into one object', async () => { + const result = await prompts.group({ + a: () => Promise.resolve('a1'), + b: () => Promise.resolve('b1'), + }); + expect(result).toEqual({ a: 'a1', b: 'b1' }); + }); + + test('a step returning BACK_SYMBOL returns to the previous step', async () => { + const visits: string[] = []; + let bWentBack = false; + const result = await prompts.group({ + a: () => { + visits.push('a'); + return Promise.resolve('a1'); + }, + b: () => { + visits.push('b'); + if (!bWentBack) { + bWentBack = true; + return Promise.resolve(BACK_SYMBOL); + } + return Promise.resolve('b1'); + }, + }); + expect(visits).toEqual(['a', 'b', 'a', 'b']); + expect(result).toEqual({ a: 'a1', b: 'b1' }); + }); + + test('offers the previous answer back to a revisited step', async () => { + const seenPrev: unknown[] = []; + let bWentBack = false; + await prompts.group({ + a: ({ previous }) => { + seenPrev.push(previous); + return Promise.resolve('a-val'); + }, + b: () => { + if (!bWentBack) { + bWentBack = true; + return Promise.resolve(BACK_SYMBOL); + } + return Promise.resolve('b-val'); + }, + }); + // `a` runs twice: first with no previous, then (after going back) with its kept answer. + expect(seenPrev).toEqual([undefined, 'a-val']); + }); + + test('preserves a submitted answer when returning to its step from further ahead', async () => { + const bPrev: unknown[] = []; + let cWentBack = false; + const result = await prompts.group({ + a: () => Promise.resolve('a'), + b: ({ previous }) => { + bPrev.push(previous); + return Promise.resolve('b-val'); + }, + c: () => { + if (!cWentBack) { + cWentBack = true; + return Promise.resolve(BACK_SYMBOL); + } + return Promise.resolve('c'); + }, + }); + // c goes back to b; b is re-offered its earlier answer. + expect(bPrev).toEqual([undefined, 'b-val']); + expect(result).toEqual({ a: 'a', b: 'b-val', c: 'c' }); + }); + + test('calls onBack with the step being left and the step returned to', async () => { + const onBack = vi.fn(); + let bWentBack = false; + await prompts.group( + { + a: () => Promise.resolve('a1'), + b: () => { + if (!bWentBack) { + bWentBack = true; + return Promise.resolve(BACK_SYMBOL); + } + return Promise.resolve('b1'); + }, + }, + { onBack } + ); + expect(onBack).toHaveBeenCalledTimes(1); + expect(onBack.mock.calls[0]?.[0]).toMatchObject({ from: 'b', to: 'a' }); + }); + + test('disables back on the first step and enables it afterwards', async () => { + const aliasDuring: boolean[] = []; + let bWentBack = false; + await prompts.group({ + a: () => { + aliasDuring.push(settings.aliases.has(SHIFT_TAB)); + return Promise.resolve('a'); + }, + b: () => { + aliasDuring.push(settings.aliases.has(SHIFT_TAB)); + if (!bWentBack) { + bWentBack = true; + return Promise.resolve(BACK_SYMBOL); + } + return Promise.resolve('b'); + }, + }); + // a (root) -> off, b -> on, back to a -> off, b -> on. + expect(aliasDuring).toEqual([false, true, false, true]); + }); + + test('a forced BACK on the first step is ignored (re-runs, never goes out of range)', async () => { + let count = 0; + const result = await prompts.group({ + a: () => { + count++; + return Promise.resolve(count === 1 ? BACK_SYMBOL : 'a-final'); + }, + }); + expect(count).toBe(2); + expect(result).toEqual({ a: 'a-final' }); + }); + + test('navigate:false disables back and never binds Shift+Tab', async () => { + const result = await prompts.group( + { a: () => Promise.resolve(BACK_SYMBOL) }, + { navigate: false } + ); + expect(isBack(result.a)).toBe(true); + expect(settings.aliases.has(SHIFT_TAB)).toBe(false); + }); + + test('restores the Shift+Tab alias state after running', async () => { + expect(settings.aliases.has(SHIFT_TAB)).toBe(false); + await prompts.group({ a: () => Promise.resolve('a1') }); + expect(settings.aliases.has(SHIFT_TAB)).toBe(false); + }); + + test('onCancel still fires and collects results', async () => { + const onCancel = vi.fn(); + const result = await prompts.group( + { + a: () => Promise.resolve('a1'), + b: () => Promise.resolve(CANCEL_SYMBOL), + }, + { onCancel } + ); + expect(onCancel).toHaveBeenCalledTimes(1); + expect(result).toMatchObject({ a: 'a1', b: 'canceled' }); + }); +}); + +describe('back navigation (core wiring)', () => { + afterEach(() => { + settings.aliases.delete(SHIFT_TAB); + }); + + test('Shift+Tab resolves a text prompt to BACK_SYMBOL when the back action is bound', async () => { + settings.aliases.set(SHIFT_TAB, 'back'); + const input = new MockReadable(); + const output = new MockWritable(); + const result = prompts.text({ message: 'foo', input, output }); + input.emit('keypress', '', { name: 'tab', shift: true, sequence: SHIFT_TAB }); + const value = await result; + expect(isBack(value)).toBe(true); + }); + + test('going back leaves no "undefined" in the rendered output', async () => { + settings.aliases.set(SHIFT_TAB, 'back'); + const input = new MockReadable(); + const output = new MockWritable(); + const result = prompts.select({ + message: 'pick one', + options: [{ value: 'opt0' }, { value: 'opt1' }], + input, + output, + }); + input.emit('keypress', '', { name: 'tab', shift: true, sequence: SHIFT_TAB }); + await result; + expect(output.buffer.join('')).not.toContain('undefined'); + }); + + test('Shift+Tab resolves a select prompt to BACK_SYMBOL', async () => { + settings.aliases.set(SHIFT_TAB, 'back'); + const input = new MockReadable(); + const output = new MockWritable(); + const result = prompts.select({ + message: 'pick one', + options: [{ value: 'opt0' }, { value: 'opt1' }], + input, + output, + }); + input.emit('keypress', '', { name: 'tab', shift: true, sequence: SHIFT_TAB }); + const value = await result; + expect(isBack(value)).toBe(true); + }); + + test('a select prompt without the back action is unaffected by Shift+Tab', async () => { + const input = new MockReadable(); + const output = new MockWritable(); + const result = prompts.select({ + message: 'pick one', + options: [{ value: 'opt0' }, { value: 'opt1' }], + input, + output, + }); + // No `back` alias bound: Shift+Tab does nothing, Enter still submits. + input.emit('keypress', '', { name: 'tab', shift: true, sequence: SHIFT_TAB }); + input.emit('keypress', '', { name: 'return' }); + const value = await result; + expect(value).toBe('opt0'); + }); +}); From 032ddabe775b9b7937592d13222cd477c57dff2b Mon Sep 17 00:00:00 2001 From: "@StringerBell69" Date: Mon, 30 Nov 2026 15:42:33 +0100 Subject: [PATCH 2/3] fix(prompts): skip conditional steps when navigating back in group Going back could not move past a step that opted out by returning undefined: the skipped step re-ran, returned undefined again, and the loop treated it as an answer and advanced, trapping focus on the next step. Track the steps actually displayed and jump back to the most recent one, skipping omitted conditional steps. onBack now reports the real step returned to. --- packages/prompts/src/group.ts | 31 +++++++++++++----- packages/prompts/test/group.test.ts | 51 +++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 9 deletions(-) diff --git a/packages/prompts/src/group.ts b/packages/prompts/src/group.ts index 9b33de28..9aa2ce48 100644 --- a/packages/prompts/src/group.ts +++ b/packages/prompts/src/group.ts @@ -109,26 +109,37 @@ export const group = async ( try { let index = 0; + // Indices of the steps that were actually displayed, in visit order. A + // conditional step opts out by returning `undefined` synchronously and is + // never shown, so it must not be a `back` target: going back jumps straight + // to the most recently displayed step, skipping over any that were omitted. + const history: number[] = []; while (index < promptNames.length) { - // There is nowhere to go back to from the first step, so `back` is - // disabled there (Shift+Tab does nothing); enabled from the second on. - setBackEnabled(index > 0); + // There is nowhere to go back to until at least one step has been shown, + // so `back` is disabled then (Shift+Tab does nothing) and enabled after. + setBackEnabled(history.length > 0); // Safe: the loop condition guarantees `index` is in range. const name = promptNames[index] as string; const prompt = prompts[name as keyof T]; // `previous` lets a revisited step restore what the user had entered. - const result = await prompt({ results, previous: results[name] })?.catch((e) => { + const step = prompt({ results, previous: results[name] }); + // Only a real prompt returns a thenable; a skipped conditional step + // returns `undefined`. We record the ones shown so `back` can skip the + // rest, and so the alias state above reflects what the user can see. + const displayed = typeof (step as Promise | undefined)?.then === 'function'; + const result = await step?.catch((e) => { throw e; }); - // `back`: return to the previous step. Answers are kept (not discarded), - // so each step can offer them back via `previous`. Guarded against the - // first step in case a caller forces `back` there programmatically. + // `back`: return to the most recently displayed step. Answers are kept + // (not discarded), so each step can offer them back via `previous`. + // Guarded against the case where nothing has been shown yet, in case a + // caller forces `back` there programmatically. if (navigate && isBack(result)) { - if (index > 0) { + if (history.length > 0) { const from = name as keyof T; - index--; + index = history.pop() as number; const to = promptNames[index] as keyof T; opts?.onBack?.({ from, to, results }); } @@ -141,11 +152,13 @@ export const group = async ( if (typeof opts?.onCancel === 'function' && isCancel(result)) { results[name] = 'canceled'; opts.onCancel({ results }); + if (displayed) history.push(index); index++; continue; } results[name] = result; + if (displayed) history.push(index); index++; } } finally { diff --git a/packages/prompts/test/group.test.ts b/packages/prompts/test/group.test.ts index ea29891a..6acf18df 100644 --- a/packages/prompts/test/group.test.ts +++ b/packages/prompts/test/group.test.ts @@ -135,6 +135,57 @@ describe('group', () => { expect(result).toEqual({ a: 'a-final' }); }); + test('going back past a skipped conditional step reaches the step before it', async () => { + const visits: string[] = []; + let cBack = 0; + const result = await prompts.group({ + a: () => { + visits.push('a'); + return Promise.resolve('a1'); + }, + // Conditional step: opts out by returning `undefined`, so it is never + // shown and must not be a `back` target. + b: () => { + visits.push('b'); + return undefined; + }, + c: () => { + visits.push('c'); + // Go back once (should land on `a`, not the skipped `b`), then answer. + if (cBack < 1) { + cBack++; + return Promise.resolve(BACK_SYMBOL); + } + return Promise.resolve('c1'); + }, + }); + // a -> b(skipped) -> c -> back -> a -> b(skipped) -> c. + expect(visits).toEqual(['a', 'b', 'c', 'a', 'b', 'c']); + expect(result).toEqual({ a: 'a1', b: undefined, c: 'c1' }); + }); + + test('onBack skips over a conditional step and reports the displayed step', async () => { + const onBack = vi.fn(); + let cBack = 0; + await prompts.group( + { + a: () => Promise.resolve('a1'), + b: () => undefined, + c: () => { + if (cBack < 1) { + cBack++; + return Promise.resolve(BACK_SYMBOL); + } + return Promise.resolve('c1'); + }, + }, + { onBack } + ); + expect(onBack).toHaveBeenCalledTimes(1); + // Returns to `a`, the previous *displayed* step, not the skipped `b`. + expect(onBack.mock.calls[0]?.[0]).toMatchObject({ from: 'c', to: 'a' }); + }); + test('navigate:false disables back and never binds Shift+Tab', async () => { const result = await prompts.group( { a: () => Promise.resolve(BACK_SYMBOL) }, From 9e3fe0602fb2c1e2b844932e0786cffdc3892071 Mon Sep 17 00:00:00 2001 From: "@StringerBell69" Date: Wed, 2 Dec 2026 08:54:02 +0100 Subject: [PATCH 3/3] fix(prompts): address review on group back navigation - Only count a step as shown when a prompt actually finished during it, so async conditional steps and non-prompt steps are skipped going back. - Erase the step being returned to before it redraws, so nothing is printed twice. - Going back no longer resolves the prompt with a symbol: the group abandons the step instead, so steps never see an unexpected value. This removes BACK_SYMBOL, isBack, the back state/event and onBack. - Make navigation opt-in (navigate defaults to false). - Fold the group tests, move keypress tests to core, regenerate the changeset. --- .changeset/few-months-accept.md | 6 + .changeset/group-back-navigation.md | 17 -- packages/core/src/index.ts | 2 - packages/core/src/prompts/prompt.ts | 94 ++++-- packages/core/src/types.ts | 10 +- packages/core/src/utils/index.ts | 6 - packages/core/test/prompts/prompt.test.ts | 61 ++++ packages/prompts/src/common.ts | 4 - packages/prompts/src/group.ts | 130 ++++---- packages/prompts/src/index.ts | 9 +- packages/prompts/test/group.test.ts | 356 +++++++--------------- 11 files changed, 313 insertions(+), 382 deletions(-) create mode 100644 .changeset/few-months-accept.md delete mode 100644 .changeset/group-back-navigation.md diff --git a/.changeset/few-months-accept.md b/.changeset/few-months-accept.md new file mode 100644 index 00000000..37be3b20 --- /dev/null +++ b/.changeset/few-months-accept.md @@ -0,0 +1,6 @@ +--- +'@clack/core': minor +'@clack/prompts': minor +--- + +Adds opt-in back navigation to `group`: with `navigate: true`, `Shift+Tab` returns to the previous step, which receives its earlier answer as `previous`. diff --git a/.changeset/group-back-navigation.md b/.changeset/group-back-navigation.md deleted file mode 100644 index a79ec43d..00000000 --- a/.changeset/group-back-navigation.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -'@clack/core': minor -'@clack/prompts': minor ---- - -Add back navigation to `group` - -The `group` utility can now return to a previous step. Pressing `Shift+Tab` -during a prompt returns to the previous one. Answers are kept, and each step -receives its previous answer as `previous`, so passing it to the prompt's -`initialValue` restores what the user had entered. It is on by default and can -be turned off with `group(prompts, { navigate: false })`; an -`onBack({ from, to, results })` callback is also available. - -Under the hood this adds a `back` action to `@clack/core` (unbound by default, so -standalone prompts are unchanged), a `BACK_SYMBOL`/`isBack()` pair mirroring -`CANCEL_SYMBOL`/`isCancel()`, and a `'back'` prompt state. Closes #39. diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 705b1b68..1ce83777 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -22,12 +22,10 @@ export type { TextOptions } from './prompts/text.js'; export { default as TextPrompt } from './prompts/text.js'; export type { ClackState as State } from './types.js'; export { - BACK_SYMBOL, block, CANCEL_SYMBOL, getColumns, getRows, - isBack, isCancel, wrapTextWithPrefix, } from './utils/index.js'; diff --git a/packages/core/src/prompts/prompt.ts b/packages/core/src/prompts/prompt.ts index 8a3e704c..f548634a 100644 --- a/packages/core/src/prompts/prompt.ts +++ b/packages/core/src/prompts/prompt.ts @@ -6,7 +6,6 @@ import { cursor, erase } from 'sisteransi'; import type { ClackEvents, ClackState } from '../types.js'; import type { Action } from '../utils/index.js'; import { - BACK_SYMBOL, CANCEL_SYMBOL, diffLines, getColumns, @@ -40,10 +39,27 @@ export interface PromptOptions> { signal?: AbortSignal; } +/** + * @internal Lets the `group` utility in `@clack/prompts` follow the prompts it + * runs so it can navigate back. Not part of the public API. + */ +export interface PromptNavigator { + /** Whether the active prompt may go back right now. */ + canGoBack(): boolean; + /** The user went back from the active prompt, which is now closed and erased. */ + back(): void; + /** A prompt was submitted or canceled, leaving `rows` lines on `output`. */ + finalized(output: Writable, rows: number): void; +} + export default class Prompt { + /** @internal See {@link PromptNavigator}. */ + static navigator: PromptNavigator | undefined; + protected input: Readable; protected output: Writable; private _abortSignal?: AbortSignal; + private _closed = false; private rl: ReadLine | undefined; private opts: Omit>, 'render' | 'input' | 'output'>; @@ -147,8 +163,7 @@ export default class Prompt { } public prompt() { - type Resolution = TValue | typeof CANCEL_SYMBOL | typeof BACK_SYMBOL | undefined; - return new Promise((resolve) => { + return new Promise((resolve) => { if (this._abortSignal) { if (this._abortSignal.aborted) { this.state = 'cancel'; @@ -160,6 +175,7 @@ export default class Prompt { this._abortSignal.addEventListener( 'abort', () => { + if (this._closed) return; this.state = 'cancel'; this.close(); }, @@ -198,12 +214,6 @@ export default class Prompt { setRawMode(this.input, false); resolve(CANCEL_SYMBOL); }); - this.once('back', () => { - this.output.write(cursor.show); - this.output.off('resize', this.render); - setRawMode(this.input, false); - resolve(BACK_SYMBOL); - }); // No answer can arrive once the input has ended (e.g. stdin is // `/dev/null` or a pipe that ran out), so cancel instead of hanging. @@ -257,6 +267,13 @@ export default class Prompt { return; } + // Inside a `group` with back navigation, `back` leaves this prompt for the + // previous step. Prompts outside such a group ignore it. + if (Prompt.navigator?.canGoBack() && isActionKey([char, key?.name, key?.sequence], 'back')) { + this.goBack(); + return; + } + if (this._track && key.name !== 'return') { if (key.name && this._isActionKey(char, key)) { this.rl?.write(null, { ctrl: true, name: 'h' }); @@ -308,20 +325,12 @@ export default class Prompt { if (isActionKey([char, key?.name, key?.sequence], 'cancel')) { this.state = 'cancel'; } - // `back` lets a caller (e.g. the `group` utility) return to a previous - // step. It is unbound by default, so standalone prompts are unaffected. - if (this.state !== 'cancel' && isActionKey([char, key?.name, key?.sequence], 'back')) { - this.state = 'back'; - } - if (this.state === 'submit' || this.state === 'cancel' || this.state === 'back') { + if (this.state === 'submit' || this.state === 'cancel') { this.emit('finalize'); } - // `back` leaves no frame behind (see close()), so skip its render. - if (this.state !== 'back') { - this.render(); - } - if (this.state === 'submit' || this.state === 'cancel' || this.state === 'back') { + this.render(); + if (this.state === 'submit' || this.state === 'cancel') { this.close(); } } @@ -330,26 +339,47 @@ export default class Prompt { this.input.unpipe(); this.input.removeListener('keypress', this.onKeypress); this.input.removeListener('end', this.onInputEnd); - if (this.state === 'back') { - // Going back: erase this step's output so navigation stays clean, - // rather than leaving a finalized frame behind like submit/cancel do. - this.restoreCursor(); - this.output.write(erase.down()); - } else { - this.output.write('\n'); - } + this.output.write('\n'); + // The final frame plus the newline above stay on screen. + Prompt.navigator?.finalized(this.output, this.frameLines() + 1); setRawMode(this.input, false); this.rl?.close(); this.rl = undefined; + this._closed = true; this.emit(`${this.state}`, this.value); this.unsubscribe(); } - private restoreCursor() { - const lines = + /** + * Leaves this prompt for the previous step of a `group`: erases its frame and + * tears it down without resolving, since the group abandons this step. + */ + private goBack() { + this.restoreCursor(); + this.output.write(erase.down()); + this.output.write(cursor.show); + this.output.off('resize', this.render); + this.input.unpipe(); + this.input.removeListener('keypress', this.onKeypress); + this.input.removeListener('end', this.onInputEnd); + setRawMode(this.input, false); + this.rl?.close(); + this.rl = undefined; + this._closed = true; + this.unsubscribe(); + Prompt.navigator?.back(); + } + + /** Line breaks in the last rendered frame, i.e. how far below its top the cursor is. */ + private frameLines() { + return ( wrapAnsi(this._prevFrame, getColumns(this.output), { hard: true, trim: false }).split('\n') - .length - 1; - this.output.write(cursor.move(-999, lines * -1)); + .length - 1 + ); + } + + private restoreCursor() { + this.output.write(cursor.move(-999, this.frameLines() * -1)); } private render() { diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index ea824fba..14c34567 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -4,14 +4,7 @@ import type { Action } from './utils/settings.js'; /** * The state of the prompt */ -export type ClackState = - | 'initial' - | 'active' - | 'cancel' - | 'back' - | 'submit' - | 'error' - | 'validating'; +export type ClackState = 'initial' | 'active' | 'cancel' | 'submit' | 'error' | 'validating'; /** * Typed event emitter for clack @@ -20,7 +13,6 @@ export interface ClackEvents { initial: (value?: any) => void; active: (value?: any) => void; cancel: (value?: any) => void; - back: (value?: any) => void; submit: (value?: any) => void; error: (value?: any) => void; validating: (value?: any) => void; diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index 8ce2f342..9c688be0 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -19,12 +19,6 @@ export function isCancel(value: unknown): value is typeof CANCEL_SYMBOL { return value === CANCEL_SYMBOL; } -export const BACK_SYMBOL = Symbol('clack:back'); - -export function isBack(value: unknown): value is typeof BACK_SYMBOL { - return value === BACK_SYMBOL; -} - export function setRawMode(input: Readable, value: boolean) { const i = input as typeof stdin; diff --git a/packages/core/test/prompts/prompt.test.ts b/packages/core/test/prompts/prompt.test.ts index efe73a6f..f383fda9 100644 --- a/packages/core/test/prompts/prompt.test.ts +++ b/packages/core/test/prompts/prompt.test.ts @@ -549,4 +549,65 @@ describe('Prompt', () => { expect(instance.state).to.equal('submit'); expect(instance.error).to.equal(''); }); + + describe('navigator', () => { + const SHIFT_TAB = { name: 'tab', shift: true, sequence: '\x1b[Z' }; + const navigator = (canGoBack: boolean) => ({ + canGoBack: () => canGoBack, + back: vi.fn(), + finalized: vi.fn(), + }); + + beforeEach(() => { + settings.aliases.set(SHIFT_TAB.sequence, 'back'); + }); + + afterEach(() => { + Prompt.navigator = undefined; + settings.aliases.delete(SHIFT_TAB.sequence); + }); + + test('ignores back without a navigator that allows it', async () => { + for (const nav of [undefined, navigator(false)]) { + Prompt.navigator = nav; + const instance = new Prompt({ input, output, render: () => 'foo' }); + const resultPromise = instance.prompt(); + input.emit('keypress', '', SHIFT_TAB); + input.emit('keypress', '', { name: 'return' }); + expect(await resultPromise).to.equal(undefined); + if (nav) expect(nav.back).not.toHaveBeenCalled(); + } + }); + + test('on back, erases its frame and notifies the navigator without resolving', async () => { + const nav = navigator(true); + Prompt.navigator = nav; + const instance = new Prompt({ input, output, render: () => 'foo\nbar' }); + const settled = vi.fn(); + instance.prompt().then(settled); + input.emit('keypress', '', SHIFT_TAB); + await waitForTick(); + + expect(nav.back).toHaveBeenCalledOnce(); + expect(nav.finalized).not.toHaveBeenCalled(); + expect(settled).not.toHaveBeenCalled(); + expect(output.buffer.slice(-3)).to.deep.equal([ + cursor.move(-999, -1), + erase.down(), + cursor.show, + ]); + }); + + test('reports the rows a finalized prompt leaves on screen', async () => { + const nav = navigator(false); + Prompt.navigator = nav; + const instance = new Prompt({ input, output, render: () => 'foo\nbar' }); + const resultPromise = instance.prompt(); + input.emit('keypress', '', { name: 'return' }); + await resultPromise; + + // `foo` and `bar`; the newline written on close puts the cursor below them. + expect(nav.finalized).toHaveBeenCalledWith(output, 2); + }); + }); }); diff --git a/packages/prompts/src/common.ts b/packages/prompts/src/common.ts index 1dca1332..e5f791fd 100644 --- a/packages/prompts/src/common.ts +++ b/packages/prompts/src/common.ts @@ -53,8 +53,6 @@ export const symbol = (state: State) => { return styleText('green', S_STEP_SUBMIT); case 'validating': return styleText('dim', S_STEP_ACTIVE); - case 'back': - return styleText('dim', S_STEP_ACTIVE); } }; @@ -69,8 +67,6 @@ export const symbolBar = (state: State) => { return styleText('yellow', S_BAR); case 'submit': return styleText('green', S_BAR); - case 'back': - return styleText('dim', S_BAR); } }; diff --git a/packages/prompts/src/group.ts b/packages/prompts/src/group.ts index 9aa2ce48..78081d3b 100644 --- a/packages/prompts/src/group.ts +++ b/packages/prompts/src/group.ts @@ -1,4 +1,6 @@ -import { isBack, isCancel, settings } from '@clack/core'; +import type { Writable } from 'node:stream'; +import { isCancel, Prompt, settings } from '@clack/core'; +import { cursor, erase } from 'sisteransi'; /** Shift+Tab. Bound to the `back` action while a navigable group is running. */ const SHIFT_TAB_SEQUENCE = '\x1b[Z'; @@ -25,24 +27,15 @@ export interface PromptGroupOptions { onCancel?: (opts: { results: Prettify>> }) => void; /** - * Enable back navigation. When `true` (the default), pressing `Shift+Tab` - * during a prompt returns to the previous step. Answers are kept, and each - * step receives its previous answer as `previous` so it can be restored. Set - * to `false` to keep the group strictly forward-only. + * Enable back navigation: pressing `Shift+Tab` during a prompt returns to the + * previous step that showed one. Answers are kept, and each step receives its + * earlier answer as `previous` so it can be restored. Steps that showed no + * prompt (skipped conditional steps, tasks) are passed over going back and run + * again going forward. * - * @default true + * @default false */ navigate?: boolean; - - /** - * Called when the user returns to a previous step, with the name of the step - * being left and the step being returned to. - */ - onBack?: (opts: { - from: keyof T; - to: keyof T; - results: Prettify>>; - }) => void; } /** @@ -53,14 +46,22 @@ export type PromptGroup = { [P in keyof T]: (opts: { results: Prettify>>>; /** - * This step's previously-submitted answer, if the user has visited it - * before (e.g. after going back). Pass it to the prompt's `initialValue` - * to restore what they had entered. + * This step's earlier answer when it is revisited with `navigate` enabled. + * Pass it to the prompt's `initialValue` to restore it. */ previous?: PromptGroupAwaitedReturn[P]; }) => undefined | Promise; }; +/** What a prompt left on screen, so going back can erase it. */ +interface Frame { + output: Writable; + rows: number; +} + +/** Settles the awaited step when the user goes back from it. */ +const BACK = Symbol('clack:group-back'); + /** * The `group` utility provides a consistent way to combine a series of prompts, * combining each answer into one object. Each prompt receives the results of @@ -73,14 +74,11 @@ export type PromptGroup = { * import { group, text, password } from '@clack/prompts'; * * const account = await group({ - * // `Shift+Tab` goes back; pass `previous` to `initialValue` to restore it. - * email: ({ previous }) => text({ + * email: () => text({ * message: 'What is your email address?', - * initialValue: previous, * }), - * username: ({ results, previous }) => text({ + * username: ({ results }) => text({ * message: 'What is your username?', - * initialValue: previous, * placeholder: results.email?.replace(/@.+$/, '').toLowerCase() ?? '', * }), * password: () => password({ @@ -88,6 +86,18 @@ export type PromptGroup = { * }), * }); * ``` + * + * @example + * ```ts + * // With `navigate`, `Shift+Tab` goes back; `previous` restores the answer. + * const answers = await group( + * { + * name: ({ previous }) => text({ message: 'Name?', initialValue: previous }), + * color: ({ previous }) => text({ message: 'Color?', initialValue: previous }), + * }, + * { navigate: true } + * ); + * ``` */ export const group = async ( prompts: PromptGroup, @@ -95,74 +105,88 @@ export const group = async ( ): Promise>> => { const results = {} as any; const promptNames = Object.keys(prompts); - const navigate = opts?.navigate !== false; + + // Steps that showed a prompt, in visit order, with what they left on screen. + const history: { index: number; frames: Frame[] }[] = []; + let frames: Frame[] = []; + let goBack = () => {}; // We bind Shift+Tab -> `back` only while a step that *can* go back is showing, // and restore the previous alias state afterwards so we never clobber a user's // own binding. We only manage the alias when the user hasn't bound it already. - const manageAlias = navigate && !settings.aliases.has(SHIFT_TAB_SEQUENCE); + const manageAlias = opts?.navigate === true && !settings.aliases.has(SHIFT_TAB_SEQUENCE); const setBackEnabled = (enabled: boolean) => { if (!manageAlias) return; if (enabled) settings.aliases.set(SHIFT_TAB_SEQUENCE, 'back'); else settings.aliases.delete(SHIFT_TAB_SEQUENCE); }; + const parent = Prompt.navigator; + if (opts?.navigate) { + Prompt.navigator = { + canGoBack: () => history.length > 0, + back: () => goBack(), + finalized: (output, rows) => { + frames.push({ output, rows }); + // An enclosing group sees this step's prompts as its own. + parent?.finalized(output, rows); + }, + }; + } + try { let index = 0; - // Indices of the steps that were actually displayed, in visit order. A - // conditional step opts out by returning `undefined` synchronously and is - // never shown, so it must not be a `back` target: going back jumps straight - // to the most recently displayed step, skipping over any that were omitted. - const history: number[] = []; while (index < promptNames.length) { - // There is nowhere to go back to until at least one step has been shown, - // so `back` is disabled then (Shift+Tab does nothing) and enabled after. + // There is nowhere to go back to until a step has shown a prompt, so + // `back` is disabled then (Shift+Tab does nothing) and enabled after. setBackEnabled(history.length > 0); // Safe: the loop condition guarantees `index` is in range. const name = promptNames[index] as string; const prompt = prompts[name as keyof T]; - // `previous` lets a revisited step restore what the user had entered. - const step = prompt({ results, previous: results[name] }); - // Only a real prompt returns a thenable; a skipped conditional step - // returns `undefined`. We record the ones shown so `back` can skip the - // rest, and so the alias state above reflects what the user can see. - const displayed = typeof (step as Promise | undefined)?.then === 'function'; - const result = await step?.catch((e) => { - throw e; + frames = []; + const back = new Promise((resolve) => { + goBack = () => resolve(BACK); }); + // Going back leaves the step's prompt unresolved, so the step is abandoned + // rather than handed a value it does not expect. + const result = await Promise.race([prompt({ results, previous: results[name] }), back]); - // `back`: return to the most recently displayed step. Answers are kept - // (not discarded), so each step can offer them back via `previous`. - // Guarded against the case where nothing has been shown yet, in case a - // caller forces `back` there programmatically. - if (navigate && isBack(result)) { - if (history.length > 0) { - const from = name as keyof T; - index = history.pop() as number; - const to = promptNames[index] as keyof T; - opts?.onBack?.({ from, to, results }); + if (result === BACK) { + // Only offered once a step showed a prompt, so `history` is not empty. + const target = history.pop() as (typeof history)[number]; + // Erase, bottom up, what this step and the target left on screen so the + // target redraws in place. Steps in between showed no prompt. + for (const frame of [...target.frames, ...frames].reverse()) { + frame.output.write(cursor.move(-999, -frame.rows)); + frame.output.write(erase.down()); } + index = target.index; continue; } + if (frames.length > 0) { + history.push({ index, frames }); + } + // Pass the results to the onCancel function // so the user can decide what to do with the results // TODO: Switch to callback within core to avoid isCancel Fn if (typeof opts?.onCancel === 'function' && isCancel(result)) { results[name] = 'canceled'; opts.onCancel({ results }); - if (displayed) history.push(index); index++; continue; } results[name] = result; - if (displayed) history.push(index); index++; } } finally { setBackEnabled(false); + if (opts?.navigate) { + Prompt.navigator = parent; + } } return results; diff --git a/packages/prompts/src/index.ts b/packages/prompts/src/index.ts index 07151f93..766b0897 100644 --- a/packages/prompts/src/index.ts +++ b/packages/prompts/src/index.ts @@ -1,12 +1,5 @@ export type { ClackSettings } from '@clack/core'; -export { - BACK_SYMBOL, - CANCEL_SYMBOL, - isBack, - isCancel, - settings, - updateSettings, -} from '@clack/core'; +export { CANCEL_SYMBOL, isCancel, settings, updateSettings } from '@clack/core'; export * from './autocomplete.js'; export * from './box.js'; diff --git a/packages/prompts/test/group.test.ts b/packages/prompts/test/group.test.ts index 6acf18df..b9225ecc 100644 --- a/packages/prompts/test/group.test.ts +++ b/packages/prompts/test/group.test.ts @@ -1,278 +1,132 @@ -import { BACK_SYMBOL, CANCEL_SYMBOL, isBack, settings } from '@clack/core'; -import { afterEach, describe, expect, test, vi } from 'vitest'; +import type { Key } from 'node:readline'; +import { Prompt, settings } from '@clack/core'; +import { beforeEach, describe, expect, test } from 'vitest'; import * as prompts from '../src/index.js'; import { MockReadable, MockWritable } from './test-utils.js'; -const SHIFT_TAB = '\x1b[Z'; +const ENTER: Key = { name: 'return' }; +const DOWN: Key = { name: 'down' }; +const SHIFT_TAB: Key = { name: 'tab', shift: true, sequence: '\x1b[Z' }; + +// biome-ignore lint/suspicious/noControlCharactersInRegex: matching ANSI escapes is the point +const TERMINAL_TOKEN = /\x1b\[(\??)(\d*)([A-Za-z])|\n|[^\x1b\n]/gu; + +/** Replays `output` on a minimal terminal and returns what is left on screen. */ +function screen(output: MockWritable) { + const lines = ['']; + let row = 0; + let col = 0; + for (const [token, privateMode, n, command] of output.buffer.join('').matchAll(TERMINAL_TOKEN)) { + if (token === '\n') { + row++; + col = 0; + } else if (command === undefined) { + const line = (lines[row] ?? '').padEnd(col); + lines[row] = line.slice(0, col) + token + line.slice(col + 1); + col++; + } else if (!privateMode) { + const count = Number(n || 1); + if (command === 'A') row = Math.max(0, row - count); + if (command === 'B') row += count; + if (command === 'C') col += count; + if (command === 'D') col = Math.max(0, col - count); + if (command === 'G') col = 0; + if (command === 'K') lines[row] = ''; + if (command === 'J') { + lines[row] = (lines[row] ?? '').slice(0, col); + lines.length = row + 1; + } + } + lines[row] ??= ''; + } + return lines.join('\n').trimEnd(); +} describe('group', () => { - afterEach(() => { - settings.aliases.delete(SHIFT_TAB); - vi.restoreAllMocks(); - }); - - test('collects each prompt result into one object', async () => { - const result = await prompts.group({ - a: () => Promise.resolve('a1'), - b: () => Promise.resolve('b1'), - }); - expect(result).toEqual({ a: 'a1', b: 'b1' }); - }); - - test('a step returning BACK_SYMBOL returns to the previous step', async () => { - const visits: string[] = []; - let bWentBack = false; - const result = await prompts.group({ - a: () => { - visits.push('a'); - return Promise.resolve('a1'); - }, - b: () => { - visits.push('b'); - if (!bWentBack) { - bWentBack = true; - return Promise.resolve(BACK_SYMBOL); - } - return Promise.resolve('b1'); - }, - }); - expect(visits).toEqual(['a', 'b', 'a', 'b']); - expect(result).toEqual({ a: 'a1', b: 'b1' }); - }); - - test('offers the previous answer back to a revisited step', async () => { - const seenPrev: unknown[] = []; - let bWentBack = false; - await prompts.group({ - a: ({ previous }) => { - seenPrev.push(previous); - return Promise.resolve('a-val'); - }, - b: () => { - if (!bWentBack) { - bWentBack = true; - return Promise.resolve(BACK_SYMBOL); - } - return Promise.resolve('b-val'); - }, - }); - // `a` runs twice: first with no previous, then (after going back) with its kept answer. - expect(seenPrev).toEqual([undefined, 'a-val']); - }); - - test('preserves a submitted answer when returning to its step from further ahead', async () => { - const bPrev: unknown[] = []; - let cWentBack = false; - const result = await prompts.group({ - a: () => Promise.resolve('a'), - b: ({ previous }) => { - bPrev.push(previous); - return Promise.resolve('b-val'); - }, - c: () => { - if (!cWentBack) { - cWentBack = true; - return Promise.resolve(BACK_SYMBOL); - } - return Promise.resolve('c'); - }, - }); - // c goes back to b; b is re-offered its earlier answer. - expect(bPrev).toEqual([undefined, 'b-val']); - expect(result).toEqual({ a: 'a', b: 'b-val', c: 'c' }); - }); - - test('calls onBack with the step being left and the step returned to', async () => { - const onBack = vi.fn(); - let bWentBack = false; - await prompts.group( + let input: MockReadable; + let output: MockWritable; + let visits: string[]; + + beforeEach(() => { + input = new MockReadable(); + output = new MockWritable(); + visits = []; + }); + + /** A step showing a select over `x`/`y` that types the next batch of keys on each visit. */ + const select = (name: string, keysPerVisit: Key[][] = []) => { + let visit = 0; + return ({ previous }: { previous?: string }) => { + visits.push(name); + const result = prompts.select({ + message: name, + options: [{ value: 'x' }, { value: 'y' }], + initialValue: previous, + input, + output, + }); + for (const key of keysPerVisit[visit++] ?? [ENTER]) input.emit('keypress', '', key); + return result; + }; + }; + + test('goes back to the last step that showed a prompt and restores its answer', async () => { + const result = await prompts.group( { - a: () => Promise.resolve('a1'), - b: () => { - if (!bWentBack) { - bWentBack = true; - return Promise.resolve(BACK_SYMBOL); - } - return Promise.resolve('b1'); + a: select('a', [[DOWN, ENTER], [ENTER]]), + // Shows nothing, even though it is async. + b: async () => { + visits.push('b'); + return undefined; + }, + // Runs work without a prompt. + c: async () => { + visits.push('c'); + return 'done'; }, + d: select('d', [[SHIFT_TAB], [ENTER]]), }, - { onBack } + { navigate: true } ); - expect(onBack).toHaveBeenCalledTimes(1); - expect(onBack.mock.calls[0]?.[0]).toMatchObject({ from: 'b', to: 'a' }); - }); - test('disables back on the first step and enables it afterwards', async () => { - const aliasDuring: boolean[] = []; - let bWentBack = false; - await prompts.group({ - a: () => { - aliasDuring.push(settings.aliases.has(SHIFT_TAB)); - return Promise.resolve('a'); - }, - b: () => { - aliasDuring.push(settings.aliases.has(SHIFT_TAB)); - if (!bWentBack) { - bWentBack = true; - return Promise.resolve(BACK_SYMBOL); - } - return Promise.resolve('b'); - }, - }); - // a (root) -> off, b -> on, back to a -> off, b -> on. - expect(aliasDuring).toEqual([false, true, false, true]); + expect(visits).toEqual(['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']); + // `a` was offered `y` back as `previous`, so Enter kept it. + expect(result).toEqual({ a: 'y', b: undefined, c: 'done', d: 'x' }); + // Leaves no global state behind. + expect(Prompt.navigator).toBeUndefined(); + expect(settings.aliases.has(SHIFT_TAB.sequence as string)).toBe(false); }); - test('a forced BACK on the first step is ignored (re-runs, never goes out of range)', async () => { - let count = 0; - const result = await prompts.group({ - a: () => { - count++; - return Promise.resolve(count === 1 ? BACK_SYMBOL : 'a-final'); - }, - }); - expect(count).toBe(2); - expect(result).toEqual({ a: 'a-final' }); - }); - - test('going back past a skipped conditional step reaches the step before it', async () => { - const visits: string[] = []; - let cBack = 0; - const result = await prompts.group({ - a: () => { - visits.push('a'); - return Promise.resolve('a1'); - }, - // Conditional step: opts out by returning `undefined`, so it is never - // shown and must not be a `back` target. - b: () => { - visits.push('b'); - return undefined; - }, - c: () => { - visits.push('c'); - // Go back once (should land on `a`, not the skipped `b`), then answer. - if (cBack < 1) { - cBack++; - return Promise.resolve(BACK_SYMBOL); - } - return Promise.resolve('c1'); - }, - }); - // a -> b(skipped) -> c -> back -> a -> b(skipped) -> c. - expect(visits).toEqual(['a', 'b', 'c', 'a', 'b', 'c']); - expect(result).toEqual({ a: 'a1', b: undefined, c: 'c1' }); - }); - - test('onBack skips over a conditional step and reports the displayed step', async () => { - const onBack = vi.fn(); - let cBack = 0; + test('going back leaves the same screen as never going back', async () => { await prompts.group( - { - a: () => Promise.resolve('a1'), - b: () => undefined, - c: () => { - if (cBack < 1) { - cBack++; - return Promise.resolve(BACK_SYMBOL); - } - return Promise.resolve('c1'); - }, - }, - { onBack } + { a: select('a'), b: select('b'), c: select('c', [[SHIFT_TAB], [ENTER]]) }, + { navigate: true } ); - expect(onBack).toHaveBeenCalledTimes(1); - // Returns to `a`, the previous *displayed* step, not the skipped `b`. - expect(onBack.mock.calls[0]?.[0]).toMatchObject({ from: 'c', to: 'a' }); - }); + const withBack = screen(output); - test('navigate:false disables back and never binds Shift+Tab', async () => { - const result = await prompts.group( - { a: () => Promise.resolve(BACK_SYMBOL) }, - { navigate: false } - ); - expect(isBack(result.a)).toBe(true); - expect(settings.aliases.has(SHIFT_TAB)).toBe(false); - }); + output = new MockWritable(); + await prompts.group({ a: select('a'), b: select('b'), c: select('c') }, { navigate: true }); - test('restores the Shift+Tab alias state after running', async () => { - expect(settings.aliases.has(SHIFT_TAB)).toBe(false); - await prompts.group({ a: () => Promise.resolve('a1') }); - expect(settings.aliases.has(SHIFT_TAB)).toBe(false); + expect(withBack).toBe(screen(output)); }); - test('onCancel still fires and collects results', async () => { - const onCancel = vi.fn(); + test('Shift+Tab does nothing on the first step', async () => { const result = await prompts.group( - { - a: () => Promise.resolve('a1'), - b: () => Promise.resolve(CANCEL_SYMBOL), - }, - { onCancel } + { a: select('a', [[SHIFT_TAB, ENTER]]) }, + { navigate: true } ); - expect(onCancel).toHaveBeenCalledTimes(1); - expect(result).toMatchObject({ a: 'a1', b: 'canceled' }); - }); -}); -describe('back navigation (core wiring)', () => { - afterEach(() => { - settings.aliases.delete(SHIFT_TAB); + expect(visits).toEqual(['a']); + expect(result).toEqual({ a: 'x' }); }); - test('Shift+Tab resolves a text prompt to BACK_SYMBOL when the back action is bound', async () => { - settings.aliases.set(SHIFT_TAB, 'back'); - const input = new MockReadable(); - const output = new MockWritable(); - const result = prompts.text({ message: 'foo', input, output }); - input.emit('keypress', '', { name: 'tab', shift: true, sequence: SHIFT_TAB }); - const value = await result; - expect(isBack(value)).toBe(true); - }); - - test('going back leaves no "undefined" in the rendered output', async () => { - settings.aliases.set(SHIFT_TAB, 'back'); - const input = new MockReadable(); - const output = new MockWritable(); - const result = prompts.select({ - message: 'pick one', - options: [{ value: 'opt0' }, { value: 'opt1' }], - input, - output, - }); - input.emit('keypress', '', { name: 'tab', shift: true, sequence: SHIFT_TAB }); - await result; - expect(output.buffer.join('')).not.toContain('undefined'); - }); - - test('Shift+Tab resolves a select prompt to BACK_SYMBOL', async () => { - settings.aliases.set(SHIFT_TAB, 'back'); - const input = new MockReadable(); - const output = new MockWritable(); - const result = prompts.select({ - message: 'pick one', - options: [{ value: 'opt0' }, { value: 'opt1' }], - input, - output, + test('Shift+Tab does nothing unless navigate is enabled', async () => { + const result = await prompts.group({ + a: select('a'), + b: select('b', [[SHIFT_TAB, DOWN, ENTER]]), }); - input.emit('keypress', '', { name: 'tab', shift: true, sequence: SHIFT_TAB }); - const value = await result; - expect(isBack(value)).toBe(true); - }); - test('a select prompt without the back action is unaffected by Shift+Tab', async () => { - const input = new MockReadable(); - const output = new MockWritable(); - const result = prompts.select({ - message: 'pick one', - options: [{ value: 'opt0' }, { value: 'opt1' }], - input, - output, - }); - // No `back` alias bound: Shift+Tab does nothing, Enter still submits. - input.emit('keypress', '', { name: 'tab', shift: true, sequence: SHIFT_TAB }); - input.emit('keypress', '', { name: 'return' }); - const value = await result; - expect(value).toBe('opt0'); + expect(visits).toEqual(['a', 'b']); + expect(result).toEqual({ a: 'x', b: 'y' }); }); });