mokkabonna / inquirer-autocomplete-prompt

Autocomplete prompt for inquirer
ISC License
354 stars 82 forks source link

Better support for default value #121

Closed benoit-hocquet closed 3 years ago

benoit-hocquet commented 4 years ago

Hello, first off, thanks you so much for your very good library. I'm having some minor troubles with default values.

Description

I have to make database searches with autocomplete for user. I want the autocomplete to return me an id, but to search by username, so I have to carry an object with {name, value}, which already works great.

The problem arises when I want to select a default user.

Code

async function issueWithDefault(){

    const inquirer = require("inquirer");
    inquirer.registerPrompt(
      "autocomplete",
      require("inquirer-autocomplete-prompt")
    );

    const dummyDB = [
        {username:"joe",_id:1},
        {username:"mikael",_id:2},
        {username:"roy",_id:3},
        {username:"dennis",_id:4},
        {username:"edward",_id:5},
        {username:"john",_id:6},
        {username:"michelle",_id:7},
        {username:"johnatan",_id:8},
    ];

    //Search dummyDB, returns list of {name,value}.
    const source = async function(answersSoFar,input){
          const user =  await dummyDB.filter(u => new RegExp(".*"+input+".*").exec(u.username))
          return user.map(u=>({name:u.username,value:u._id}))
    }

    const promptObj = {
        type: "autocomplete",
        default:4,
        name: "user",
        message: "Type a username",
        source: source
      }

     const rslt = await inquirer.prompt([promptObj]);

     console.log(rslt);
}

issueWithDefault();

The prompt shows the id, not the username (which is expected since I only entered the id as a default value, see code above, default:4).

? Type a username (4) (Use arrow keys or type to search)
  No results...

Proposal

The default should be able to take an object with {value, name} keys so that prompt will be able to show the username instead of an ID.

    const promptObj = {
        type: "autocomplete",
        default:{name:"dennis",value:4},
        name: "user",
        message: "Type a username",
        source: source
      }

Current behaviour

? Type a username ([object Object]) (Use arrow keys or type to search)
  No results...

Expected behaviour

? Type a username (dennis) (Use arrow keys or type to search)
  No results...
mokkabonna commented 3 years ago

Thanks for contributing!

Actually I consider it a bug on my part that the default value is shown at all when suggestOnly is false. So in list mode.

Inquirer list mode does not show default value next to the question but selects it if it is in the list.

So I will be removing showing of (4) in this case.

When suggestOnly is true it is in normal input mode and it will be shown as normal, but that is a raw text input so it is fine.