mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
feat: 部署 TUI 支持多选服务与分层返回
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
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<T> = Promise<T> & { cancel: () => void };
|
||||
|
||||
function isCancelPrompt(e: unknown): boolean {
|
||||
return (e as { name?: string })?.name === 'CancelPromptError';
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行可取消的 inquirer prompt:← 左键 → cancel → 返回 BACK。
|
||||
*/
|
||||
export async function withLeftBack<T>(start: () => Cancellable<T>): Promise<T | Nav> {
|
||||
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<Value>(config: Parameters<typeof select<Value>>[0]) {
|
||||
return withLeftBack(() =>
|
||||
select({
|
||||
...config,
|
||||
theme: { ...selectHelp, ...(config.theme as object | undefined) },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** checkbox:← 返回 BACK */
|
||||
export function checkboxNav<Value>(config: Parameters<typeof checkbox<Value>>[0]) {
|
||||
return withLeftBack(() =>
|
||||
checkbox({
|
||||
...config,
|
||||
theme: { ...checkboxHelp, ...(config.theme as object | undefined) },
|
||||
}),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user