-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
_generic_prompt.ts
378 lines (323 loc) 路 9.62 KB
/
_generic_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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import type { Cursor } from "../ansi/cursor_position.ts";
import { tty } from "../ansi/tty.ts";
import { KeyCode, parse } from "../keycode/key_code.ts";
import { blue, bold, dim, green, italic, red } from "./deps.ts";
import { Figures } from "./figures.ts";
/** Prompt validation return tape. */
export type ValidateResult = string | boolean | Promise<string | boolean>;
/** Input keys options. */
export interface GenericPromptKeys {
submit?: string[];
}
/** Generic prompt options. */
export interface GenericPromptOptions<T, V> {
message: string;
default?: T;
hideDefault?: boolean;
validate?: (value: V) => ValidateResult;
transform?: (value: V) => T | undefined;
hint?: string;
pointer?: string;
indent?: string;
keys?: GenericPromptKeys;
cbreak?: boolean;
prefix?: string;
}
/** Generic prompt settings. */
export interface GenericPromptSettings<T, V>
extends GenericPromptOptions<T, V> {
pointer: string;
indent: string;
prefix: string;
}
/** Static generic prompt interface. */
export interface StaticGenericPrompt<
T,
V,
O extends GenericPromptOptions<T, V>,
S extends GenericPromptSettings<T, V>,
P extends GenericPrompt<T, V, S>,
> {
inject?(value: T): void;
prompt(options: O): Promise<T>;
}
/** Generic prompt representation. */
export abstract class GenericPrompt<
T,
V,
S extends GenericPromptSettings<T, V>,
> {
protected static injectedValue: unknown | undefined;
protected readonly settings: S;
protected readonly tty = tty;
protected readonly indent: string;
protected readonly cursor: Cursor = {
x: 0,
y: 0,
};
#value: T | undefined;
#lastError: string | undefined;
#isFirstRun = true;
/**
* Inject prompt value. Can be used for unit tests or pre selections.
* @param value Input value.
*/
public static inject(value: unknown): void {
GenericPrompt.injectedValue = value;
}
protected constructor(settings: S) {
this.settings = {
...settings,
keys: {
submit: ["enter", "return"],
...(settings.keys ?? {}),
},
};
this.indent = this.settings.indent ?? " ";
}
/** Execute the prompt and show cursor on end. */
public async prompt(): Promise<T> {
try {
return await this.#execute();
} finally {
this.tty.cursorShow();
}
}
/** Clear prompt output. */
protected clear(): void {
this.tty.cursorLeft.eraseDown();
}
/** Execute the prompt. */
#execute = async (): Promise<T> => {
// Throw errors on unit tests.
if (typeof GenericPrompt.injectedValue !== "undefined" && this.#lastError) {
throw new Error(await this.error());
}
await this.render();
this.#lastError = undefined;
if (!await this.read()) {
return this.#execute();
}
if (typeof this.#value === "undefined") {
throw new Error("internal error: failed to read value");
}
this.clear();
const successMessage: string | undefined = this.success(
this.#value,
);
if (successMessage) {
console.log(successMessage);
}
GenericPrompt.injectedValue = undefined;
this.tty.cursorShow();
return this.#value;
};
/** Render prompt. */
protected async render(): Promise<void> {
const result: [string, string | undefined, string | undefined] =
await Promise.all([
this.message(),
this.body?.(),
this.footer(),
]);
const content: string = result.filter(Boolean).join("\n");
const y: number = content.split("\n").length - this.cursor.y - 1;
if (!this.#isFirstRun || this.#lastError) {
this.clear();
}
this.#isFirstRun = false;
if (Deno.build.os === "windows") {
console.log(content);
this.tty.cursorUp();
} else {
Deno.stdout.writeSync(new TextEncoder().encode(content));
}
if (y) {
this.tty.cursorUp(y);
}
this.tty.cursorTo(this.cursor.x);
}
/** Read user input from stdin, handle events and validate user input. */
protected async read(): Promise<boolean> {
if (typeof GenericPrompt.injectedValue !== "undefined") {
const value: V = GenericPrompt.injectedValue as V;
await this.#validateValue(value);
} else {
const events: KeyCode[] = await this.#readKey();
if (!events.length) {
return false;
}
for (const event of events) {
await this.handleEvent(event);
}
}
return typeof this.#value !== "undefined";
}
protected submit(): Promise<void> {
return this.#validateValue(this.getValue());
}
protected message(): string {
return `${this.settings.indent}${this.settings.prefix}` +
bold(this.settings.message) + this.defaults();
}
protected defaults(): string {
let defaultMessage = "";
if (
typeof this.settings.default !== "undefined" && !this.settings.hideDefault
) {
defaultMessage += dim(` (${this.format(this.settings.default)})`);
}
return defaultMessage;
}
/** Get prompt success message. */
protected success(value: T): string | undefined {
return `${this.settings.indent}${this.settings.prefix}` +
bold(this.settings.message) + this.defaults() +
" " + this.settings.pointer +
" " + green(this.format(value));
}
protected body?(): string | undefined | Promise<string | undefined>;
protected footer(): string | undefined {
return this.error() ?? this.hint();
}
protected error(): string | undefined {
return this.#lastError
? this.settings.indent + red(bold(`${Figures.CROSS} `) + this.#lastError)
: undefined;
}
protected hint(): string | undefined {
return this.settings.hint
? this.settings.indent +
italic(blue(dim(`${Figures.POINTER} `) + this.settings.hint))
: undefined;
}
protected setErrorMessage(message: string) {
this.#lastError = message;
}
/**
* Handle user input event.
* @param event Key event.
*/
protected async handleEvent(event: KeyCode): Promise<void> {
switch (true) {
case event.name === "c" && event.ctrl:
this.clear();
this.tty.cursorShow();
Deno.exit(130);
return;
case this.isKey(this.settings.keys, "submit", event):
await this.submit();
break;
}
}
/**
* Map input value to output value.
* @param value Input value.
* @return Output value.
*/
protected abstract transform(value: V): T | undefined;
/**
* Validate input value.
* @param value User input value.
* @return True on success, false or error message on error.
*/
protected abstract validate(value: V): ValidateResult;
/**
* Format output value.
* @param value Output value.
*/
protected abstract format(value: T): string;
/** Get input value. */
protected abstract getValue(): V;
/** Read user input from stdin and pars ansi codes. */
#readKey = async (): Promise<KeyCode[]> => {
const data: Uint8Array = await this.#readChar();
return data.length ? parse(data) : [];
};
/** Read user input from stdin. */
#readChar = async (): Promise<Uint8Array> => {
const buffer = new Uint8Array(8);
const isTty = Deno.isatty(Deno.stdin.rid);
if (isTty) {
// cbreak is only supported on deno >= 1.6.0, suppress ts-error.
(Deno.setRaw as setRaw)(
Deno.stdin.rid,
true,
{ cbreak: this.settings.cbreak === true },
);
}
const nread: number | null = await Deno.stdin.read(buffer);
if (isTty) {
Deno.setRaw(Deno.stdin.rid, false);
}
if (nread === null) {
return buffer;
}
return buffer.subarray(0, nread);
};
/**
* Map input value to output value. If a custom transform handler ist set, the
* custom handler will be executed, otherwise the default transform handler
* from the prompt will be executed.
* @param value The value to transform.
*/
#transformValue = (value: V): T | undefined => {
return this.settings.transform
? this.settings.transform(value)
: this.transform(value);
};
/**
* Validate input value. Set error message if validation fails and transform
* output value on success.
* If a default value is set, the default will be used as value without any
* validation.
* If a custom validation handler ist set, the custom handler will
* be executed, otherwise a prompt specific default validation handler will be
* executed.
* @param value The value to validate.
*/
#validateValue = async (value: V): Promise<void> => {
if (!value && typeof this.settings.default !== "undefined") {
this.#value = this.settings.default;
return;
}
this.#value = undefined;
this.#lastError = undefined;
const validation =
await (this.settings.validate
? this.settings.validate(value)
: this.validate(value));
if (validation === false) {
this.#lastError = `Invalid answer.`;
} else if (typeof validation === "string") {
this.#lastError = validation;
} else {
this.#value = this.#transformValue(value);
}
};
/**
* Check if key event has given name or sequence.
* @param keys Key map.
* @param name Key name.
* @param event Key event.
*/
protected isKey<K extends unknown, N extends keyof K>(
keys: K | undefined,
name: N,
event: KeyCode,
): boolean {
// deno-lint-ignore no-explicit-any
const keyNames: Array<unknown> | undefined = keys?.[name] as any;
return typeof keyNames !== "undefined" && (
(typeof event.name !== "undefined" &&
keyNames.indexOf(event.name) !== -1) ||
(typeof event.sequence !== "undefined" &&
keyNames.indexOf(event.sequence) !== -1)
);
}
}
type setRaw = (
rid: number,
mode: boolean,
options?: { cbreak?: boolean },
) => void;