# @harnessio/forms 中文文档

规范地址：https://npmcn.com/package/%40harnessio/forms/

版本：1\.2\.0
npm 元数据更新时间：2026-11-16T17:37:08.105Z
中文译文更新时间：2026-11-17T10:16:19.650Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40harnessio/forms
原文对照：https://npmcn.com/package/%40harnessio/forms/?lang=original
项目主页：https://github.com/harness/canary/tree/main#readme
源码仓库：https://github.com/harness/canary#main

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：916 kB，52 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：yup ^0\.29\.1，zod ^4\.0\.0，uuid ^8\.3\.0，react ^17\.0\.2，lodash-es ^4\.17\.21，react-dom ^17\.0\.2，react-hook-form ^7\.55\.0，@hookform/resolvers ^5\.0\.0
- 首次发布：2025-03-07T18:16:01.329Z
- 最新版本发布：2026-10-01T13:35:01.855Z
- 近 30 天下载量：59019（2026-10-18 至 2026-11-16，npm 官方下载统计）
- 已发布版本数：57（近 12 个月 31 个）

## 中文简介

调色表库

## 安装

```sh
npm install @harnessio/forms
```

也可以使用：`pnpm add @harnessio/forms`、`yarn add @harnessio/forms`、`bun add @harnessio/forms`

## README

# @ 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\. 界定输入类型

每个输入都有独特的类型标识符:

```typescript
export enum InputType {
  text = 'text',
  number = 'number',
  checkbox = 'checkbox',
  array = 'array',
  list = 'list'
  // ... more types
}
```

### 2\. 创建输入组件

定义输入配置和组件 :

```typescript
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} />
  }
}
```

**参见实例:** [游乐场/俱乐部/执行/投入/](https://npmcn.com/package/%40harnessio/forms/playground/src/implementation/inputs/)

### 3\. 登记投入

使用 `InputFactory` 以注册输入组件:

```typescript
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`数字 :

```typescript
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')
      }
    }
  ]
}
```

**使用自定义的输入配置用于类型安全 :**

```typescript
// 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` 组件 :

```typescript
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 路径语法

```typescript
// 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' }
  ]
}
```

**示例** 见 [游乐场/游乐场/游乐场/游乐场/游乐场/游乐场](https://npmcn.com/package/%40harnessio/forms/playground/src/examples/tuple-example/)

## 验证

图书馆与Zod合并,进行计划验证.

### 按产出进行验证

在输入定义中直接定义验证计划 :

**静态验证 :**

```typescript
{
  inputType: 'text',
  path: 'email',
  label: 'Email',
  required: true,
  validation: {
    schema: z.string().email('Invalid email format')
  }
}
```

**动态验证( 取决于其它形式值):**

```typescript
{
  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`数字 :

```typescript
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
)
```

**所需字段的验证解析令:**

1.  `requiredSchemaPerInput[inputType]`
2.  `requiredSchema`
3.  内建默认验证

## 其他特征

### 有条件的可见度

基于窗体值的控制输入能见度 :

```typescript
{
  inputType: 'select',
  path: 'authType',
  label: 'Authentication Type'
},
{
  inputType: 'text',
  path: 'apiToken',
  label: 'API Token',
  isVisible: (values) => values.authType === 'token'
}
```

### 默认值

使用 `default` 财产或 `collectDefaultValues`数字 :

```typescript
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)
```

### 数值变换器

数据模型和窗体状态之间的转换值 :

```typescript
{
  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 参考

### 核心类型

```typescript
// 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)` - 从窗体定义中提取默认值

## 实例

完整的工作实例可见于 [游乐场/游乐场/实例/](https://npmcn.com/package/%40harnessio/forms/playground/src/examples/)数字 :

-   [基本示例](https://npmcn.com/package/%40harnessio/forms/playground/src/examples/basic-example/) - 有文字和数字输入的简单形式
-   [Tuple 示例](https://npmcn.com/package/%40harnessio/forms/playground/src/examples/tuple-example/) - 固定位置阵列
-   [矩阵示例](https://npmcn.com/package/%40harnessio/forms/playground/src/examples/array-example/) - 动态阵列
-   [列表示例](https://npmcn.com/package/%40harnessio/forms/playground/src/examples/list-example/) - 动态对象列表
-   [条件示例](https://npmcn.com/package/%40harnessio/forms/playground/src/examples/conditional-example/) - 有条件的能见度

## 许可证

见主寄存许可证.

## 常见问题

### @harnessio/forms 是什么？

调色表库

### 如何安装 @harnessio/forms？

在项目目录运行 npm install @harnessio/forms，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：yup（^0\.29\.1）、zod（^4\.0\.0）、uuid（^8\.3\.0）、react（^17\.0\.2）、lodash-es（^4\.17\.21）、react-dom（^17\.0\.2）、react-hook-form（^7\.55\.0）、@hookform/resolvers（^5\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @harnessio/forms 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @harnessio/forms 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @harnessio/forms 可以商用吗？

@harnessio/forms 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @harnessio/forms 的下载量有多少？

根据 npm 官方下载统计，@harnessio/forms 在 2026/10/18 – 2026/11/16 这 30 天内被下载 59,019 次，日均约 1,967 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @harnessio/forms 还在维护吗？

最新版本 1\.2\.0 发布于 2026/10/01（1 个月前）；至今共发布 57 个版本，其中过去 12 个月发布了 31 个；首次发布于 2025/03/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

