Repository navigation
feat(prompts): add back navigation to group (#39) - #617
StringerBell69 wants to merge 3 commits into
Conversation
🦋 Changeset detectedLatest commit: 9e3fe06 The changes in this PR will be included in the next version bump. This PR includes changesets to release 2 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
8fb6fce to
8c4775b
Compare
|
hey @StringerBell69, thanks for picking this up! before i review, could you update the description to follow our pr template? looks like your agent wrote its own structure instead, so the type of change, checklist and ai disclosure sections are missing. i'd also love a short description in your own words of how you tackled this, it helps a lot to know where to focus on a change this size. and since the description says it's a draft for design feedback, could you mark the pr as draft too? |
|
I was building a CLI with clack (with Claude's help) and got really annoyed when I made a wrong move and couldn't go back a step. I thought it was a misconfiguration on my end. I figured that someone else had probably hit the same thing, so I asked how to add a back option in the least intrusive way, without denaturing the app. That's why the whole thing is modeled on the existing I built this with Claude, but I reviewed the design and the full diff and ran the tests locally. Happy to adjust the approach. I'll be on my way back from school, so I won't be as responsive. (wrote this in french and asked claude to translate) |
|
Hello, and thanks for this PR. I also miss the ability to go back: I maintain a CLI built with Within const result = await prompts.group({
migration: () => prompts.select({ message: 'Migrations', options: [/* flyway, liquibase */] }),
liquibaseFormat: ({ results }) =>
results.migration === 'liquibase' ? prompts.select({ /* ... */ }) : undefined,
libs: () => prompts.multiselect({ /* ... */ }),
});If the user selects Flyway and then presses Shift+Tab while at the
The cause: after A possible solution: keep a history of the steps that have been displayed. Navigating back would then return directly to the most recently viewed step, without re-traversing the skipped steps. I reproduced the blockage on the branch (commit 8c4775b) using this test import { BACK_SYMBOL } from '@clack/core';
import { expect, test } from 'vitest';
import * as prompts from '../src/index.js';
test('going back past a skipped (conditional) step reaches the step before it', async () => {
const visits: string[] = [];
let cBack = 0;
await prompts.group({
a: () => {
visits.push('a');
return Promise.resolve('a1');
},
b: () => {
visits.push('b');
return undefined; // conditional step, skipped
},
c: () => {
visits.push('c');
// The user presses Shift+Tab twice, then answers.
if (cBack < 2) {
cBack++;
return Promise.resolve(BACK_SYMBOL);
}
return Promise.resolve('c1');
},
});
expect(visits.filter((v) => v === 'a').length).toBeGreaterThan(1);
});Result: Drafted with AI assistance; I reviewed it. |
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 bombshell-dev#39
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.
8c4775b to
032ddab
Compare
commit: |
dreyfus92
left a comment
There was a problem hiding this comment.
hey @StringerBell69, thanks for the fix on the skipped steps, and thanks @anthonydeseille for the repro 🙌 i pulled the branch and played with it, left a few comments inline. the main ones are the stuck back navigation on async steps and the type hole, the rest is cleanup
cc. @43081j for a second look on the design
| // 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<unknown> | undefined)?.then === 'function'; |
There was a problem hiding this comment.
an async conditional step still gets stuck here since it always returns a promise. anthony's test with b: async () => undefined gives a, b, c, b, c, b, c. same with a non-prompt step like a spinner task, it re-runs every time you go back and you can't get past it
There was a problem hiding this comment.
Fixed in 9e3fe06. A step now counts as shown only if a prompt actually finished during it (core reports it to group), so async () => undefined and non-prompt steps like a spinner task are skipped going back, and run again going forward. Covered by the lifecycle test.
| 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(); |
There was a problem hiding this comment.
this only erases the step you're leaving, so the steps you go back to get printed twice. going back from ok? to name? leaves name? paul / color? blue on screen two times
There was a problem hiding this comment.
Fixed. Each finished prompt now reports how many rows it left on screen, and going back erases the step you return to before it redraws. There's a test that replays the output on a tiny terminal and checks the screen is the same as never going back.
|
|
||
| public prompt() { | ||
| return new Promise<TValue | typeof CANCEL_SYMBOL | undefined>((resolve) => { | ||
| type Resolution = TValue | typeof CANCEL_SYMBOL | typeof BACK_SYMBOL | undefined; |
There was a problem hiding this comment.
text() and friends still cast this to T | typeof CANCEL_SYMBOL, so a step that awaits a prompt inside it gets BACK_SYMBOL typed as a string. if (isCancel(city)) return; city.toUpperCase() typechecks and throws on shift+tab
There was a problem hiding this comment.
Good catch. I changed the mechanism so a step never sees a back value: on Shift+Tab the prompt no longer resolves, group abandons the step and moves back. That removes BACK_SYMBOL entirely, so the type hole is gone. The tradeoff is that code after the await in an abandoned step never runs. Since this is a design change, happy to go back to BACK_SYMBOL with opt-in only if you and 43081j prefer.
| ): Promise<Prettify<PromptGroupAwaitedReturn<T>>> => { | ||
| const results = {} as any; | ||
| const promptNames = Object.keys(prompts); | ||
| const navigate = opts?.navigate !== false; |
There was a problem hiding this comment.
because of the type thing above, i'm wondering if this should be opt-in instead of on by default, since existing groups could break without changing anything
There was a problem hiding this comment.
Agreed, navigate now defaults to false, so existing groups behave exactly as before.
| // 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); |
There was a problem hiding this comment.
not sure about group toggling the global shift+tab alias while it runs, @43081j what do you think?
There was a problem hiding this comment.
Left this as is for now until 43081j weighs in.
| export type { ClackSettings } from '@clack/core'; | ||
| export { CANCEL_SYMBOL, isCancel, settings, updateSettings } from '@clack/core'; | ||
| export { | ||
| BACK_SYMBOL, |
There was a problem hiding this comment.
this is a fair bit of new public api (BACK_SYMBOL, isBack, a back state, navigate, onBack, previous). could we trim it to what group actually needs?
There was a problem hiding this comment.
Trimmed: BACK_SYMBOL, isBack, the back state and event, and onBack are gone. What's left is navigate and previous on group, the back action (so the key can be remapped like cancel), and a Prompt.navigator hook marked @internal that group uses.
| }); | ||
| }); | ||
|
|
||
| describe('back navigation (core wiring)', () => { |
There was a problem hiding this comment.
the tests feel like a lot for this change, 16 tests and almost 280 lines with quite a bit of overlap. could we fold the back/previous/onBack/skip cases into one lifecycle test, keep the first step and navigate: false ones, and move these keypress tests to packages/core/test since that's what they cover?
There was a problem hiding this comment.
Done: one lifecycle test (going back over an async empty step and a non-prompt step, answer restored), the first step and navigate: false ones, plus one screen test for the double print. The keypress tests moved to packages/core/test/prompts/prompt.test.ts.
| --- | ||
| '@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. |
There was a problem hiding this comment.
could you regenerate this with pnpm changeset? looks hand written and it's pretty long for a changelog entry. one or two sentences on what users get is plenty, the implementation details and closes #39 can live in the pr description
There was a problem hiding this comment.
Regenerated with pnpm changeset, it's one sentence now. The details and closes #39 are going in the PR description.
- 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.
|
Thanks @dreyfus92 for trying it out and for the detailed review, and @anthonydeseille for the original repro. Pushed 9e3fe06, replies are inline. @43081j one design point for your second look: to fix the type hole and trim the API, going back no longer resolves the prompt with a Known limitations:
|
What does this PR do?
Adds opt-in back navigation to the
group()utility. Withgroup(prompts, { navigate: true }), pressing Shift+Tab returns to the previous step that showed a prompt. Answers are kept, and each step receives its earlier answer asprevious, so passing it toinitialValuerestores what was entered. Back does nothing until a step has shown a prompt, and nothing changes for groups that don't opt in.How I approached it (in my own words): I was building a CLI with clack (with Claude's help) and got really annoyed when I made a wrong keystroke and couldn't go back a step. I figured clack probably had this requested already if it was open source — found #39 — and wanted the least intrusive way to add a back option without changing how clack works for everyone else.
How it works
backaction, unbound by default, so standalone prompts behave exactly as before.Promptgets an internalPrompt.navigatorhook (marked@internal) thatgroupinstalls while it runs:backis pressed and the navigator allows it, the prompt erases its frame, tears down, and tells the navigator, without resolving. Steps never receive a back value, so there is no new symbol to type or check;group()keeps a history of the steps that actually showed a prompt. Going back abandons the current step, erases what the target step left on screen, and reruns it withprevious. Steps that showed no prompt (skipped conditional steps, async steps returningundefined, tasks) are passed over going back and run again going forward.groupbindsShift+Tabtobackonly while a step that can go back is showing, and restores the previous alias state afterwards.Known limitations
date, Shift+Tab goes back to the previous step instead of the previous segment once going back is possible.awaitin an abandoned step doesn't run.Closes #39
Type of change
Checklist
pnpm testpasses (the only failing tests are 4 pre-existingnote.test.tssnapshot cases that also fail onmainin my environment, unrelated to this PR)pnpm formathas been runAI-generated code disclosure
Built with Claude (Anthropic). I described the problem and the "least intrusive" constraint, reviewed the design and the full diff, and ran the tests locally. Flagging it so reviewers can pay extra attention to the core keypress/render edges (the unresolved prompt on back, the row counting used to erase) and the
group()alias handling.