mokkabonna / inquirer-autocomplete-prompt Goto Github PK
View Code? Open in Web Editor NEWAutocomplete prompt for inquirer
License: ISC License
Autocomplete prompt for inquirer
License: ISC License
Hi there!
Following-up on d46752f#commitcomment-75535326, would you mind adding release notes to https://github.com/mokkabonna/inquirer-autocomplete-prompt/releases/tag/v2.0.0 so we have a list of changes and, more importantly, breaking changes between 1.4.0 and 2.0.0?
That would give us some guidance and peace of mind before we can upgrade it on our codebase :)
Thank you!
Hello,
How add in Yeoman ?
Thank you
I have a use-case for an attribute that I'd like to contribute, but before I do I'm curious if it's something you'd be open to accepting:
alwaysValidate
: boolean (default: false)Generically speaking, there's something to be said for forcing validation, even if the list is limited. To keep inquirer's pizza
example, what if the Pizza API has an ingredients API, but a separate one to confirm whether they have an ingredient in supply?
In my use-case, I want to scaffold a test for a component. I do a glob for component files in the project to prepopulate the list, but then have to do some poking around to see if there's a test already maybe (we have some non-standard locations so I have to brute-force it a bit).
I can write the code & tests myself and submit a PR, but I thought it prudent to gauge interest first :).
Because of the rotating nature of the selection list, if the list size is greater than pageSize
, I'd like to put a separator at the end of my list. Adding new inquirer.Separator()
to the choices
array works for type "list", but it appears to be omitted in the "autocomplete" version.
Please create a typings file so Typescript users could enjoy this package.
Thanks :)
Hi I am doing like this, but it answers returns empty string
function searchUser(answers, input) {
var names = [ { name: "Test1", accountId: "a746hsjikel" }, { name: "Test2", accountId: "982bjkkgkbnd" } ]
return new Promise(function(resolve) {
setTimeout(function() {
var options = {
extract: function(el) {
return el.name;
}
};
var fuzzyResult = fuzzy.filter(input, names, options);
resolve(
fuzzyResult.map(function(el) {
return el.string;
})
);
}, 2000);
});
}
inquirer
.prompt([
{
type: "autocomplete",
name: "test",
message: "Search user",
source: searchUsers,
pageSize: 4,
suggestOnly: true
}
])
.then(function(answers) {
console.log(JSON.stringify(answers, null, 2));
});
test
Hi,
I'm really interested in this plugin. I also just discovered inquirer, so I'm not very experienced with it.
I do know that the question type "list" works fine. But autocomplete doesn't show any reaction. I can't input any text nor can I select values from the list. The initial content of the list works fine though.
I've created this little test script:
'use strict';
const inquirer = require('inquirer');
inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'));
inquirer.prompt([
{
type: 'autocomplete',
name: 'first',
message: 'What do you want to do?',
source: (answers, input) => {
return new Promise((resolve, reject) => {
resolve([input + ' 1', input + ' 2', input + ' 3']);
});
}
}
], answers => {
console.log(JSON.stringify(answers));
});
When I start it I get the output, which is fine obviously:
? What do you want to do? (Use arrow keys or type to search)
> null 1
null 2
null 3
But after showing the question the script basically "freezes". I can accept the first entry with enter
or stop it with Ctrl
+ C
.
Currently the version of rxjs used in this project is the same as inquirer 6.x. This doesn't allow flattening of deps if one is using the latest inquirer 8.x. And, unfortunately, rxjs is a huge dependency with ~3K files :/ https://packagephobia.com/result?p=rxjs%406.6.7%2Crxjs%407.5.2
Could you update to the latest version please? Or even better, see if you could drop/replace rxjs? If you manage to drop/replace it, it doesn't even need to be a major version.
Thanks!
inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'))
I get this error in the editor: "Could not find a declaration file for module 'inquirer-autocomplete-prompt'. '/Users/lando/Documents/Code/nt-cli/node_modules/inquirer-autocomplete-prompt/index.js' implicitly has an 'any' type."
When I try to run my inquirer script, it works up until I get to the autocomplete prompt then hangs.
`
const inquirer = require('inquirer')
var _ = require('lodash')
inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'))
var foods = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Lichi', 'Grapefruit'];
function searchFood(answers, input) {
input = input || ''
return new Promise(function(resolve) {
setTimeout(function() {
var fuzzyResult = fuzzy.filter(input, foods)
resolve(
fuzzyResult.map(function(el) {
return el.original
})
)
}, _.random(30, 500))
})
}
program
.command('add')
.alias('a')
.action(() => {
inquirer
.prompt([
{
message: 'What is the note name?',
type: 'input',
name: 'name',
validate: function checkForDuplicates(name) {
return Note.findOne({name : name})
.then(note => note ? 'Note already exists' : true)
},
},
{
message: 'Please enter the content',
type: 'input',
name: 'content',
},
{
type: 'autocomplete',
name: 'fruit',
suggestOnly: true,
message: 'What is your favorite fruit?',
source: searchFood,
pageSize: 4,
validate: function(val) {
return val ? true : 'Type something!'
},
},
])`
I'm looking for an inquirer plugin that would present a list as a starting off point but allow for an arbitrary string if the list doesn't have what the user wants. This module looks like a great starting point. Do you have any guidance on where to tweak it for that behavior?
Hey! 👋
Thanks for building & maintaining inquirer-autocomplete-prompt
!
We've been using inquirer-autocomplete-prompt
in our project ClearTax/pivotal-flow with [email protected]
for a while now without any issues (as per our use case).
Just wondering if there are any plans to support that version officially in inquirer-autocomplete-prompt
- since it keeps showing peer dependency warnings.
At the moment, the source
parameter is a function that takes in two parameters: answers
and input
That means that if I want to use answers
to decide which choices are available and input
to sort them, I have to do it like this:
source: (answers, input) => {
const choices = getChoicesFromAnswers(answers);
return filterChoices(choices, input);
}
There is no way to set this up so that getChoicesFromAnswers
doesn't get called every time input
changes (without implementing caching myself)
It would be nice to have it split into two functions, the first takes in answers
and returns another function which takes in input
, the result of which is the filtering
source: (answers) => {
const choices = getChoicesFromAnswers(answers);
return (input) => filterChoices(choices, input);
}
That way getChoicesFromAnswers
isn't called every time input
changes
Tests fail because istanbul has no coverage files
No coverage information was collected, exit without writing coverage information
> [email protected] posttest /Users/mike/wrk/test/inquirer-autocomplete-prompt
> istanbul check-coverage --statements 85 --branches 70 --functions 100 --lines 90 && rm -rf coverage
/Users/mike/wrk/test/inquirer-autocomplete-prompt/node_modules/istanbul/lib/cli.js:38
throw ex; // turn it into an uncaught exception
^
ERROR: No coverage files found.
npm ERR! Test failed. See above for more details.
I'm currently using a command line api that allows you to pass in a name
to identify which projected the user wants to compile, and if the user passes is s
as their name
argument it's not going to match anything in the exactly but it would reduce the initial list that's displayed if I could pass in an initial
option that would be the first thing passed into the source
function instead of null
Here's some screenshots of what I'm talking about.
Currently this is what's happening. If the user passes in a name that's not an exact match my app will return throw that warning and run the auto complete prompt, and the list is untouched.
Here's what I would like it to look like if there was a initial search term. Where the initial search term was s
and it shows the matched results based off of s
.
Thanks for a great plugin! Really enjoy it.
I got tripped up with the default value of the input
parameter of the source function.
const exampleSearch = async (answers, input = "") => {
// since `null` is passed to input, default parameters won't work here
}
I see in your example you are doing something like input = input || ""
but I was curious if the value can be undefined
and work just as well. This would allow for default parameters to work instead of overloading the parameter on the first line of the function.
Hello, first off, thanks you so much for your very good library. I'm having some minor troubles with default values.
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.
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...
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
}
? Type a username ([object Object]) (Use arrow keys or type to search)
No results...
? Type a username (dennis) (Use arrow keys or type to search)
No results...
Attempting to update my project deps from inquirer v8.2.4 to v9.0.2, I encounter this error.
$ npm update
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/inquirer
npm ERR! dev inquirer@"^9.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer inquirer@"^8.0.0" from [email protected]
npm ERR! node_modules/inquirer-autocomplete-prompt
npm ERR! dev inquirer-autocomplete-prompt@"2.0.0" from the root project
inquirer-autocomplete-prompt/index.js
Line 16 in 47a42bc
Yarn@2
doesn't allow hidden dependencies, so I get an Error when I'm trying to use inquirer-autocomplete-prompt
:
Error: inquirer-autocomplete-prompt tried to access rxjs, but it isn't declared in its dependencies; this makes the require call ambiguous and unsound.
I was wondering if this prompt can allow multiple options to be selected
I don't see a mention in the docs about this.
Thanks for this great autocompleter!
Is it difficult to make source not promise (single resolve) but stream-like, that would allow periodical update of the suggestions without user input?
Off the top of your head, do you know if it would be possible to implement pagination when the user scrolls down far enough in the search results? Or is it impossible to get notified by inquirer
that that's happened?
I want to make helpers for selecting AWS resources, and it would be nice to be able to use AWS pagination.
On the other hand, I want to cache and immediately show recent selections while new results are being fetched, which probably isn't possible with this...maybe I should make my own thing that doesn't rely on inquirer
...
To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:
.travis.yml
If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.
Greenkeeper has checked the engines
key in any package.json
file, the .nvmrc
file, and the .travis.yml
file, if present.
engines
was only updated if it defined a single version, not a range..nvmrc
was updated to Node.js 10.travis.yml
was only changed if there was a root-level node_js
that didn’t already include Node.js 10, such as node
or lts/*
. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.For many simpler .travis.yml
configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Often for lists and choices inquirer supports objects containing name, value and short properties for display, resulting value and displayed short value after selection.
It seems like autocomplete only accepts strings currently. I'd like to request the above as a feature.
If you are just doing a local search, then it flickers. A delay option would solve this. Maybe the loading effect could be a configurable callback too...
filter
is not applied to the selected value / answer. To reproduce adjust your example.js
file prompts to:
{
type: 'autocomplete',
name: 'fruit',
suggestOnly: true,
message: 'What is your favorite fruit?',
source: searchFood,
pageSize: 4,
filter: answer => answer.slice(0, 2),
validate: function(val) {
return val ? true : 'Type something!';
},
}, {
type: 'autocomplete',
name: 'state',
message: 'Select a state to travel from',
source: searchStates,
filter: answer => answer.slice(0, 2),
},
Notice the values remain unchained.
Why don't we mention inquirer
as a peer dependency in this project rather than using it as a dependency?
Also, can we upgrade inquirer to version 5.1.0
It'd be really useful to make the bottomContent configurable.
It'll allow for a much better user experience - providing pertinent feedback on what to do to fix the "no results" case, since that varies by prompt.
Thank you very much for building this amazing tool!
I find it weird that the initial search string being passed to source
is set to null
. I think it would make more sense if ''
is passed. Is there any philosophy behind this decision?
Would be happy to submit a pull request to change this.
Hello, me again :D
So the recent filter update you made works great, thanks again for adding that! In default inquirer
prompts, if you supply a filter, that filter value will become the answer in the UI.
I've provided a gif to make it easier to explain what I mean. Notice the default input
type prompt's display answer is converted to ab
even though abc123
was entered. However in the autocomplete prompt
the answer value is not changed even though a filter is supplied. The filter for both prompts is simply: answer.slice(0, 2)
.
Whenever I type something /[^A-Z]/i
, it crashes with TypeError: Cannot read property 'name' of undefined
.
got this error when the module is invoked.
Error: Cannot find module 'rxjs/operators'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object. (/path/to/mypackage/node_modules/inquirer-autocomplete-prompt/index.js:16:21)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
{
type: 'autocomplete',
name: 'name',
message: 'which do you choose?',
source: (answersSoFar, input) => search(input),
suggestOnly: true,
validate: value => console.log(value)
}
using
"inquirer-autocomplete-prompt": "^0.11.0",
value passed to validate is empty, search is async.
It would also be nice if I could validate an input even when suggestOnly is false. There are times when I want to check async things and the validate step is the most appropriate place to do it.
sometimes, we fetch data(a list for object) to auto-complete-select, but which key in each object should to be the "Display Name"?
For Now: I need store the data's key mapping, after user select a item, use regular express to get the key, and get the result. It's too troublesome.
Getting the follow exception after attempting to tab complete with suggestOnly: true
TypeError: Cannot read property 'length' of null at InquirerFuzzyPath.Prompt.onKeypress (/Users/jranz/amplify/amplify-cli/packages/amplify-category-xr/node_modules/inquirer-autocomplete-prompt/index.js:221:61) ...
https://github.com/mokkabonna/inquirer-autocomplete-prompt/blob/master/index.js#L215
Related to: adelsz/inquirer-fuzzy-path#7
It crashes when I tab on "Tab" button for autocomplete. This is how I works with inquirer modules.
await inquirer.prompt([
{
type: "autocomplete",
name: "product",
message: `test`,
suggestOnly: true,
source: function (ans, input) {
return new Promise(async function (res) {
const search = input
? await Product.find({
name: { $regex: new RegExp(input, `i`) },
}).lean()
: [];
const choices = search.map((x) => ({
name: x.name,
value: x,
}));
res(choices);
});
},
},
]);
This error happens when I set value as object to the source
function. Once I changed back the value to string, It works fine.
Hi, I am seeing a weird behavior using suggestOnly=true.
suppose I start typing and autocomplete returns a list of options, and then I hit <TAB> to pick one. If I decide to change my answer, I have to type <BACKSPACE> several times before it actually starts modifying the live contents of the prompt.
I would expect the desired behavior would be for the live input string to be transformed to the chosen autocomplete value when pressing <TAB>, then upon receiving a <BACKSPACE> to immediately make the live value start erasing the last character.
How can I ask the user for multiple values in one question, something similar to http://peterkaleta.github.io/react-token-autocomplete/?
Hello mokkabonna
i am using this module and found an issue. Prefix and suffix is missing from base.js file. i am using inquirer which is supporting prefix and suffix and was presuming that this module is using inquirer as it is as dependency but i was wrong i have gone through the files and manually added prefix and suffix in my local node_module.
this.opt = _.defaults(_.clone(question), {
validate: function () {
return true;
},
filter: function (val) {
return val;
},
when: function () {
return true;
},
suffix: '',
prefix: chalk.green('?')
});
Prompt.prototype.getQuestion = function () {
var message = this.opt.prefix + ' ' + chalk.bold(this.opt.message) + this.opt.suffix + chalk.reset(' ');
.......
}
I'd really like to specify the default when using this module. All I want is the cursor to start on the item who's string matches the default value, if specified.
I'm willing to do the work and create a PR if you are open to this extention.
Would be awesome if command arguments could be tab-completed. For example with the command prog.command('install <cms>')
, you could specify some options for <cms>
, so let's say Wordpress or Drupal, and when I'm typing out the command if I type Wo
and press tab then it would autocomplete to Wordpress. Similar to Vorpal's autocomplete
It is common to select multiple items in 'choices'; an idea will be to modify the 'onSubmit' callback and distinguish between an action to pick current selected item and an action to continue to next prompt.
How to use this library with typescript? It's said no typings were found
You might already have gotten the data before the prompt is created. Instead of forcing me to wrap my results in a promise, it would be nice if you just did: Promise.resolve().then(() => opts.source)
.
Note, I'm intentionally not suggesting Promise.resolve(opts.source())
as that would not catch any synchronous error.
Right now, I'm doing:
source: (answers, input) => Promise.resolve().then(() => filterProcesses(input, processes))
Hello !
Package fails to install after inquirer last update to 8.0.0.
$ npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/inquirer
npm ERR! inquirer@"^8.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer inquirer@"^5.0.0 || ^6.0.0 || ^7.0.0" from [email protected]
npm ERR! node_modules/inquirer-autocomplete-prompt
npm ERR! inquirer-autocomplete-prompt@"^1.3.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
I don't see a way to autocomplete multiple items. For instance, if I wanted a user to be able to tab-autocomplete multiple inputs on the same line, each separated by a comma (e.g.,my-selection-1, my-selection-2
).
Is this a feature that is going to be added in the future?
Default inquirer transformer
option is not working with this plugin. Looking at the sources, it looks like it is not handled at all.
Is there an alternative way to transform the data returned by the source
?
const inquirer = require('inquirer')
const autocomplete = require('inquirer-autocomplete-prompt')
const array = ['red', 'green', 'blue', 'yellow']
inquirer.registerPrompt('autocomplete', autocomplete)
inquirer.prompt({
type: 'autocomplete',
name: 'server',
message: 'Select a server to sync mods with',
source: (answersSoFar, input) => {
return array.filter(e => e.startsWith(input))
},
})
process.on('unhandledRejection', err => console.log(err))
TypeError: thisPromise.then is not a function
at Prompt.search (D:\Yuta\Desktop\node_modules\inquirer-autocomplete-prompt\index.js:186:22)
at Prompt._run (D:\Yuta\Desktop\node_modules\inquirer-autocomplete-prompt\index.js:71:8)
at Prompt.<anonymous> (D:\Yuta\Desktop\node_modules\inquirer-autocomplete-prompt\node_modules\inquirer\lib\prompts\base.js:56:10)
at new Promise (<anonymous>)
at Prompt.run (D:\Yuta\Desktop\node_modules\inquirer-autocomplete-prompt\node_modules\inquirer\lib\prompts\base.js:55:10)
at DeferSubscriber.Rx.Observable.defer [as factory] (D:\Yuta\Desktop\node_modules\inquirer\lib\ui\prompt.js:84:27)
at DeferSubscriber._callFactory (D:\Yuta\Desktop\node_modules\rxjs\observable\DeferObservable.js:92:27)
at DeferSubscriber.tryDefer (D:\Yuta\Desktop\node_modules\rxjs\observable\DeferObservable.js:85:18)
at new DeferSubscriber (D:\Yuta\Desktop\node_modules\rxjs\observable\DeferObservable.js:81:14)
at DeferObservable._subscribe (D:\Yuta\Desktop\node_modules\rxjs\observable\DeferObservable.js:71:16)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.