Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/few-months-accept.md
Original file line number Diff line number Diff line change
@@ -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`.
61 changes: 57 additions & 4 deletions packages/core/src/prompts/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,27 @@ export interface PromptOptions<TValue, Self extends Prompt<TValue>> {
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<TValue> {
/** @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<PromptOptions<TValue, Prompt<TValue>>, 'render' | 'input' | 'output'>;
Expand Down Expand Up @@ -158,6 +175,7 @@ export default class Prompt<TValue> {
this._abortSignal.addEventListener(
'abort',
() => {
if (this._closed) return;
this.state = 'cancel';
this.close();
},
Expand Down Expand Up @@ -249,6 +267,13 @@ export default class Prompt<TValue> {
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' });
Expand Down Expand Up @@ -315,18 +340,46 @@ export default class Prompt<TValue> {
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() {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/utils/settings.ts
Original file line number Diff line number Diff line change
@@ -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 = [
Expand Down
61 changes: 61 additions & 0 deletions packages/core/test/prompts/prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});
139 changes: 123 additions & 16 deletions packages/prompts/src/group.ts
Original file line number Diff line number Diff line change
@@ -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<T> = {
[P in keyof T]: T[P];
Expand All @@ -20,6 +25,17 @@ export interface PromptGroupOptions<T> {
* Called when any one of the prompts is canceled.
*/
onCancel?: (opts: { results: Prettify<Partial<PromptGroupAwaitedReturn<T>>> }) => 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;
}

/**
Expand All @@ -29,9 +45,23 @@ export interface PromptGroupOptions<T> {
export type PromptGroup<T> = {
[P in keyof T]: (opts: {
results: Prettify<Partial<PromptGroupAwaitedReturn<Omit<T, P>>>>;
/**
* This step's earlier answer when it is revisited with `navigate` enabled.
* Pass it to the prompt's `initialValue` to restore it.
*/
previous?: PromptGroupAwaitedReturn<T>[P];
}) => undefined | Promise<T[P] | undefined>;
};

/** 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
Expand All @@ -56,6 +86,18 @@ export type PromptGroup<T> = {
* }),
* });
* ```
*
* @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 <T>(
prompts: PromptGroup<T>,
Expand All @@ -64,22 +106,87 @@ export const group = async <T>(
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<typeof BACK>((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;
Expand Down
Loading
Loading