/** * ============================================================ * src/cli/wizards/fieldForm.tsx —— 通用顺序字段录入组件 * ------------------------------------------------------------ * 搜索引擎/生图模型/顾问模型/语音合成/OpenRouter 这 5 个子向导只是 * "字段不同、保存目标不同",录入交互本身完全一样:一次问一个字段, * Enter 确认进入下一个,最后一个字段确认后调用 onSubmit(values)。 * 抽成通用组件避免 5 份几乎相同的状态机(仓库"轻量简洁"原则)。 * * 左方向键返回上一步,保存失败回到最后一项且保留整份草稿。 * ============================================================ */ import React, { useCallback, useMemo, useState } from 'react'; import { Box, Text, useInput } from 'ink'; export type FieldType = 'text' | 'password' | 'boolean' | 'select'; export interface FieldDef { key: string; label: string; type: FieldType; /** select 类型的候选项 */ options?: string[]; /** 初始值(重新编辑已有配置时预填) */ default?: string | boolean; /** 允许留空提交:Enter 空值 = 沿用 default(通常是"保持原值不变") */ optional?: boolean; /** 字段下方的补充说明(灰色小字) */ hint?: string; } export type FieldValues = Record; interface Props { title: string; fields: FieldDef[]; onSubmit: (values: FieldValues) => Promise; onCancel: () => void; submittingMessage?: string; } type Phase = 'input' | 'submitting' | 'error'; /** 进入某字段时的 draft 预填:以 seed(已录入值或 default)为准。 */ function initialDraft(f: FieldDef | undefined, seed: string | boolean | undefined): string { if (!f) return ''; if (f.type === 'select') { const opts = f.options ?? []; const idx = opts.indexOf(String(seed ?? '')); return opts[idx >= 0 ? idx : 0] ?? ''; } if (f.type === 'boolean') return ''; return seed !== undefined ? String(seed) : ''; } /** 进入某字段时的高亮预选:boolean 按 seed 定 是/否,select 定位到 seed 项。 */ function initialSelect(f: FieldDef | undefined, seed: string | boolean | undefined): number { if (!f) return 0; if (f.type === 'select') { const opts = f.options ?? []; const idx = opts.indexOf(String(seed ?? '')); return idx >= 0 ? idx : 0; } if (f.type === 'boolean') return seed === true ? 0 : 1; return 0; } export function FieldForm({ title, fields, onSubmit, onCancel, submittingMessage }: Props): JSX.Element { const [index, setIndex] = useState(0); const [values, setValues] = useState(() => { const initial: FieldValues = {}; for (const f of fields) if (f.default !== undefined) initial[f.key] = f.default; return initial; }); // 首字段不经过 enterField,预填必须在 useState 初始化器里做——否则 // boolean 首字段的高亮永远停在"是"(default=false 时直接 Enter 会误改值)。 const [draft, setDraft] = useState(() => initialDraft(fields[0], fields[0]?.default)); const [selectIndex, setSelectIndex] = useState(() => initialSelect(fields[0], fields[0]?.default)); const [phase, setPhase] = useState('input'); const [errorMsg, setErrorMsg] = useState(null); const field = fields[index]; const enterField = useCallback( (i: number) => { const f = fields[i]!; setErrorMsg(null); // 优先用已录入的值(保存失败重试时不吞用户敲过的输入),其次才是 default。 const seed = values[f.key] !== undefined ? values[f.key] : f.default; setSelectIndex(initialSelect(f, seed)); setDraft(initialDraft(f, seed)); setIndex(i); setPhase('input'); }, [fields, values], ); const finish = useCallback( async (finalValues: FieldValues) => { setPhase('submitting'); setErrorMsg(null); try { await onSubmit(finalValues); } catch (e) { setErrorMsg((e as Error).message || '保存失败'); setPhase('error'); } }, [onSubmit], ); const commitField = useCallback( (value: string | boolean) => { const next = { ...values, [field!.key]: value }; setValues(next); if (index + 1 < fields.length) { enterField(index + 1); } else { void finish(next); } }, [values, field, index, fields, enterField, finish], ); useInput((input, key) => { if (phase === 'submitting') return; if (phase === 'error') { if (key.return) setPhase('input'); else if (key.escape) onCancel(); return; } if (key.escape) { onCancel(); return; } if (key.leftArrow && index > 0) { enterField(index - 1); return; } if (!field) return; if (field.type === 'boolean') { if (key.upArrow || key.downArrow) { setSelectIndex((i) => (i === 0 ? 1 : 0)); } else if (key.return) { commitField(selectIndex === 0); } return; } if (field.type === 'select') { const opts = field.options ?? []; if (key.upArrow) { setSelectIndex((i) => (i - 1 + opts.length) % opts.length); } else if (key.downArrow) { setSelectIndex((i) => (i + 1) % opts.length); } else if (key.return) { commitField(opts[selectIndex] ?? ''); } return; } // text / password if (key.return) { const trimmed = draft.trim(); if (trimmed.length === 0) { // 留空 Enter:可选字段沿用 default(通常是"保持原值不变");必填字段拦下不提交。 if (!field.optional) return; commitField(field.default !== undefined ? String(field.default) : ''); return; } commitField(trimmed); } else if (key.backspace || key.delete) { setDraft((s) => s.slice(0, -1)); } else if (input && !key.meta && !key.ctrl) { setDraft((s) => s + input); } }); const masked = useMemo(() => '*'.repeat(Math.min(draft.length, 32)), [draft]); return ( {title} {phase !== 'error' && field && ( 第 {index + 1}/{fields.length} 项 · {field.label} {field.type === 'boolean' && ( {['是', '否'].map((label, i) => ( {i === selectIndex ? '> ' : ' '}{label} ))} )} {field.type === 'select' && ( {(field.options ?? []).map((opt, i) => ( {i === selectIndex ? '> ' : ' '}{opt} ))} )} {(field.type === 'text' || field.type === 'password') && ( {(field.type === 'password' ? masked : draft) || ' '} )} {field.hint && ( {field.hint} )} Enter 确认{field.optional ? '(留空保持不变)' : ''} · ← 上一步 · ESC 取消 )} {phase === 'submitting' && ( ⏳ {submittingMessage ?? '正在保存...'} )} {phase === 'error' && ( ✗ 保存失败 {errorMsg ?? '未知错误'} 按 Enter 保留草稿继续修改 · ESC 取消 )} ); }