@ harnesio/ 形式
用于 React 应用程序的型号安全,配置驱动的窗体库.
概览
@harnessio/forms 提供了一种使用配置方案构建表格的申报方法。 库从类型安全定义中生成表格,处理验证,并通过React Hook Form集成管理形式状态.
关键特性 :
- 使用 TypeScript 通用软件的类型安全形式定义
- QQ 配置驱动的窗体生成
- QQ 与 Zod 整合的内置验证
- QQ 固定位置阵列的 Tuple 支持
- * 灵活输入部分系统
- 有条件的能见度和动态形式
核心原则
- 从配置生成表单
- 每个输入定义了自己的配置界面
- 验证计划是输入配置的一部分
- 通过通用类型参数确定安全性
- 可通过自定义输入组件扩展
类型系统
库对类型安全使用通用类型参数 :
IInputDefinition<TConfig, TValue, TInputType>
TConfig- 输入特定配置类型TValue- 输入值类型TInputType- 输入类型的字符串字词类型
InputProps<TValue, TConfig>
TValue- 输入值类型TConfig- 输入特定配置类型
快速启动
1. 界定输入类型
每个输入都有独特的类型标识符:
export enum InputType {
text = 'text',
number = 'number',
checkbox = 'checkbox',
array = 'array',
list = 'list'
// ... more types
}
2. 创建输入组件
定义输入配置和组件 :
import { InputComponent, InputProps, useController } from '@harnessio/forms'
// 1. Define input config type
export interface TextInputConfig {
placeholder?: string
}
// 2. Define value type
export type TextInputValueType = string
// 3. Create component with typed props
function TextInputInternal(
props: InputProps<TextInputValueType, TextInputConfig>
): JSX.Element {
const { readonly, path, input } = props
const { label, required, inputConfig } = input
const { field } = useController({ name: path })
return (
<>
<label>{label}</label>
<input
placeholder={inputConfig?.placeholder}
{...field}
disabled={readonly}
/>
</>
)
}
// 4. Register as InputComponent
export class TextInput extends InputComponent<TextInputValueType, TextInputConfig> {
public internalType = InputType.text
renderComponent(props: InputProps<TextInputValueType, TextInputConfig>): JSX.Element {
return <TextInputInternal {...props} />
}
}
参见实例: 游乐场/俱乐部/执行/投入/
3. 登记投入
使用 InputFactory 以注册输入组件:
import { InputFactory } from '@harnessio/forms'
import { NumberInput } from './inputs/number-input'
import { TextInput } from './inputs/text-input'
const inputComponentFactory = new InputFactory()
inputComponentFactory.registerComponent(new TextInput())
inputComponentFactory.registerComponent(new NumberInput())
export default inputComponentFactory
4. 定义表格Schema
使用 IFormDefinition数字 :
import { z } from 'zod'
import { IFormDefinition } from '@harnessio/forms'
// Basic form without custom input configs
export const basicFormDefinition: IFormDefinition = {
inputs: [
{
inputType: 'text',
path: 'name',
label: 'Name',
required: true,
validation: {
schema: z.string().min(3, 'Name must be at least 3 characters')
}
},
{
inputType: 'number',
path: 'age',
label: 'Age',
validation: {
schema: z.coerce.number().min(18, 'Must be 18 or older')
}
}
]
}
使用自定义的输入配置用于类型安全 :
// 1. Define config types for each custom input
export interface ListInputConfig {
inputType: 'list'
inputConfig: {
inputs: IInputDefinition[]
layout?: 'grid' | 'default'
}
}
export interface TextInputConfig {
inputType: 'text'
inputConfig?: {
placeholder?: string
}
}
// 2. Create union type
export type InputConfigType = ListInputConfig | TextInputConfig
// 3. Use union type for type-safe form definition
export const formDefinition: IFormDefinition<InputConfigType> = {
inputs: [
{
inputType: 'text',
path: 'username',
label: 'Username',
inputConfig: {
placeholder: 'Enter username' // ✅ Type-safe
}
},
{
inputType: 'list',
path: 'items',
label: 'Items',
inputConfig: {
inputs: [...], // ✅ Type-safe
layout: 'grid'
}
}
]
}
5. 招标表
使用 RootForm 财务报告和审定财务报表 RenderForm 组件 :
import { RootForm, RenderForm, useZodValidationResolver } from '@harnessio/forms'
import { inputComponentFactory } from './factory'
import { formDefinition } from './form-definition'
function MyForm() {
const resolver = useZodValidationResolver(formDefinition)
const handleSubmit = (values: AnyFormValue) => {
console.log('Form values:', values)
}
return (
<RootForm
defaultValues={{}}
onSubmit={handleSubmit}
resolver={resolver}
>
{rootForm => (
<>
<RenderForm
factory={inputComponentFactory}
inputs={formDefinition}
/>
<button onClick={() => rootForm.submitForm()}>
Submit
</button>
</>
)}
</RootForm>
)
}
Tuple 支持( Fixed- Position 阵列)
库支持 二进制路径 对固定位置数组使用数字指数,每个位置可以有自己的方案.
何时使用 Tuples
· 使用tuples用于:
- 要素的固定数量(例如,
[x, y]坐标) - 特定位置计划(例如,
[primary, backup]服务器) - 不应动态添加/删除的元素
使用时间 array 或者说 list 用于:
- 项目的可变数量
- 添加/移动功能
- 所有项目都采用相同的方案
Tuple 路径语法
// Coordinates: [10, 20]
{
inputs: [
{ inputType: 'number', path: 'coordinates.0', label: 'X' },
{ inputType: 'number', path: 'coordinates.1', label: 'Y' }
]
}
// Nested objects: [{ name: 'Primary', url: '...' }, { name: 'Backup', url: '...' }]
{
inputs: [
{ inputType: 'text', path: 'servers.0.name', label: 'Primary Server' },
{ inputType: 'text', path: 'servers.0.url', validation: { schema: z.string().url() } },
{ inputType: 'text', path: 'servers.1.name', label: 'Backup Server' },
{ inputType: 'text', path: 'servers.1.url', validation: { schema: z.string().url() } }
]
}
// Different schemas per position
{
inputs: [
{ inputType: 'text', path: 'owners.0.email', validation: { schema: z.string().email() } },
{ inputType: 'select', path: 'owners.1.role', inputConfig: { options: [...] } }
]
}
// Sparse indices: ['Critical', null, null, null, null, 'Low']
{
inputs: [
{ inputType: 'text', path: 'priorities.0', label: 'High Priority' },
{ inputType: 'text', path: 'priorities.5', label: 'Low Priority' }
]
}
验证
图书馆与Zod合并,进行计划验证.
按产出进行验证
在输入定义中直接定义验证计划 :
静态验证 :
{
inputType: 'text',
path: 'email',
label: 'Email',
required: true,
validation: {
schema: z.string().email('Invalid email format')
}
}
动态验证( 取决于其它形式值):
{
inputType: 'text',
path: 'password',
label: 'Password',
required: true
},
{
inputType: 'text',
path: 'confirmPassword',
label: 'Confirm Password',
required: true,
validation: {
schema: (values) =>
z.string().refine(
(val) => val === values.password,
{ message: 'Passwords must match' }
)
}
}
需要嵌入的字段 : required 即使路径中的父对象在窗体值中缺失,也会执行。 譬如说, spec.connectorRef 与 required: true 当值没有时失败 spec 一点也不 其子孙都是可选的物体失踪时仍然通过. 嵌入 inputs 当他们的母输入有自己的时,也会被验证 required 或者说 validation 规则; 当父规则通过时, 将检查嵌入输入 .
全局验证配置
使用 useZodValidationResolver数字 :
const resolver = useZodValidationResolver(
formDefinition,
{
// Custom required message for all inputs
requiredMessage: 'This field is required',
// Custom required message per input type
requiredMessagePerInput: {
text: 'Text field is required',
number: 'Please enter a number'
},
// Custom required schema per input type
requiredSchemaPerInput: {
text: z.string().min(1),
number: z.number(),
myCustomInput: z.custom(...)
},
// Global validation function
globalValidation: (value, input, metadata) => {
// Custom validation logic
return { continue: true }
}
},
metadata
)
所需字段的验证解析令:
requiredSchemaPerInput[inputType]requiredSchema- 内建默认验证
其他特征
有条件的可见度
基于窗体值的控制输入能见度 :
{
inputType: 'select',
path: 'authType',
label: 'Authentication Type'
},
{
inputType: 'text',
path: 'apiToken',
label: 'API Token',
isVisible: (values) => values.authType === 'token'
}
默认值
使用 default 财产或 collectDefaultValues数字 :
import { collectDefaultValues } from '@harnessio/forms'
// In input definition
{
inputType: 'text',
path: 'name',
default: 'John Doe'
}
// Collect all defaults from form definition
const defaultValues = collectDefaultValues(formDefinition)
数值变换器
数据模型和窗体状态之间的转换值 :
{
inputType: 'text',
path: 'tags',
label: 'Tags',
// Transform incoming data (array) to form display (string)
inputTransform: (value: string[]) => ({
value: value.join(', ')
}),
// Transform form value (string) back to data model (array)
outputTransform: (value: string) => ({
value: value.split(',').map(s => s.trim())
})
}
变形器函数 :
inputTransform- 转换数据模型 → 窗体状态(数据被装入时运行)outputTransform- 转换状态-数据模型(提交时运行)- 两人都要回来
{ value: any }或者说undefined - 通过提供阵列可连锁多个变压器
API 参考
核心类型
// Input definition with generic parameters
IInputDefinition<TConfig = unknown, TValue = unknown, TInputType extends string = string>
// Input component props
InputProps<TValue = unknown, TConfig = unknown>
// Form definition
IFormDefinition<TConfig = unknown>
// Value types
AnyFormValue // any form value type
主要组成部分
RootForm- 有反应钩形式集成的根形式组件RenderForm- 从形式定义中输入格式InputFactory- 输入部分登记册InputComponent<TValue, TConfig>- 输入组件的基本类别
钩子
useZodValidationResolver(definition, config?, metadata?)- 创建 Zod 验证解析器useController(options)- 反应钩式控制钩
公用事业
collectDefaultValues(definition)- 从窗体定义中提取默认值
实例
完整的工作实例可见于 游乐场/游乐场/实例/数字 :
许可证
见主寄存许可证.