Skip to content

Commit

Permalink
Update new confirm prompt to use the hook API
Browse files Browse the repository at this point in the history
  • Loading branch information
SBoudrias committed Sep 21, 2019
1 parent f07cbba commit c172c75
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 24 deletions.
31 changes: 31 additions & 0 deletions packages/confirm/README.md
@@ -0,0 +1,31 @@
# `@inquirer/confirm`

Simple interactive command line prompt to gather boolean input from users.

# Installation

```sh
npm install @inquirer/confirm

yarn add @inquirer/confirm
```

# Usage

```js
import confirm from '@inquirer/confirm';

const answer = await confirm({ message: 'Enter your name' });
```

## Options

| Property | Type | Required | Description |
| -------- | --------- | -------- | ------------------------------ |
| message | `string` | yes | The question to ask |
| default | `boolean` | no | Default answer (true or false) |

# License

Copyright (c) 2019 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))
Licensed under the MIT license.
50 changes: 26 additions & 24 deletions packages/confirm/index.js
@@ -1,30 +1,32 @@
const { createPrompt } = require('@inquirer/core');
const chalk = require('chalk');
const { createPrompt, useState, useKeypress } = require('@inquirer/core/hooks');
const { isEnterKey } = require('@inquirer/core/lib/key');
const { usePrefix } = require('@inquirer/core/lib/prefix');

module.exports = createPrompt(
{
mapStateToValue({ value, default: rawDefault }) {
if (value) {
return /^y(es)?/i.test(value);
}
module.exports = createPrompt((config, done) => {
const [status, setStatus] = useState('pending');
const [value, setValue] = useState('');
const prefix = usePrefix();

return rawDefault !== false;
}
},
(state, { mapStateToValue }) => {
const { prefix, value = '', status } = state;
const message = chalk.bold(state.message);
let formattedValue = value;
if (status === 'done') {
const value = mapStateToValue(state);
formattedValue = chalk.cyan(value ? 'yes' : 'no');
}

let defaultValue = '';
if (status !== 'done') {
defaultValue = chalk.dim(state.default === false ? ' (y/N)' : ' (Y/n)');
useKeypress((key, rl) => {
if (isEnterKey(key)) {
const answer = value ? /^y(es)?/i.test(value) : config.default !== false;
setValue(answer ? 'yes' : 'no');
setStatus('done');
done(answer);
} else {
setValue(rl.line);
}
});

return `${prefix} ${message}${defaultValue} ${formattedValue}`;
let formattedValue = value;
let defaultValue = '';
if (status === 'done') {
formattedValue = chalk.cyan(value ? 'yes' : 'no');
} else {
defaultValue = chalk.dim(config.default === false ? ' (y/N)' : ' (Y/n)');
}
);

const message = chalk.bold(config.message);
return `${prefix} ${message}${defaultValue} ${formattedValue}`;
});

0 comments on commit c172c75

Please sign in to comment.