interpolate.js
6.64 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
'use strict';
const colors = require('ansi-colors');
const clean = (str = '') => {
return typeof str === 'string' ? str.replace(/^['"]|['"]$/g, '') : '';
};
/**
* This file contains the interpolation and rendering logic for
* the Snippet prompt.
*/
class Item {
constructor(token) {
this.name = token.key;
this.field = token.field || {};
this.value = clean(token.initial || this.field.initial || '');
this.message = token.message || this.name;
this.cursor = 0;
this.input = '';
this.lines = [];
}
}
const tokenize = async(options = {}, defaults = {}, fn = token => token) => {
let unique = new Set();
let fields = options.fields || [];
let input = options.template;
let tabstops = [];
let items = [];
let keys = [];
let line = 1;
if (typeof input === 'function') {
input = await input();
}
let i = -1;
let next = () => input[++i];
let peek = () => input[i + 1];
let push = token => {
token.line = line;
tabstops.push(token);
};
push({ type: 'bos', value: '' });
while (i < input.length - 1) {
let value = next();
if (/^[^\S\n ]$/.test(value)) {
push({ type: 'text', value });
continue;
}
if (value === '\n') {
push({ type: 'newline', value });
line++;
continue;
}
if (value === '\\') {
value += next();
push({ type: 'text', value });
continue;
}
if ((value === '$' || value === '#' || value === '{') && peek() === '{') {
let n = next();
value += n;
let token = { type: 'template', open: value, inner: '', close: '', value };
let ch;
while ((ch = next())) {
if (ch === '}') {
if (peek() === '}') ch += next();
token.value += ch;
token.close = ch;
break;
}
if (ch === ':') {
token.initial = '';
token.key = token.inner;
} else if (token.initial !== void 0) {
token.initial += ch;
}
token.value += ch;
token.inner += ch;
}
token.template = token.open + (token.initial || token.inner) + token.close;
token.key = token.key || token.inner;
if (defaults.hasOwnProperty(token.key)) {
token.initial = defaults[token.key];
}
token = fn(token);
push(token);
keys.push(token.key);
unique.add(token.key);
let item = items.find(item => item.name === token.key);
token.field = fields.find(ch => ch.name === token.key);
if (!item) {
item = new Item(token);
items.push(item);
}
item.lines.push(token.line - 1);
continue;
}
let last = tabstops[tabstops.length - 1];
if (last.type === 'text' && last.line === line) {
last.value += value;
} else {
push({ type: 'text', value });
}
}
push({ type: 'eos', value: '' });
return { input, tabstops, unique, keys, items };
};
module.exports = async prompt => {
let options = prompt.options;
let required = new Set(options.required === true ? [] : (options.required || []));
let defaults = { ...options.values, ...options.initial };
let { tabstops, items, keys } = await tokenize(options, defaults);
let result = createFn('result', prompt, options);
let format = createFn('format', prompt, options);
let isValid = createFn('validate', prompt, options, true);
let isVal = prompt.isValue.bind(prompt);
return async(state = {}, submitted = false) => {
let index = 0;
state.required = required;
state.items = items;
state.keys = keys;
state.output = '';
let validate = async(value, state, item, index) => {
let error = await isValid(value, state, item, index);
if (error === false) {
return 'Invalid field ' + item.name;
}
return error;
};
for (let token of tabstops) {
let value = token.value;
let key = token.key;
if (token.type !== 'template') {
if (value) state.output += value;
continue;
}
if (token.type === 'template') {
let item = items.find(ch => ch.name === key);
if (options.required === true) {
state.required.add(item.name);
}
let val = [item.input, state.values[item.value], item.value, value].find(isVal);
let field = item.field || {};
let message = field.message || token.inner;
if (submitted) {
let error = await validate(state.values[key], state, item, index);
if ((error && typeof error === 'string') || error === false) {
state.invalid.set(key, error);
continue;
}
state.invalid.delete(key);
let res = await result(state.values[key], state, item, index);
state.output += colors.unstyle(res);
continue;
}
item.placeholder = false;
let before = value;
value = await format(value, state, item, index);
if (val !== value) {
state.values[key] = val;
value = prompt.styles.typing(val);
state.missing.delete(message);
} else {
state.values[key] = void 0;
val = `<${message}>`;
value = prompt.styles.primary(val);
item.placeholder = true;
if (state.required.has(key)) {
state.missing.add(message);
}
}
if (state.missing.has(message) && state.validating) {
value = prompt.styles.warning(val);
}
if (state.invalid.has(key) && state.validating) {
value = prompt.styles.danger(val);
}
if (index === state.index) {
if (before !== value) {
value = prompt.styles.underline(value);
} else {
value = prompt.styles.heading(colors.unstyle(value));
}
}
index++;
}
if (value) {
state.output += value;
}
}
let lines = state.output.split('\n').map(l => ' ' + l);
let len = items.length;
let done = 0;
for (let item of items) {
if (state.invalid.has(item.name)) {
item.lines.forEach(i => {
if (lines[i][0] !== ' ') return;
lines[i] = state.styles.danger(state.symbols.bullet) + lines[i].slice(1);
});
}
if (prompt.isValue(state.values[item.name])) {
done++;
}
}
state.completed = ((done / len) * 100).toFixed(0);
state.output = lines.join('\n');
return state.output;
};
};
function createFn(prop, prompt, options, fallback) {
return (value, state, item, index) => {
if (typeof item.field[prop] === 'function') {
return item.field[prop].call(prompt, value, state, item, index);
}
return [fallback, value].find(v => prompt.isValue(v));
};
}