UNPKG

3.33 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6/// <reference path="./inquirer.d.ts" />
7const chalk_1 = __importDefault(require("chalk"));
8const input_1 = __importDefault(require("inquirer/lib/prompts/input"));
9const events_1 = __importDefault(require("inquirer/lib/utils/events"));
10class InputCustomPrompt extends input_1.default {
11 constructor(question, readLine, answers) {
12 super(question, readLine, answers);
13 if (this.opt.log) {
14 this.rl.write(this.opt.log(answers));
15 }
16 if (!this.opt.maxLength) {
17 this.throwParamError('maxLength');
18 }
19 const events = (0, events_1.default)(this.rl);
20 this.lineSubscription = events.keypress.subscribe(this.onKeyPress2.bind(this));
21 this.tabCompletion = (this.opt.tabCompletion || [])
22 .map((item) => item.value)
23 .sort((a, b) => a.localeCompare(b));
24 }
25 onEnd(state) {
26 this.lineSubscription.unsubscribe();
27 super.onEnd(state);
28 }
29 /**
30 * @see https://nodejs.org/api/readline.html#readline_rl_write_data_key
31 * @see https://nodejs.org/api/readline.html#readline_rl_line
32 */
33 updateLine(line) {
34 this.rl.write(null, { ctrl: true, name: 'b' });
35 this.rl.write(null, { ctrl: true, name: 'd' });
36 this.rl.write(line.substr(this.rl.line.length));
37 }
38 onKeyPress2(e) {
39 if (e.key.name === 'tab' && this.tabCompletion.length > 0) {
40 let line = this.rl.line.trim();
41 if (line.length > 0) {
42 for (const item of this.tabCompletion) {
43 if (item.startsWith(line) && item !== line) {
44 line = item;
45 break;
46 }
47 }
48 }
49 this.updateLine(line);
50 }
51 }
52 measureInput(input) {
53 if (this.opt.filter) {
54 return this.opt.filter(input).length;
55 }
56 return input.length;
57 }
58 render(error) {
59 const answered = this.status === 'answered';
60 let message = this.getQuestion();
61 const length = this.measureInput(this.rl.line);
62 if (answered) {
63 message += chalk_1.default.cyan(this.answer);
64 }
65 else if (this.opt.transformer) {
66 message += this.opt.transformer(this.rl.line, this.answers, {});
67 }
68 let bottomContent = '';
69 if (error) {
70 bottomContent = chalk_1.default.red('>> ') + error;
71 }
72 else if (!answered) {
73 const maxLength = this.opt.maxLength(this.answers);
74 if (maxLength < Infinity) {
75 const lengthRemaining = maxLength - length;
76 const color = lengthRemaining <= 5
77 ? chalk_1.default.red
78 : lengthRemaining <= 10
79 ? chalk_1.default.yellow
80 : chalk_1.default.grey;
81 bottomContent = color(`${lengthRemaining} characters left`);
82 }
83 }
84 this.screen.render(message, bottomContent);
85 }
86}
87exports.default = InputCustomPrompt;
88//# sourceMappingURL=InputCustomPrompt.js.map
\No newline at end of file