c69ced11a53de151074aadc982b6ad4fc018e20f
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / inquirer / lib / prompts / checkbox.js
1 'use strict';
2 /**
3  * `list` type prompt
4  */
5
6 var _ = {
7   isArray: require('lodash/isArray'),
8   map: require('lodash/map'),
9   isString: require('lodash/isString'),
10 };
11 var chalk = require('chalk');
12 var cliCursor = require('cli-cursor');
13 var figures = require('figures');
14 var { map, takeUntil } = require('rxjs/operators');
15 var Base = require('./base');
16 var observe = require('../utils/events');
17 var Paginator = require('../utils/paginator');
18
19 class CheckboxPrompt extends Base {
20   constructor(questions, rl, answers) {
21     super(questions, rl, answers);
22
23     if (!this.opt.choices) {
24       this.throwParamError('choices');
25     }
26
27     if (_.isArray(this.opt.default)) {
28       this.opt.choices.forEach(function (choice) {
29         if (this.opt.default.indexOf(choice.value) >= 0) {
30           choice.checked = true;
31         }
32       }, this);
33     }
34
35     this.pointer = 0;
36
37     // Make sure no default is set (so it won't be printed)
38     this.opt.default = null;
39
40     this.paginator = new Paginator(this.screen);
41   }
42
43   /**
44    * Start the Inquiry session
45    * @param  {Function} cb      Callback when prompt is done
46    * @return {this}
47    */
48
49   _run(cb) {
50     this.done = cb;
51
52     var events = observe(this.rl);
53
54     var validation = this.handleSubmitEvents(
55       events.line.pipe(map(this.getCurrentValue.bind(this)))
56     );
57     validation.success.forEach(this.onEnd.bind(this));
58     validation.error.forEach(this.onError.bind(this));
59
60     events.normalizedUpKey
61       .pipe(takeUntil(validation.success))
62       .forEach(this.onUpKey.bind(this));
63     events.normalizedDownKey
64       .pipe(takeUntil(validation.success))
65       .forEach(this.onDownKey.bind(this));
66     events.numberKey
67       .pipe(takeUntil(validation.success))
68       .forEach(this.onNumberKey.bind(this));
69     events.spaceKey
70       .pipe(takeUntil(validation.success))
71       .forEach(this.onSpaceKey.bind(this));
72     events.aKey.pipe(takeUntil(validation.success)).forEach(this.onAllKey.bind(this));
73     events.iKey.pipe(takeUntil(validation.success)).forEach(this.onInverseKey.bind(this));
74
75     // Init the prompt
76     cliCursor.hide();
77     this.render();
78     this.firstRender = false;
79
80     return this;
81   }
82
83   /**
84    * Render the prompt to screen
85    * @return {CheckboxPrompt} self
86    */
87
88   render(error) {
89     // Render question
90     var message = this.getQuestion();
91     var bottomContent = '';
92
93     if (!this.spaceKeyPressed) {
94       message +=
95         '(Press ' +
96         chalk.cyan.bold('<space>') +
97         ' to select, ' +
98         chalk.cyan.bold('<a>') +
99         ' to toggle all, ' +
100         chalk.cyan.bold('<i>') +
101         ' to invert selection)';
102     }
103
104     // Render choices or answer depending on the state
105     if (this.status === 'answered') {
106       message += chalk.cyan(this.selection.join(', '));
107     } else {
108       var choicesStr = renderChoices(this.opt.choices, this.pointer);
109       var indexPosition = this.opt.choices.indexOf(
110         this.opt.choices.getChoice(this.pointer)
111       );
112       var realIndexPosition =
113         this.opt.choices.reduce(function (acc, value, i) {
114           // Dont count lines past the choice we are looking at
115           if (i > indexPosition) {
116             return acc;
117           }
118           // Add line if it's a separator
119           if (value.type === 'separator') {
120             return acc + 1;
121           }
122
123           var l = value.name;
124           // Non-strings take up one line
125           if (typeof l !== 'string') {
126             return acc + 1;
127           }
128
129           // Calculate lines taken up by string
130           l = l.split('\n');
131           return acc + l.length;
132         }, 0) - 1;
133       message +=
134         '\n' + this.paginator.paginate(choicesStr, realIndexPosition, this.opt.pageSize);
135     }
136
137     if (error) {
138       bottomContent = chalk.red('>> ') + error;
139     }
140
141     this.screen.render(message, bottomContent);
142   }
143
144   /**
145    * When user press `enter` key
146    */
147
148   onEnd(state) {
149     this.status = 'answered';
150     this.spaceKeyPressed = true;
151     // Rerender prompt (and clean subline error)
152     this.render();
153
154     this.screen.done();
155     cliCursor.show();
156     this.done(state.value);
157   }
158
159   onError(state) {
160     this.render(state.isValid);
161   }
162
163   getCurrentValue() {
164     var choices = this.opt.choices.filter(function (choice) {
165       return Boolean(choice.checked) && !choice.disabled;
166     });
167
168     this.selection = _.map(choices, 'short');
169     return _.map(choices, 'value');
170   }
171
172   onUpKey() {
173     var len = this.opt.choices.realLength;
174     this.pointer = this.pointer > 0 ? this.pointer - 1 : len - 1;
175     this.render();
176   }
177
178   onDownKey() {
179     var len = this.opt.choices.realLength;
180     this.pointer = this.pointer < len - 1 ? this.pointer + 1 : 0;
181     this.render();
182   }
183
184   onNumberKey(input) {
185     if (input <= this.opt.choices.realLength) {
186       this.pointer = input - 1;
187       this.toggleChoice(this.pointer);
188     }
189
190     this.render();
191   }
192
193   onSpaceKey() {
194     this.spaceKeyPressed = true;
195     this.toggleChoice(this.pointer);
196     this.render();
197   }
198
199   onAllKey() {
200     var shouldBeChecked = Boolean(
201       this.opt.choices.find(function (choice) {
202         return choice.type !== 'separator' && !choice.checked;
203       })
204     );
205
206     this.opt.choices.forEach(function (choice) {
207       if (choice.type !== 'separator') {
208         choice.checked = shouldBeChecked;
209       }
210     });
211
212     this.render();
213   }
214
215   onInverseKey() {
216     this.opt.choices.forEach(function (choice) {
217       if (choice.type !== 'separator') {
218         choice.checked = !choice.checked;
219       }
220     });
221
222     this.render();
223   }
224
225   toggleChoice(index) {
226     var item = this.opt.choices.getChoice(index);
227     if (item !== undefined) {
228       this.opt.choices.getChoice(index).checked = !item.checked;
229     }
230   }
231 }
232
233 /**
234  * Function for rendering checkbox choices
235  * @param  {Number} pointer Position of the pointer
236  * @return {String}         Rendered content
237  */
238
239 function renderChoices(choices, pointer) {
240   var output = '';
241   var separatorOffset = 0;
242
243   choices.forEach(function (choice, i) {
244     if (choice.type === 'separator') {
245       separatorOffset++;
246       output += ' ' + choice + '\n';
247       return;
248     }
249
250     if (choice.disabled) {
251       separatorOffset++;
252       output += ' - ' + choice.name;
253       output += ' (' + (_.isString(choice.disabled) ? choice.disabled : 'Disabled') + ')';
254     } else {
255       var line = getCheckbox(choice.checked) + ' ' + choice.name;
256       if (i - separatorOffset === pointer) {
257         output += chalk.cyan(figures.pointer + line);
258       } else {
259         output += ' ' + line;
260       }
261     }
262
263     output += '\n';
264   });
265
266   return output.replace(/\n$/, '');
267 }
268
269 /**
270  * Get the checkbox
271  * @param  {Boolean} checked - add a X or not to the checkbox
272  * @return {String} Composited checkbox string
273  */
274
275 function getCheckbox(checked) {
276   return checked ? chalk.green(figures.radioOn) : figures.radioOff;
277 }
278
279 module.exports = CheckboxPrompt;