Skip to content

Commit

Permalink
Add new editor prompt
Browse files Browse the repository at this point in the history
  • Loading branch information
SBoudrias committed Sep 21, 2019
1 parent 6a2aa06 commit 3ab4549
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/editor/demo.js
@@ -0,0 +1,17 @@
const editor = require('.');

(async () => {
let answer;

answer = await editor({
message: 'Please write a short bio of at least 3 lines.',
validate: function(text) {
if (text.split('\n').length < 3) {
return 'Must be at least 3 lines.';
}

return true;
}
});
console.log('Answer:', answer);
})();
55 changes: 55 additions & 0 deletions packages/editor/index.js
@@ -0,0 +1,55 @@
const chalk = require('chalk');
const { editAsync } = require('external-editor');
const { createPrompt, useState, useKeypress } = require('@inquirer/core/hooks');
const { usePrefix } = require('@inquirer/core/lib/prefix');
const { isEnterKey } = require('@inquirer/core/lib/key');

module.exports = createPrompt((config, done) => {
const [status, setStatus] = useState('pending');
const [errorMsg, setError] = useState();

useKeypress(async (key, rl) => {
// Ignore keypress while our prompt is doing other processing.
if (status !== 'pending') {
return;
}

if (isEnterKey(key)) {
rl.pause();
editAsync(config.default || '', async (error, answer) => {
rl.resume();
if (error) {
setError(error);
} else {
setStatus('loading');
const isValid = await config.validate(answer);
if (isValid === true) {
setError(undefined);
setStatus('done');
done(answer);
} else {
setError(isValid || 'You must provide a valid value');
setStatus('pending');
}
}
});
}
});

const isLoading = status === 'loading';
const prefix = usePrefix(isLoading);

let message = chalk.bold(config.message);
if (status === 'loading') {
message += chalk.dim(' Received');
} else if (status === 'pending') {
message += chalk.dim(' Press <enter> to launch your preferred editor.');
}

let error = '';
if (errorMsg) {
error = chalk.red(`> ${errorMsg}`);
}

return [`${prefix} ${message}`, error];
});
23 changes: 23 additions & 0 deletions packages/editor/package.json
@@ -0,0 +1,23 @@
{
"name": "@inquirer/editor",
"version": "0.0.0",
"description": "Inquirer multiline editor prompt",
"main": "index.js",
"repository": "SBoudrias/Inquirer.js",
"keywords": [
"cli",
"prompt",
"command-line",
"input"
],
"author": "Simon Boudrias <admin@simonboudrias.com>",
"license": "MIT",
"dependencies": {
"@inquirer/core": "^0.0.6-alpha.0",
"chalk": "^2.4.1",
"external-editor": "^3.0.3"
},
"publishConfig": {
"access": "public"
}
}

0 comments on commit 3ab4549

Please sign in to comment.