Skip to content

Commit

Permalink
Refactor(@inquirer/core) Remove direct store handling from createProm…
Browse files Browse the repository at this point in the history
…pt()
  • Loading branch information
SBoudrias committed Jul 29, 2024
1 parent 3b99af9 commit 47d2331
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
15 changes: 5 additions & 10 deletions packages/core/src/lib/create-prompt.mts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function createPrompt<Value, Config>(view: ViewFunction<Value, Config>) {

let cancel: () => void = () => {};
const answer = new CancelablePromise<Value>((resolve, reject) => {
withHooks(rl, (store) => {
withHooks(rl, (cycle) => {
function checkCursorPos() {
screen.checkCursorPos();
}
Expand All @@ -58,7 +58,7 @@ export function createPrompt<Value, Config>(view: ViewFunction<Value, Config>) {
screen.done();

removeExitListener();
store.rl.input.removeListener('keypress', checkCursorPos);
rl.input.removeListener('keypress', checkCursorPos);
});

cancel = () => {
Expand All @@ -76,9 +76,7 @@ export function createPrompt<Value, Config>(view: ViewFunction<Value, Config>) {
});
}

function workLoop() {
store.index = 0;

cycle(() => {
try {
const nextView = view(config, done);

Expand All @@ -91,16 +89,13 @@ export function createPrompt<Value, Config>(view: ViewFunction<Value, Config>) {
onExit();
reject(error);
}
}

store.handleChange = () => workLoop();
workLoop();
});

// Re-renders only happen when the state change; but the readline cursor could change position
// and that also requires a re-render (and a manual one because we mute the streams).
// We set the listener after the initial workLoop to avoid a double render if render triggered
// by a state change sets the cursor to the right position.
store.rl.input.on('keypress', checkCursorPos);
rl.input.on('keypress', checkCursorPos);
});
});

Expand Down
16 changes: 14 additions & 2 deletions packages/core/src/lib/hook-engine.mts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,22 @@ function createStore(rl: InquirerReadline) {
}

// Run callback in with the hook engine setup.
export function withHooks(rl: InquirerReadline, cb: (store: HookStore) => void) {
export function withHooks(
rl: InquirerReadline,
cb: (cycle: (render: () => void) => void) => void,
) {
const store = createStore(rl);
return hookStorage.run(store, () => {
cb(store);
function cycle(render: () => void) {
store.handleChange = () => {
store.index = 0;
render();
};

store.handleChange();
}

cb(cycle);
});
}

Expand Down

0 comments on commit 47d2331

Please sign in to comment.