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/packages/core/src/prompts/prompt.ts b/packages/core/src/prompts/prompt.ts index 4b45612c..f548634a 100644 --- a/packages/core/src/prompts/prompt.ts +++ b/packages/core/src/prompts/prompt.ts @@ -39,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'>; @@ -158,6 +175,7 @@ export default class Prompt { this._abortSignal.addEventListener( 'abort', () => { + if (this._closed) return; this.state = 'cancel'; this.close(); }, @@ -249,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' }); @@ -315,18 +340,46 @@ export default class Prompt { this.input.removeListener('keypress', this.onKeypress); this.input.removeListener('end', this.onInputEnd); 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/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/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/group.ts b/packages/prompts/src/group.ts index 0e4b9246..78081d3b 100644 --- a/packages/prompts/src/group.ts +++ b/packages/prompts/src/group.ts @@ -1,4 +1,9 @@ -import { isCancel } 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'; type Prettify = { [P in keyof T]: T[P]; @@ -20,6 +25,17 @@ export interface PromptGroupOptions { * Called when any one of the prompts is canceled. */ onCancel?: (opts: { results: Prettify>> }) => void; + + /** + * 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 false + */ + navigate?: boolean; } /** @@ -29,9 +45,23 @@ export interface PromptGroupOptions { export type PromptGroup = { [P in keyof T]: (opts: { results: Prettify>>>; + /** + * 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 @@ -56,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, @@ -64,22 +106,87 @@ export const group = async ( const results = {} as any; const promptNames = Object.keys(prompts); - for (const name of promptNames) { - const prompt = prompts[name as keyof T]; - const result = await prompt({ results })?.catch((e) => { - throw e; - }); - - // 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; - } + // 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 = 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; + while (index < promptNames.length) { + // 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]; + 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]); - results[name] = result; + 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 }); + index++; + continue; + } + + results[name] = result; + index++; + } + } finally { + setBackEnabled(false); + if (opts?.navigate) { + Prompt.navigator = parent; + } } return results; diff --git a/packages/prompts/test/group.test.ts b/packages/prompts/test/group.test.ts new file mode 100644 index 00000000..b9225ecc --- /dev/null +++ b/packages/prompts/test/group.test.ts @@ -0,0 +1,132 @@ +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 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', () => { + 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: 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]]), + }, + { navigate: 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('going back leaves the same screen as never going back', async () => { + await prompts.group( + { a: select('a'), b: select('b'), c: select('c', [[SHIFT_TAB], [ENTER]]) }, + { navigate: true } + ); + const withBack = screen(output); + + output = new MockWritable(); + await prompts.group({ a: select('a'), b: select('b'), c: select('c') }, { navigate: true }); + + expect(withBack).toBe(screen(output)); + }); + + test('Shift+Tab does nothing on the first step', async () => { + const result = await prompts.group( + { a: select('a', [[SHIFT_TAB, ENTER]]) }, + { navigate: true } + ); + + expect(visits).toEqual(['a']); + expect(result).toEqual({ a: 'x' }); + }); + + 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]]), + }); + + expect(visits).toEqual(['a', 'b']); + expect(result).toEqual({ a: 'x', b: 'y' }); + }); +});