import { checkbox, select } from '@inquirer/prompts'; import type { Key } from 'node:readline'; /** 导航:左方向键返回 */ export const BACK = '__back__' as const; export type Nav = typeof BACK; type Cancellable = Promise & { cancel: () => void }; function isCancelPrompt(e: unknown): boolean { return (e as { name?: string })?.name === 'CancelPromptError'; } /** * 运行可取消的 inquirer prompt:← 左键 → cancel → 返回 BACK。 */ export async function withLeftBack(start: () => Cancellable): Promise { const prompt = start(); const onKeypress = (_input: string, key: Key) => { // 左方向键;忽略带修饰键,避免误触 if (key?.name === 'left' && !key.ctrl && !key.meta && !key.shift) { prompt.cancel(); } }; process.stdin.on('keypress', onKeypress); try { return await prompt; } catch (e) { if (isCancelPrompt(e)) return BACK; throw e; } finally { process.stdin.off('keypress', onKeypress); } } const selectHelp = { style: { keysHelpTip: () => '↑↓ 选择 · ⏎ 确认 · ← 返回', }, } as const; const checkboxHelp = { style: { keysHelpTip: () => '↑↓ 移动 · 空格 勾选 · a 全选 · ⏎ 确认 · ← 返回', }, } as const; /** select:← 返回 BACK */ export function selectNav(config: Parameters>[0]) { return withLeftBack(() => select({ ...config, theme: { ...selectHelp, ...(config.theme as object | undefined) }, }), ); } /** checkbox:← 返回 BACK */ export function checkboxNav(config: Parameters>[0]) { return withLeftBack(() => checkbox({ ...config, theme: { ...checkboxHelp, ...(config.theme as object | undefined) }, }), ); }