Giter Club home page Giter Club logo

prompts's Introduction

Prompts

❯ Prompts

version test downloads licenses

Lightweight, beautiful and user-friendly interactive prompts
>_ Easy to use CLI prompts to enquire users for information▌


  • Simple: prompts has no big dependencies nor is it broken into a dozen tiny modules that only work well together.
  • User friendly: prompt uses layout and colors to create beautiful cli interfaces.
  • Promised: uses promises and async/await. No callback hell.
  • Flexible: all prompts are independent and can be used on their own.
  • Testable: provides a way to submit answers programmatically.
  • Unified: consistent experience across all prompts.

split

❯ Install

$ npm install --save prompts

This package supports Node 14 and above

split

❯ Usage

example prompt

const prompts = require('prompts');

(async () => {
  const response = await prompts({
    type: 'number',
    name: 'value',
    message: 'How old are you?',
    validate: value => value < 18 ? `Nightclub is 18+ only` : true
  });

  console.log(response); // => { value: 24 }
})();

See example.js for more options.

split

❯ Examples

Single Prompt

Prompt with a single prompt object. Returns an object with the response.

const prompts = require('prompts');

(async () => {
  const response = await prompts({
    type: 'text',
    name: 'meaning',
    message: 'What is the meaning of life?'
  });

  console.log(response.meaning);
})();

Prompt Chain

Prompt with a list of prompt objects. Returns an object with the responses. Make sure to give each prompt a unique name property to prevent overwriting values.

const prompts = require('prompts');

const 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 something about yourself',
    initial: 'Why should I?'
  }
];

(async () => {
  const response = await prompts(questions);

  // => response => { username, age, about }
})();

Dynamic Prompts

Prompt properties can be functions too. Prompt Objects with type set to falsy values are skipped.

const prompts = require('prompts');

const questions = [
  {
    type: 'text',
    name: 'dish',
    message: 'Do you like pizza?'
  },
  {
    type: prev => prev == 'pizza' ? 'text' : null,
    name: 'topping',
    message: 'Name a topping'
  }
];

(async () => {
  const response = await prompts(questions);
})();

split

❯ API

prompts(prompts, options)

Type: Function
Returns: Object

Prompter function which takes your prompt objects and returns an object with responses.

prompts

Type: Array|Object

Array of prompt objects. These are the questions the user will be prompted. You can see the list of supported prompt types here.

Prompts can be submitted (return, enter) or canceled (esc, abort, ctrl+c, ctrl+d). No property is being defined on the returned response object when a prompt is canceled.

options.onSubmit

Type: Function
Default: () => {}

Callback that's invoked after each prompt submission. Its signature is (prompt, answer, answers) where prompt is the current prompt object, answer the user answer to the current question and answers the user answers so far. Async functions are supported.

Return true to quit the prompt chain and return all collected responses so far, otherwise continue to iterate prompt objects.

Example:

(async () => {
  const questions = [{ ... }];
  const onSubmit = (prompt, answer) => console.log(`Thanks I got ${answer} from ${prompt.name}`);
  const response = await prompts(questions, { onSubmit });
})();

options.onCancel

Type: Function
Default: () => {}

Callback that's invoked when the user cancels/exits the prompt. Its signature is (prompt, answers) where prompt is the current prompt object and answers the user answers so far. Async functions are supported.

Return true to continue and prevent the prompt loop from aborting. On cancel responses collected so far are returned.

Example:

(async () => {
  const questions = [{ ... }];
  const onCancel = prompt => {
    console.log('Never stop prompting!');
    return true;
  }
  const response = await prompts(questions, { onCancel });
})();

override

Type: Function

Preanswer questions by passing an object with answers to prompts.override. Powerful when combined with arguments of process.

Example

const prompts = require('prompts');
prompts.override(require('yargs').argv);

(async () => {
  const response = await prompts([
    {
      type: 'text',
      name: 'twitter',
      message: `What's your twitter handle?`
    },
    {
      type: 'multiselect',
      name: 'color',
      message: 'Pick colors',
      choices: [
        { title: 'Red', value: '#ff0000' },
        { title: 'Green', value: '#00ff00' },
        { title: 'Blue', value: '#0000ff' }
      ],
    }
  ]);

  console.log(response);
})();

inject(values)

Type: Function

Programmatically inject responses. This enables you to prepare the responses ahead of time. If any injected value is found the prompt is immediately resolved with the injected value. This feature is intended for testing only.

values

Type: Array

Array with values to inject. Resolved values are removed from the internal inject array. Each value can be an array of values in order to provide answers for a question asked multiple times. If a value is an instance of Error it will simulate the user cancelling/exiting the prompt.

Example:

const prompts = require('prompts');

prompts.inject([ '@terkelg', ['#ff0000', '#0000ff'] ]);

(async () => {
  const response = await prompts([
    {
      type: 'text',
      name: 'twitter',
      message: `What's your twitter handle?`
    },
    {
      type: 'multiselect',
      name: 'color',
      message: 'Pick colors',
      choices: [
        { title: 'Red', value: '#ff0000' },
        { title: 'Green', value: '#00ff00' },
        { title: 'Blue', value: '#0000ff' }
      ],
    }
  ]);

  // => { twitter: 'terkelg', color: [ '#ff0000', '#0000ff' ] }
})();

split

❯ Prompt Objects

Prompts Objects are JavaScript objects that define the "questions" and the type of prompt. Almost all prompt objects have the following properties:

{
  type: String | Function,
  name: String | Function,
  message: String | Function,
  initial: String | Function | Async Function
  format: Function | Async Function,
  onRender: Function
  onState: Function
  stdin: Readable
  stdout: Writeable
}

Each property be of type function and will be invoked right before prompting the user.

The function signature is (prev, values, prompt), where prev is the value from the previous prompt, values is the response object with all values collected so far and prompt is the previous prompt object.

Function example:

{
  type: prev => prev > 3 ? 'confirm' : null,
  name: 'confirm',
  message: (prev, values) => `Please confirm that you eat ${values.dish} times ${prev} a day?`
}

The above prompt will be skipped if the value of the previous prompt is less than 3.

type

Type: String|Function

Defines the type of prompt to display. See the list of prompt types for valid values.

If type is a falsy value the prompter will skip that question.

{
  type: null,
  name: 'forgetme',
  message: `I'll never be shown anyway`,
}

name

Type: String|Function

The response will be saved under this key/property in the returned response object. In case you have multiple prompts with the same name only the latest response will be stored.

Make sure to give prompts unique names if you don't want to overwrite previous values.

message

Type: String|Function

The message to be displayed to the user.

initial

Type: String|Function

Optional default prompt value. Async functions are supported too.

format

Type: Function

Receive the user input and return the formatted value to be used inside the program. The value returned will be added to the response object.

The function signature is (val, values), where val is the value from the current prompt and values is the current response object in case you need to format based on previous responses.

Example:

{
  type: 'number',
  name: 'price',
  message: 'Enter price',
  format: val => Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(val);
}

onRender

Type: Function

Callback for when the prompt is rendered. The function receives kleur as its first argument and this refers to the current prompt.

Example:

{
  type: 'number',
  message: 'This message will be overridden',
  onRender(kleur) {
    this.msg = kleur.cyan('Enter a number');
  }
}

onState

Type: Function

Callback for when the state of the current prompt changes. The function signature is (state) where state is an object with a snapshot of the current state. The state object has two properties value and aborted. E.g { value: 'This is ', aborted: false }

stdin and stdout

Type: Stream

By default, prompts uses process.stdin for receiving input and process.stdout for writing output. If you need to use different streams, for instance process.stderr, you can set these with the stdin and stdout properties.

split

❯ Types


text(message, [initial], [style])

Text prompt for free text input.

Hit tab to autocomplete to initial value when provided.

Example

text prompt

{
  type: 'text',
  name: 'value',
  message: `What's your twitter handle?`
}

Options

Param Type Description
message string Prompt message to display
initial string Default string value
style string Render style (default, password, invisible, emoji). Defaults to default
format function Receive user input. The returned value will be added to the response object
validate function Receive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


password(message, [initial])

Password prompt with masked input.

This prompt is a similar to a prompt of type 'text' with style set to 'password'.

