Code Monkey home page Code Monkey logo

prompts's Introduction

prompts's People

Contributors

creatyvtype avatar dependabot[bot] avatar elie-g avatar forsakenharmony avatar jeysal avatar joeykilpatrick avatar krishna-acondy avatar lukeed avatar lumio avatar madhavarshney avatar milesj avatar millette avatar oskarrough avatar paralax avatar pieh avatar pvdlg avatar ranyitz avatar rluvaton avatar saurabhdaware avatar sckelemen avatar simonepri avatar suriona avatar terkelg avatar th317erd avatar vdrg avatar vsn4ik avatar wilmouths avatar wittbulter avatar yiiu avatar yoavmmn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prompts's Issues

Remove handling of CTRL+C

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)?

Configurable prompt symbols

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 👍

A `default` property in prompt obect

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.

Support node 6

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:

  1. Transpile the code using babel to dist
  2. Create a main file that will route between dist/index.js and lib/index.js according to the user's node version.
  3. Add another travis run using node 6.

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.

How can I use prompts without a transpilation step?

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?

Support keyboard shortcuts that move the cursor

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:
asciicast

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.

Select prompt: Problems & more friendlier `initial`

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.

https://asciinema.org/a/166247 or

Update documentation

Update documentation to reflect v0.1.7

  • stdin and stdout option for all prompts.
  • Tab functionality for initial values in TextPrompt and NumberPrompt.
  • hint in SelectPrompt.
  • float, round and increment in NumberPrompt
  • fallback and initial for AutocompletePrompt
  • emoji renderer option
  • validate option (Coming in next release)
  • Make new gif for autocomplete
  • Make new gif to show filter function

Arrow keys not working for the "select" prompt type

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

Allow `onSubmit` to be an async/Promise returning function

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:

  • Save current answers to recover later
  • Send answers to a remote server
  • Get derived values from a remote server, that could be used for following questions

Maybe it can be done by simply using https://github.com/sindresorhus/emittery instead of EventEmitter?

Text prompt: bug in deleting (backspace)

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.

Clip: https://asciinema.org/a/166257

Cancelling a prompt hangs the process

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:

grafik

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)

Dynamic prompts not working

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

Packaging

Is it possible to pack prompts via electron-builder?

Convenient way to select initial values in tests

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 })

multiselect stalls

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()
    })
}

type: 'number' does not allow 0 value

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);

Possible typo in the source code

Heya. As ususal, i always review the whole code of libraries or whatever.

So found that the this.rl here

const rl = readline.createInterface(this.in);
readline.emitKeypressEvents(this.in, this.rl);

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.

Prompts doesn't work in global packages with Git Bash or Windows CMD

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);
})();

Await is only valid in async function

This is probably some configuration mistake, but when I run the example code, I get the following error:
image

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);

Delete-Key yields 'undefined'

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)

TypeScript support

It would be nice if this package has type definitions or refactor it in typescript and generate typings automatically 😄

How to scroll the autocomplete?

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.

Default Value

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.

Dynamic Choices?

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.

Drop engines field in package.json

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?

Autocomplete to support Tab (or add a notice in docs)

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).

Provide a way to submit answers programmatically

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'

Add format property

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

Working example

Could you provide a working example?

image

I get this only with 1 line (require) or even with import.

Feature: loading indicator

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!

Unexpected Identifier

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"

Cannot use a function for `message` since 0.1.5

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
}

Automatic Non-Interaction Default

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:

  • if the shell is detected to be non-interactive then the noninteraction value is just instantly applied
  • if any sort of interaction happens then the noninteraction timeout disabled completely
  • there are some checks for the interaction to be meaningful (garbage characters or signals are treated as just noise)
  • a small countdown appears when it's in the last 3s before it just triggers non-interaction

Add validate property

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.
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.