2022-01-21 08:28:41 +00:00
|
|
|
'use strict';
|
|
|
|
/**
|
|
|
|
* `confirm` type prompt
|
|
|
|
*/
|
|
|
|
|
2022-04-07 07:06:43 +00:00
|
|
|
const chalk = require('chalk');
|
|
|
|
const { take, takeUntil } = require('rxjs/operators');
|
|
|
|
const Base = require('./base');
|
|
|
|
const observe = require('../utils/events');
|
2022-01-21 08:28:41 +00:00
|
|
|
|
|
|
|
class ConfirmPrompt extends Base {
|
|
|
|
constructor(questions, rl, answers) {
|
|
|
|
super(questions, rl, answers);
|
|
|
|
|
2022-04-07 07:06:43 +00:00
|
|
|
let rawDefault = true;
|
2022-01-21 08:28:41 +00:00
|
|
|
|
2022-04-07 07:06:43 +00:00
|
|
|
Object.assign(this.opt, {
|
|
|
|
filter(input) {
|
|
|
|
let value = rawDefault;
|
2022-01-21 08:28:41 +00:00
|
|
|
if (input != null && input !== '') {
|
|
|
|
value = /^y(es)?/i.test(input);
|
|
|
|
}
|
|
|
|
|
|
|
|
return value;
|
2022-04-07 07:06:43 +00:00
|
|
|
},
|
2022-01-21 08:28:41 +00:00
|
|
|
});
|
|
|
|
|
2022-04-07 07:06:43 +00:00
|
|
|
if (this.opt.default != null) {
|
|
|
|
rawDefault = Boolean(this.opt.default);
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
this.opt.default = rawDefault ? 'Y/n' : 'y/N';
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Start the Inquiry session
|
|
|
|
* @param {Function} cb Callback when prompt is done
|
|
|
|
* @return {this}
|
|
|
|
*/
|
|
|
|
|
|
|
|
_run(cb) {
|
|
|
|
this.done = cb;
|
|
|
|
|
|
|
|
// Once user confirm (enter key)
|
2022-04-07 07:06:43 +00:00
|
|
|
const events = observe(this.rl);
|
2022-01-21 08:28:41 +00:00
|
|
|
events.keypress.pipe(takeUntil(events.line)).forEach(this.onKeypress.bind(this));
|
|
|
|
|
|
|
|
events.line.pipe(take(1)).forEach(this.onEnd.bind(this));
|
|
|
|
|
|
|
|
// Init
|
|
|
|
this.render();
|
|
|
|
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Render the prompt to screen
|
|
|
|
* @return {ConfirmPrompt} self
|
|
|
|
*/
|
|
|
|
|
|
|
|
render(answer) {
|
2022-04-07 07:06:43 +00:00
|
|
|
let message = this.getQuestion();
|
2022-01-21 08:28:41 +00:00
|
|
|
|
|
|
|
if (typeof answer === 'boolean') {
|
|
|
|
message += chalk.cyan(answer ? 'Yes' : 'No');
|
|
|
|
} else {
|
|
|
|
message += this.rl.line;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.screen.render(message);
|
|
|
|
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* When user press `enter` key
|
|
|
|
*/
|
|
|
|
|
|
|
|
onEnd(input) {
|
|
|
|
this.status = 'answered';
|
|
|
|
|
2022-04-07 07:06:43 +00:00
|
|
|
const output = this.opt.filter(input);
|
2022-01-21 08:28:41 +00:00
|
|
|
this.render(output);
|
|
|
|
|
|
|
|
this.screen.done();
|
|
|
|
this.done(output);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* When user press a key
|
|
|
|
*/
|
|
|
|
|
|
|
|
onKeypress() {
|
|
|
|
this.render();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = ConfirmPrompt;
|