Example

password prompt

{
  type: 'password',
  name: 'value',
  message: 'Tell me a secret'
}

Options

Param Type Description
message string Prompt message to display
initial string Default string value
format function Receive user input. The returned value will be added to the response object
validate function Receive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


invisible(message, [initial])

Prompts user for invisible text input.

This prompt is working like sudo where the input is invisible. This prompt is a similar to a prompt of type 'text' with style set to 'invisible'.

Example

invisible prompt

{
  type: 'invisible',
  name: 'value',
  message: 'Enter password'
}

Options

Param Type Description
message string Prompt message to display
initial string Default string value
format function Receive user input. The returned value will be added to the response object
validate function Receive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


number(message, initial, [max], [min], [style])

Prompts user for number input.

You can type in numbers and use up/down to increase/decrease the value. Only numbers are allowed as input. Hit tab to autocomplete to initial value when provided.

Example

number prompt

{
  type: 'number',
  name: 'value',
  message: 'How old are you?',
  initial: 0,
  style: 'default',
  min: 2,
  max: 10
}

Options

Param Type Description
message string Prompt message to display
initial number Default number value
format function Receive user input. The returned value will be added to the response object
validate function Receive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
max number Max value. Defaults to Infinity
min number Min value. Defaults to -infinity
float boolean Allow floating point inputs. Defaults to false
round number Round float values to x decimals. Defaults to 2
increment number Increment step when using arrow keys. Defaults to 1
style string Render style (default, password, invisible, emoji). Defaults to default
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


confirm(message, [initial])

Classic yes/no prompt.

Hit y or n to confirm/reject.

Example

confirm prompt

{
  type: 'confirm',
  name: 'value',
  message: 'Can you confirm?',
  initial: true
}

Options

Param Type Description
message string Prompt message to display
initial boolean Default value. Default is false
format function Receive user input. The returned value will be added to the response object
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


list(message, [initial])

List prompt that return an array.

Similar to the text prompt, but the output is an Array containing the string separated by separator.

{
  type: 'list',
  name: 'value',
  message: 'Enter keywords',
  initial: '',
  separator: ','
}

list prompt

Param Type Description
message string Prompt message to display
initial boolean Default value
format function Receive user input. The returned value will be added to the response object
separator string String separator. Will trim all white-spaces from start and end of string. Defaults to ','
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


toggle(message, [initial], [active], [inactive])

Interactive toggle/switch prompt.

Use tab or arrow keys/tab/space to switch between options.

Example

toggle prompt

{
  type: 'toggle',
  name: 'value',
  message: 'Can you confirm?',
  initial: true,
  active: 'yes',
  inactive: 'no'
}

Options

Param Type Description
message string Prompt message to display
initial boolean Default value. Defaults to false
format function Receive user input. The returned value will be added to the response object
active string Text for active state. Defaults to 'on'
inactive string Text for inactive state. Defaults to 'off'
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


select(message, choices, [initial], [hint], [warn])

Interactive select prompt.

Use up/down to navigate. Use tab to cycle the list.

Example

select prompt

{
  type: 'select',
  name: 'value',
  message: 'Pick a color',
  choices: [
    { title: 'Red', description: 'This option has a description', value: '#ff0000' },
    { title: 'Green', value: '#00ff00', disabled: true },
    { title: 'Blue', value: '#0000ff' }
  ],
  initial: 1
}

Options

Param Type Description
message string Prompt message to display
initial number Index of default value
format function Receive user input. The returned value will be added to the response object
hint string Hint to display to the user
warn string Message to display when selecting a disabled option
choices Array Array of strings or choices objects [{ title, description, value, disabled }, ...]. The choice's index in the array will be used as its value if it is not specified.
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


multiselect(message, choices, [initial], [max], [hint], [warn])

autocompleteMultiselect(same)

Interactive multi-select prompt. Autocomplete is a searchable multiselect prompt with the same options. Useful for long lists.

Use space to toggle select/unselect and up/down to navigate. Use tab to cycle the list. You can also use right to select and left to deselect. By default this prompt returns an array containing the values of the selected items - not their display title.

Example

multiselect prompt

