Skip to content

Instantly share code, notes, and snippets.

@codebymikey
Created August 11, 2021 11:28
Show Gist options
  • Save codebymikey/4036f3e0d55e9a35f7a579645e5dd48a to your computer and use it in GitHub Desktop.
Save codebymikey/4036f3e0d55e9a35f7a579645e5dd48a to your computer and use it in GitHub Desktop.
Plop.js Inquirer.js multiple inputs e.g. for input tags or taxonomies.
const BaseInput = require('inquirer/lib/prompts/input');
/**
* A custom inquirer input plugin that keeps requesting the same input until
* nothing is specified.
* Useful for taking in the same input multiple times e.g. tags.
*/
class InputMultiplePrompt extends BaseInput {
constructor(...args) {
super(...args)
this.opt.validate = this.createValidator(this.opt.validate)
this.multipleInputOutput = []
}
createValidator(validate) {
return (...args) => {
const [input] = args;
const isValid = validate(...args);
// Empty response, simply an Enter.
const noResponse = !input;
if (isValid && input) {
this.multipleInputOutput.push(input);
// Allow it to print a second time.
this.screen.done();
}
return isValid && noResponse;
};
}
onEnd(state) {
state.value = this.multipleInputOutput;
this.answer = state.value;
this.status = 'answered';
// No need to re-render prompt.
// this.render();
this.screen.done();
this.done(state.value);
}
}
/**
* Plop support - https://github.com/plopjs/plop#3rd-party-prompt-bypass
*/
InputMultiplePrompt.bypass = function bypass(rawValue, promptConfig) {
let value = rawValue;
if (typeof rawValue === 'string') {
try {
value = JSON.parse( String(rawValue) );
} catch ( e ) {
throw new Error(`"${ rawValue }" is not a valid JSON string.`);
}
}
if (!Array.isArray(value)) {
throw new Error(`"${ rawValue }" is not a valid array.`);
}
return value;
};
module.exports = InputMultiplePrompt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment