-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathcliPicker.ts
More file actions
96 lines (81 loc) · 2.16 KB
/
cliPicker.ts
File metadata and controls
96 lines (81 loc) · 2.16 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
/**
* 인터랙티브 목록 선택 유틸리티
*
* 번호 선택, /키워드 필터, all(전체 복원), 0(취소)을 지원합니다.
*/
type WriteFn = (message: string) => void;
export interface ChoicePrompt {
ask: (question: string) => Promise<string>;
}
interface PickerOptions<T> {
prompt: ChoicePrompt;
writeOut: WriteFn;
title: string;
emptyText: string;
cancelText: string;
items: T[];
renderItem: (item: T, index: number) => string;
indexText?: string;
filterText?: (item: T) => string;
}
function normalize(value: string): string {
return value.toLowerCase();
}
function defaultFilterText<T>(item: T): string {
return typeof item === 'string' ? item : JSON.stringify(item);
}
export async function pickFromList<T>(options: PickerOptions<T>): Promise<T | null> {
const {
prompt,
writeOut,
title,
emptyText,
cancelText,
items,
renderItem,
indexText = '입력: 번호 선택 | /키워드 필터 | all 전체보기 | 0 취소',
filterText = defaultFilterText,
} = options;
if (items.length === 0) {
writeOut(emptyText);
return null;
}
let visibleItems = items;
while (true) {
writeOut('');
writeOut(title);
for (let i = 0; i < visibleItems.length; i += 1) {
writeOut(renderItem(visibleItems[i], i));
}
writeOut(indexText);
const answer = await prompt.ask('선택: ');
if (answer === '0') {
writeOut(cancelText);
return null;
}
if (answer === 'all') {
visibleItems = items;
continue;
}
if (answer.startsWith('/')) {
const query = answer.slice(1).trim();
if (!query) {
visibleItems = items;
continue;
}
const needle = normalize(query);
const filtered = items.filter((item) => normalize(filterText(item)).includes(needle));
if (filtered.length === 0) {
writeOut(`"${query}" 검색 결과가 없습니다.`);
continue;
}
visibleItems = filtered;
continue;
}
const picked = Number.parseInt(answer, 10);
if (Number.isNaN(picked) || picked < 1 || picked > visibleItems.length) {
continue;
}
return visibleItems[picked - 1];
}
}