1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | const _ = {
|
7 | extend: require('lodash/extend'),
|
8 | isBoolean: require('lodash/isBoolean'),
|
9 | };
|
10 | const chalk = require('chalk');
|
11 | const { take, takeUntil } = require('rxjs/operators');
|
12 | const Base = require('./base');
|
13 | const observe = require('../utils/events');
|
14 |
|
15 | class ConfirmPrompt extends Base {
|
16 | constructor(questions, rl, answers) {
|
17 | super(questions, rl, answers);
|
18 |
|
19 | let rawDefault = true;
|
20 |
|
21 | _.extend(this.opt, {
|
22 | filter(input) {
|
23 | let value = rawDefault;
|
24 | if (input != null && input !== '') {
|
25 | value = /^y(es)?/i.test(input);
|
26 | }
|
27 |
|
28 | return value;
|
29 | },
|
30 | });
|
31 |
|
32 | if (_.isBoolean(this.opt.default)) {
|
33 | rawDefault = this.opt.default;
|
34 | }
|
35 |
|
36 | this.opt.default = rawDefault ? 'Y/n' : 'y/N';
|
37 | }
|
38 |
|
39 | |
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 | _run(cb) {
|
46 | this.done = cb;
|
47 |
|
48 |
|
49 | const events = observe(this.rl);
|
50 | events.keypress.pipe(takeUntil(events.line)).forEach(this.onKeypress.bind(this));
|
51 |
|
52 | events.line.pipe(take(1)).forEach(this.onEnd.bind(this));
|
53 |
|
54 |
|
55 | this.render();
|
56 |
|
57 | return this;
|
58 | }
|
59 |
|
60 | |
61 |
|
62 |
|
63 |
|
64 |
|
65 | render(answer) {
|
66 | let message = this.getQuestion();
|
67 |
|
68 | if (typeof answer === 'boolean') {
|
69 | message += chalk.cyan(answer ? 'Yes' : 'No');
|
70 | } else {
|
71 | message += this.rl.line;
|
72 | }
|
73 |
|
74 | this.screen.render(message);
|
75 |
|
76 | return this;
|
77 | }
|
78 |
|
79 | |
80 |
|
81 |
|
82 |
|
83 | onEnd(input) {
|
84 | this.status = 'answered';
|
85 |
|
86 | const output = this.opt.filter(input);
|
87 | this.render(output);
|
88 |
|
89 | this.screen.done();
|
90 | this.done(output);
|
91 | }
|
92 |
|
93 | |
94 |
|
95 |
|
96 |
|
97 | onKeypress() {
|
98 | this.render();
|
99 | }
|
100 | }
|
101 |
|
102 | module.exports = ConfirmPrompt;
|