Inquirer.js icon indicating copy to clipboard operation
Inquirer.js copied to clipboard

when i accidentally hit enter before propts appeared, propts will receive this enter

Open kongku opened this issue 1 year ago • 3 comments

when i accidentally hit enter before propts appeared, propts will receive this enter,How to fix this situation?

import { select } from '@inquirer/prompts'

console.log('wait.....')

setTimeout(() => {
  select({
    message: 'select',
    choices: [
      { name: 'a', value: 'a' },
      { name: 'b', value: 'b' },
      { name: 'c', value: 'c' },
    ],
  })
}, 2000)

kongku avatar Sep 12 '23 06:09 kongku

Thanks for the bug report and the code example. I can reproduce it with your snippet easily.

This is a weird behaviour because at the time we press "enter", the readline isn't set, and there's no keypress listener. So it's like there's some kind of replay of the events.

SBoudrias avatar Sep 16 '23 11:09 SBoudrias

Using a debugger helps me find out what might be the cause of the problem.

In create-prompt.mts

  const prompt: Prompt<Value, Config> = (config, context) => {
    // Default `input` to stdin
    const input = context?.input ?? process.stdin;

    // Add mute capabilities to the output
    const output = new MuteStream();
    output.pipe(context?.output ?? process.stdout);

    const rl = readline.createInterface({
      terminal: true,
      input,
      output,
    }) as InquirerReadline;
    const screen = new ScreenManager(rl);

Even though rl is set here, the ReadableStream (process.stdin) already has data from user in the stream when an enter key is pressed.

After the 2 seconds wait, the readline would register keypress event automatically for the input ("This is automatically called by any readline instance on its input if the input is a terminal." from Node's doc) and the data hasn't been read in input would emit the keypress events.

Haven't thought of a good solution to the problem for now, but I would like to share what I found.

PoHengLinTW avatar Jul 20 '24 03:07 PoHengLinTW

Yeah that's the problem. I tried a few approach, but can't get to flush the stdin before the prompt shows...

SBoudrias avatar Jul 20 '24 18:07 SBoudrias