refactor: 中间栏三层架构 — useUI 组件体系 + useModelUI Hook

- 新建 useUI/ 目录:12 个文件,10 个 Qt 控件 → antd 组件封装 + 类型 + 注册表
- 新建 useModelUI Hook:param_schema → UIFieldConfig[] 自动映射
- ModelInputForm 瘦身 ~160 行:删除 buildParamDescriptors/renderParamControl/文件状态管理
- WIDGET_MAP: Record<string, ComponentType<WidgetProps>> — 零 any,完全类型安全
- 新增控件只需两步:创建组件文件 + 在 WIDGET_MAP 加一行
- 删除旧 widgets/ 目录

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-09 15:32:17 +08:00
parent 76e66a37c8
commit d5ba7e63cd
14 changed files with 733 additions and 339 deletions

View File

@@ -1,126 +1,37 @@
// ============================================================
// ModelInputForm — 动态模型输入表单
// 根据选中模型的 param_schema + ui_config 动态渲染表单控件
// ModelInputForm — 模型输入表单(纯布局外壳)
//
// 布局Header模型信息+meta → Bodyfields.map 渲染) → Footer价格+提交)
//
// 与旧版的区别:
// - 控件渲染逻辑已提取到 useUI/ 组件体系
// - param_schema 解析已提取到 useModelUI Hook
// - 本组件只负责布局、Form 容器、提交逻辑
// ============================================================
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useEffect, useMemo, useCallback } from 'react';
import {
Form,
Input,
InputNumber,
Select,
Slider,
Button,
Typography,
Empty,
Upload,
Switch,
Tag,
Space,
theme as antTheme,
message,
} from 'antd';
import {
SendOutlined,
UploadOutlined,
InboxOutlined,
} from '@ant-design/icons';
import { SendOutlined, ClockCircleOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload';
import { useHomeContext } from '@/pages/home/HomeContent';
import { useAppContext } from '@/components/AppProvider';
import { useSubmitTask } from '@/hooks/use-api';
import { emit, EVENTS } from '@/utils/event-bus';
import type { ModelsListResponseBody } from '@/services/modules/models';
import type { TaskInfoItemResponseBody } from '@/services/modules/task';
import { OutputTypeMap } from '@/services/modules/task';
import type { OutputTypeString, TaskInfoItemResponseBody } from '@/services/modules/task';
import { useModelUI, type UIFieldConfig } from './useModelUI';
const { Text, Title } = Typography;
const { TextArea } = Input;
const { Dragger } = Upload;
// ---------- 参数类型映射 ----------
/** 从 ui_config 中解析的参数描述 */
interface ParamDescriptor {
/** React keyitem.id保证唯一 */
key: string;
/** API 字段名item.map_to */
name: string;
label: string;
/** 控件类型 */
controlType: 'text' | 'number' | 'textarea' | 'select' | 'slider' | 'switch' | 'image-upload';
defaultValue?: unknown;
required?: boolean;
placeholder?: string;
/** 数值型:最小值 */
min?: number;
/** 数值型:最大值 */
max?: number;
/** 数值型:步长 */
step?: number;
/** select 型:选项列表 */
options?: Array<{ label: string; value: string | number }>;
}
/** 从 ui_config 对象中解析控件类型 */
function inferControlType(config: Record<string, unknown>): ParamDescriptor['controlType'] {
const type = config.type as string | undefined;
if (!type) return 'text';
switch (type) {
case 'number':
case 'integer':
case 'float':
return 'number';
case 'textarea':
case 'text_area':
case 'prompt':
return 'textarea';
case 'select':
case 'dropdown':
case 'enum':
return 'select';
case 'slider':
case 'range':
return 'slider';
case 'switch':
case 'boolean':
case 'bool':
return 'switch';
case 'image':
case 'image-upload':
case 'file':
return 'image-upload';
default:
return 'text';
}
}
/**
* 从 param_schema 构建参数描述符列表
*
* 后端 param_schema 格式为 ParamSchemaItem[](对象数组),
* 每项的 ui 字段内嵌了控件类型、标签、校验规则等 UI 配置。
*/
function buildParamDescriptors(
paramSchema: ModelsListResponseBody['param_schema'],
): ParamDescriptor[] {
return paramSchema.map((item) => {
const config = (item.ui || {}) as Record<string, unknown>;
const controlType = inferControlType(config);
return {
key: item.id,
name: item.map_to,
label: (config.label as string) || item.map_to,
controlType,
defaultValue: config.default ?? config.defaultValue,
required: (config.required as boolean) || false,
placeholder: (config.placeholder as string) || `请输入${config.label || item.map_to}`,
min: config.min as number | undefined,
max: config.max as number | undefined,
step: config.step as number | undefined,
options: (config.options as ParamDescriptor['options']) || undefined,
};
});
}
// ---------- 组件 ----------
@@ -129,35 +40,39 @@ export function ModelInputForm() {
const { isLoggedIn } = useAppContext();
const { selectedModel } = useHomeContext();
const [form] = Form.useForm();
const [referenceFiles, setReferenceFiles] = useState<UploadFile[]>([]);
// 提交突变 Hook(自动处理 loading / error / 日志)
// 提交突变 Hook
const { execute: submitTask, loading: submitting, errorMessage } = useSubmitTask({
onSuccess: useCallback(
(_data: TaskInfoItemResponseBody) => {
message.success('任务已提交');
// 通过事件总线通知 TaskHistory 刷新(替代 Context 中的 refreshTaskSignal
emit(EVENTS.TASK_SUBMITTED);
},
[],
),
onSuccess: useCallback((_data: TaskInfoItemResponseBody) => {
message.success('任务已提交');
emit(EVENTS.TASK_SUBMITTED);
}, []),
});
// 选中模型时重置表单(仅当有选中模型时操作,避免 form 未连接警告)
// ======== useModelUIparam_schema → UIFieldConfig[] ========
const fields: UIFieldConfig[] = useModelUI(selectedModel?.param_schema || []);
// 构建初始值
const initialValues = useMemo(() => {
const iv: Record<string, unknown> = {};
fields.forEach((f) => {
if (f.defaultValue !== undefined && f.defaultValue !== null) {
iv[f.name] = f.defaultValue;
}
});
return iv;
}, [fields]);
// 选中模型时重置表单
useEffect(() => {
if (selectedModel) {
form.resetFields();
}
setReferenceFiles([]);
}, [selectedModel?.id]); // eslint-disable-line react-hooks/exhaustive-deps
// 参数描述符
const paramDescriptors = useMemo(() => {
if (!selectedModel) return [];
return buildParamDescriptors(selectedModel.param_schema || []);
}, [selectedModel]);
// ======== 提交 ========
// 提交
const handleSubmit = async () => {
if (!isLoggedIn) {
message.warning('请先登录后再提交任务');
@@ -168,128 +83,47 @@ export function ModelInputForm() {
try {
const values = await form.validateFields();
// 分离固定字段和模型动态参数
const { prompt, negative_prompt, num_outputs, ...dynamicParams } = values;
// 将表单值全部转为字符串CreatTaskRequestBody.params 为 Record<string, string>
const params: Record<string, string> = {};
// 构建提交参数(全部转为字符串值)
const params: Record<string, string> = {
prompt: String(prompt ?? ''),
negative_prompt: String(negative_prompt ?? ''),
num_outputs: String(num_outputs ?? 1),
};
for (const field of fields) {
const value = values[field.name];
if (value === undefined || value === null) continue;
// 动态参数统一转字符串
for (const [key, value] of Object.entries(dynamicParams)) {
if (value !== undefined && value !== null) {
params[key] = String(value);
// 文件上传 → 提取 URL 数组 → JSON 字符串
if (field.isFileWidget) {
const fileList = value as UploadFile[];
const urls = fileList
.filter((f) => f.status === 'done')
.map((f) => f.response?.url || f.url || f.name)
.filter(Boolean) as string[];
if (urls.length > 0) {
params[field.name] = urls.length === 1 ? urls[0] : JSON.stringify(urls);
}
continue;
}
// 布尔值 → "true"/"false"
if (typeof value === 'boolean') {
params[field.name] = String(value);
continue;
}
// 数值 / 字符串 → String
params[field.name] = String(value);
}
// 参考图
if (referenceFiles.length > 0) {
const refUrls = referenceFiles
.filter((f) => f.status === 'done')
.map((f) => f.response?.url || f.url || f.name)
.filter(Boolean) as string[];
if (refUrls.length > 0) {
params.reference_images = JSON.stringify(refUrls);
}
}
// 使用 mutation Hook 提交(自动处理 loading / error / 日志)
await submitTask({ model_id: selectedModel.id, params });
} catch (err) {
if (err && typeof err === 'object' && 'errorFields' in err) {
// 表单验证错误antd 自动提示
return;
return; // 表单验证错误antd 自动提示
}
// 错误消息由 Hook 自动通过 errorMessage 提供
message.error(errorMessage || '任务提交失败,请重试');
}
};
// 渲染单个参数控件
const renderParamControl = (desc: ParamDescriptor) => {
const commonProps = {
placeholder: desc.placeholder,
style: { width: '100%' },
};
// ======== 未选择模型 ========
switch (desc.controlType) {
case 'number':
return (
<InputNumber
{...commonProps}
min={desc.min}
max={desc.max}
step={desc.step}
style={{ width: '100%' }}
/>
);
case 'textarea':
return <TextArea rows={3} {...commonProps} />;
case 'select':
return (
<Select
{...commonProps}
options={desc.options}
allowClear
/>
);
case 'slider':
return (
<Slider
min={desc.min ?? 1}
max={desc.max ?? 100}
step={desc.step ?? 1}
marks={
desc.min !== undefined && desc.max !== undefined
? { [desc.min]: `${desc.min}`, [desc.max]: `${desc.max}` }
: undefined
}
tooltip={{ formatter: (v) => v }}
/>
);
case 'switch':
return <Switch />;
case 'image-upload':
return (
<Upload
listType="picture-card"
maxCount={1}
accept="image/png,image/jpg,image/jpeg,image/webp"
beforeUpload={(file) => {
const isImage = file.type.startsWith('image/');
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isImage) {
message.error('只能上传图片文件');
return Upload.LIST_IGNORE;
}
if (!isLt10M) {
message.error('图片大小不能超过 10MB');
return Upload.LIST_IGNORE;
}
return false; // 手动上传
}}
>
<div>
<UploadOutlined />
<div style={{ marginTop: 4, fontSize: 12 }}></div>
</div>
</Upload>
);
default:
return <Input {...commonProps} />;
}
};
// ---- 未选择模型 ----
if (!selectedModel) {
return (
<div
@@ -305,7 +139,24 @@ export function ModelInputForm() {
);
}
// ---- 表单 ----
// ======== 提取 meta 信息 ========
const metaConfig = (selectedModel.meta_config || {}) as Record<string, unknown>;
const uiConfig = (selectedModel.ui_config || {}) as Record<string, unknown>;
const pricingConfig = (selectedModel.pricing_config || {}) as Record<string, unknown>;
const outputType = metaConfig.output_type as OutputTypeString | undefined;
const estimatedDuration = metaConfig.estimated_duration_seconds as number | undefined;
const badge = uiConfig.badge as string | undefined;
const group = uiConfig.group as string | undefined;
const helpUrl = metaConfig.help_url as string | undefined;
const priceUnit = (pricingConfig.unit as Record<string, unknown>)?.name as string | undefined;
const price = pricingConfig.price as number | undefined;
const priceType = pricingConfig.price_type as string | undefined;
// ======== 正常渲染 ========
return (
<div
style={{
@@ -315,7 +166,7 @@ export function ModelInputForm() {
overflow: 'hidden',
}}
>
{/* 模型标题 */}
{/* ======== Header模型信息 ======== */}
<div
style={{
padding: '16px 20px',
@@ -323,130 +174,131 @@ export function ModelInputForm() {
flexShrink: 0,
}}
>
<Title level={4} style={{ margin: 0, fontSize: 18 }}>
{selectedModel.name}
</Title>
<Text type="secondary" style={{ fontSize: 12 }}>
{selectedModel.provider_name} · {selectedModel.category_name}
</Text>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
{badge && <span style={{ fontSize: 20 }}>{badge}</span>}
<Title level={4} style={{ margin: 0, fontSize: 18 }}>
{selectedModel.name}
</Title>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<Text type="secondary" style={{ fontSize: 12 }}>
{selectedModel.provider_name}
{group
? ` · ${group}`
: selectedModel.category_name
? ` · ${selectedModel.category_name}`
: ''}
</Text>
</div>
<Space size={4} style={{ marginTop: 8 }} wrap>
{outputType && (
<Tag color="blue" style={{ fontSize: 11, lineHeight: '18px' }}>
{OutputTypeMap[outputType] || outputType}
</Tag>
)}
{estimatedDuration !== undefined && (
<Tag
icon={<ClockCircleOutlined />}
color="default"
style={{ fontSize: 11, lineHeight: '18px' }}
>
{estimatedDuration}
</Tag>
)}
{helpUrl && (
<a
href={helpUrl}
target="_blank"
rel="noopener noreferrer"
style={{ fontSize: 11 }}
>
使
</a>
)}
</Space>
</div>
{/* 可滚动表单区 */}
{/* ======== Body参数列表useModelUI 驱动) ======== */}
<div style={{ flex: 1, overflow: 'auto', padding: '16px 20px' }}>
<Form
form={form}
layout="vertical"
size="small"
initialValues={{ num_outputs: 1 }}
>
{/* ======== 固定字段 ======== */}
{/* 提示词 */}
<Form.Item
name="prompt"
label={<Text strong></Text>}
rules={[{ required: true, message: '请输入提示词' }]}
{fields.length === 0 ? (
<Empty
description="该模型无需额外参数"
image={Empty.PRESENTED_IMAGE_SIMPLE}
style={{ marginTop: 24 }}
/>
) : (
<Form
form={form}
layout="vertical"
size="small"
initialValues={initialValues}
>
<TextArea
rows={4}
placeholder="描述你想要的画面、视频或音频内容..."
showCount
maxLength={2000}
/>
</Form.Item>
{/* 负面提示词 */}
<Form.Item
name="negative_prompt"
label={<Text type="secondary"></Text>}
>
<TextArea
rows={2}
placeholder="描述你不希望在结果中出现的内容(可选)"
maxLength={1000}
/>
</Form.Item>
{/* 参考图 */}
<Form.Item label={<Text strong></Text>}>
<Dragger
multiple
listType="picture"
fileList={referenceFiles}
onChange={({ fileList }) => setReferenceFiles(fileList)}
accept="image/png,image/jpg,image/jpeg,image/webp"
beforeUpload={(file) => {
const isImage = file.type.startsWith('image/');
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isImage) {
message.error('只能上传图片文件');
return Upload.LIST_IGNORE;
}
if (!isLt10M) {
message.error('图片大小不能超过 10MB');
return Upload.LIST_IGNORE;
}
return false;
}}
maxCount={5}
style={{ marginBottom: 8 }}
>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text"></p>
<p className="ant-upload-hint">
PNG / JPG / WebP 10MB
</p>
</Dragger>
</Form.Item>
{/* 生成数量 */}
<Form.Item
name="num_outputs"
label={<Text strong></Text>}
>
<InputNumber min={1} max={10} style={{ width: '100%' }} />
</Form.Item>
{/* ======== 模型动态参数 ======== */}
{paramDescriptors.length > 0 && (
<div
style={{
marginTop: 16,
paddingTop: 16,
borderTop: `1px solid ${token.colorBorderSecondary}`,
}}
>
<Text strong style={{ display: 'block', marginBottom: 12 }}>
</Text>
{paramDescriptors.map((desc) => (
{fields.map((field) => (
<Form.Item
key={desc.key}
name={desc.name}
label={desc.label}
rules={desc.required ? [{ required: true, message: `请输入${desc.label}` }] : undefined}
initialValue={desc.defaultValue}
valuePropName={desc.controlType === 'switch' ? 'checked' : 'value'}
key={field.index}
name={field.name}
label={
<span>
<Text strong={field.must}>{field.label}</Text>
{field.tips && (
<Text
type="secondary"
style={{ fontSize: 11, marginLeft: 6 }}
>
{field.tips.length > 60
? `${field.tips.slice(0, 60)}...`
: field.tips}
</Text>
)}
</span>
}
rules={
field.must
? [{ required: true, message: `请输入${field.label}` }]
: undefined
}
valuePropName={field.valuePropName}
// 文件控件:从 Upload onChange 事件中提取 fileList
{...(field.isFileWidget
? { getValueFromEvent: (e: { fileList: UploadFile[] }) => e.fileList }
: {})}
>
{renderParamControl(desc)}
<field.component config={field.widgetConfig} />
</Form.Item>
))}
</div>
)}
</Form>
</Form>
)}
</div>
{/* 提交按钮 */}
{/* ======== Footer价格 + 提交 ======== */}
<div
style={{
padding: '12px 20px',
borderTop: `1px solid ${token.colorBorderSecondary}`,
flexShrink: 0,
display: 'flex',
alignItems: 'center',
gap: 12,
}}
>
{price !== undefined && priceType === 'SIMPLE' && (
<Text type="secondary" style={{ fontSize: 12, whiteSpace: 'nowrap' }}>
¥{price}/{priceUnit || '次'}
</Text>
)}
{priceType === 'MULTI_DIMENSION' && (
<Text type="secondary" style={{ fontSize: 12, whiteSpace: 'nowrap' }}>
</Text>
)}
{priceType === 'BILLING_ADAPTER' && (
<Text type="secondary" style={{ fontSize: 12, whiteSpace: 'nowrap' }}>
</Text>
)}
<Button
type="primary"
icon={<SendOutlined />}