Giter Site home page Giter Site logo

prompts's Introduction

Prompts

❯ Prompts

version travis downloads

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.

split

❯ Install

$ npm install --save prompts

This package uses async/await and requires Node.js 7.6

split

❯ Usage

example prompt

const prompts = require('prompts');

let response = await prompts({
    type: 'number',
    name: 'value',
    message: 'How old are you?'
});

console.log(response.value); // => 23

split

❯ Examples

Single Prompt

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

const prompts = require('prompts');

let 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 object with response. Make sure to give each prompt a unique name property to prevent overwriting values.

const prompt = require('prompts');

let questions = [
    {
        type: 'text',
        name: 'username',
        message: 'What is your GitHub username?'
    },
    {
        type: 'age',
        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);

// => response => { username, age, about }

Dynamic Prompts

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

const prompts = require('prompts');

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

let 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, response) where prompt is the current prompt object.

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

Example:

let questions = [{ ... }];
let onSubmit = (prompt, response) => console.log(`Thanks I got ${response} from ${prompt.name}`);
let 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) where prompt is the current prompt object.

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

Example:

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

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
}

If type is null the prompter will skip that question.

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

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

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

Its signature is (prev, values, prompt), where prev is the value from the previous prompt, values is all values collected so far and prompt is the provious prompt object.

split

❯ Types

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

Text prompt for free text input.

Example

text prompt

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

Options

Param Type Default Description
message string Prompt message to display
initial string '' Default string value
style string 'default' Render style (default, password, invisible)

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',
  initial '',
}

Options

Param Type Description
message string Prompt message to display
initial string Default string value

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',
  initial: ''
}

Options

Param Type Description
message string Prompt message to display
initial string Default string value

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

Prompts user for number input.

You can use up/down to increase/decrease the value. Only numbers are allowed as input. Default resolve value is null.

Example

number prompt

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

Options

Param Type Default Description
message string Prompt message to display
initial number null Default number value
max number Infinity Max value
min number -infinity Min value
style string 'default' Render style (default, password, invisible)

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 Default Description
message string Prompt message to display
initial boolean false Default value

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 Default Description
message string Prompt message to display
initial boolean false Default value
seperator string ',' String seperator. Will trim all white-spaces from start and end of string

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

Interactive toggle/switch prompt.

Use tab or arrow keys to switch between options.

Example

toggle prompt

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

Options

Param Type Default Description
message string Prompt message to display
initial boolean false Default value
active string 'on' Text for active state
inactive string 'off' Text for inactive state

select(message, choices, [initial])

Interactive select prompt.

Use space to select/unselect and arrow keys to navigate the list.

Example

select prompt

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

Options

Param Type Description
message string Prompt message to display
initial number Index of default value
choices Array Array of choices objects [{ title, value }, ...]

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

Interactive multi-select prompt.

Use space to select/unselect and arrow keys to navigate the list. 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' },
        { title: 'Blue', value: '#0000ff', selected: true }
    ],
    initial: 1,
    max: 2,
    hint: '- Space to select. Return to submit'
}

Options

Param Type Description
message string Prompt message to display
choices Array Array of choices objects [{ title, value, [selected] }, ...]
max number Max select
hint string Hint to display user

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.

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

Interactive auto complete prompt.

The prompt will list options based on user input.

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 Default Description
message string Prompt message to display
choices Array Array of auto-complete choices objects [{ title, value }, ...]
suggest function By title string Filter function. Defaults to stort by title property. Suggest should always return a promise
limit number 10 Max number of results to show
style string 'default' Render style (default, password, invisible)

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

split

❯ Credit

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

❯ License

MIT © Terkel Gjervig

prompts's People

Contributors

simonepri avatar terkelg avatar

Watchers

 avatar  avatar

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.