-
Notifications
You must be signed in to change notification settings - Fork 915
/
Copy pathget-prompt.ts
239 lines (195 loc) · 5.97 KB
/
get-prompt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import chalk from 'chalk';
import type {InputSetting, Prompter, Result, RuleEntry} from './types';
import format from './format';
import getForcedCaseFn from './get-forced-case-fn';
import getForcedLeadingFn from './get-forced-leading-fn';
import meta from './meta';
import {
enumRuleIsActive,
ruleIsNotApplicable,
ruleIsApplicable,
ruleIsActive,
getHasName,
getMaxLength,
} from './utils';
/**
* Get a cli prompt based on rule configuration
* @param type type of the data to gather
* @param context rules to parse
* @return prompt instance
*/
export default function getPrompt(
type: string,
context: {
rules?: RuleEntry[];
settings?: InputSetting;
results?: Result;
prompter?: () => Prompter;
} = {}
): Promise<string | undefined> {
const {rules = [], settings = {}, results = {}, prompter} = context;
if (typeof prompter !== 'function') {
throw new TypeError('Missing prompter function in getPrompt context');
}
const prompt = prompter();
if (typeof prompt.removeAllListeners !== 'function') {
throw new TypeError(
'getPrompt: prompt.removeAllListeners is not a function'
);
}
if (typeof prompt.command !== 'function') {
throw new TypeError('getPrompt: prompt.command is not a function');
}
if (typeof prompt.catch !== 'function') {
throw new TypeError('getPrompt: prompt.catch is not a function');
}
if (typeof prompt.addListener !== 'function') {
throw new TypeError('getPrompt: prompt.addListener is not a function');
}
if (typeof prompt.log !== 'function') {
throw new TypeError('getPrompt: prompt.log is not a function');
}
if (typeof prompt.delimiter !== 'function') {
throw new TypeError('getPrompt: prompt.delimiter is not a function');
}
if (typeof prompt.show !== 'function') {
throw new TypeError('getPrompt: prompt.show is not a function');
}
const enumRule = rules.filter(getHasName('enum')).find(enumRuleIsActive);
const emptyRule = rules.find(getHasName('empty'));
const mustBeEmpty =
emptyRule && ruleIsActive(emptyRule) && ruleIsApplicable(emptyRule);
const mayNotBeEmpty =
emptyRule && ruleIsActive(emptyRule) && ruleIsNotApplicable(emptyRule);
const mayBeEmpty = !mayNotBeEmpty;
if (mustBeEmpty) {
prompt.removeAllListeners('keypress');
prompt.removeAllListeners('client_prompt_submit');
prompt.ui.redraw.done();
return Promise.resolve(undefined);
}
const caseRule = rules.find(getHasName('case'));
const forceCaseFn = getForcedCaseFn(caseRule);
const leadingBlankRule = rules.find(getHasName('leading-blank'));
const forceLeadingBlankFn = getForcedLeadingFn(leadingBlankRule);
const maxLengthRule = rules.find(getHasName('max-length'));
const inputMaxLength = getMaxLength(maxLengthRule);
const headerLength = settings.header ? settings.header.length : Infinity;
const remainingHeaderLength = headerLength
? headerLength -
[
results.type,
results.scope,
results.scope ? '()' : '',
results.type && results.scope ? ':' : '',
results.subject,
].join('').length
: Infinity;
const maxLength = Math.min(inputMaxLength, remainingHeaderLength);
return new Promise((resolve) => {
// Add the defined enums as sub commands if applicable
if (enumRule) {
const [, [, , enums]] = enumRule;
enums.forEach((enumerable) => {
const enumSettings = (settings.enumerables || {})[enumerable] || {};
prompt
.command(enumerable)
.description(enumSettings.description || '')
.action(() => {
prompt.removeAllListeners();
prompt.ui.redraw.done();
return resolve(forceLeadingBlankFn(forceCaseFn(enumerable)));
});
});
} else {
prompt.catch('[text...]').action((parameters) => {
const {text = ''} = parameters;
prompt.removeAllListeners();
prompt.ui.redraw.done();
return resolve(forceLeadingBlankFn(forceCaseFn(text.join(' '))));
});
}
if (mayBeEmpty) {
// Add an easy exit command
prompt
.command(':skip')
.description('Skip the input if possible.')
.action(() => {
prompt.removeAllListeners();
prompt.ui.redraw.done();
resolve('');
});
}
// Handle empty input
const onSubmit = (input: string) => {
if (input.length > 0) {
return;
}
// Show help if enum is defined and input may not be empty
if (mayNotBeEmpty) {
prompt.ui.log(chalk.yellow(`⚠ ${chalk.bold(type)} may not be empty.`));
}
if (mayBeEmpty) {
prompt.ui.log(
chalk.blue(
`ℹ Enter ${chalk.bold(':skip')} to omit ${chalk.bold(type)}.`
)
);
}
if (enumRule) {
prompt.exec('help');
}
};
const drawRemaining = (length: number) => {
if (length < Infinity) {
const colors = [
{
threshold: 5,
color: chalk.red,
},
{
threshold: 10,
color: chalk.yellow,
},
{
threshold: Infinity,
color: chalk.grey,
},
];
const el = colors.find((item) => item.threshold >= length);
const color = el ? el.color : chalk.grey;
prompt.ui.redraw(color(`${length} characters left`));
}
};
const onKey = (event: {value: string}) => {
const sanitized = forceCaseFn(event.value);
const cropped = sanitized.slice(0, maxLength);
// We **could** do live editing, but there are some quirks to solve
/* const live = merge({}, results, {
[type]: cropped
});
prompt.ui.redraw(`\n\n${format(live, true)}\n\n`); */
if (maxLength) {
drawRemaining(maxLength - cropped.length);
}
prompt.ui.input(cropped);
};
prompt.addListener('keypress', onKey);
prompt.addListener('client_prompt_submit', onSubmit);
prompt.log(
`\n\nPlease enter a ${chalk.bold(type)}: ${meta({
optional: !mayNotBeEmpty,
required: mayNotBeEmpty,
'tab-completion': typeof enumRule !== 'undefined',
header: typeof settings.header !== 'undefined',
'multi-line': settings.multiline,
})}`
);
if (settings.description) {
prompt.log(chalk.grey(`${settings.description}\n`));
}
prompt.log(`\n\n${format(results, true)}\n\n`);
drawRemaining(maxLength);
prompt.delimiter(`❯ ${type}:`).show();
});
}