feat: complete public Form migration and validation focus contract

This commit is contained in:
maoyingjie
2026-10-27 18:28:13 +08:00
parent f424fa5597
commit 2c221e0995
22 changed files with 843 additions and 35 deletions
+1
View File
@@ -381,6 +381,7 @@ async function copyMarkdownCode(event: MouseEvent) {
<IconArrowUpRight :size="12" aria-hidden="true" />
</Link>
<Link
v-if="frontmatter.stylesSource !== false"
:href="`https://github.com/heroui-inc/heroui/blob/ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960/packages/styles/components/${componentSlug}.css`"
target="_blank"
rel="noreferrer noopener"
+5
View File
@@ -180,6 +180,11 @@ export const componentItems: DocsItem[] = [
url: "/components/fieldset",
category: "forms",
},
{
title: "Form 表单",
url: "/components/form",
category: "forms",
},
{
title: "Header 标题",
url: "/components/header",
+185
View File
@@ -0,0 +1,185 @@
---
title: Form 表单
description: 用于表单校验与提交处理的包裹组件
component: form
stylesSource: false
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import { Form } from "@heroui-vue/components";
</script>
```
<ComponentPreview name="form-basic" />
## 组件结构
```vue
<script setup lang="ts">
import { Form, Button } from "@heroui-vue/components";
</script>
<template>
<Form>
<!-- 表单字段 -->
<Button type="submit">提交</Button>
<Button type="reset">重置</Button>
</Form>
</template>
```
## 示例
### 渲染函数
上游 `render={(props) => <form {...props} data-custom="foo" />}` 在 Vue 中直接通过 `data-custom="foo"` 透传到同一个原生 `<form>`;无需为添加属性替换根元素。Form 始终保留表单语义,不提供 React `render` prop 或替换为非表单元素的 API。
<ComponentPreview name="form-render-function" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="form-custom-styles" />
### 全局 CSS
要自定义表单布局与间距,可在 `<Form>` 上使用 `class`,或通过 `@layer components` 添加项目级类。
`Form` 渲染原生 `<form>` 元素,聚焦校验与提交。本库样式包中无专用 BEM 类;从全局 CSS 应用容器样式,控件级自定义请使用字段组件。
```css
@layer components {
.form-layout {
@apply flex flex-col gap-4 rounded-xl border border-border bg-surface p-4 shadow-sm;
}
}
```
```vue
<Form class="form-layout" @submit.prevent="handleSubmit">
<!-- TextField、Input、Button 等 -->
</Form>
```
分组字段与共享布局请使用 [Fieldset](./fieldset),并定位 `.hv-fieldset`、`.hv-fieldset__legend` 等相关类。单个控件请参阅 [TextField](./text-field)、[Input](./input)、[Label](./label)、[FieldError](./field-error) 的全局 CSS 部分。
## 样式参考
本库对提供样式的组件遵循 BEM 方法论。
`Form` 渲染原生 `<form>` 元素,无专用 BEM 类或 variants。通过 `class` 应用布局、间距与表面样式。字段外观与校验状态来自 `TextField`、`Input`、`Label`、`Description`、`FieldError` 等子组件。结构化多字段布局请与 Fieldset 组合使用。
## API 参考
### Form / FormRoot
Form 复用本库共享字段上下文与浏览器 Constraint Validation API。`FormRoot` 是同一组件别名;原生属性、ARIA、class、style 与 DOM 监听器透传到实际 form。
| Prop / 事件 | 类型 | 默认值 | 描述 |
| --- | --- | --- | --- |
| `action` | `string` | - | 提交表单数据的 URL;保留浏览器传统提交 |
| `class` | Vue class 绑定 | - | 应用于 form 元素的布局与样式 |
| 默认插槽 | `() => VNodeChild` | - | 表单内容(字段、按钮等) |
| `enctype` | `string` | - | 原生编码类型,如 `multipart/form-data` |
| `method` | `string` | - | 原生提交方法,如 `get` / `post` |
| `@invalid` | `(event: Event) => void` | - | 每个无效控件每次检查通知一次;`preventDefault()` 取消默认焦点,不放行无效提交 |
| `@reset` | `(event: Event) => void` | - | 原生重置事件;可 `preventDefault()` 取消 |
| `@submit` | `(event: SubmitEvent) => void` | - | 校验通过或显式跳过校验时调用;使用 `.prevent` 接管提交 |
| `target` | `string` | - | 提交后显示响应的位置 |
| `validationBehavior` | `'native' \| 'aria'` | `'native'` | 默认字段校验策略;字段可覆盖 |
| `validationErrors` | `Record<string, string \| string[]>` | `{}` | 按字段名映射的服务端错误;编辑该字段后忽略当前响应中的错误 |
| `aria-label` | `string` | - | 表单的无障碍名称 |
| `aria-labelledby` | `string` | - | 标注表单的元素 ID |
| `novalidate` / `noValidate` | `boolean` | `false`(调用方意图) | 为 `true` 或空属性时跳过本库提交检查;实际 DOM 始终有 novalidate,见下文 |
| `render`(上游) | Vue attrs / 默认插槽替代 | - | 添加原生属性直接透传;不移植 React DOMRenderFunction |
公开类型包含 `FormProps`、`FormRootProps`、`FormSlots`、`FormExpose`。实例能力是 Vue 扩展:
| 实例成员 | 类型 | 说明 |
| --- | --- | --- |
| `element` | `HTMLFormElement \| undefined` | 挂载后实际 form |
| `checkValidity()` | `() => boolean` | 按 native/aria 策略检查并产生 invalid;不自动聚焦 |
| `reportValidity()` | `() => boolean` | 检查并聚焦首个无效字段,除非调用方取消;错误由 FieldError 展示,不重复调用原生气泡校验 |
| `reset()` | `() => void` | 调用原生 form.reset(),遵守取消与既有受控值协议 |
### Form Validation
Form 支持:
- 内置 HTML5 校验属性(`required`、`minLength`、`pattern` 等)。
- TextField 的同步 `validate(value)` 校验函数。
- FieldError 展示字段错误。
- 校验通过后处理提交。
- `validationErrors` 提供服务端校验结果。
#### Validation Behavior
`validationBehavior` 控制校验展示方式:
- **`native`**(默认):有错误时阻止提交,提交尝试后显示错误并聚焦首个无效字段。
- **`aria`**:实时显示错误语义,允许提交,由调用方处理。
可在表单级或单个字段级设置。Form 在实际 DOM 上使用 `novalidate` 接管验证,再按每个控件的 `data-validation-behavior` 或表单默认值检查,因此允许混合两种策略。调用方显式 `novalidate`、提交按钮的 `formnovalidate` 可跳过提交检查。即使监听 `@submit.capture`,无效提交也先由 Form 拦截。
`validationErrors` 使用新的响应对象更新。编辑一个字段只忽略当前响应里该字段的错误,不修改传入对象。同步 `validate` 不接受 Promise;异步请求和竞态由调用方管理。原生外部 `form` 关联的控件也在验证集合中;字段的服务端错误上下文仍按 Vue 组件祖先继承,DOM form 关联不会跨组件树注入上下文。
### Form Submission
表单支持传统 `action` 提交、JavaScript 事件处理及 FormData API:
```vue
<script setup lang="ts">
function handleSubmit(event: SubmitEvent) {
const formData = new FormData(event.currentTarget as HTMLFormElement);
const data = Object.fromEntries(formData);
console.log("Form data:", data);
}
</script>
<template>
<Form @submit.prevent="handleSubmit">
<!-- 表单字段 -->
</Form>
</template>
```
默认插槽不维护第二份表单值。禁用控件不进入 FormData,只读控件保留。reset 恢复非受控初始值,受控值仍由父级决定;取消 reset 会保留当前值。`element.submit()` 遵循浏览器行为并绕过校验与 submit 事件,常规提交应使用按钮或 `element.requestSubmit()`。
### Integration with Form Fields
Form 与共享字段组件协作:
- **TextField**:带标签与校验的文本输入。
- **Checkbox / CheckboxGroup**:布尔选择及多选集合。
- **RadioGroup**:多选一。
- **Switch**:开关控件。
- **Button**:提交与重置。
值、错误关联与重置使用各字段现有协议;复杂日期、颜色、数值和集合字段的具体差异仍以各自组件页为准。
### Advanced Usage
可组合第三方校验库,将结果映射到 `validationErrors`;无需为使用 Input 强制引入其他库。自定义错误焦点使用 `@invalid` 并调用 `event.preventDefault()`。共享上下文和集成验证示例见[字段与表单基础](/fields)。不提供 React Form Context、React 函数 action 或完整 React Aria ValidationResult。
## 无障碍
- 原生 `<form>` 语义。
- 使用 `aria-label` 或 `aria-labelledby` 提供 form landmark 名称。
- 无效提交默认聚焦首个无效字段;组合字段聚焦其可操作部件。
- 错误通过 FieldError 与真实控件的 ARIA 描述关联。
- `validationBehavior="aria"` 保留错误语义但不阻止提交。
三个预览沿用固定源的字段、文案、校验与布局;为适应窄屏增加 `max-w-full`,提交结果用页内 `status` 替代上游 `alert`,reset 同时清除该反馈。React 专属机制按上述 Vue 方式适配。当前仅支持浏览器客户端;未将完整读屏矩阵或逐像素比较视为已完成。
## 相关案例
[字段与表单基础](/fields)提供服务端错误注入、原生 FormData 和重置的额外组合示例。
## 相关组件
[TextField](./text-field) · [Fieldset](./fieldset) · [FieldError](./field-error) · [Button](./button)
+74
View File
@@ -0,0 +1,74 @@
<script setup lang="ts">
import { ref } from "vue";
import { IconCheck } from "@tabler/icons-vue";
import {
Button,
Description,
FieldError,
Form,
Input,
Label,
TextField,
} from "@heroui-vue/components";
const result = ref("");
function onSubmit(event: Event) {
event.preventDefault();
const formData = new FormData(event.currentTarget as HTMLFormElement);
const data: Record<string, string> = {};
formData.forEach((value, key) => {
data[key] = value.toString();
});
result.value = `表单提交数据:${JSON.stringify(data, null, 2)}`;
}
function validateEmail(value: string) {
return /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(value)
? null
: "请输入有效的邮箱地址";
}
function validatePassword(value: string) {
if (value.length < 8) return "密码至少需要 8 个字符";
if (!/[A-Z]/.test(value)) return "密码至少需要包含一个大写字母";
if (!/[0-9]/.test(value)) return "密码至少需要包含一个数字";
return null;
}
</script>
<template>
<Form
class="flex w-96 max-w-full flex-col gap-4"
@submit="onSubmit"
@reset="result = ''"
>
<TextField is-required name="email" type="email" :validate="validateEmail">
<Label>邮箱</Label>
<Input placeholder="john@example.com" />
<FieldError />
</TextField>
<TextField
is-required
:min-length="8"
name="password"
type="password"
:validate="validatePassword"
>
<Label>密码</Label>
<Input placeholder="输入密码" />
<Description>至少 8 个字符,且包含 1 个大写字母和 1 个数字</Description>
<FieldError />
</TextField>
<div class="flex gap-2">
<Button type="submit">
<IconCheck aria-hidden="true" class="size-4 shrink-0" />
提交
</Button>
<Button type="reset" variant="secondary">重置</Button>
</div>
<pre
v-if="result"
role="status"
aria-label="提交结果"
class="whitespace-pre-wrap break-all text-xs"
>{{ result }}</pre>
</Form>
</template>
+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
import { Button, Form, Input, Label, TextField } from "@heroui-vue/components";
</script>
<template>
<Form
class="flex w-80 max-w-full flex-col gap-3 rounded-xl border border-border/80 bg-surface p-4 shadow-sm"
@submit.prevent
>
<TextField is-required name="email" type="email">
<Label>工作邮箱</Label>
<Input class="bg-field" placeholder="you@company.com" />
</TextField>
<Button class="w-full" type="submit">继续</Button>
</Form>
</template>
+75
View File
@@ -0,0 +1,75 @@
<script setup lang="ts">
import { ref } from "vue";
import { IconCheck } from "@tabler/icons-vue";
import {
Button,
Description,
FieldError,
Form,
Input,
Label,
TextField,
} from "@heroui-vue/components";
const result = ref("");
function onSubmit(event: Event) {
event.preventDefault();
const formData = new FormData(event.currentTarget as HTMLFormElement);
const data: Record<string, string> = {};
formData.forEach((value, key) => {
data[key] = value.toString();
});
result.value = `表单提交数据:${JSON.stringify(data, null, 2)}`;
}
function validateEmail(value: string) {
return /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(value)
? null
: "请输入有效的邮箱地址";
}
function validatePassword(value: string) {
if (value.length < 8) return "密码至少需要 8 个字符";
if (!/[A-Z]/.test(value)) return "密码至少需要包含一个大写字母";
if (!/[0-9]/.test(value)) return "密码至少需要包含一个数字";
return null;
}
</script>
<template>
<Form
class="flex w-96 max-w-full flex-col gap-4"
data-custom="foo"
@submit="onSubmit"
@reset="result = ''"
>
<TextField is-required name="email" type="email" :validate="validateEmail">
<Label>邮箱</Label>
<Input placeholder="john@example.com" />
<FieldError />
</TextField>
<TextField
is-required
:min-length="8"
name="password"
type="password"
:validate="validatePassword"
>
<Label>密码</Label>
<Input placeholder="输入密码" />
<Description>至少 8 个字符,且包含 1 个大写字母和 1 个数字</Description>
<FieldError />
</TextField>
<div class="flex gap-2">
<Button type="submit">
<IconCheck aria-hidden="true" class="size-4 shrink-0" />
提交
</Button>
<Button type="reset" variant="secondary">重置</Button>
</div>
<pre
v-if="result"
role="status"
aria-label="提交结果"
class="whitespace-pre-wrap break-all text-xs"
>{{ result }}</pre>
</Form>
</template>
+2 -3
View File
@@ -59,6 +59,7 @@ Form 的 `validation-errors` 是以字段 name 为键、字符串或字符串数
本页交付共享协议和验证场景,是字段/表单基础设施指南,不替代独立组件文档。TextField、Label、Description、FieldError、TextArea 的完整 API 与基线示例见各自组件页:
- [Form 表单](/components/form)
- [TextField 文本输入框](/components/text-field)
- [Label 标签](/components/label)
- [Description 描述](/components/description)
@@ -67,6 +68,4 @@ Form 的 `validation-errors` 是以字段 name 为键、字符串或字符串数
已迁移的三个 TextField 基线示例仍在此展示,便于联调验证。
SSR 支持标准的直接子部件、原生元素/Fragment 包裹的 Description/FieldError,即使说明放在控件之后也能生成完整 ID 关联。自定义 Vue 包装组件中的描述在客户端注册;若首屏 SSR 必须关联,请显式提供控件 aria-describedby 和对应描述 id。Nuxt 完整消费验收尚未进行。
Fieldset 的禁用继承、Checkbox/Radio/集合字段、异步校验调度仍是后续任务,不从本页示例推断已经实现。
当前仅支持浏览器客户端使用,SSR/水合/Nuxt 服务端不在支持范围。Form 的正式 API、3 个固定源示例及行为差异见 [Form 表单](/components/form)。Fieldset 和 Checkbox/Radio 已集成;异步校验调度仍由调用方处理。
+5 -1
View File
@@ -66,7 +66,7 @@
| empty-state | 验证中(M16) | 单根 EmptyState;4 个自编示例(基线无页面/示例);默认 fallback;空节点判断与上游 children 真值回退边界不同 |
| field-error | 验证中(通用字段) | 作用域插槽 validationErrors;独立页 2/2 示例;无完整 validationDetails(见基础协议) |
| fieldset | 验证中(FORM-02) | 四部件、3 基线例与禁用验证例;响应式禁用、首 Legend 例外,边界见 FORM-02 |
| form | 验证中(基础设施) | native/aria 校验、FormData/reset、服务端错误;完整基线文档与生态集成未完成 |
| form | 已迁移(客户端,有已知差异) | Form/FormRoot;3/3固定源例与独立中文页;native/aria、FormData/reset、服务端错误、invalid通知/取消焦点、首个无效组合字段;render→attrs,原生函数action/完整RAC上下文不移植;见FORM结果 |
| header | 验证中(M31) | Header/HeaderRoot;原生 `<header>` 集合分组标题;基线无独立文档/演示,自编 3 例并标注;无 v-model |
| radio | 验证中(基线实现) | 原生 radio + Content/Control/Indicator;须在 RadioGroup 内,成员禁用/只读、作用域状态 |
| radio-group | 验证中(基线实现) | 标量模型、roving Tab/方向键/dir/loop、原生提交/校验/reset;12 个基线预览 |
@@ -280,3 +280,7 @@ ComboBox/Autocomplete的正式组合、原30项返修和本轮定位/ref/ARIA/lo
公开 DateRangePicker/Root、Trigger、TriggerIndicator、RangeSeparator、Popover、dateRangePickerVariants 及 Props/RenderProps/state/time 类型;起止输入复用 DateFieldGroup/Input/InputContainer/Segment/Suffix,端点为可类型检查的 `endpoint` prop;日历复用 RangeCalendar 与 CalendarYearPicker 具名部件。固定源中文 10 个预览、API/插槽/状态表与导航已接入;Picker 拥有唯一完整范围接受值、双端点字段校验、两个命名提交值和 reset,未显式绑定的内嵌 RangeCalendar 继承范围、上下界、不可用、禁用/只读/无效、locale/dir 与非连续策略。
不完整范围、第一下日历点击和空值时间草稿都不提交;清空两端提交 null,清空一端在关闭/外部替换/reset 时回到接受状态。受控拒绝后可重试,日历修改保留两端各自的日期类、时间、时区与历法,字段编辑保留不可显示精度。固定源 `slot="start"/"end"` 映射为 `endpoint` prop;格式选项的 `w-full` 弹层宽度映射为 252px 日历加 24px 内边距。真实浏览器、定向回归和最终 tarball 验证见 [任务结果](tasks/results/DATE-RANGE-PICKER.md)。
## FORM 正式迁移(2026-10-27)
复用已有字段/FormData/reset协议,公开FormRoot及Props/实例/插槽类型;固定源中文3例与正式文档已接入。新增表单级invalid通知、取消默认焦点、外部form关联控件检查,避免重复invalid与后续组合字段抢焦点;choice共享适配与Switch尊重已取消事件。源Form无专用CSS,不新增variants或样式。具体范围/验证见 [FORM结果](tasks/results/FORM.md)。
+4
View File
@@ -80,3 +80,7 @@ ColorPicker/ColorPickerRoot、ColorPickerTrigger、ColorPickerPopover、Props/
## AVATAR(2026-10-27)
Avatar/AvatarRoot、Image/Fallback 已完成公共客户端迁移补齐,见 [结果](tasks/results/AVATAR.md)。修复Image asChild丢失默认插槽与delayMs=0永久隐藏;可选src、三部件as/asChild、原生事件类型和AvatarRootProps公开。加载状态仍由Reka持有,回退延迟使用本库定时器以处理零值/动态切换与卸载取消。实际img在加载中隐藏而不卸载,srcSet/sizes仅透传实际图片、预加载仍只探测src;与固定源差异已在文档记录。既有AvatarGroup直接子级继承不变。
## FORM(2026-10-27)
Form已有基础协议在本轮完成正式文档与3例迁移。Root保持原生form,render添加属性以attrs替代,不支持替换为非表单根。DOM始终novalidate,由本库按native/aria及字段覆盖验证;显式novalidate/formnovalidate跳过提交检查。invalid原生捕获后通知调用方,取消事件不放行提交、可阻止默认焦点;checkValidity不聚焦,report/submit仅首个无效字段可聚焦。组合字段共享适配/Switch保留错误更新并尊重取消;避免多控件抢焦点与重复reportValidity事件。错误使用FieldError而不承诺原生气泡。详见 [结果](tasks/results/FORM.md),React函数action/完整RAC ValidationResult/跨树上下文不移植。
+4
View File
@@ -53,3 +53,7 @@
## FORM-02 更新(2026-10-22)
M12–M14 已提交并复核,以上阶段 0 的“示例仅三项、尚未派发”属于历史。TextField 的状态/SSR/校验实现现位于 field/useTextField.ts,SearchField 复用同一内核;useTextControl 仍负责真实 Input/TextArea 的值恢复/reset。Fieldset 的独立禁用作用域已接入现有控件,首个直接 Legend 例外和嵌套有专项测试。完整交付见 FORM-02 报告;选择分组后续实施契约见 selection-field-foundation.md。
## FORM 正式迁移更新(2026-10-27)
正式组件页与3例已补齐,见 [FORM结果](../tasks/results/FORM.md)。Form使用原生invalid捕获传递同一可取消事件,不调用控件reportValidity重复发送事件;表单report/submit允许首个无效字段聚焦,check不聚焦,后续组合字段收到已取消事件而只更新错误。choice共享invalidEvent与Switch遵守进入处理器前的defaultPrevented状态。实例reportValidity使用本库错误展示与聚焦,不承诺浏览器原生气泡。其余既有值/服务器错误/reset与混合native/aria策略不变。
+3 -1
View File
@@ -10,7 +10,7 @@
- 字段/Form、Checkbox/Radio、数值/Slider/OTP、弹层/菜单、集合/ListBox/Select、ComboBox/Autocomplete、Tag、Toast/Table已集成。
- DateField、TimeField、Calendar、CalendarYearPicker、DatePicker 与 DateRangePicker 已有公共组件;RangeCalendar 已完成公共客户端迁移(20 个基线预览),范围选择与 Calendar 共用视图/焦点/年份设施。DatePicker 复用 DateField 字段、Calendar 视图与 Popover 弹层,10 个基线预览已接入。DateRangePicker 复用双端点 DateField、RangeCalendar 与 Popover,10 个基线预览已接入。
- ColorSwatch/ColorSwatchRoot及Color/parseColor公共子集已公开;ColorArea/ColorAreaRoot、ColorAreaThumb 与 colorAreaVariants 已公开,复用共享颜色 owner、二维交互与固定源 7 例;ColorSlider/ColorSliderRoot、ColorSliderOutput/Track/Thumb 与 colorSliderVariants 已公开,复用共享通道/轨道内核与固定源 9 例。ColorField/ColorFieldRoot、配套 ColorInputGroup 与具名字段部件、两套 variants 已完成客户端迁移,含固定源 13 例,并按用户授权合入 main。ColorSwatchPicker/ColorSwatchPickerRoot、ColorSwatchPickerItem/Swatch/Indicator 与 colorSwatchPickerVariants 已完成客户端迁移,含固定源 10 例(见 [结果](tasks/results/COLOR-SWATCH-PICKER.md),复核通过并已按用户授权合入 main)。ColorPicker/ColorPickerRoot、ColorPickerTrigger/Popover 与 colorPickerVariants 已完成客户端迁移,含固定源 6 例(见 [结果](tasks/results/COLOR-PICKER.md),独立复核通过,已按用户授权合入 main)。颜色家族公开迁移已完成。
- 兼容矩阵目前85条(包含子部件与基础设施),文档有72个组件页面。矩阵中的“验证中”保留其原有限制,不升级为完整兼容。
- 兼容矩阵目前85条(包含子部件与基础设施),文档有74个组件页面。矩阵中的“验证中”保留其原有限制,不升级为完整兼容。
## 尚未完成的公共家族
@@ -38,3 +38,5 @@ ColorSwatchPicker 最终修复 `3c8473d`,已合入 main(`457d340`),原
ColorPicker 独立复核修复 `74cd597`,已合入 main(`23eecaf`);main 集成全量107文件/1571项、类型、文档构建和十契约最终tarball通过。补验390px窄屏与焦点恢复,原公开差异保留;远端同步以实际Git状态为准。
Avatar 头像已由主会话亲自补齐迁移,未委派其他AI;自定义图片插槽、零延迟回退、可选src、原生事件类型与Root别名已修正。7/7固定源例核对、加载回归及真实浏览器范围见 [AVATAR结果](tasks/results/AVATAR.md)。
Form 已完成正式客户端迁移收尾:FormRoot/公开类型、独立组件页与3/3固定源例、invalid取消及默认焦点管理;继续复用已有字段协议。实施/验收由主会话亲自完成,见 [FORM结果](tasks/results/FORM.md)。
+6 -8
View File
@@ -1,10 +1,8 @@
# 当前工作区交接
- 任务:AVATAR 已由主会话亲自完成并自测通过,状态 accepted;未委派其他AI。
- 工作区/分支:heroui-vue / `main`;当前无实施占用。
- 起点:`6de246de49cfdb0ce8c8770de9049d6e7644e4ed`;实施 `fa8b22719ece4ad0c6c3a93caeb77c871da28de2`;验收记录 `4f2061a`。
- 已按用户授权合main,合并SHA `8f3880073db8cbdea4333ab95d6ee88a2dd779d7`;本轮未push。
- 验证:定向2文件/37项、main全量108文件/1577项、typecheck、build:docs、最终tarball avatar契约通过;浏览器图片加载/失败回退/浅深色/32-40-48px/562px窄屏通过。
- 入口:`docs/tasks/AVATAR.md`、`docs/tasks/results/AVATAR.md`。
- 预览:保留原有5173服务,`/components/avatar`;未停止他人服务,主题已恢复跟随系统。
- 接续:从实际git状态与docs/tasks选择新工作,不从历史自动猜测。
- 任务:FORM;主会话亲自实施、自测,不委派其他AI。
- 工作区/分支:heroui-vue / `feat/form-public`。
- 起点:`f424fa559725ef62909eccf56c9d63a3f0e161e6`;此前main `ee43cc6`,起始工作区干净。
- 用户授权:验证通过后提交并合main,不push。
- 入口:`docs/tasks/FORM.md`。
- 保留已有5173服务,单目录串行。
+1
View File
@@ -20,6 +20,7 @@
| 卡 | 用途 |
| ----------------------------------------- | ----------------------------------------------------------- |
| [FORM](FORM.md) | 主会话亲自迁移表单正式API、3例与校验/焦点验收 |
| [AVATAR](AVATAR.md) | 主会话亲自补齐头像三部件、7例与加载回退验收 |
| [COLOR-PICKER](COLOR-PICKER.md) | 公共可组合颜色选择器迁移,含固定源 6 例、共享颜色与嵌套弹层验收 |
| [COLOR-SWATCH-PICKER](COLOR-SWATCH-PICKER.md) | 公共色块选择集合迁移,含固定源 10 例与产物验收 |
+4
View File
@@ -324,3 +324,7 @@ CSS/tv 仅加 `hv-` 前缀与 Apache-2.0 来源;`colorPickerVariants` 保持
## AVATAR 迁移补齐(2026-10-27)
重新核对固定提交 `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960` 的 `packages/react/src/components/avatar/{avatar.tsx,index.ts}`、Avatar CSS/variants、中文 `(media)/avatar.mdx` 与 `apps/docs/src/demos/cn/avatar` 全7例。保留既有来源/许可与hv命名空间、全部视觉数值;补Image默认插槽、可选src、Root别名/部件替换/原生事件类型及零延迟适配。仍用Reka处理图片状态,框架/预加载差异见组件文档与 [结果](tasks/results/AVATAR.md)。
## FORM(2026-10-27)
固定 `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`:`packages/react/src/components/form/{form.tsx,index.ts}`、中文 `(forms)/form.mdx` 与 `apps/docs/src/demos/cn/form/{basic,render-function,custom-styles}.tsx`。源无专用CSS/variants;复用已有字段样式。保留3例布局、文案、验证规则与字段,render添加data-custom改为Vue attrs、Gravity Check图标用Tabler IconCheck、alert提交反馈改页内status、增加max-w-full适应窄屏;差异见 [Form文档](../apps/docs/components/form.md)。
+2 -1
View File
@@ -189,9 +189,10 @@ export function useChoiceField<T>(
dismissed.value = form?.validationErrors.value;
}
function invalidEvent(event: Event, focus: () => void) {
const canceled = event.defaultPrevented;
event.preventDefault();
touched.value = true;
void nextTick(focus);
if (!canceled) void nextTick(focus);
}
function validity(control: HTMLInputElement | undefined) {
control?.setCustomValidity(
+67 -18
View File
@@ -1,5 +1,12 @@
<script setup lang="ts">
import { computed, provide, ref, useAttrs } from "vue";
import {
computed,
provide,
ref,
useAttrs,
onMounted,
onBeforeUnmount,
} from "vue";
import {
formContextKey,
type ValidationBehavior,
@@ -13,39 +20,81 @@ const props = withDefaults(
}>(),
{ validationBehavior: "native", validationErrors: () => ({}) },
);
const emit = defineEmits<{ invalid: [event: Event] }>();
defineSlots<{ default?: () => unknown }>();
const attrs = useAttrs();
provide(formContextKey, {
validationBehavior: computed(() => props.validationBehavior),
validationErrors: computed(() => props.validationErrors),
});
const element = ref<HTMLFormElement>();
let validation: { report: boolean; first?: EventTarget | null } | undefined;
function invalid(event: Event) {
// Native invalid does not bubble. Forward it during capture, while preserving
// the same cancelable event for consumer-controlled focus management.
if ((event.target as HTMLInputElement).form !== element.value) return;
emit("invalid", event);
// Composite fields redirect focus from their validation proxy. Only the
// first invalid field may do so during report/submit, none during check.
if (validation) {
if (!validation.report || validation.first) event.preventDefault();
validation.first ??= event.target;
}
}
// Use a native capture listener: a Vue capture invoker stamps invalid events
// before child Vue listeners run, which can suppress freshly mounted fields'
// handlers in the same millisecond. Do not touch Vue's private event markers.
onMounted(() => element.value?.addEventListener("invalid", invalid, true));
onBeforeUnmount(() =>
element.value?.removeEventListener("invalid", invalid, true),
);
function checkValidity(report = false) {
let first:
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | undefined;
for (const control of Array.from(element.value?.elements ?? [])) {
if (
!("checkValidity" in control) ||
(control.getAttribute("data-validation-behavior") ??
props.validationBehavior) === "aria"
)
continue;
const field = control as
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
if (!field.checkValidity() && !first) first = field;
}
if (report && first) {
first.focus();
first.reportValidity();
let firstEvent: Event | undefined;
const previous = validation;
validation = { report };
try {
for (const control of Array.from(element.value?.elements ?? [])) {
if (
!("checkValidity" in control) ||
(control.getAttribute("data-validation-behavior") ??
props.validationBehavior) === "aria"
)
continue;
const field = control as
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
let invalidEvent: Event | undefined;
const observe = (event: Event) => {
invalidEvent = event;
// Associated controls outside the form DOM cannot reach its capture
// listener, but are still part of the native form.elements collection.
if (!element.value?.contains(field)) invalid(event);
};
field.addEventListener("invalid", observe, true);
try {
if (!field.checkValidity() && !first) {
first = field;
firstEvent = invalidEvent;
}
} finally {
field.removeEventListener("invalid", observe, true);
}
}
} finally {
validation = previous;
}
// A second reportValidity() on the control would dispatch invalid twice.
// FieldError provides the message; only apply the form's default focus here.
if (report && first && !firstEvent?.defaultPrevented) first.focus();
return !first;
}
function submit(event: Event) {
const submitter = (event as SubmitEvent).submitter as
HTMLButtonElement | HTMLInputElement | null;
const booleanAttribute = (value: unknown) => value != null && value !== false;
const skip =
attrs.novalidate === "" ||
attrs.novalidate === true ||
attrs.noValidate === true;
booleanAttribute(attrs.novalidate) || booleanAttribute(attrs.noValidate);
if (!skip && !submitter?.formNoValidate && !checkValidity(true)) {
event.preventDefault();
event.stopImmediatePropagation();
@@ -167,9 +167,11 @@ watchEffect(() => {
);
});
function onInvalid(event: Event) {
const canceled = event.defaultPrevented;
event.preventDefault();
showError.value = true;
element.value?.querySelector<HTMLButtonElement>("[role=switch]")?.focus();
if (!canceled)
element.value?.querySelector<HTMLButtonElement>("[role=switch]")?.focus();
}
function reset(event: Event) {
void nextTick(() => {
+7 -1
View File
@@ -170,7 +170,10 @@ export {
} from "./components/alert/context";
export { default as TextField } from "./components/textfield/TextField.vue";
export { default as Form } from "./components/form/Form.vue";
export {
default as Form,
default as FormRoot,
} from "./components/form/Form.vue";
export {
fieldContextKey,
formContextKey,
@@ -189,6 +192,9 @@ export { useFieldPart } from "./components/field/useFieldPart";
export type {
TextFieldProps,
FormProps,
FormRootProps,
FormSlots,
FormExpose,
DescriptionProps,
FieldErrorProps,
} from "./types";
+14 -1
View File
@@ -108,7 +108,20 @@ import type Form from "./components/form/Form.vue";
import type Description from "./components/description/Description.vue";
import type FieldError from "./components/field/FieldError.vue";
export type TextFieldProps = InstanceType<typeof TextField>["$props"];
export type FormProps = InstanceType<typeof Form>["$props"];
export type FormProps = InstanceType<typeof Form>["$props"] &
Omit<import("vue").FormHTMLAttributes, "onSubmit" | "onReset" | "onInvalid"> & {
noValidate?: boolean;
onSubmit?: (event: SubmitEvent) => void;
onReset?: (event: Event) => void;
};
export type FormRootProps = FormProps;
export interface FormSlots {
default?: () => import("vue").VNodeChild;
}
export type FormExpose = Pick<
InstanceType<typeof Form>,
"element" | "checkValidity" | "reportValidity" | "reset"
>;
export type DescriptionProps = InstanceType<typeof Description>["$props"];
export type FieldErrorProps = InstanceType<typeof FieldError>["$props"];
+313
View File
@@ -0,0 +1,313 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import {
Form,
TextField,
Input,
FieldError,
CheckboxGroup,
Switch,
} from "../packages/vue/src";
import FormBasic from "../apps/docs/demos/form-basic.vue";
import FormRenderFunction from "../apps/docs/demos/form-render-function.vue";
import FormCustomStyles from "../apps/docs/demos/form-custom-styles.vue";
const wrappers: ReturnType<typeof mount>[] = [];
// Submit occurs after mounting, as with real user input. Keep Vue's listener
// timestamp guard deterministic without changing private event properties.
beforeEach(() => vi.useFakeTimers({ toFake: ["Date"] }));
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
vi.useRealTimers();
});
function render(content: () => unknown, attrs: Record<string, unknown> = {}) {
const w = mount(Form, {
attrs,
slots: { default: content as () => ReturnType<typeof h> },
attachTo: document.body,
});
wrappers.push(w);
return w;
}
function submit(form: HTMLFormElement, submitter?: HTMLButtonElement) {
vi.setSystemTime(Date.now() + 1);
const event = new SubmitEvent("submit", {
bubbles: true,
cancelable: true,
submitter,
});
form.dispatchEvent(event);
return event;
}
const settle = async () => {
await nextTick();
await nextTick();
};
describe("Form public validation", () => {
it.each(["", "true", "false", true, false])(
"uses native boolean-attribute semantics for novalidate=%s",
(value) => {
const submitted = vi.fn((event: Event) => event.preventDefault());
const w = render(() => h("input", { required: true }), {
novalidate: value,
onSubmit: submitted,
});
submit(w.element as HTMLFormElement);
expect(submitted).toHaveBeenCalledTimes(value === false ? 0 : 1);
},
);
it.each([
() => h(CheckboxGroup, { isRequired: true }),
() => h(Switch, { isRequired: true }),
])(
"cancels composite focus and preserves the first invalid field across mixed controls",
async (Control) => {
const w = render(() => [h("input", { required: true }), Control()]);
submit(w.element as HTMLFormElement);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
w.unmount();
wrappers.splice(wrappers.indexOf(w), 1);
const canceled = render(() => [Control(), h("button", "anchor")], {
onInvalid: (e: Event) => e.preventDefault(),
});
const button = canceled.get("button").element as HTMLButtonElement;
button.focus();
submit(canceled.element as HTMLFormElement);
await settle();
expect(document.activeElement).toBe(button);
canceled.vm.checkValidity();
await settle();
expect(document.activeElement).toBe(button);
},
);
it("notifies once per invalid control and allows canceling default focus", async () => {
const invalid = vi.fn((e: Event) => e.preventDefault());
const submitted = vi.fn();
const w = render(
() => [
h("input", { required: true, name: "one" }),
h("input", { required: true, name: "two" }),
h("button", { type: "submit" }, "submit"),
],
{ onInvalid: invalid, onSubmit: submitted },
);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
const event = submit(w.element as HTMLFormElement, button);
await settle();
expect(event.defaultPrevented).toBe(true);
expect(submitted).not.toHaveBeenCalled();
expect(invalid).toHaveBeenCalledTimes(2);
expect(invalid.mock.calls[0][0].target).toBe(w.get("input").element);
expect(document.activeElement).toBe(button);
});
it("focuses the first invalid control and updates associated field errors", async () => {
const invalid = vi.fn();
const w = render(
() => [
h(TextField, { name: "email", isRequired: true }, () => [
h(Input),
h(FieldError),
]),
h("input", { required: true, name: "second" }),
],
{ onInvalid: invalid },
);
await settle();
expect(submit(w.element as HTMLFormElement).defaultPrevented).toBe(true);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
expect(invalid).toHaveBeenCalledTimes(2);
expect(w.get("input").attributes("aria-describedby")).toContain(
w.get("[data-slot=field-error]").attributes("id"),
);
});
it("honors invalid cancellation on the field itself", async () => {
const w = render(() => [
h("input", {
required: true,
onInvalid: (e: Event) => e.preventDefault(),
}),
h("button", "anchor"),
]);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
expect(submit(w.element as HTMLFormElement).defaultPrevented).toBe(true);
expect(document.activeElement).toBe(button);
});
it("validates externally associated controls and can cancel their default focus", async () => {
const invalid = vi.fn((e: Event) => e.preventDefault());
const w = mount(
defineComponent({
render: () =>
h("div", [
h(Form, { id: "external-form", onInvalid: invalid }),
h("input", { form: "external-form", required: true }),
h("button", "anchor"),
]),
}),
{ attachTo: document.body },
);
wrappers.push(w);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
expect(
submit(w.get("form").element as HTMLFormElement).defaultPrevented,
).toBe(true);
expect(invalid).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(button);
});
it("skips validation for formnovalidate and respects canceled submission/reset", async () => {
const invalid = vi.fn();
const submitted = vi.fn((event: Event) => event.preventDefault());
const reset = vi.fn((event: Event) => event.preventDefault());
const w = render(
() => [
h(Input, { name: "value", defaultValue: "initial", required: true }),
h("button", { formnovalidate: true, type: "submit" }, "skip"),
],
{ onInvalid: invalid, onSubmit: submitted, onReset: reset },
);
await w.get("input").setValue("");
const event = submit(
w.element as HTMLFormElement,
w.get("button").element as HTMLButtonElement,
);
expect(event.defaultPrevented).toBe(true);
expect(submitted).toHaveBeenCalledTimes(1);
expect(invalid).not.toHaveBeenCalled();
(w.element as HTMLFormElement).reset();
await settle();
expect(reset).toHaveBeenCalledTimes(1);
expect((w.get("input").element as HTMLInputElement).value).toBe("");
});
it("exposes native form access and policy-aware validation without duplicate invalid events", async () => {
const invalid = vi.fn();
const w = render(() => h("input", { name: "value", required: true }), {
onInvalid: invalid,
});
expect(w.vm.element).toBe(w.element);
expect(w.vm.checkValidity()).toBe(false);
expect(invalid).toHaveBeenCalledTimes(1);
invalid.mockClear();
expect(w.vm.reportValidity()).toBe(false);
expect(invalid).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(w.get("input").element);
await w.get("input").setValue("valid");
expect(w.vm.checkValidity()).toBe(true);
w.vm.reset();
await settle();
expect((w.get("input").element as HTMLInputElement).value).toBe("");
});
it("keeps dynamic native attrs and policy overrides on the real form", async () => {
const method = ref("post");
const submitted = vi.fn();
const w = mount(
defineComponent({
setup: () => () =>
h(
Form,
{
action: "/submit",
method: method.value,
validationBehavior: "aria",
onSubmit: submitted,
"data-custom": "foo",
},
() => h("input", { required: true }),
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
expect(w.get("form").attributes("action")).toBe("/submit");
expect(w.get("form").attributes("data-custom")).toBe("foo");
method.value = "get";
await settle();
expect(w.get("form").attributes("method")).toBe("get");
submit(w.get("form").element as HTMLFormElement);
expect(submitted).toHaveBeenCalledTimes(1);
});
});
describe("Form fixed-source demos", () => {
it.each([FormBasic, FormRenderFunction])(
"validates both fields, submits exact data, and resets values/errors/results",
async (Demo) => {
const w = mount(Demo, { attachTo: document.body });
wrappers.push(w);
const form = w.get("form").element as HTMLFormElement;
await settle();
expect(submit(form).defaultPrevented).toBe(true);
await settle();
expect(w.findAll("[data-slot=field-error]")).toHaveLength(2);
const email = w.get('input[name="email"]');
const password = w.get('input[name="password"]');
expect(document.activeElement).toBe(email.element);
expect(w.get("[data-slot=field-error]").text()).toBe(
"请输入有效的邮箱地址",
);
await email.setValue("john@example.com");
for (const [value, error] of [
["short", "密码至少需要 8 个字符"],
["lowercase1", "密码至少需要包含一个大写字母"],
["Password", "密码至少需要包含一个数字"],
]) {
await password.setValue(value);
await settle();
submit(form);
await settle();
expect(w.get("[data-slot=field-error]").text()).toBe(error);
expect(w.find('[role="status"]').exists()).toBe(false);
}
await password.setValue("Password1");
await settle();
submit(form);
await settle();
expect(w.get('[role="status"]').text()).toContain("表单提交数据:");
expect(w.get('[role="status"]').text()).toContain(
'"email": "john@example.com"',
);
expect(w.get('[role="status"]').text()).toContain(
'"password": "Password1"',
);
expect([...new FormData(form)]).toEqual([
["email", "john@example.com"],
["password", "Password1"],
]);
form.reset();
await settle();
expect((email.element as HTMLInputElement).value).toBe("");
expect((password.element as HTMLInputElement).value).toBe("");
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
expect(w.find('[role="status"]').exists()).toBe(false);
if (Demo === FormRenderFunction) expect(form.dataset.custom).toBe("foo");
},
);
it("keeps the custom-styles example as a native validated form", async () => {
const w = mount(FormCustomStyles, { attachTo: document.body });
wrappers.push(w);
const form = w.get("form").element as HTMLFormElement;
expect(w.get("label").text()).toBe("工作邮箱");
expect(w.get("button").text()).toBe("继续");
expect(submit(form).defaultPrevented).toBe(true);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
await w.get("input").setValue("you@company.com");
await settle();
expect(form.checkValidity()).toBe(true);
expect(submit(form).defaultPrevented).toBe(true);
expect([...new FormData(form)]).toEqual([["email", "you@company.com"]]);
});
});
+4
View File
@@ -549,5 +549,9 @@
".hv-avatar--lg",
".hv-avatar--soft"
]
},
"form": {
"exports": ["Form", "FormRoot", "TextField", "Input", "Label", "FieldError", "Button"],
"css": [".hv-textfield", ".hv-input", ".hv-field-error", ".hv-button"]
}
}
+48
View File
@@ -0,0 +1,48 @@
import { h } from "vue";
import {
Form,
FormRoot,
type FormProps,
type FormRootProps,
type FormSlots,
type FormExpose,
} from "@heroui-vue/components";
const props: FormProps = {
validationBehavior: "native",
validationErrors: { email: ["Invalid"] },
action: "/submit",
method: "post",
enctype: "multipart/form-data",
target: "_self",
noValidate: true,
"aria-label": "Account",
class: ["flex", { compact: true }],
onSubmit: (event: SubmitEvent) => event.preventDefault(),
onReset: (event: Event) => event.preventDefault(),
onInvalid: (event: Event) => event.preventDefault(),
};
const rootProps: FormRootProps = props;
const slots: FormSlots = { default: () => h("input", { name: "email" }) };
h(Form, rootProps, { default: slots.default });
h(FormRoot, { validationBehavior: "aria" });
declare const form: FormExpose;
const valid: boolean = form.checkValidity();
const reported: boolean = form.reportValidity();
form.reset();
form.element?.requestSubmit();
// @ts-expect-error validation mode is constrained
const invalidMode: FormProps = { validationBehavior: "automatic" };
// @ts-expect-error field errors accept strings or string arrays
const invalidErrors: FormProps = { validationErrors: { email: 42 } };
// @ts-expect-error no React render function API
const invalidRender: FormProps = { render: () => h("form") };
// @ts-expect-error submit receives native SubmitEvent, not a field value
const invalidSubmit: FormProps = { onSubmit: (value: string) => value };
void [
valid,
reported,
invalidMode,
invalidErrors,
invalidRender,
invalidSubmit,
];