/
_generic_suggestions.ts
514 lines (466 loc) 路 13.9 KB
/
_generic_suggestions.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import type { KeyCode } from "../keycode/key_code.ts";
import {
GenericInput,
GenericInputKeys,
GenericInputPromptOptions,
GenericInputPromptSettings,
} from "./_generic_input.ts";
import {
bold,
brightBlue,
dim,
dirname,
join,
normalize,
stripColor,
underline,
} from "./deps.ts";
import { Figures, getFiguresByKeys } from "./figures.ts";
import { distance } from "../_utils/distance.ts";
interface LocalStorage {
getItem(key: string): string | null;
removeItem(key: string): void;
setItem(key: string, value: string): void;
}
/** Input keys options. */
export interface GenericSuggestionsKeys extends GenericInputKeys {
complete?: string[];
next?: string[];
previous?: string[];
nextPage?: string[];
previousPage?: string[];
}
export type SuggestionHandler = (
input: string,
) => Array<string | number> | Promise<Array<string | number>>;
export type CompleteHandler = (
input: string,
suggestion?: string,
) => Promise<string> | string;
/** Generic input prompt options. */
export interface GenericSuggestionsOptions<TValue, TRawValue>
extends GenericInputPromptOptions<TValue, TRawValue> {
keys?: GenericSuggestionsKeys;
id?: string;
suggestions?: Array<string | number> | SuggestionHandler;
complete?: CompleteHandler;
files?: boolean | RegExp;
list?: boolean;
info?: boolean;
listPointer?: string;
maxRows?: number;
}
/** Generic input prompt settings. */
export interface GenericSuggestionsSettings<TValue, TRawValue>
extends GenericInputPromptSettings<TValue, TRawValue> {
keys?: GenericSuggestionsKeys;
id?: string;
suggestions?: Array<string | number> | SuggestionHandler;
complete?: CompleteHandler;
files?: boolean | RegExp;
list?: boolean;
info?: boolean;
listPointer: string;
maxRows: number;
}
const sep = Deno.build.os === "windows" ? "\\" : "/";
/** Generic input prompt representation. */
export abstract class GenericSuggestions<
TValue,
TRawValue,
TSettings extends GenericSuggestionsSettings<TValue, TRawValue>,
> extends GenericInput<TValue, TRawValue, TSettings> {
protected suggestionsIndex = -1;
protected suggestionsOffset = 0;
protected suggestions: Array<string | number> = [];
#hasReadPermissions?: boolean;
/**
* Prompt constructor.
* @param settings Prompt settings.
*/
protected constructor(settings: TSettings) {
super({
...settings,
keys: {
complete: ["tab"],
next: ["up"],
previous: ["down"],
nextPage: ["pageup"],
previousPage: ["pagedown"],
...(settings.keys ?? {}),
},
});
}
protected get localStorage(): LocalStorage | null {
// Keep support for deno < 1.10.
if (this.settings.id && "localStorage" in window) {
try {
// deno-lint-ignore no-explicit-any
return (window as any).localStorage;
} catch (_) {
// Ignore error if --location is not set.
}
}
return null;
}
protected loadSuggestions(): Array<string | number> {
if (this.settings.id) {
const json = this.localStorage?.getItem(this.settings.id);
const suggestions: Array<string | number> = json ? JSON.parse(json) : [];
if (!Array.isArray(suggestions)) {
return [];
}
return suggestions;
}
return [];
}
protected saveSuggestions(...suggestions: Array<string | number>): void {
if (this.settings.id) {
this.localStorage?.setItem(
this.settings.id,
JSON.stringify([
...suggestions,
...this.loadSuggestions(),
].filter(uniqueSuggestions)),
);
}
}
protected async render(): Promise<void> {
if (this.settings.files && this.#hasReadPermissions === undefined) {
const status = await Deno.permissions.request({ name: "read" });
// disable path completion if read permissions are denied.
this.#hasReadPermissions = status.state === "granted";
}
await this.match();
return super.render();
}
protected async match(): Promise<void> {
this.suggestions = await this.getSuggestions();
this.suggestionsIndex = Math.max(
this.getCurrentInputValue().trim().length === 0 ? -1 : 0,
Math.min(this.suggestions.length - 1, this.suggestionsIndex),
);
this.suggestionsOffset = Math.max(
0,
Math.min(
this.suggestions.length - this.getListHeight(),
this.suggestionsOffset,
),
);
}
protected input(): string {
return super.input() + dim(this.getSuggestion());
}
protected getSuggestion(): string {
return this.suggestions[this.suggestionsIndex]?.toString()
.substr(
this.getCurrentInputValue().length,
) ?? "";
}
protected async getUserSuggestions(
input: string,
): Promise<Array<string | number>> {
return typeof this.settings.suggestions === "function"
? await this.settings.suggestions(input)
: this.settings.suggestions ?? [];
}
#isFileModeEnabled(): boolean {
return !!this.settings.files && this.#hasReadPermissions === true;
}
protected async getFileSuggestions(
input: string,
): Promise<Array<string | number>> {
if (!this.#isFileModeEnabled()) {
return [];
}
const path = await Deno.stat(input)
.then((file) => file.isDirectory ? input : dirname(input))
.catch(() => dirname(input));
return await listDir(path, this.settings.files);
}
protected async getSuggestions(): Promise<Array<string | number>> {
const input = this.getCurrentInputValue();
const suggestions = [
...this.loadSuggestions(),
...await this.getUserSuggestions(input),
...await this.getFileSuggestions(input),
].filter(uniqueSuggestions);
if (!input.length) {
return suggestions;
}
return suggestions
.filter((value: string | number) =>
stripColor(value.toString())
.toLowerCase()
.startsWith(input.toLowerCase())
)
.sort((a: string | number, b: string | number) =>
distance((a || a).toString(), input) -
distance((b || b).toString(), input)
);
}
protected body(): string | Promise<string> {
return this.getList() + this.getInfo();
}
protected getInfo(): string {
if (!this.settings.info) {
return "";
}
const selected: number = this.suggestionsIndex + 1;
const matched: number = this.suggestions.length;
const actions: Array<[string, Array<string>]> = [];
if (this.suggestions.length) {
if (this.settings.list) {
actions.push(
["Next", getFiguresByKeys(this.settings.keys?.next ?? [])],
["Previous", getFiguresByKeys(this.settings.keys?.previous ?? [])],
["Next Page", getFiguresByKeys(this.settings.keys?.nextPage ?? [])],
[
"Previous Page",
getFiguresByKeys(this.settings.keys?.previousPage ?? []),
],
);
} else {
actions.push(
["Next", getFiguresByKeys(this.settings.keys?.next ?? [])],
["Previous", getFiguresByKeys(this.settings.keys?.previous ?? [])],
);
}
actions.push(
["Complete", getFiguresByKeys(this.settings.keys?.complete ?? [])],
);
}
actions.push(
["Submit", getFiguresByKeys(this.settings.keys?.submit ?? [])],
);
let info = this.settings.indent;
if (this.suggestions.length) {
info += brightBlue(Figures.INFO) + bold(` ${selected}/${matched} `);
}
info += actions
.map((cur) => `${cur[0]}: ${bold(cur[1].join(" "))}`)
.join(", ");
return info;
}
protected getList(): string {
if (!this.suggestions.length || !this.settings.list) {
return "";
}
const list: Array<string> = [];
const height: number = this.getListHeight();
for (
let i = this.suggestionsOffset;
i < this.suggestionsOffset + height;
i++
) {
list.push(
this.getListItem(
this.suggestions[i],
this.suggestionsIndex === i,
),
);
}
if (list.length && this.settings.info) {
list.push("");
}
return list.join("\n");
}
/**
* Render option.
* @param value Option.
* @param isSelected Set to true if option is selected.
*/
protected getListItem(
value: string | number,
isSelected?: boolean,
): string {
let line = this.settings.indent ?? "";
line += isSelected ? `${this.settings.listPointer} ` : " ";
if (isSelected) {
line += underline(this.highlight(value));
} else {
line += this.highlight(value);
}
return line;
}
/** Get suggestions row height. */
protected getListHeight(
suggestions: Array<string | number> = this.suggestions,
): number {
return Math.min(
suggestions.length,
this.settings.maxRows || suggestions.length,
);
}
/**
* Handle user input event.
* @param event Key event.
*/
protected async handleEvent(event: KeyCode): Promise<void> {
switch (true) {
case this.isKey(this.settings.keys, "next", event):
if (this.settings.list) {
this.selectPreviousSuggestion();
} else {
this.selectNextSuggestion();
}
break;
case this.isKey(this.settings.keys, "previous", event):
if (this.settings.list) {
this.selectNextSuggestion();
} else {
this.selectPreviousSuggestion();
}
break;
case this.isKey(this.settings.keys, "nextPage", event):
if (this.settings.list) {
this.selectPreviousSuggestionsPage();
} else {
this.selectNextSuggestionsPage();
}
break;
case this.isKey(this.settings.keys, "previousPage", event):
if (this.settings.list) {
this.selectNextSuggestionsPage();
} else {
this.selectPreviousSuggestionsPage();
}
break;
case this.isKey(this.settings.keys, "complete", event):
await this.#completeValue();
break;
case this.isKey(this.settings.keys, "moveCursorRight", event):
if (this.inputIndex < this.inputValue.length) {
this.moveCursorRight();
} else {
await this.#completeValue();
}
break;
default:
await super.handleEvent(event);
}
}
/** Delete char right. */
protected deleteCharRight(): void {
if (this.inputIndex < this.inputValue.length) {
super.deleteCharRight();
if (!this.getCurrentInputValue().length) {
this.suggestionsIndex = -1;
this.suggestionsOffset = 0;
}
}
}
async #completeValue() {
this.inputValue = await this.complete();
this.inputIndex = this.inputValue.length;
this.suggestionsIndex = 0;
this.suggestionsOffset = 0;
}
protected async complete(): Promise<string> {
let input: string = this.getCurrentInputValue();
const suggestion: string | undefined = this
.suggestions[this.suggestionsIndex]?.toString();
if (this.settings.complete) {
input = await this.settings.complete(input, suggestion);
} else if (
this.#isFileModeEnabled() &&
input.at(-1) !== sep &&
await isDirectory(input) &&
(
this.getCurrentInputValue().at(-1) !== "." ||
this.getCurrentInputValue().endsWith("..")
)
) {
input += sep;
} else if (suggestion) {
input = suggestion;
}
return this.#isFileModeEnabled() ? normalize(input) : input;
}
/** Select previous suggestion. */
protected selectPreviousSuggestion(): void {
if (this.suggestions.length) {
if (this.suggestionsIndex > -1) {
this.suggestionsIndex--;
if (this.suggestionsIndex < this.suggestionsOffset) {
this.suggestionsOffset--;
}
}
}
}
/** Select next suggestion. */
protected selectNextSuggestion(): void {
if (this.suggestions.length) {
if (this.suggestionsIndex < this.suggestions.length - 1) {
this.suggestionsIndex++;
if (
this.suggestionsIndex >=
this.suggestionsOffset + this.getListHeight()
) {
this.suggestionsOffset++;
}
}
}
}
/** Select previous suggestions page. */
protected selectPreviousSuggestionsPage(): void {
if (this.suggestions.length) {
const height: number = this.getListHeight();
if (this.suggestionsOffset >= height) {
this.suggestionsIndex -= height;
this.suggestionsOffset -= height;
} else if (this.suggestionsOffset > 0) {
this.suggestionsIndex -= this.suggestionsOffset;
this.suggestionsOffset = 0;
}
}
}
/** Select next suggestions page. */
protected selectNextSuggestionsPage(): void {
if (this.suggestions.length) {
const height: number = this.getListHeight();
if (this.suggestionsOffset + height + height < this.suggestions.length) {
this.suggestionsIndex += height;
this.suggestionsOffset += height;
} else if (this.suggestionsOffset + height < this.suggestions.length) {
const offset = this.suggestions.length - height;
this.suggestionsIndex += offset - this.suggestionsOffset;
this.suggestionsOffset = offset;
}
}
}
}
function uniqueSuggestions(
value: unknown,
index: number,
self: Array<unknown>,
) {
return typeof value !== "undefined" && value !== "" &&
self.indexOf(value) === index;
}
function isDirectory(path: string): Promise<boolean> {
return Deno.stat(path)
.then((file) => file.isDirectory)
.catch(() => false);
}
async function listDir(
path: string,
mode?: boolean | RegExp,
): Promise<Array<string>> {
const fileNames: string[] = [];
for await (const file of Deno.readDir(path || ".")) {
if (
mode === true && (file.name.startsWith(".") || file.name.endsWith("~"))
) {
continue;
}
const filePath = join(path, file.name);
if (mode instanceof RegExp && !mode.test(filePath)) {
continue;
}
fileNames.push(filePath);
}
return fileNames.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
}