pal-code 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,11 @@
1
1
  /** Model picker — lists exactly what each configured provider reports. */
2
2
 
3
- import {Text} from '../tui/components/text.js';
4
- import {SelectList} from '@earendil-works/pi-tui';
5
3
  import type {TUI, Container, Editor, SelectItem} from '@earendil-works/pi-tui';
6
4
  import {PROVIDERS, resolveModelIds, saveSetting} from '@pal-code/core';
7
5
  import type {Provider, ProviderKeys} from '@pal-code/core';
8
6
 
9
- import {c, surface} from '../theme.js';
10
7
  import {state} from '../state.js';
8
+ import {showSelectOverlay} from './select.js';
11
9
 
12
10
  /**
13
11
  * Build the /model picker from each provider's live /models response.
@@ -41,7 +39,7 @@ export async function buildModelOptions(allKeys: ProviderKeys): Promise<SelectIt
41
39
  * Swap the editor for an inline model list. Selecting persists the choice and
42
40
  * rebuilds the live provider; the caller's `providerRef` is updated in place.
43
41
  */
44
- export async function showModelSelector(
42
+ export function showModelSelector(
45
43
  config: {model: string},
46
44
  container: Container,
47
45
  editor: Editor,
@@ -50,58 +48,22 @@ export async function showModelSelector(
50
48
  providerRef: {current: Provider},
51
49
  createProviderFn: (model: string) => Provider,
52
50
  allKeys: ProviderKeys,
53
- ): Promise<void> {
54
- state.overlayMode = 'model-select';
55
-
56
- // Remove the editor from view
57
- editorRow.removeChild(editor);
58
-
59
- // Loading placeholder while we fetch live model lists
60
- const label = new Text(`\n${c.bold}Select model:${c.reset} ${c.dim}loading…${c.reset}\n`, 1, 0);
61
- container.addChild(label);
62
- tui.requestRender();
63
-
64
- const options = await buildModelOptions(allKeys);
65
-
66
- const selectList = new SelectList(options, 14, {
67
- selectedPrefix: (_text: string) => `${surface.overlay.selectedPrefix}> ${c.reset}`,
68
- selectedText: (text: string) => `${surface.overlay.selectedText}${text}${c.reset}`,
69
- description: (text: string) => `${surface.overlay.description}${text}${c.reset}`,
70
- scrollInfo: (text: string) => `${surface.overlay.scrollInfo}${text}${c.reset}`,
71
- noMatch: (text: string) => `${surface.overlay.noMatch}${text}${c.reset}`,
72
- });
73
-
74
- // Highlight the current model
75
- const currentIdx = options.findIndex((m) => m.value === config.model);
76
- if (currentIdx >= 0) selectList.setSelectedIndex(currentIdx);
77
-
78
- // Swap the placeholder for the real prompt + list
79
- label.setText(
80
- `\n${c.bold}Select model:${c.reset} ${c.dim}(type to filter, ↑↓ navigate, Enter select, Esc cancel)${c.reset}\n`,
51
+ ): void {
52
+ showSelectOverlay(
53
+ {
54
+ title: 'Select model',
55
+ items: buildModelOptions(allKeys),
56
+ loadingText: 'loading…',
57
+ selectedValue: config.model,
58
+ noMatch: 'No models available.',
59
+ onSelect: (item) => {
60
+ config.model = item.value;
61
+ saveSetting('model', item.value);
62
+ providerRef.current = createProviderFn(item.value);
63
+ providerRef.current.init();
64
+ state.refreshStatusLine();
65
+ },
66
+ },
67
+ {container, editor, editorRow, tui},
81
68
  );
82
- container.addChild(selectList);
83
- tui.setFocus(selectList);
84
- tui.requestRender();
85
-
86
- const close = (): void => {
87
- container.removeChild(label);
88
- container.removeChild(selectList);
89
- editorRow.addChild(editor);
90
- tui.setFocus(editor);
91
- state.overlayMode = 'none';
92
- tui.requestRender();
93
- };
94
-
95
- selectList.onSelect = (item) => {
96
- config.model = item.value;
97
- saveSetting('model', item.value);
98
- // Recreate the provider for the new model
99
- providerRef.current = createProviderFn(item.value);
100
- providerRef.current.init();
101
- close();
102
- // Reflect the new model name in the status bar immediately.
103
- state.refreshStatusLine();
104
- };
105
-
106
- selectList.onCancel = close;
107
69
  }
@@ -0,0 +1,102 @@
1
+ /** Standard filterable list overlay shared by every "pick one" flow. */
2
+
3
+ import {SelectList} from '@earendil-works/pi-tui';
4
+ import type {TUI, Container, Editor, SelectItem} from '@earendil-works/pi-tui';
5
+
6
+ import {Text} from '../tui/components/text.js';
7
+ import {c, surface} from '../theme.js';
8
+ import {state} from '../state.js';
9
+
10
+ export interface SelectContext {
11
+ container: Container;
12
+ editor: Editor;
13
+ editorRow: Container;
14
+ tui: TUI;
15
+ }
16
+
17
+ export interface SelectOverlayOptions {
18
+ title: string;
19
+ items: SelectItem[] | Promise<SelectItem[]>;
20
+ hint?: string;
21
+ height?: number;
22
+ selectedValue?: string;
23
+ noMatch?: string;
24
+ loadingText?: string;
25
+ onSelect: (item: SelectItem) => void;
26
+ onCancel?: () => void;
27
+ }
28
+
29
+ const DEFAULT_HINT = 'type to filter, ↑↓ navigate, Enter select, Esc cancel';
30
+
31
+ export function showSelectOverlay(opts: SelectOverlayOptions, ctx: SelectContext): void {
32
+ const {container, editor, editorRow, tui} = ctx;
33
+ state.overlayMode = 'select';
34
+ editorRow.removeChild(editor);
35
+
36
+ const header = (text: string): string =>
37
+ `\n${c.bold}${opts.title}:${c.reset} ${c.dim}${text}${c.reset}\n`;
38
+ const pending = typeof (opts.items as {then?: unknown}).then === 'function';
39
+
40
+ const label = new Text(
41
+ header(pending ? (opts.loadingText ?? 'loading…') : (opts.hint ?? DEFAULT_HINT)),
42
+ 1,
43
+ 0,
44
+ );
45
+ container.addChild(label);
46
+ tui.requestRender();
47
+
48
+ const restore = (): void => {
49
+ editorRow.addChild(editor);
50
+ tui.setFocus(editor);
51
+ state.overlayMode = 'none';
52
+ tui.requestRender();
53
+ };
54
+
55
+ const render = (items: SelectItem[]): void => {
56
+ if (items.length === 0) {
57
+ label.setText(header(opts.noMatch ?? 'Nothing to select.'));
58
+ restore();
59
+ return;
60
+ }
61
+
62
+ label.setText(header(opts.hint ?? DEFAULT_HINT));
63
+
64
+ const list = new SelectList(items, opts.height ?? 14, {
65
+ selectedPrefix: (_text: string) => `${surface.overlay.selectedPrefix}> ${c.reset}`,
66
+ selectedText: (text: string) => `${surface.overlay.selectedText}${text}${c.reset}`,
67
+ description: (text: string) => ` ${surface.overlay.description}${text}${c.reset}`,
68
+ scrollInfo: (text: string) => `${surface.overlay.scrollInfo}${text}${c.reset}`,
69
+ noMatch: (text: string) => `${surface.overlay.noMatch}${text}${c.reset}`,
70
+ });
71
+
72
+ if (opts.selectedValue) {
73
+ const index = items.findIndex((item) => item.value === opts.selectedValue);
74
+ if (index >= 0) list.setSelectedIndex(index);
75
+ }
76
+
77
+ container.addChild(list);
78
+ tui.setFocus(list);
79
+ tui.requestRender();
80
+
81
+ const close = (): void => {
82
+ container.removeChild(label);
83
+ container.removeChild(list);
84
+ restore();
85
+ };
86
+
87
+ list.onSelect = (item) => {
88
+ close();
89
+ opts.onSelect(item);
90
+ };
91
+ list.onCancel = () => {
92
+ close();
93
+ opts.onCancel?.();
94
+ };
95
+ };
96
+
97
+ if (pending) {
98
+ (opts.items as Promise<SelectItem[]>).then(render).catch(() => render([]));
99
+ } else {
100
+ render(opts.items as SelectItem[]);
101
+ }
102
+ }
@@ -6,19 +6,19 @@
6
6
  */
7
7
 
8
8
  import {Text} from '../tui/components/text.js';
9
- import {SelectList} from '@earendil-works/pi-tui';
10
9
  import type {TUI, Container, Editor, SelectItem} from '@earendil-works/pi-tui';
11
10
 
12
- import {c, surface} from '../theme.js';
11
+ import {c} from '../theme.js';
13
12
  import {truncate} from '../tui/render/format.js';
14
13
  import type {ConversationMessage as Message, Session, SessionStore} from '@pal-code/core';
14
+ import {showSelectOverlay} from './select.js';
15
15
 
16
16
  export function groupByDate(sessions: readonly Session[]): Map<string, Session[]> {
17
17
  const now = new Date();
18
18
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
19
19
  const yesterday = today - 86_400_000;
20
20
  const weekAgo = today - 7 * 86_400_000;
21
- const groups = new Map<string, any[]>();
21
+ const groups = new Map<string, Session[]>();
22
22
  for (const s of sessions) {
23
23
  const ts = s.createdAt ?? s.updatedAt ?? 0;
24
24
  let label: string;
@@ -72,43 +72,16 @@ export function showSessionSelector(
72
72
  }
73
73
  }
74
74
 
75
- const selectList = new SelectList(items, 12, {
76
- selectedPrefix: (_text: string) => `${surface.overlay.selectedPrefix}> ${c.reset}`,
77
- selectedText: (text: string) => `${surface.overlay.selectedText}${text}${c.reset}`,
78
- description: (text: string) => ` ${surface.overlay.description}${text}${c.reset}`,
79
- scrollInfo: (text: string) => `${surface.overlay.scrollInfo}${text}${c.reset}`,
80
- noMatch: (_text: string) => `${surface.overlay.noMatch} No matching sessions.${c.reset}`,
81
- });
82
-
83
- const label = new Text(
84
- `\n${c.bold}Select session:${c.reset} ${c.dim}(type to filter, ↑↓ navigate, Enter select, Esc cancel)${c.reset}\n`,
85
- 1,
86
- 0,
75
+ showSelectOverlay(
76
+ {
77
+ title: 'Select session',
78
+ items,
79
+ height: 12,
80
+ noMatch: ' No matching sessions.',
81
+ onSelect: (item) => onSessionSelected(item.value),
82
+ },
83
+ {container, editor, editorRow, tui},
87
84
  );
88
- container.addChild(label);
89
- container.addChild(selectList);
90
- tui.setFocus(selectList);
91
- tui.requestRender();
92
-
93
- selectList.onSelect = (item) => {
94
- container.removeChild(label);
95
- container.removeChild(selectList);
96
- editorRow.addChild(editor);
97
- tui.setFocus(editor);
98
- onSessionSelected(item.value);
99
- tui.requestRender();
100
- };
101
-
102
- selectList.onCancel = () => {
103
- container.removeChild(label);
104
- container.removeChild(selectList);
105
- editorRow.addChild(editor);
106
- tui.setFocus(editor);
107
- tui.requestRender();
108
- };
109
-
110
- // Remove editor from view while selecting
111
- editorRow.removeChild(editor);
112
85
  }
113
86
 
114
87
  /**
@@ -1,14 +1,28 @@
1
1
  /**
2
2
  * First-run BYOK setup — runs BEFORE the TUI takes over stdin.
3
3
  *
4
- * It needs its own line reader because bun's `readline/promises` never
5
- * resolves on piped stdin, and the raw `data`-event reader below is also what
6
- * lets the wizard run without entering raw mode.
4
+ * Provider selection uses the standalone raw-mode picker in `prompt/select.ts`
5
+ * (no pi-tui); key entry uses the line reader below because bun's
6
+ * `readline/promises` never resolves on piped stdin.
7
7
  */
8
8
 
9
- import {PROVIDERS, detectProvider, saveKey, saveSetting, configPath} from '@pal-code/core';
9
+ import {
10
+ PROVIDERS,
11
+ detectProvider,
12
+ resolveAllKeys,
13
+ saveKey,
14
+ saveSetting,
15
+ configPath,
16
+ } from '@pal-code/core';
17
+ import type {ProviderKeys} from '@pal-code/core';
10
18
 
11
19
  import {c} from '../theme.js';
20
+ import {canPromptInteractively, promptSelect} from '../prompt/select.js';
21
+ import type {PromptItem} from '../prompt/select.js';
22
+
23
+ type Provider = (typeof PROVIDERS)[number];
24
+
25
+ const PASTE_KEY = '__paste__';
12
26
 
13
27
  const _lineQueue: string[] = [];
14
28
  let _pendingLine: ((line: string) => void) | null = null;
@@ -69,8 +83,8 @@ export async function ask(prompt: string): Promise<string> {
69
83
  }
70
84
 
71
85
  /**
72
- * Interactive first-run setup. Plain stdin/stdout (not the TUI) so it works
73
- * before raw mode. Saves the key + default model into ~/.pal/config.json.
86
+ * Interactive first-run setup. Saves the key + default model into
87
+ * ~/.pal/config.json.
74
88
  */
75
89
  export async function runSetupWizard(): Promise<boolean> {
76
90
  console.log('');
@@ -79,47 +93,18 @@ export async function runSetupWizard(): Promise<boolean> {
79
93
  `${c.dim} pal is BYOK (bring your own key). Pick a provider, paste your key.${c.reset}`,
80
94
  );
81
95
  console.log('');
82
- PROVIDERS.forEach((p, i) => {
83
- const tag = p.keyOptional ? `${c.green}free-ok${c.reset}` : '';
84
- console.log(
85
- ` ${c.bold}${String(i + 1).padStart(2)}${c.reset}. ${p.name.padEnd(16)} ${c.dim}${providerHint(p)}${c.reset} ${tag}`,
86
- );
87
- });
88
- console.log('');
96
+ const configured = resolveAllKeys();
89
97
 
90
- const first = await ask(` ${c.bold}Provider number or paste an API key:${c.reset} `);
91
- if (!first) {
98
+ const picked = canPromptInteractively()
99
+ ? await pickProviderInteractive(configured)
100
+ : await pickProviderNumeric(configured);
101
+ if (!picked) {
92
102
  console.log(`${c.red} Setup cancelled. Run pal again to retry.${c.reset}`);
93
103
  return false;
94
104
  }
95
105
 
96
- let provider = null as (typeof PROVIDERS)[number] | null;
97
- let key = '';
98
-
99
- const asNum = Number(first);
100
- if (Number.isInteger(asNum) && asNum >= 1 && asNum <= PROVIDERS.length) {
101
- provider = PROVIDERS[asNum - 1];
102
- key = await ask(
103
- provider.keyOptional
104
- ? ` ${c.bold}Paste your ${provider.name} API key (Enter for keyless):${c.reset} `
105
- : ` ${c.bold}Paste your ${provider.name} API key:${c.reset} `,
106
- );
107
- } else {
108
- key = first;
109
- provider = detectProvider(key);
110
- if (!provider) {
111
- console.log(`${c.yellow} Could not detect the provider from that key shape.${c.reset}`);
112
- const pick = await ask(` ${c.bold}Provider number:${c.reset} `);
113
- const n = Number(pick);
114
- provider = Number.isInteger(n) && n >= 1 && n <= PROVIDERS.length ? PROVIDERS[n - 1] : null;
115
- }
116
- }
117
-
118
- if (!provider) {
119
- console.log(`${c.red} Setup cancelled — no provider selected.${c.reset}`);
120
- return false;
121
- }
122
- if (!key && !provider.keyOptional) {
106
+ const {provider, key} = picked;
107
+ if (!key && !(provider.keyOptional && !configured[provider.id])) {
123
108
  console.log(`${c.red} Setup cancelled — no key saved.${c.reset}`);
124
109
  return false;
125
110
  }
@@ -143,3 +128,83 @@ export async function runSetupWizard(): Promise<boolean> {
143
128
  console.log('');
144
129
  return true;
145
130
  }
131
+
132
+ async function pickProviderInteractive(
133
+ configured: ProviderKeys,
134
+ ): Promise<{provider: Provider; key: string} | null> {
135
+ const items: PromptItem[] = [
136
+ ...PROVIDERS.map((p) => ({
137
+ value: p.id,
138
+ label: p.name,
139
+ description: [providerHint(p), p.keyOptional && !configured[p.id] ? 'free-ok' : '']
140
+ .filter(Boolean)
141
+ .join(' · '),
142
+ })),
143
+ {value: PASTE_KEY, label: 'Paste an API key…', description: 'Auto-detect the provider'},
144
+ ];
145
+ const selectedValue =
146
+ PROVIDERS.find((p) => configured[p.id])?.id ?? PROVIDERS.find((p) => p.keyOptional)?.id;
147
+
148
+ for (;;) {
149
+ const picked = await promptSelect({title: 'Select provider', items, selectedValue});
150
+ if (!picked) return null;
151
+
152
+ if (picked.value === PASTE_KEY) {
153
+ const pasted = await ask(` ${c.bold}Paste your API key:${c.reset} `);
154
+ if (!pasted) continue;
155
+ const detected = detectProvider(pasted);
156
+ if (!detected) {
157
+ console.log(`${c.yellow} Could not detect the provider from that key shape.${c.reset}`);
158
+ continue;
159
+ }
160
+ return {provider: detected, key: pasted};
161
+ }
162
+
163
+ const provider = PROVIDERS.find((p) => p.id === picked.value);
164
+ if (!provider) continue;
165
+ const key = await ask(
166
+ provider.keyOptional && !configured[provider.id]
167
+ ? ` ${c.bold}Paste your ${provider.name} API key (Enter for keyless):${c.reset} `
168
+ : ` ${c.bold}Paste your ${provider.name} API key:${c.reset} `,
169
+ );
170
+ return {provider, key};
171
+ }
172
+ }
173
+
174
+ async function pickProviderNumeric(
175
+ configured: ProviderKeys,
176
+ ): Promise<{provider: Provider; key: string} | null> {
177
+ PROVIDERS.forEach((p, i) => {
178
+ const tag = p.keyOptional && !configured[p.id] ? `${c.green}free-ok${c.reset}` : '';
179
+ console.log(
180
+ ` ${c.bold}${String(i + 1).padStart(2)}${c.reset}. ${p.name.padEnd(16)} ${c.dim}${providerHint(p)}${c.reset} ${tag}`,
181
+ );
182
+ });
183
+ console.log('');
184
+
185
+ const first = await ask(` ${c.bold}Provider number or paste an API key:${c.reset} `);
186
+ if (!first) return null;
187
+
188
+ const asNum = Number(first);
189
+ if (Number.isInteger(asNum) && asNum >= 1 && asNum <= PROVIDERS.length) {
190
+ const provider = PROVIDERS[asNum - 1];
191
+ const key = await ask(
192
+ provider.keyOptional && !configured[provider.id]
193
+ ? ` ${c.bold}Paste your ${provider.name} API key (Enter for keyless):${c.reset} `
194
+ : ` ${c.bold}Paste your ${provider.name} API key:${c.reset} `,
195
+ );
196
+ return {provider, key};
197
+ }
198
+
199
+ const detected = detectProvider(first);
200
+ if (detected) return {provider: detected, key: first};
201
+
202
+ console.log(`${c.yellow} Could not detect the provider from that key shape.${c.reset}`);
203
+ const pick = await ask(` ${c.bold}Provider number:${c.reset} `);
204
+ const n = Number(pick);
205
+ const provider = Number.isInteger(n) && n >= 1 && n <= PROVIDERS.length ? PROVIDERS[n - 1] : null;
206
+ if (!provider) return null;
207
+
208
+ const key = await ask(` ${c.bold}Paste your ${provider.name} API key:${c.reset} `);
209
+ return {provider, key};
210
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Minimal interactive picker for flows that run before the pi-tui app owns
3
+ * stdin. Self-contained: raw stdin + ANSI, no TUI dependency.
4
+ */
5
+
6
+ import {emitKeypressEvents} from 'node:readline';
7
+ import type {Key} from 'node:readline';
8
+
9
+ import {c} from '../theme.js';
10
+ import {truncate} from '../tui/render/format.js';
11
+
12
+ export interface PromptItem {
13
+ value: string;
14
+ label: string;
15
+ description?: string;
16
+ }
17
+
18
+ export interface PromptSelectOptions {
19
+ title: string;
20
+ items: PromptItem[];
21
+ selectedValue?: string;
22
+ height?: number;
23
+ hint?: string;
24
+ }
25
+
26
+ const DEFAULT_HINT = 'type to filter, ↑↓ navigate, Enter select, Esc cancel';
27
+
28
+ export function canPromptInteractively(): boolean {
29
+ return Boolean(
30
+ process.stdin.isTTY && process.stdout.isTTY && typeof process.stdin.setRawMode === 'function',
31
+ );
32
+ }
33
+
34
+ export function filterItems(items: PromptItem[], query: string): PromptItem[] {
35
+ const needle = query.trim().toLowerCase();
36
+ if (!needle) return items;
37
+ return items.filter((item) =>
38
+ `${item.label} ${item.description ?? ''}`.toLowerCase().includes(needle),
39
+ );
40
+ }
41
+
42
+ export function moveSelection(index: number, delta: number, length: number): number {
43
+ if (length === 0) return 0;
44
+ return (index + delta + length) % length;
45
+ }
46
+
47
+ export function promptSelect(opts: PromptSelectOptions): Promise<PromptItem | null> {
48
+ if (!canPromptInteractively()) return Promise.resolve(null);
49
+
50
+ return new Promise((resolve) => {
51
+ const stdin = process.stdin;
52
+ const height = Math.max(3, opts.height ?? 12);
53
+ let query = '';
54
+ let index = Math.max(
55
+ 0,
56
+ opts.items.findIndex((item) => item.value === opts.selectedValue),
57
+ );
58
+ let rendered = 0;
59
+ let done = false;
60
+
61
+ const visible = (): PromptItem[] => filterItems(opts.items, query);
62
+
63
+ const render = (): void => {
64
+ const items = visible();
65
+ if (index >= items.length) index = Math.max(0, items.length - 1);
66
+ const start = Math.max(0, Math.min(index - Math.floor(height / 2), items.length - height));
67
+ const width = Math.max(24, (process.stdout.columns ?? 80) - 5);
68
+ const hint = query
69
+ ? `filter: ${truncate(query, Math.min(24, width - 10))}`
70
+ : (opts.hint ?? DEFAULT_HINT);
71
+
72
+ const lines = [
73
+ ` ${c.bold}${truncate(opts.title, width)}${c.reset}`,
74
+ ` ${c.dim}${hint}${c.reset}`,
75
+ ];
76
+ for (let i = start; i < Math.min(items.length, start + height); i += 1) {
77
+ const item = items[i];
78
+ const active = i === index;
79
+ const label = truncate(item.label, 30);
80
+ const room = width - label.length - 2;
81
+ const description =
82
+ item.description && room > 8
83
+ ? ` ${c.dim}${truncate(item.description, room)}${c.reset}`
84
+ : '';
85
+ lines.push(
86
+ ` ${active ? `${c.cyan}>${c.reset}` : ' '} ${active ? `${c.cyan}${label}${c.reset}` : label}${description}`,
87
+ );
88
+ }
89
+ if (items.length === 0) lines.push(` ${c.dim}No matches.${c.reset}`);
90
+ if (items.length > height) lines.push(` ${c.dim}${index + 1}/${items.length}${c.reset}`);
91
+
92
+ if (rendered > 0) process.stdout.write(`\x1b[${rendered}A`);
93
+ process.stdout.write(`\x1b[0J${lines.join('\n')}\n`);
94
+ rendered = lines.length;
95
+ };
96
+
97
+ const cleanup = (): void => {
98
+ if (done) return;
99
+ done = true;
100
+ stdin.off('keypress', onKey);
101
+ stdin.off('end', onEnd);
102
+ process.off('SIGINT', onSigint);
103
+ if (typeof stdin.setRawMode === 'function') stdin.setRawMode(false);
104
+ stdin.pause();
105
+ process.stdout.write('\x1b[?25h');
106
+ };
107
+
108
+ const finish = (item: PromptItem | null): void => {
109
+ if (done) return;
110
+ if (rendered > 0) process.stdout.write(`\x1b[${rendered}A\x1b[0J`);
111
+ cleanup();
112
+ if (item) process.stdout.write(` ${c.green}✓${c.reset} ${item.label}\n`);
113
+ resolve(item);
114
+ };
115
+
116
+ const onKey = (str: string | undefined, key: Key): void => {
117
+ if (done) return;
118
+ if (key.name === 'up') {
119
+ index = moveSelection(index, -1, visible().length);
120
+ render();
121
+ return;
122
+ }
123
+ if (key.name === 'down') {
124
+ index = moveSelection(index, 1, visible().length);
125
+ render();
126
+ return;
127
+ }
128
+ if (key.name === 'return' || key.name === 'enter') {
129
+ const item = visible()[index];
130
+ if (item) finish(item);
131
+ return;
132
+ }
133
+ if (key.name === 'escape') {
134
+ if (query) {
135
+ query = '';
136
+ index = 0;
137
+ render();
138
+ } else {
139
+ finish(null);
140
+ }
141
+ return;
142
+ }
143
+ if (key.ctrl && key.name === 'c') {
144
+ finish(null);
145
+ return;
146
+ }
147
+ if (key.ctrl && key.name === 'u') {
148
+ query = '';
149
+ index = 0;
150
+ render();
151
+ return;
152
+ }
153
+ if (key.name === 'backspace') {
154
+ query = query.slice(0, -1);
155
+ index = 0;
156
+ render();
157
+ return;
158
+ }
159
+ if (str && !key.ctrl && !key.meta) {
160
+ const printable = str.replace(/[^\x20-\x7e]/g, '');
161
+ if (printable) {
162
+ query += printable;
163
+ index = 0;
164
+ render();
165
+ }
166
+ }
167
+ };
168
+
169
+ const onEnd = (): void => finish(null);
170
+ const onSigint = (): void => finish(null);
171
+
172
+ process.stdout.write('\x1b[?25l');
173
+ emitKeypressEvents(stdin);
174
+ if (typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
175
+ stdin.resume();
176
+ stdin.on('keypress', onKey);
177
+ stdin.on('end', onEnd);
178
+ process.once('SIGINT', onSigint);
179
+ render();
180
+ });
181
+ }