ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

FiftyOne SmartForm 深度指南:基于 RJSF 的 SchemaIO 表单自动翻译与双向数据转换

FiftyOne SmartForm 深度指南:基于 RJSF 的 SchemaIO 表单自动翻译与双向数据转换 FiftyOne SmartForm 深度指南基于 RJSF 的 SchemaIO 表单自动翻译与双向数据转换【免费下载链接】fiftyoneRefine high-quality datasets and visual AI models项目地址: https://gitcode.com/GitHub_Trending/fi/fiftyoneSmartForm 是 FiftyOne 前端fiftyone/components包中的一个 React JSON Schema Form (RJSF) 封装组件它把 FiftyOne 插件体系中的 SchemaIO 架构schema自动翻译成标准 JSON Schema 与 UI Schema并完成 SchemaIO ↔ RJSF 之间的双向数据格式转换。阅读本文后你将掌握 SmartForm 的核心用法、props 语义、翻译 API、自定义 widget 机制、与 SchemaIOComponent 的集成方式以及从 DynamicIO 迁移到 SmartForm 的完整路径可以直接在 FiftyOne 插件面板开发中落地使用。SmartForm 是什么SmartForm 是一个 RJSF 包装器wrapper核心职责是自动翻译把 FiftyOne SchemaIO 格式的 schema带view视图描述翻译为标准 JSON Schema UI Schema交给rjsf/mui渲染成 Material-UI 风格的表单同时在数据进出表单时自动完成 SchemaIO 与 RJSF 两种数据格式的互转。它的能力清单如下自动翻译将 SchemaIO schemas 转换为 JSON Schema UI Schema双向数据转换处理 SchemaIO ↔ RJSF 数据格式互转自定义 Widgets复用现有 SchemaIO 组件Dropdown、AutoComplete 等类型安全完整的 TypeScript 支持并导出类型Material-UI 风格构建在rjsf/mui之上保持设计一致性可扩展可覆盖生成的 UI Schema 实现精细控制从源码入口看SmartForm 是一个极简的门面facadeSmartForm/index.tsx 中SmartForm直接把 props 转交给内部的RJSF组件渲染注释中明确写道未来可能在此支持 RJSF 的替代实现说明该层刻意保持了替换灵活性。快速上手安装SmartForm 是fiftyone/components包的一部分yarn add fiftyone/components运行时依赖rjsf/core— React JSON Schema Form 核心rjsf/mui— Material-UI 主题rjsf/validator-ajv8— JSON Schema 校验器rjsf/utils— RJSF 工具函数这些依赖在 RJSF/index.tsx 中直接体现Form来自rjsf/muivalidator默认使用rjsf/validator-ajv8。最小示例import SmartForm from fiftyone/components/SmartForm; const schema { type: object, view: { component: ObjectView }, properties: { name: { type: string, view: { label: Name, placeholder: Enter name }, }, email: { type: string, view: { label: Email }, required: true, }, }, }; SmartForm schema{schema} data{{ name: John Doe }} onChange{(data) console.log(data)} /;注意 SchemaIO 中required: true写在字段自身而非 JSON Schema 的顶层required数组翻译器会在对象层级自动收集这些字段生成 JSON Schema 的required数组。带选择项的基本示例import SmartForm, { type SmartFormProps, } from fiftyone/components/SmartForm; function MyForm() { const schema { type: object, properties: { category: { type: string, view: { component: DropdownView, label: Category, choices: [ { value: cat, label: Cat }, { value: dog, label: Dog }, ], }, }, }, }; return ( SmartForm schema{schema} onChange{(data) console.log(Changed:, data)} onSubmit{(data) console.log(Submitted:, data)} / ); }Props 详解SmartFormProps的定义位于 SmartForm/types.ts与 README 中的版本相比实际源码还额外支持jsonSchema直接传 JSON Schema 跳过翻译和formProps透传 RJSF FormPropsinterface SmartFormProps { schema?: SchemaType; // SchemaIO schema jsonSchema?: RJSFSchema; // 直接提供 JSON Schema跳过翻译 uiSchema?: UiSchema; // 覆盖生成的 UI Schema data?: unknown; // 初始表单数据 onChange?: (data: unknown) void; // 变更回调 onSubmit?: (data: unknown) void; // 提交回调 formProps?: PartialFormProps; // 透传给 RJSF Form 的其他属性 }schema与jsonSchema二选一在 RJSF/index.tsx 中若两者都未提供会打印[SmartForm][RJSF] Either \schema or jsonSchema must be provided并返回null若提供了schema则走translateSchema翻译路径否则直接使用传入的jsonSchema和uiSchema。类型枚举types.ts还导出了两个枚举是理解翻译器映射关系的关键SmartFormInputsstring、number、integer、boolean、null、object、array、oneOf八种输入类型SmartFormComponents覆盖FieldView、CheckboxView、DropdownView、RadioView、AutocompleteView、ColorView、CodeView、JSONView、FileView、TabsView、ObjectView、GridView、ListView、TupleView、MapView、OneOfView、ProgressView、LinkView、DashboardView、FileExplorerView、LazyFieldView、MenuView、ButtonView、NoticeView、MarkdownView、PlotlyView、SliderView、ToggleView、LabelValueView、DatePickerView、JsonEditorView、TaxonomyView等三十余种视图组件。工作原理三步核心流程SmartForm 执行三个主要操作源码分别落在 RJSF/translators 目录的schema.ts、ui.ts、data.tsREADME 架构图中标注中。1. Schema 翻译输入 SchemaIO 格式{ type: string, view: { component: DropdownView, choices: [ { value: a, label: Option A }, { value: b, label: Option B } ] } }输出 JSON Schema UI Schema{ schema: { type: string, enum: [a, b], enumNames: [Option A, Option B] }, uiSchema: { ui:widget: Dropdown } }实现细节translateToJSONSchemaschema.ts按类型分发处理——数字类型会把min/max/multipleOf翻译为 JSON Schema 的minimum/maximum/multipleOf对象类型会遍历properties递归翻译并收集required: true的字段数组类型区分单条目与元组tuple两种形态元组会设置minItems/maxItems为固定长度oneOf类型映射为oneOf数组。view.label与view.description会被提升为 JSON Schema 的title与description。addChoicesToSchemaschema.ts#L137-L202负责把view.choices后处理为enum/enumNames数组类型生成items.enum与examples非数组类型直接挂在 schema 顶层对于没有 choices 的AutocompleteView数组还会补一个{ type: string }的默认 items 以支持 freeSolo 模式。2. 数据转换输入方向// SchemaIO 格式null 表示空 { name: John, age: null } // 转换为 RJSF 格式合适的空值 { name: John, age: undefined }在 RJSF/index.tsx 中deserializeFormData会递归处理服务端数据识别{_cls: DateTime, datetime: 12345...}形态的日期序列化结构并转成 ISO 字符串其余对象与数组逐层递归。3. 数据转换输出方向// RJSF 格式的 onChange 数据 { name: John, age: undefined } // 转换回 SchemaIO 格式 { name: John, age: null }getEmptyValueForTypetranslators/utils.ts定义了各类型对应的空值约定string 为boolean 为falseobject 为{}array 为[]null 为nullnumber/integer 为undefined。变更与提交处理handleChangeRJSF/index.tsx#L86-L98在 props.data 与 formData 均为对象时会调用filterEmptyArrays清理空数组避免与初始数据比较时产生无意义的数组差异handleSubmit则直接回调onSubmit(event.formData)。支持的字段类型映射SchemaIO ComponentRJSF Widget说明FieldViewTextWidget文本输入CheckboxViewcheckbox复选框DropdownViewDropdown单选/多选下拉框RadioViewradio单选按钮AutocompleteViewAutoComplete可搜索自动补全ColorViewcolor取色器CodeViewtextarea代码/文本域FileViewfile文件上传ObjectView(fieldset)嵌套对象ListView(array)动态列表TupleView(array)定长元组这张表在 ui.ts 的translateToUISchemaswitch 中有更完整的实现实际映射比 README 表格更丰富还包括ToggleView→BooleanWidgetSelectWidget/Select→SelectWidget带multiple选项TaxonomyView→TaxonomyWidget带taxonomy、multiSelect选项CheckboxesView→checkboxesSliderView→RangeWidget支持bare、labeled、minLabel、maxLabelDatePickerView→DatePickerWidget支持date_onlyJsonEditorView→JsonEditorWidget支持heightLabelValueView→LabelValueWidget只读文本展示无输入TabsView→ 降级为radio单选按钮并产生警告GridView→ 布局容器隐藏标题并支持gap、align_x、align_y、水平布局MapView→ 映射为可增删的additionalProperties结构addable: true, orderable: false, removable: true并提示需要自定义实现OneOfView→ 设置discriminator: true选项所有 view 都统一支持的后处理ui.ts#L249-L266read_only/readOnly→ui:readonlyplaceholder→ui:placeholdercaption/description→ui:help并默认隐藏提交按钮ui:submitButtonOptions.norender: true。高级用法自定义 UI Schemaconst uiSchema { name: { ui:placeholder: John Doe, ui:help: Your display name, }, email: { ui:widget: email, }, }; SmartForm schema{schema} uiSchema{uiSchema} // 覆盖生成的 UI Schema /;注意当同时传入schema与uiSchema时uiSchema会覆盖翻译器生成的同名键值。如果希望完全绕开翻译器直接掌控 schema 与 uiSchema也可以使用jsonSchemauiSchema组合此时翻译器不参与。自定义校验器import validator from rjsf/validator-ajv8; SmartForm schema{schema} validator{validator} // 自定义校验器 /;默认情况下 SmartForm 已使用rjsf/validator-ajv8传入自定义validator可扩展校验逻辑例如自定义 format 校验。另外通过formProps.liveValidate可以开启实时校验——RJSF/index.tsx#L60-L65 中在挂载时若开启liveValidate会主动调用formRef.current.validateForm()进行一次校验并把校验错误经transformErrors处理RJSF/utils.ts后展示。类型安全import type { SmartFormProps } from fiftyone/components/SmartForm; const props: SmartFormProps { schema: mySchema, data: initialData, onChange: (data) { // data 的类型为 unknown // 按需校验或断言类型 }, };SmartForm 还导出了SmartFormInputs、SmartFormComponents枚举见 SmartForm/types.ts可用于在自定义翻译或 widget 中引用组件名与类型名常量。翻译 APITranslatorsSmartForm 导出了可供高级场景直接调用的翻译函数translators/index.tsimport { translateSchemaComplete, translateSchema, isSchemaIOSchema, isJSONSchema, } from fiftyone/components/SmartForm/translators; // 完整翻译含数据 const result translateSchemaComplete(schema, data); console.log(result.schema); // JSON Schema console.log(result.uiSchema); // UI Schema console.log(result.formData); // 转换后的数据 console.log(result.warnings); // 翻译警告 // 仅翻译 schema const { schema, uiSchema, warnings } translateSchema(schemaIO); // 类型守卫 if (isSchemaIOSchema(someSchema)) { // someSchema 此时是 SchemaType }类型守卫的实现逻辑在 translators/utils.ts#L54-L73isSchemaIOSchema对象同时具有view与type属性SchemaIO 的特征是必有viewisJSONSchema对象有type但没有view属性。TranslationOptions支持strictMode默认false时遇到不支持的特性只收集warnings置为true时addWarning会直接抛出 Errortranslators/utils.ts#L21-L27适合在需要严格校验的测试或 CI 场景使用。翻译产生的 warnings 在渲染时会通过console.warn([SmartForm][RJSF] Schema translation warnings:, ...)打印RJSF/index.tsx#L82-L84。自定义 WidgetsSmartForm 内置了包装 SchemaIO 组件的自定义 RJSF widgets位于 RJSF/widgets 目录包括AutoComplete.tsx、Dropdown.tsx、TextWidget.tsx、CheckboxWidget.tsx、CheckboxesWidget.tsx、DatePickerWidget.tsx、JsonEditorWidget.tsx、LabelValueWidget.tsx、RadioWidget.tsx、SelectWidget.tsx、SliderWidget.tsx、TaxonomyWidget.tsx、ToggleWidget.tsx等十余个。AutoComplete WidgetAutocompleteView会自动映射为AutoCompletewidgetui.ts#L78-L85{ type: array, view: { component: AutocompleteView, choices: [...], allow_user_input: true, // → ui:options.freeSolo默认 true allow_duplicates: false, // → ui:options.allowDuplicates默认 false } }注意allow_clearing会映射为allowClear默认true且源码注释明确指出allowDuplicates为true时会在 Material UI 中产生错误因此默认关闭。Dropdown WidgetDropdownView会自动映射为Dropdownwidgetui.ts#L42-L51支持multiple、compact、color、variant等ui:options{ type: string, view: { component: DropdownView, choices: [...], multiple: true, } }架构一览app/packages/components/src/components/SmartForm/ ├── index.tsx # 主组件门面转发给 RJSF ├── types.ts # SmartFormProps 输入/组件枚举 ├── RJSF/ │ ├── index.tsx # RJSF 实现表单渲染核心 │ ├── utils.ts # filterEmptyArrays / transformErrors 等 │ ├── templates/ # 自定义 RJSF 模板 │ │ ├── FieldTemplate.tsx │ │ └── ObjectFieldTemplate.tsx │ ├── translators/ # Schema 翻译 │ │ ├── index.ts # 主 APItranslateSchema 等 │ │ ├── schema.ts # JSON Schema 翻译 │ │ ├── ui.ts # UI Schema 翻译 │ │ ├── data.ts # 数据转换 │ │ └── utils.ts # 共享工具与类型守卫 │ └── widgets/ # 自定义 RJSF widgets │ ├── AutoComplete.tsx │ ├── Dropdown.tsx │ ├── TextWidget.tsx │ └── ... # 其余十余个 widget └── README.md / USAGE_EXAMPLES.md与 README 中给出的目录结构相比实际仓库将实现组织在RJSF/子目录下index.tsx作为门面types.ts单独成文件结构更清晰。测试SmartForm 拥有覆盖完整的测试体系vitest测试文件与翻译器同目录存放# 运行全部测试 yarn test SmartForm # 运行指定测试套件 yarn test translators yarn test schema.test yarn test ui.test yarn test data.test测试覆盖对应 RJSF/translators/schema.test.ts、ui.test.ts、index.test.ts、utils.test.ts以及RJSF/utils.test.tsx170 条测试用例全部字段类型primitive 类型、default 值、view 元数据、object/array/oneOf双向数据转换边界情况如default: null不写入 schema、未知类型产生警告、strictMode 下抛错、缺少 label 时用 value 充当 enumNames集成测试例如schema.test.ts验证了number 类型的min/max翻译为minimum/maximum整数配合multipleOftuple 数组固定minItems/maxItemsrequired字段的正确收集addChoicesToSchema对数组/非数组/无 choices 的 AutocompleteView 的分支处理等。与 SchemaIOComponent 的集成SmartForm 可以单独使用也可以通过SchemaIOComponent位于fiftyone/core/plugins/SchemaIO使用直接使用import SmartForm from fiftyone/components/SmartForm; SmartForm schema{schema} data{data} /;通过 SchemaIOComponent自动检测import { SchemaIOComponent } from fiftyone/core/plugins/SchemaIO; // 对 JSON Schema 自动使用 SmartForm SchemaIOComponent schema{jsonSchema} / // 强制 SchemaIO schema 走 SmartForm SchemaIOComponent schema{schemaIOSchema} useJSONSchema{true} /这意味着 SmartForm 是 SchemaIO 渲染体系在JSON Schema 形态下的渲染后端当面板声明采用 JSON Schema 时SchemaIOComponent自动路由到 SmartForm从而复用 RJSF 生态的校验、模板与 widget 能力。迁移指南从 SchemaIO DynamicIO迁移前DynamicIOimport { SchemaIOComponent } from fiftyone/core/plugins/SchemaIO; SchemaIOComponent schema{schema} data{data} onChange{(data, liteValues) handleChange(data)} onPathChange{(path, value) handlePathChange(path, value)} /;迁移后SmartFormimport SmartForm from fiftyone/components/SmartForm; SmartForm schema{schema} data{data} onChange{(data) handleChange(data)} // 注意不支持 onPathChange // 请改用携带完整数据的 onChange /;已知限制自定义组件部分 SchemaIO 组件没有 RJSF 等价物翻译时会记录 warningui.ts#L229-L246PlotlyViewDashboardViewFileExplorerViewMarkdownViewButtonViewLinkViewNoticeViewMenuViewLazyFieldViewProgressView变通方案不使用useJSONSchema标志直接走SchemaIOComponent的原生渲染路径。基于路径的更新RJSF 不支持 SchemaIO 那样的onPathChange路径级变更回调请改用携带完整数据的onChange。Lite ValuesRJSF 没有对应 SchemaIO lite values 的概念。性能与浏览器支持SmartForm 针对以下场景做了优化快速的 schema 翻译带缓存最小化重渲染revision机制当data为 nullish 时递增 key 强制重建表单见 RJSF/index.tsx#L54-L58高效的数据转换大型表单100 字段浏览器支持与 RJSF 一致Chrome / Firefox / Safari / Edge 的最新版本。扩展阅读SmartForm 完整使用示例翻译器测试SmartForm 组件源码SchemaIO 类型定义SmartForm 的许可证为 Apache-2.0。在 FiftyOne 插件开发中凡是需要在面板里渲染由 SchemaIO schema 描述、带校验与 Material-UI 风格的表单都可以优先考虑 SmartForm——它把 SchemaIO 的描述能力与 RJSF 的表单生态无缝衔接让表单渲染逻辑从插件代码中彻底剥离。【免费下载链接】fiftyoneRefine high-quality datasets and visual AI models项目地址: https://gitcode.com/GitHub_Trending/fi/fiftyone创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表