terkelg / prompts Goto Github PK
View Code? Open in Web Editor NEW❯ Lightweight, beautiful and user-friendly interactive prompts
License: MIT License
❯ Lightweight, beautiful and user-friendly interactive prompts
License: MIT License
OS: Windows 7 Ultimate 64-bit SP1
Node: v9.5.0
Prompts: v0.1.4
Whenever I press 'enter' on a prompts.select
or prompts.text
, I get:
TypeError: this.in.setRawMode is not a function
at TextPrompt.close (C:\projects\_PLAYGROUND\PromptsDontWorkGlobal\node_modules\prompts\lib\elements\prompt.js:39:15)
at TextPrompt.submit (C:\projects\_PLAYGROUND\PromptsDontWorkGlobal\node_modules\prompts\lib\elements\text.js:50:10)
at Socket.keypress (C:\projects\_PLAYGROUND\PromptsDontWorkGlobal\node_modules\prompts\lib\elements\prompt.js:30:16)
at Socket.emit (events.js:160:13)
at emitKeys (internal/readline.js:420:14)
at emitKeys.next (<anonymous>)
at Socket.onData (readline.js:1021:36)
at Socket.emit (events.js:165:20)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
CODE:
#!/usr/bin/env node
const prompts = require('prompts');
const presets = {
'App': 'OTHERDATA',
'(Express|EJS)': 'OTHERDATA',
'Webpack-Dev-Server + (Webpack|ES6-BABEL|SCSS)': 'OTHERDATA',
'React + Webpack-Dev-Server + (Webpack|ES6-BABEL)': 'OTHERDATA',
'React + Redux + Webpack-Dev-Server + (Webpack|ES6-BABEL)': 'OTHERDATA'
};
(async () => {
const { answer } = await prompts({
type: 'text',
name: 'answer',
message: 'Hello FöRVaiS'
});
console.log(answer);
const { data: [, data] } = await prompts({
type: 'select',
name: 'data',
message: 'Select a preset from this list',
choices: Object.entries(presets).map(preset => ({ title: preset[0], value: preset })),
initial: 0
});
console.log(data);
})();
Shortcuts that are designed to move around the input output undefined
.
Here's what I mean:
For example, I have ⌥ + Left Arrow
set in iTerm to Send ^[ b
. What this escape sequence achieves is that it skips one word to the left.
Here's an example of it in action:
When I try to do the same thing with prompts
, it just constantly outputs undefined
and the cursor moves to the left.
Apologies if I haven't explained myself properly.
PR #30 breaks the dynamic renderer
prompt
seems to be a reserved word and throws an error when compiling a TypeScript file.
In this case we have to use prompts
.
How did you create gifs form readme?
single select prompts and text prompts are working fine for me, but when i try to use a multiselect, the process just stalls out until i hit ctrl-c. then i see then next prompt in line after the multiselect before exiting.
✔ Deploy last commit? › no
✔ Rebuild assets? › yes
✔ Release type? › patch
✖ Flush cache? › yes
there should be a "select deployment targets" before that "flush cache." here's my object.
async function targets () {
d.t = await prompts({
type: 'multiselect',
messages: 'Select deployment targets:',
choices: [
{ title: 'dev', value: 'nylon-dev', selected: true },
{ title: 'staging', value: 'nylon-staging' },
{ title: 'production', value: 'nylon-production' }
],
max: 3
})
.then(() => {
return Promise.resolve()
})
}
It seems that it not completes the word. But also, it's not a problem, because it is in the result when click enter - we can add notice for it in docs.
Example (i know for this question is more good the select
but, yea, why not autocomplete [i dont like arrows ;d]).
async function run() {
const response = await prompts({
type: 'autocomplete',
name: 'type',
message: 'What is the type of the change?',
choices: [
{ title: 'fix' },
{ title: 'feat', value: 'feature' },
{ title: 'break' },
{ title: 'major' },
{ title: 'chore' },
],
});
console.log(response);
// => { type: 'feature' }
}
run()
type fe
and Enter. Result is correct anyway, but users has habits to click Tab to finish the word (i believe).
New scrolling list element
Can this be implemented?
Heya! ✋
The thing is that there is the initial
currently. But i believe it would be better the initial to be set in parens before the ›
. It's cool feature, and it can be used to set default values, but if user dont want the default he need to waste time in deleting it to set another. As about if we have default
then it can be shown in parens
same as initial
(if initial not set) and if user like the default then just to click enter
.
One more thing that i'm thinking about is required
boolean prop to allow the question to be required or not. If required and not set then throw, end the stream or show message which is kinda related to the discussion in #2 (comment) thread.
If not adding required
then validate
is good option too. Use case.
Should that be the new tagline?
Great library, works really well and has an easy to use API.
One thing I'd like to see / make use of is a loading spinner or maybe a progress bar?
I would like to for example show progress of an action, i.e downloading a file.
Would make this even more epic!
It's too beautiful!Can you tell me? thank you!
Some projects still support node 6.
My use case is that I want to use prompts in jestjs/jest#6442
The solution for that could be fairly easy:
dist
dist/index.js
and lib/index.js
according to the user's node version.It shouldn't interfere with the development, and there will be no performance change for users that use node > 8
.
Let me know your thoughts.
I don't know what I did wrong I'll provide whatever files to help with debugging.
const response = await prompts ({
------------------------ ^^^^^^^
SyntaxError: Unexpected identifier
at Object.exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:422:7)
at startup (bootstrap_node.js:143:9)
at bootstrap_node.js:537:3
EDIT:
I've also run into the issue with the error: "SyntaxError: await is only valid in async function"
Heya. As ususal, i always review the whole code of libraries or whatever.
So found that the this.rl
here
prompts/lib/elements/prompt.js
Lines 18 to 19 in 230c1a6
probably is meant to be the rl
const, because the this.rl
is not defined in any other place in the code base, even in that file.
Proposal to add a validate
property:
validate: (Function || Async Function) Receive the user input and answers of a chain.
Should return true if the value is valid, and an error message (String) otherwise.
If false is returned, a default error message is provided.
To do this we need to add a way to render errors messages.
API Usage Example:
validate: (input, answers) => {
if (input === 'invalid') return 'The answer is invalid.';
return true; // Proceed to the next prompt of the chain if any.
}
Heya again. This time a bug.
Consider following example
async function run() {
const response = await prompts({
type: 'text',
name: 'subject',
message: 'Short description of the change',
});
console.log(response);
}
run().catch(console.error);
and you already wrote some sentence, but you want to back and replace some word with another (or fix a typo) they you use Backspace to delete it. But it seems that it deletes characters from the end of the sentence.
This is probably some configuration mistake, but when I run the example code, I get the following error:
Code:
const prompt = require('prompts');
let questions = [
{
type: 'text',
name: 'username',
message: 'What is your GitHub username?'
},
{
type: 'number',
name: 'age',
message: 'How old are you?'
},
{
type: 'text',
name: 'about',
message: 'Tell somethign about yourself',
initial: 'Why should I?'
}
];
let response = await prompts(questions);
I have a simple index.js with a single text prompt and when I press the ESCAPE-key (not backspace!) it just hangs forever.
index.js:
var prompts = require("prompts");
async function main() {
var prefix = await prompts({
type: "text",
name: "prefix",
message: "Prefix!"
// initial: "muh"
});
console.log(prefix);
}
main();
I run node .\index.js
in powershell and press ESCAPE. The result looks like this and nothing changes anymore: Only CTRL+c helps me. Entering any text in the prompt and pressing enter just works btw:
Expected behavior: my prefix variable is becomes {} or undefined or null.
Versions:
node: v10.3.0
npm: 6.1.0
prompts: 1.0.0
Windows Server 2016 Datacenter (azure vm)
All prompts have onAbort
and onSubmit
after #43. This is not yet documented.
Just trying to reproduce the example and I have the error
Error: prompt type (prev => (prev == 'pizza' ? 'text' : null)) is not defined
at prompt (/container-init/node_modules/prompts/lib/index.js:43:13)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
Great work on this library none the less 😺
EDIT:
node version: 8.9.4
Pressing the arrow keys to change the selected value in a prompt of type select does not work visually. The initial value remains the one selected / colored. Though, when I press enter/return it does not necessarily return the initial value. In other words, pressing the arrow keys changes the selected value but does not change the highlighted line in console / terminal.
Edit:
Arrow keys work in a DOS terminal but not in bash
Proposal to add a format
property:
filter: (Function || Async Function) Receive the user input and return the formatted value to be used inside the program.
The value returned will be added to the answers.
API Usage Example::
format: confirm => !confirm
Hi, is it possible to scroll through autocomplete results somehow?
When you're at the last or first item, I expected up/down to page through the results. Search works great though, super fast here.
Is it actually possible to customize the question prefix ?
with emoji for exemple.
It could be really cool to offert a more contextual experience.
And nice job for this project 👍
Currently the example.js file uses top level await and ESM, which aren't supported without transpilation in Node.js.
I could be misunderstanding, but I'd ❤️ to use Prompts. Curious if there's currently a way to do it without transpiling?
Can submit a PR at some point if needed.
So it need two newlines to be submitted.
Update documentation to reflect v0.1.7
stdin
and stdout
option for all prompts.initial
values in TextPrompt and NumberPrompt.hint
in SelectPrompt.float
, round
and increment
in NumberPromptfallback
and initial
for AutocompletePromptemoji
renderer optionvalidate
option (Coming in next release)autocomplete
0.1.4
was the last version I could do
{
type: 'autocomplete',
message: (prev, values) => `something with ${ prev } or ${ values.something }`,
choices: [{ title: 'title' }]
}
Since 0.1.5 I get:
UnhandledPromiseRejectionWarning: Error: prompt message is required
at prompt (node_modules/prompts/lib/index.js:29:13)
Either the code should allow functions, or the Readme should not define prompt objects as:
{
type: String || Function,
name: String || Function,
message: String || Function,
initial: String || Function || Async Function
format: Function || Async Function,
onState: Function
}
inject
is great when, within a test, you want to simulate the user supplying an answer, but what about when you want to simulate them choosing the initial or default value? I can submit a PR if we can decide on how to implement this. My proposal is that if an injected answer is undefined
prompts would just use the initial value. e.g.:
prompts.inject({ a: undefined })
One more issue, sorry but.. 😆
I understand that it is normal to be zero based, but is an exposed API, why we should think about it.
Btw, from here we can see one problem. Consider the example
async function run() {
const response = await prompts({
type: 'select',
name: 'type',
message: 'What is the type of the change?',
choices: [
{ title: 'Fixing a bug', value: 'fix' },
{ title: 'New feature', value: 'feat' },
{ title: 'Breaking change', value: 'major' },
{ title: 'Non code changes', value: 'chore' },
{ title: 'Documentation changes', value: 'docs' },
],
initial: 3,
});
console.log(response);
// => { type: 'chore' }
}
run()
then click Enter. The response is correct, it selects the fourth (cuz it is zero based, okey). But visually it is not selected when run the program - it stays on the Fix a bug
. I'll record asciinema record. So you can see what i'm talking.
Very often when adding these sort of prompts there's one requirement that always pops up, and that's the ability to turn them off.
Usually it's cases such as trying to get things to automate and questions like "Re-build?" that get in the way. Or it can be just a case of "well I just want to run with defaults, don't want to sit here waiting for the next prompt" (with regard to why not ask upfront, it's because sometimes you dont know the options, the "default" may be just "first of available" or some such logic)
How about having the ability to timeout to a noninteraction default value?
const response = await prompts({
type: 'number',
name: 'value',
message: 'How old are you?',
// a function is prefered, but in this case just "16" would have been fine too
assume: () => 16,
timeout: 4000,
// basically: disable entirely, defaults to assume value
// convenient if you have some --auto or --non-interactive flag already present
off: some_boolean_variable_or_function
});
Behavior would be:
I was thinking there could be an option to allow for default values. I was thinking this could be implemented in a similar way to NPM does it, for example when you do
> npm init
.
.
.
> entrypoint (index.js):
The default option is picked when no option is supplied. I am happy to work on this issue if it is something that you think should be added.
When I provide an initial value of something other than 0, 1 for example, I am not able to override that initial value when I provide 0 as a response.
I believe I have tracked this down to this section in lib/elements/number.js:
submit() {
this.value = this.value || this.initial;
My test:
var response = await prompts( [{
type: 'number',
name: 'test',
message: 'Try providing 0',
initial: 1,
format: val => {
return parseInt( val, 10 );
}
});
console.log(response.test);
I have a simple index.js with a single text prompt and when I press the DEL-key (not backspace!) the text becomes literally "undefined". I can then delete the u but nothing else.
index.js:
var prompts = require("prompts");
async function main() {
var prefix = await prompts({
type: "text",
name: "prefix",
message: "Prefix!"
// initial: "muh"
});
console.log(prefix);
}
main();
shell:
PS C:\test\muh> node .\index.js
√ Prefix! ... undefined
{ prefix: 'undefined' }
PS C:\test\muh>
I pressed DEL, then ENTER
Expected behavior: DEL changes nothing or deletes the character which is right from the cursor (this does also not work!)
Versions:
node: v10.3.0
npm: 6.1.0
prompts: 1.0.0
Windows Server 2016 Datacenter (azure vm)
This package seems promising, a thing that packages like inquirer
are missing, is a way to submit answer programmatically.
But this is essential to test the prompts.
The API may look like this:
const prompts = require('prompts');
prompts.prepare({
meaning: '42'
});
let response = await prompts({
type: 'text',
name: 'meaning',
message: 'What is the meaning of life?'
});
console.log(response.meaning); // => '42'
It would be nice if this package has type definitions or refactor it in typescript
and generate typings automatically 😄
Is it possible to pack prompts via electron-builder?
Currently if onSubmit
is an async
or Promise
returning function, prompt exit after the first question.
It would be useful to allow onSubmit
to be an async
or Promise
returning function so we could do asynchronous things in between user answers.
That would allow for example to:
Maybe it can be done by simply using https://github.com/sindresorhus/emittery instead of EventEmitter?
In most cases it is used to kill whole program and i'm pretty used to it. Don't want to be used as canceling questions.
Secondary issues: CTRL+Z and CTRL+X are not working too, so you literally don't have any chance to close the program earlier, except to CTRL+C until questions end, what if you have dozens (not my case)?
It should be obvious i believe and only name
and message
are enough.
The state
event is already being emitted from the base class.
Just nede to be exposed and documented.
What should the name of the option be? Click to vote
Thanks for this awesome project!
We are trying to use it inside of Jest, But Jest only supports node 6 and above. That's why I've opened #64
There is another option, suggested here jestjs/jest#6442 (comment). We'll use prompts
without transpilation because it should run only on developers machines, which probably already have node > 8
.
The only problem is that Jest still supports node version 6, and will fail if we'll use prompts as a dependency due to the engines
property in package.json
.
@terkelg Can we drop the engines
restriction and add a manual message instead?
It seems like, if for no other reason than consistency, the choices
key on selects & multiselects can/should accept a function that receives all answer and the immediately preceding answer before it in the chain.
The use case is to dynamically show/hide choices based on the value/existence of a previous answer.
With PWA, for example, I only want to show TSLint
as a choice in the "Linter or Formatter" list if TypeScript
had been selected previously in the "Features" section. There are also some other instances where this would come in handy, but that's the simplest one to explain.
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.