{
  type: 'multiselect',
  name: 'value',
  message: 'Pick colors',
  choices: [
    { title: 'Red', value: '#ff0000' },
    { title: 'Green', value: '#00ff00', disabled: true },
    { title: 'Blue', value: '#0000ff', selected: true }
  ],
  max: 2,
  hint: '- Space to select. Return to submit'
}

Options

Param Type Description
message string Prompt message to display
format function Receive user input. The returned value will be added to the response object
instructions string or boolean Prompt instructions to display
choices Array Array of strings or choices objects [{ title, value, disabled }, ...]. The choice's index in the array will be used as its value if it is not specified.
optionsPerPage number Number of options displayed per page (default: 10)
min number Min select - will display error
max number Max select
hint string Hint to display to the user
warn string Message to display when selecting a disabled option
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

This is one of the few prompts that don't take a initial value. If you want to predefine selected values, give the choice object an selected property of true.

↑ back to: Prompt types


autocomplete(message, choices, [initial], [suggest], [limit], [style])

Interactive auto complete prompt.

The prompt will list options based on user input. Type to filter the list. Use / to navigate. Use tab to cycle the result. Use Page Up/Page Down (on Mac: fn + / ) to change page. Hit enter to select the highlighted item below the prompt.

The default suggests function is sorting based on the title property of the choices. You can overwrite how choices are being filtered by passing your own suggest function.

Example

auto complete prompt

{
  type: 'autocomplete',
  name: 'value',
  message: 'Pick your favorite actor',
  choices: [
    { title: 'Cage' },
    { title: 'Clooney', value: 'silver-fox' },
    { title: 'Gyllenhaal' },
    { title: 'Gibson' },
    { title: 'Grant' }
  ]
}

Options

Param Type Description
message string Prompt message to display
format function Receive user input. The returned value will be added to the response object
choices Array Array of auto-complete choices objects [{ title, value }, ...]
suggest function Filter function. Defaults to sort by title property. suggest should always return a promise. Filters using title by default
limit number Max number of results to show. Defaults to 10
style string Render style (default, password, invisible, emoji). Defaults to 'default'
initial string | number Default initial value
clearFirst boolean The first ESCAPE keypress will clear the input
fallback string Fallback message when no match is found. Defaults to initial value if provided
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with three properties: value, aborted and exited

Example on what a suggest function might look like:

const suggestByTitle = (input, choices) =>
    Promise.resolve(choices.filter(i => i.title.slice(0, input.length) === input))

↑ back to: Prompt types


date(message, [initial], [warn])

Interactive date prompt.

Use left/right/tab to navigate. Use up/down to change date.

Example

date prompt

{
  type: 'date',
  name: 'value',
  message: 'Pick a date',
  initial: new Date(1997, 09, 12),
  validate: date => date > Date.now() ? 'Not in the future' : true
}

Options

Param Type Description
message string Prompt message to display
initial date Default date
locales object Use to define custom locales. See below for an example.
mask string The format mask of the date. See below for more information.
Default: YYYY-MM-DD HH:mm:ss
validate function Receive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
onRender function On render callback. Keyword this refers to the current prompt
onState function On state change callback. Function signature is an object with two properties: value and aborted

Default locales:

{
  months: [
    'January', 'February', 'March', 'April',
    'May', 'June', 'July', 'August',
    'September', 'October', 'November', 'December'
  ],
  monthsShort: [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  ],
  weekdays: [
    'Sunday', 'Monday', 'Tuesday', 'Wednesday',
    'Thursday', 'Friday', 'Saturday'
  ],
  weekdaysShort: [
    'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
  ]
}

Formatting: See full list of formatting options in the wiki

split

↑ back to: Prompt types


❯ Credit

Many of the prompts are based on the work of derhuerst.

❯ License

MIT © Terkel Gjervig

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

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)

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

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!

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?

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

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.

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
}

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

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?

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"

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

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.

TypeScript support

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

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)

Working example

Could you provide a working example?

image

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

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 👍

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

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'

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

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.

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

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.

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.

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

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.

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

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

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.

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

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?

Packaging

Is it possible to pack prompts via electron-builder?

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

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

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.