feat: establish shared field and form foundation
This commit is contained in:
@@ -291,3 +291,9 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V
|
||||
- 同步维护 `docs/compatibility.md`(能力与差异)、`docs/upstream.md`(来源与许可)、`docs/verification.md`(实际验证与限制)。详细历史留在这些文件,AGENTS.md 维护后续可执行的规则。
|
||||
- 上游部分包清单标注 MIT,但本地根许可证实际为 Apache-2.0。保留 `third-party/HEROUI-LICENSE` 与样式包许可证,不根据包清单猜测移植许可;新增第三方图标包按其自身许可记录。
|
||||
- 自动浏览器/逐像素对比、完整触屏/读屏、Nuxt 水合与打包后独立安装仍未完成,不在交付说明中暗示已通过。
|
||||
|
||||
## 2026-10-21:字段与表单基础设施
|
||||
|
||||
- 后续文本输入、InputGroup 与字段文档任务先读 [字段/表单协议](docs/decisions/field-form-foundation.md)。通用 fieldContextKey 管理状态/ID/错误;TextFieldContext 管理单文本控件,useTextControl 复用 Input/TextArea 值恢复与 reset。
|
||||
- 不再把 Label/Description/FieldError 绑定到 Switch 私有上下文,不新建第二份值/错误/表单队列。跨组件协议、Form guard、SSR 预规划和 Fieldset 禁用继承由集成人维护。
|
||||
- 已实现的是基础设施与纵向验证,完整 Form/TextField/字段文档尚未迁完。可交出的 M12–M14 范围与禁止越界项见协议,不把计划写成完成状态。
|
||||
|
||||
@@ -39,6 +39,7 @@ const groups = [
|
||||
{ title: "介绍", url: "/introduction" },
|
||||
{ title: "安装", url: "/guide" },
|
||||
{ title: "主题", url: "/themes" },
|
||||
{ title: "字段与表单基础", url: "/fields" },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Button,
|
||||
Description,
|
||||
FieldError,
|
||||
Form,
|
||||
Input,
|
||||
Label,
|
||||
TextArea,
|
||||
TextField,
|
||||
Switch,
|
||||
SwitchContent,
|
||||
SwitchControl,
|
||||
SwitchThumb,
|
||||
type ValidationErrors,
|
||||
} from "@heroui-vue/components";
|
||||
const result = ref("");
|
||||
const validationErrors = ref<ValidationErrors>({});
|
||||
function submit(event: Event) {
|
||||
const data = new FormData(event.currentTarget as HTMLFormElement);
|
||||
result.value = JSON.stringify(Object.fromEntries(data), null, 2);
|
||||
}
|
||||
function reset() {
|
||||
result.value = "";
|
||||
validationErrors.value = {};
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<Form
|
||||
class="flex w-full max-w-md flex-col gap-4"
|
||||
:validation-errors="validationErrors"
|
||||
@submit.prevent="submit"
|
||||
@reset="reset"
|
||||
>
|
||||
<TextField
|
||||
name="email"
|
||||
type="email"
|
||||
is-required
|
||||
default-value=""
|
||||
full-width
|
||||
>
|
||||
<Label>邮箱</Label>
|
||||
<Input placeholder="name@example.com" />
|
||||
<Description>输入有效邮箱后可提交,必填错误会在提交时显示。</Description>
|
||||
<FieldError />
|
||||
</TextField>
|
||||
<TextField
|
||||
name="bio"
|
||||
default-value=""
|
||||
full-width
|
||||
:validate="
|
||||
(value) => (value.length > 80 ? '个人简介不能超过 80 个字符。' : null)
|
||||
"
|
||||
>
|
||||
<Label>个人简介</Label>
|
||||
<TextArea placeholder="介绍一下你自己…" :rows="3" />
|
||||
<FieldError />
|
||||
</TextField>
|
||||
<Switch name="notifications" default-checked>
|
||||
<SwitchContent>
|
||||
<SwitchControl><SwitchThumb /></SwitchControl>
|
||||
<Label>接收活动通知</Label>
|
||||
</SwitchContent>
|
||||
<Description>关闭时原生 FormData 不包含此项。</Description>
|
||||
</Switch>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button type="submit">提交</Button>
|
||||
<Button type="reset" variant="secondary">重置</Button>
|
||||
<Button
|
||||
variant="tertiary"
|
||||
@click="
|
||||
validationErrors = { email: '此邮箱已被使用,请修改后再提交。' }
|
||||
"
|
||||
>
|
||||
显示服务端错误
|
||||
</Button>
|
||||
</div>
|
||||
<pre
|
||||
v-if="result"
|
||||
aria-label="提交结果"
|
||||
role="status"
|
||||
class="whitespace-pre-wrap text-xs"
|
||||
>{{ result }}</pre>
|
||||
</Form>
|
||||
</template>
|
||||
@@ -0,0 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { Input, Label, TextField } from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<TextField class="w-full max-w-64" name="email" type="email">
|
||||
<Label>邮箱</Label>
|
||||
<Input placeholder="输入你的邮箱" />
|
||||
</TextField>
|
||||
</template>
|
||||
@@ -0,0 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import {
|
||||
Description,
|
||||
FieldError,
|
||||
Input,
|
||||
Label,
|
||||
TextArea,
|
||||
TextField,
|
||||
} from "@heroui-vue/components";
|
||||
const username = ref("");
|
||||
const bio = ref("");
|
||||
const isUsernameInvalid = computed(
|
||||
() => username.value.length > 0 && username.value.length < 3,
|
||||
);
|
||||
const isBioInvalid = computed(
|
||||
() => bio.value.length > 0 && bio.value.length < 20,
|
||||
);
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex w-full max-w-64 flex-col gap-4">
|
||||
<TextField
|
||||
v-model="username"
|
||||
is-required
|
||||
:is-invalid="isUsernameInvalid"
|
||||
name="username"
|
||||
>
|
||||
<Label>用户名</Label>
|
||||
<Input placeholder="jane_doe" />
|
||||
<FieldError v-if="isUsernameInvalid">
|
||||
用户名至少需要 3 个字符。
|
||||
</FieldError>
|
||||
<Description v-else>为你的资料选择一个唯一的用户名。</Description>
|
||||
</TextField>
|
||||
<TextField v-model="bio" is-required :is-invalid="isBioInvalid" name="bio">
|
||||
<Label>个人简介</Label>
|
||||
<TextArea placeholder="介绍一下你自己…" />
|
||||
<FieldError v-if="isBioInvalid">个人简介至少需要 20 个字符。</FieldError>
|
||||
<Description v-else>至少 20 个字符 ({{ bio.length }}/20).</Description>
|
||||
</TextField>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { Description, Input, Label, TextField } from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<TextField class="w-full max-w-64" name="username">
|
||||
<Label>用户名</Label>
|
||||
<Input placeholder="输入用户名" />
|
||||
<Description>为你的账户选择一个唯一的用户名</Description>
|
||||
</TextField>
|
||||
</template>
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
title: 字段与表单基础
|
||||
description: 组合标签、说明、校验和原生表单提交
|
||||
---
|
||||
|
||||
## 基本组合
|
||||
|
||||
`TextField` 管理一个文本控件的值、状态和关联。`Label` 自动关联到实际控件,`Description` 与 `FieldError` 负责说明和错误提示。`Input` 与 `TextArea` 也可以独立使用。
|
||||
|
||||
<ComponentPreview name="textfield-basic" />
|
||||
|
||||
## 描述与错误
|
||||
|
||||
说明可位于控件之后;动态替换描述或错误时,关联 ID 会同步更新。以下两个示例沿用固定上游的文案与布局。
|
||||
|
||||
<ComponentPreview name="textfield-with-description" />
|
||||
<ComponentPreview name="textfield-validation" />
|
||||
|
||||
## 提交与重置
|
||||
|
||||
填写邮箱后点击“提交”,结果来自原生 `FormData`;“重置”恢复初始值。“显示服务端错误”用于体验错误关联,修改对应字段后清除本次错误;这里没有真实服务端请求。
|
||||
|
||||
<ComponentPreview name="form-foundation" />
|
||||
|
||||
## 值与状态
|
||||
|
||||
优先在 `TextField` 使用 `v-model` 或 `default-value`,子控件负责渲染和输入;每个 TextField 只放一个 Input 或 TextArea。兼容已有的子控件 `v-model`,但不要同时在父字段与子控件绑定两个不同的受控值源。
|
||||
|
||||
| 能力 | 用法 | 说明 |
|
||||
| ---------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
||||
| 受控值 | `v-model` | 父级拒绝更新时恢复实际 DOM 值 |
|
||||
| 初始值 | `default-value` | 非受控 reset 恢复初始值;受控值由父级决定 |
|
||||
| 原生提交 | `name`、`type` | TextField 下发到控件;禁用项省略、只读项保留 |
|
||||
| 状态 | `is-required`、`is-disabled`、`is-read-only`、`is-invalid` | 统一控件状态、标签样式和错误展示;isInvalid 是展示状态,自定义提交约束用 validate 或 validationErrors |
|
||||
| 变体 | `variant`、`full-width` | 继承到控件,子控件可显式覆盖视觉变体 |
|
||||
| 原生约束 | `min-length`、`max-length`、`pattern` | 下发到实际文本控件,额外原生属性可放在 Input/TextArea |
|
||||
| 标签 | `Label` | id 优先使用控件显式 id,其次 TextField id,最后自动生成 |
|
||||
| 描述 | `Description` | 合并调用方 aria-describedby;支持多个描述与动态 ID |
|
||||
| 错误 | `FieldError` | 自动取当前字段错误,也可用默认/作用域插槽自定义 |
|
||||
| 自定义样式 | `class` | 遵循 Vue 字符串、数组、对象绑定,class/style 留在对应根节点 |
|
||||
|
||||
## 校验
|
||||
|
||||
默认 `validation-behavior="native"`:原生约束与同步 `validate(value)` 会拦截无效提交,错误在提交后展示。`validate` 返回错误字符串、字符串数组或表示通过的 `true` / `null` / `undefined`。
|
||||
|
||||
`validation-behavior="aria"`:显示错误语义但允许提交,由调用方决定处理。可以在 Form 统一配置,也可在字段局部覆盖。自定义 Form 通过原生 Constraint Validation API 检查 native 控件,并跳过 aria 控件;使用普通原生 form 配合 aria 模式时,由调用方设置 novalidate 并负责提交决策。
|
||||
|
||||
Form 的 `validation-errors` 是以字段 name 为键、字符串或字符串数组为值的对象。它不替代实际后端验证。修改某字段会忽略当前这次服务端响应中该字段的错误;下一次响应请提供新的对象。异步请求、竞态控制和 schema 库由调用方负责,当前 validate 不接受 Promise。
|
||||
|
||||
| Form 能力 | 类型 / 用法 | 说明 |
|
||||
| -------------------- | ------------------------------------------------ | ----------------------------------------------- |
|
||||
| `validationBehavior` | `'native' \| 'aria'` | 默认 native,向字段提供默认策略 |
|
||||
| `validationErrors` | `Record<string, string \| string[]>` | 服务端错误或外部 schema 的错误结果 |
|
||||
| `@submit` | 原生 SubmitEvent | 验证通过后触发;使用 @submit.prevent 接管提交 |
|
||||
| `@reset` | 原生 Event | 可 preventDefault 取消;不强行覆盖受控值 |
|
||||
| 实例方法 | `checkValidity()`、`reportValidity()`、`reset()` | 按 native/aria 策略验证,报告错误时聚焦无效控件 |
|
||||
|
||||
## 当前边界
|
||||
|
||||
本页交付共享协议和验证场景,尚未宣称完整迁移 Form、TextField 的所有上游文档。已迁移的三个 TextField 基线示例在此展示,其余示例后续按清单补齐。
|
||||
|
||||
SSR 支持标准的直接子部件、原生元素/Fragment 包裹的 Description/FieldError,即使说明放在控件之后也能生成完整 ID 关联。自定义 Vue 包装组件中的描述在客户端注册;若首屏 SSR 必须关联,请显式提供控件 aria-describedby 和对应描述 id。Nuxt 完整消费验收尚未进行。
|
||||
|
||||
Fieldset 的禁用继承、Checkbox/Radio/集合字段、异步校验调度仍是后续任务,不从本页示例推断已经实现。
|
||||
+11
-7
@@ -53,18 +53,18 @@
|
||||
| toggle-button-group | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| toolbar | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| tooltip | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| input | 验证中(最小实现) | primary/secondary、fullWidth、原生属性、v-model/defaultValue、表单 reset;TextField 上下文未实现 |
|
||||
| input | 验证中(字段接入) | 接入 TextField;复用值恢复/reset/ARIA;独立使用保持兼容;完整消费验收未完成 |
|
||||
| input-group | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| textarea | 验证中(演示依赖) | 变体、v-model、表单 reset;为 Surface 表单演示移植,未完成独立 TextField 体系验收 |
|
||||
| textfield | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| textarea | 验证中(字段接入) | 接入 TextField 与共享 useTextControl;独立文档/全部示例仍待补齐 |
|
||||
| textfield | 验证中(基础设施) | 一个文本控件;值/状态/约束/校验/ID;3 个基线示例;完整文档与其余示例待补齐 |
|
||||
| search-field | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| typography | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| label | 验证中(原生标签) | for 关联、required/disabled/invalid;Switch 内采用 span 避免嵌套交互 |
|
||||
| description | 验证中(描述关联) | 唯一 ID、多个描述、Switch aria-describedby 关联 |
|
||||
| label | 验证中(通用字段) | 文本字段自动 for,Switch 内 span;继承 required/disabled/invalid;完整独立文档待补齐 |
|
||||
| description | 验证中(通用字段) | 通用字段描述注册与动态 ID 清理;外部 describedby 合并;SSR 包装限制见基础协议 |
|
||||
| empty-state | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| field-error | 验证中(Switch) | 错误消息、ARIA 关联;完整 TextField 上下文未实现 |
|
||||
| field-error | 验证中(通用字段) | 通用 FieldContext;TextField 与 Switch 错误/动态 ID;validationDetails 等差异见基础协议 |
|
||||
| fieldset | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| form | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| form | 验证中(基础设施) | native/aria 校验、FormData/reset、服务端错误;完整基线文档与生态集成未完成 |
|
||||
| header | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| radio | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| radio-group | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
@@ -141,3 +141,7 @@ Card 图片、头像、横向布局、表单与自定义样式已补齐;Input
|
||||
修复 loading 别名误设原生 disabled 的问题:它与 isPending 都保留焦点并拦截重复激活;isDisabled/disabled 才设置原生禁用。固定加载示例只展示上传中的外观,动态上传示例 2 秒后恢复且可再次触发。asChild 将交互合并到自定义原生 button;涟漪采用 Vue/CSS 实现,图标采用 Tabler 官方 Vue 组件,这些框架适配差异已在文档说明。
|
||||
|
||||
未宣称 Button 的所有 React Aria 行为已完全复刻;PressEvent、路由链接等框架专属能力仍不等价。
|
||||
|
||||
## 字段与表单基础协议(2026-10-21)
|
||||
|
||||
见 [基础协议与可交接范围](./decisions/field-form-foundation.md)。TextField、Form 已形成纵向验证,不代表全部上游示例或复杂表单家族已完成;验证页为 `/fields`。
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# 字段与表单基础协议(FORM-01)
|
||||
|
||||
日期:2026-10-21。实施者:集成人。上游固定 HeroUI 3.2.6 / ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960。
|
||||
|
||||
本阶段建立可复用协议和纵向验证,不声称 Form / TextField / TextArea 全部公开能力、示例与生态集成已经迁移完成。能力状态以 compatibility.md 为准。
|
||||
|
||||
## 职责与文件
|
||||
|
||||
| 层次 | 实现 | 责任 |
|
||||
| ---------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
|
||||
| 字段公共上下文 | `packages/vue/src/components/field/context.ts` | controlId、kind、禁用/只读/必填/错误状态、错误数组及描述/错误 ID 集合;Form 的策略与服务端错误上下文 |
|
||||
| 字段部件 | `field/useFieldPart.ts`、Label、Description、FieldError | 标签与实际控件关联;动态 ID 注册与卸载清理;最邻近字段隔离 |
|
||||
| 文本字段上下文 | `textfield/context.ts`、TextField.vue | 字符串值、初始值、校验、原生约束、继承变体、控件引用;标准组合的 SSR 描述预规划 |
|
||||
| 原生文本控件适配 | `field/useTextControl.ts` | Input / TextArea 复用;值恢复、DOM 事件、ARIA/属性落点、原生 form reset 与清理 |
|
||||
| Form | `form/Form.vue` | validationBehavior / validationErrors、提交校验、聚焦、原生 reset;不维护另一份字段值模型 |
|
||||
| 既有 Switch | Switch.vue | 保留已验证的布尔值/原生 checkbox 逻辑,提供公共 FieldContext,接入 Form 策略与服务端错误 |
|
||||
|
||||
## 不变条件
|
||||
|
||||
1. 一个 TextField 对应一个实际 Input 或 TextArea。优先由 TextField 的 modelValue/defaultValue 管理值;兼容独立控件与已有叶子控件 v-model,但不支持两个互相冲突的受控值源。父级拒绝更新后实际 DOM 值必须恢复,不能只检查事件发出。
|
||||
2. 输入控件的 name/type、原生约束与 ARIA 落在真实 input/textarea;class/style/data-* 保留各组件自己的根节点。TextField 的 id 用作控件 ID;显式控件 id 优先,Label 的 for 跟随它变化。
|
||||
3. Label、Description、FieldError 不依赖 Switch 私有 key。Switch 与 TextField 都提供通用上下文,内层 Switch 的描述/错误不得泄漏到外层 TextField。
|
||||
4. Description / FieldError ID 使用 Vue useId 和可变显式 id;支持多个描述、外部 aria-describedby 合并及卸载清理。FieldError 只在字段 invalid 时渲染,默认展示错误数组并提供 validationErrors / isInvalid 作用域插槽。
|
||||
5. SSR 直接子部件或原生元素/Fragment 包裹的描述/错误,由 TextField 在控件渲染前预规划 ID,保证 Input 在前、Description 在后时首屏引用完整。自定义 Vue 包装组件不能静态展开,客户端依然会注册;需要首屏 SSR 关联时显式设置控件 aria-describedby 与描述 id。不能宣称任意包装层级均已 SSR 验收。
|
||||
6. native 模式通过 Constraint Validation API 检查必填、类型、pattern 与同步自定义错误;提交尝试后展示错误,聚焦首个无效控件。aria 模式展示语义但不拦截提交。isInvalid 是展示状态;提交拦截使用 validate 或 validationErrors,不把静态错误插槽反向解析成校验函数。
|
||||
7. Form 固定使用原生 novalidate 来接管提交时机,再按各控件 data-validation-behavior / Form 默认策略调用 checkValidity。这样能混用局部 native 与 aria 字段。调用方 novalidate 或 submitter.formNoValidate 明确跳过 guard。@submit.capture 也不能先于 guard 处理无效提交。普通原生 form 的 aria 字段需调用方自行配置 novalidate。
|
||||
8. Form 的 validationErrors 按字段 name 映射字符串/数组。用户编辑字段后忽略当前响应对象中的该字段错误,下一响应应提供新对象。异步请求的时序与竞态由调用方负责,validate 目前仅同步,不接受 Promise。
|
||||
9. reset 遵守 preventDefault;非受控恢复初始值,受控保留父级值;禁用项从 FormData 省略,只读项保留。监听随卸载或原生 form 关联改变而清理/重新绑定。Form 不截获数据提交,不强制引入 schema 库。
|
||||
|
||||
## 开发者复用入口
|
||||
|
||||
新增与文本输入同语义的控件应优先复用 `useTextControl`,而不是复制 Input 的值/reset/ARIA 管理。该 hook 暂为仓库内协议,路径与签名由集成人维护;对外只承诺已导出的公共组件/上下文类型,不要求消费应用调用它。
|
||||
|
||||
通用描述部件可以复用 `useFieldPart` 与 `fieldContextKey`。其他 AI 不改动公共协议、Form guard、Switch 原生字段与 SSR 预规划;需要扩展先给出失败用例,由集成人整合。
|
||||
|
||||
## 已验证与范围边界
|
||||
|
||||
- 专项行为覆盖:受控拒绝、初始值与 reset、取消 reset、FormData、动态 ID/描述卸载、状态/变体、原生/aria、同步校验、服务器错误替换、Switch 嵌套隔离和 Form 错误接入。
|
||||
- node 环境 SSR 引用完整且无重复 ID;标准组合在 jsdom 中进行实际 SSR→hydrate,无 hydration mismatch。此结果不代替 Nuxt 消费或完整读屏验收。
|
||||
- 浏览器证据见 verification.md;基线 TextField 示例仅迁移 basic / with-description / validation 三个,位于 /fields 验证页。完整文档后续分任务补齐。
|
||||
- 尚未建立:Fieldset 对非原生控件的完整禁用继承、Checkbox/Radio/集合字段协议、异步校验调度、schema 库/SSR 框架与独立安装验收。FieldError 尚未提供完整 React Aria validationDetails 对象,第三方任务不得据此声明完全兼容。
|
||||
|
||||
## 可以交出的下一步
|
||||
|
||||
| 任务 | 可执行范围 | 约束 |
|
||||
| --------------------------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
||||
| M12 InputGroup | 核对上游实际导出,迁移 Root/Input/TextArea/Prefix/Suffix 等真实部件及全部基线示例 | 接入既有 TextField/useTextControl;不再维护第二份值、错误或 reset 状态;文档/API/主题及定位照基线验收 |
|
||||
| M13 字段文档与演示 | 补齐 TextField、Label、Description、FieldError 独立页面与基线示例 | 先做清单,复用已有三个示例;API 仅描述实际能力,碰到缺口报告集成人;不因补文档而重写核心 |
|
||||
| M14 TextArea 文档与消费验证 | 对照上游核对 TextArea 缺口,补独立文档、示例和适用测试 | 已有 TextArea 值/表单逻辑不复制;尚不支持的能力列清单,必要协议修改由集成人完成 |
|
||||
|
||||
一次先交 M12 或 M13,两者共享导航、导出、矩阵等文件由单一负责人整合;尚未安排或派发这些任务。SearchField 的清空/提交事件语义、Fieldset 与 Checkbox/Radio 体系仍由集成人先验证,不在本次交出的范围。
|
||||
@@ -207,3 +207,9 @@ API 表落实本文“M07–M09 文档契约返工”:className→class,chil
|
||||
每条问题给出严重性、文件与行号、触发条件、实际/预期、依据及修复后的验证方式。优先级顺序为:数据丢失/安全与无法使用的问题 → 公共契约、表单、焦点与关键状态 → 视觉、示例与文档偏差 → 可维护性建议。高一致性是明确要求,明显视觉或内容偏差同样可以阻止验收。
|
||||
|
||||
最后的复核报告列出:发现的问题、已复核通过的范围、执行的检查、未验证项和下一步。若没有发现问题,也明确审查边界,不能保证不存在任何缺陷。
|
||||
|
||||
## FORM-01 之后的任务边界
|
||||
|
||||
字段与表单基础设施及稳定接口见 [field-form-foundation.md](./decisions/field-form-foundation.md)。当前可交出 M12 InputGroup、M13 字段文档/演示补齐、M14 TextArea 独立文档与消费验证,先任选一项,不代表已经派发。
|
||||
|
||||
这些任务必须复用现有 field/textfield/form 协议。SearchField 清空/提交、Fieldset 禁用继承、Checkbox/Radio 家族仍由集成人先做纵向验证。不要顺手重写 shared context、Form guard、Switch 字段或者为文档承诺尚不存在的能力。
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# FORM-01:字段与表单基础设施交付
|
||||
|
||||
日期:2026-10-21。起始提交:`4f43789`(Badge / Alert 已独立复核提交)。
|
||||
|
||||
## 实际交付
|
||||
|
||||
- 通用 FieldContext 与 FormContext、动态字段部件 ID 注册;Label / Description / FieldError 脱离 Switch 私有依赖。
|
||||
- TextField 单文本控件上下文;Input / TextArea 使用同一个 useTextControl 适配值恢复、状态、约束、ARIA 与 reset。
|
||||
- Form 原生/ARIA 校验 guard、错误聚焦、按 name 的外部错误、原生 FormData/reset;Switch 接入同一公共字段/表单协议并保留原布尔值实现。
|
||||
- TextField / FieldError 样式来自固定上游,仅作 hv- 命名空间移植;3 个 TextField 基线示例及 1 个独立基建回归场景。
|
||||
- 说明与演示:`http://127.0.0.1:5173/fields`;协议/限制:`docs/decisions/field-form-foundation.md`。
|
||||
|
||||
## 验证
|
||||
|
||||
- `pnpm test`:11 文件 / 168 项通过。
|
||||
- `pnpm test:unit`:10 文件 / 166 项通过,不含 2 项 SSR。
|
||||
- `pnpm typecheck`、`pnpm build:docs`、`pnpm format`、`git diff --check` 通过。
|
||||
- 新增字段专项 19 项(含标准组合 SSR→hydrate):动态关联、FormData、受控拒绝、取消/reset、状态、native/aria、服务端错误、Switch 隔离与模式覆盖。node SSR 新增首屏 ID 引用完整/唯一检查。
|
||||
- IAB 桌面与 390×844 窄屏:空邮箱被拦截、错误关联并聚焦;真实 FormData 提交结果、未选中 Switch 字段省略;原生 reset 恢复;服务端错误显示/编辑清除;浅深切换正确。表格分别铺满 736 / 350px,页面及单元格无横向溢出。
|
||||
- 截图:`/private/tmp/heroui-vue-field-foundation.png`(本机会话临时证据,不属于发布包)。
|
||||
|
||||
## 已知边界
|
||||
|
||||
- 交付基础设施,不是所有 Form / TextField 文档/示例完成。3 个已移植 TextField 示例为 basic / with-description / validation。
|
||||
- 自定义 Vue 包装组件内部的 Description/FieldError 需要显式 ID 来保证 SSR 首屏关联;标准直接/原生/Fragment 组合已验证。
|
||||
- validate 同步;异步请求竞态和第三方 schema 集成由调用方管理。isInvalid 是展示状态,拦截提交使用 validate / validationErrors。
|
||||
- Fieldset、Checkbox/Radio/集合、SearchField、完整 validationDetails、Nuxt 与打包后独立安装未完成,不据已有测试声称通过。
|
||||
|
||||
## 可交接断点
|
||||
|
||||
已达到可拆分任务的阶段。优先交出 M12 InputGroup,完整提示词在 `M12-input-group-prompt.md`;也可先做 M13 字段文档/演示补齐或 M14 TextArea 文档与消费验证。共享协议由集成人维护,其他 AI 不各自新增状态层。任务尚未派发。
|
||||
@@ -0,0 +1,38 @@
|
||||
# M12 InputGroup 迁移提示词
|
||||
|
||||
以下可交给其他 AI;当前未派发。
|
||||
|
||||
```text
|
||||
在 heroui-vue 独立仓库迁移 M12 InputGroup。
|
||||
先读取 AGENTS.md、docs/migration-handoff.md、docs/decisions/field-form-foundation.md、
|
||||
docs/compatibility.md、docs/upstream.md,确认 FORM-01 的最终提交已在当前 checkout。
|
||||
上游只读 ../heroui,固定 HeroUI 3.2.6 / ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960。
|
||||
|
||||
范围:InputGroup、InputGroupInput、InputGroupTextArea、InputGroupPrefix、InputGroupSuffix,
|
||||
及样式/变体、公开类型/导出、中文文档、全部基线示例、测试与交接。
|
||||
先对照 packages/react/src/components/input-group、对应 CSS/变体、CN input-group.mdx、
|
||||
apps/docs/src/demos/cn/input-group 的文档引用清单,逐项核对示例名称、布局、文案与行为。
|
||||
|
||||
复用已经落地的 TextFieldContext 和 field/useTextControl,统一值、disabled/readonly/required、
|
||||
校验、ARIA、focus和reset;不要再维护一份字段值/错误/表单上下文。
|
||||
根节点管理组合外观,真实 Input/TextArea 承接 name、原生约束与ARIA。
|
||||
前后缀不应成为第二个表单字段,嵌入按钮 type=button,验证复制/密码显示等操作不误提交。
|
||||
显式variant优先于TextField继承;动态前后缀与加载指示器不破坏实际输入控件的焦点和值。
|
||||
|
||||
不修改 field/context.ts、useFieldPart.ts、useTextControl.ts、TextField、Form guard 或 Switch
|
||||
核心协议;如果遇到缺口,提交可复现失败用例,由集成人扩展。
|
||||
共享导出/导航/样式入口/矩阵仅作本批必要更新,不重写主题、布局或构建链路。
|
||||
|
||||
样式、文档、主题与固定基线高度一致;图标用Tabler,预览/复制/高亮共用SFC。
|
||||
API逐个部件核对Vue契约:class而非className、插槽而非children/ReactNode。
|
||||
正文表格铺满内容区并换行,不缩字号、不截断、不横向滚动。
|
||||
测试动态attrs空→新增→修改→删除→再次新增、class合并、事件替换、受控拒绝、
|
||||
原生FormData/reset/取消reset、描述/错误关联、native/aria、SSR与卸载。
|
||||
在真实浏览器验证前后缀布局、聚焦、响应式、浅深主题、复制与密码显示等适用交互。
|
||||
|
||||
执行 pnpm test、pnpm test:unit、pnpm typecheck、pnpm build:docs、pnpm format。
|
||||
新增测试文件同步unit列表,分别记录各入口实际数量及是否含SSR;未验证项明确说明。
|
||||
交接 docs/migrations/M12-input-group.md:起点、范围、API/示例逐项清单、命令与浏览器证据、
|
||||
已知差异、未验证项、来源许可及最短复核路径。
|
||||
不自行提交/推送或宣布集成验收通过。
|
||||
```
|
||||
@@ -42,3 +42,11 @@
|
||||
- Chip 演示将上游 `@gravity-ui/icons` 的 CircleFill / CircleInfo / Check / TriangleExclamation / Ban / CircleCheckFill / Clock / Xmark / ChevronDown / CircleDashed 替换为 Tabler `IconCircleFilled` / `IconInfoCircle` / `IconCheck` / `IconAlertTriangle` / `IconBan` / `IconCircleCheckFilled` / `IconClock` / `IconX` / `IconChevronDown` / `IconCircleDashed`(MIT)。
|
||||
- Badge 带内容示例的 Bell 图标替换为 Tabler `IconBell`。Alert 默认指示图标为移植的基线 SVG,非 Tabler。
|
||||
- 图标统一使用 @tabler/icons-vue(MIT)的官方组件,未移植 React 图标依赖;尚未完成自动逐像素对比。
|
||||
|
||||
## FORM-01 字段与表单基础
|
||||
|
||||
- `packages/react/src/components/{textfield,form,label,description,field-error}`:公共语义与组合设计;Vue 以原生控件与类型化上下文实现,不移植 React Aria runtime。
|
||||
- `packages/styles/components/{textfield,field-error}.css`:移植为 hv- 命名空间,保留 Apache-2.0 来源与许可头。
|
||||
- `apps/docs/src/demos/cn/textfield/{basic,with-description,validation}.tsx`:三个基线演示,保留文案/布局,仅把状态与事件改为 Vue。
|
||||
- Form/字段验证页的 `form-foundation.vue` 为本库基础设施回归场景,未冒充上游完整 Form 示例。
|
||||
- 原 Switch 专属 FieldError 移到通用 field 目录;复用 fieldContextKey,而非复制一套说明/错误基础组件。具体差异与 SSR 包装边界见 decisions/field-form-foundation.md。
|
||||
|
||||
@@ -189,3 +189,11 @@
|
||||
### 未验证
|
||||
|
||||
浅/深一键切换交互、IAB 位图截图、Nuxt 水合、RTL、触屏、读屏、独立安装 dist、`test:browser/visual/package`(未建立)。
|
||||
|
||||
## FORM-01 共享字段与表单基础(2026-10-21)
|
||||
|
||||
- 新增 TextField/Form、通用字段上下文与部件注册;Input/TextArea 共用适配;Switch 通过公共上下文与 Form 关联,既有测试无回归。
|
||||
- `pnpm test`:11 文件/168 项;`pnpm test:unit`:10 文件/166 项(不含 2 SSR);类型、文档构建、Prettier 与 diff 检查通过。
|
||||
- 新增字段专项 19 项;node SSR 验证首屏 ID 引用完整且唯一,jsdom 实际 SSR→hydrate 无 mismatch。不是 Nuxt 消费验收。
|
||||
- 实际浏览器 `/fields`:拦截空邮箱并聚焦、提交真实 FormData、关闭 Switch 省略字段、reset 恢复、服务端错误替换与编辑清除;浅色/深色切换。桌面正文表格 736px,390px 窄屏正文表格 350px,无页面或表格横向溢出。已恢复默认视口与浅色主题。
|
||||
- 协议、限制和可交出的任务见 `decisions/field-form-foundation.md`;完整交付记录见 `migrations/FORM-01-foundation.md`。完整 Form/字段系列文档与未验证能力不标为完成。
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
"build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:unit": "vitest run tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts",
|
||||
"test:unit": "vitest run tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/field-foundation.test.ts",
|
||||
"test:ssr": "vitest run tests/ssr.test.ts",
|
||||
"format": "prettier --check .",
|
||||
"format:fix": "prettier --write .",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
|
||||
* See third-party/HEROUI-LICENSE. Modified: hv- namespace. */
|
||||
/* Field error styles */
|
||||
.hv-field-error {
|
||||
@apply h-0 px-1 text-xs wrap-break-word text-danger opacity-0 data-visible:h-auto data-visible:opacity-100;
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
opacity 150ms var(--ease-out),
|
||||
height 350ms var(--ease-smooth);
|
||||
@apply motion-reduce:transition-none;
|
||||
}
|
||||
|
||||
/*
|
||||
* Toggle fields (checkbox/switch): stack below the label like description.
|
||||
* Disable collapsible height/opacity — those styles break flex-col content layout.
|
||||
*/
|
||||
.hv-checkbox > .hv-field-error,
|
||||
.hv-checkbox > [data-slot="field-error"],
|
||||
.hv-switch > .hv-field-error,
|
||||
.hv-switch > [data-slot="field-error"],
|
||||
.hv-radio > .hv-field-error,
|
||||
.hv-radio > [data-slot="field-error"] {
|
||||
@apply m-0 h-auto min-h-0 p-0 text-muted opacity-100;
|
||||
transition: none;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
|
||||
* See third-party/HEROUI-LICENSE. Modified: hv- namespace. */
|
||||
/* Text field styles */
|
||||
/* use textfield instead of text-field to avoid conflict with Tailwind `text-` prefix */
|
||||
.hv-textfield {
|
||||
@apply flex flex-col gap-1;
|
||||
|
||||
&[data-invalid="true"],
|
||||
&[aria-invalid="true"] {
|
||||
[data-slot="description"] {
|
||||
@apply hidden;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Full width modifier */
|
||||
.hv-textfield--full-width {
|
||||
@apply w-full;
|
||||
|
||||
/* Automatically make Input full width when TextField is full width */
|
||||
[data-slot="input"],
|
||||
[data-slot="textarea"] {
|
||||
@apply w-full;
|
||||
}
|
||||
}
|
||||
@@ -56,3 +56,6 @@
|
||||
font-size: var(--text-xs);
|
||||
}
|
||||
}
|
||||
|
||||
@import "./components/textfield.css";
|
||||
@import "./components/field-error.css";
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { inject, onBeforeUnmount, useId, useAttrs } from "vue";
|
||||
import { switchKey } from "../switch/context";
|
||||
const ctx = inject(switchKey, undefined);
|
||||
import { useAttrs } from "vue";
|
||||
import { useFieldPart } from "../field/useFieldPart";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const attrs = useAttrs();
|
||||
const id = String(attrs.id ?? useId());
|
||||
if (ctx) ctx.descriptionIds.value = [...ctx.descriptionIds.value, id];
|
||||
onBeforeUnmount(() => {
|
||||
if (ctx)
|
||||
ctx.descriptionIds.value = ctx.descriptionIds.value.filter(
|
||||
(value) => value !== id,
|
||||
);
|
||||
});
|
||||
const { id } = useFieldPart("description", attrs);
|
||||
</script>
|
||||
<template>
|
||||
<p :id="id" class="hv-description" data-slot="description"><slot /></p>
|
||||
<p v-bind="attrs" :id="id" class="hv-description" data-slot="description">
|
||||
<slot />
|
||||
</p>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { useAttrs } from "vue";
|
||||
import { useFieldPart } from "./useFieldPart";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const attrs = useAttrs();
|
||||
const { field, id } = useFieldPart("error", attrs);
|
||||
</script>
|
||||
<template>
|
||||
<p
|
||||
v-if="!field || field.invalid.value"
|
||||
v-bind="attrs"
|
||||
:id="id"
|
||||
data-slot="field-error"
|
||||
data-visible
|
||||
class="hv-field-error"
|
||||
role="alert"
|
||||
>
|
||||
<slot
|
||||
:validation-errors="field?.errors.value ?? []"
|
||||
:is-invalid="field?.invalid.value ?? false"
|
||||
>
|
||||
{{ field?.errors.value.join(" ") }}
|
||||
</slot>
|
||||
</p>
|
||||
</template>
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ComputedRef, InjectionKey, Ref } from "vue";
|
||||
|
||||
export type ValidationBehavior = "native" | "aria";
|
||||
export type ValidationErrors = Record<string, string | string[]>;
|
||||
export type ValidateResult = string | string[] | true | null | undefined;
|
||||
export type FieldPart = "description" | "error";
|
||||
export interface FieldContext {
|
||||
controlId: ComputedRef<string>;
|
||||
kind: "text" | "toggle";
|
||||
disabled: ComputedRef<boolean>;
|
||||
readOnly: ComputedRef<boolean>;
|
||||
required: ComputedRef<boolean>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
errors: ComputedRef<string[]>;
|
||||
descriptionIds: Ref<string[]>;
|
||||
errorIds: Ref<string[]>;
|
||||
}
|
||||
export const fieldContextKey: InjectionKey<FieldContext> =
|
||||
Symbol("HeroUIVue.Field");
|
||||
export interface FormContext {
|
||||
validationBehavior: ComputedRef<ValidationBehavior>;
|
||||
validationErrors: ComputedRef<ValidationErrors>;
|
||||
}
|
||||
export const formContextKey: InjectionKey<FormContext> =
|
||||
Symbol("HeroUIVue.Form");
|
||||
|
||||
export function mergeIds(...values: (string | string[] | undefined)[]) {
|
||||
const ids = values
|
||||
.flatMap((value) =>
|
||||
typeof value === "string" ? value.split(/\s+/) : (value ?? []),
|
||||
)
|
||||
.filter(Boolean);
|
||||
return [...new Set(ids)].join(" ") || undefined;
|
||||
}
|
||||
export function errorMessages(result: ValidateResult | false): string[] {
|
||||
return (
|
||||
typeof result === "string" ? [result] : Array.isArray(result) ? result : []
|
||||
).filter(Boolean);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { computed, inject, onBeforeUnmount, useId, watch } from "vue";
|
||||
import { fieldContextKey, type FieldPart } from "./context";
|
||||
|
||||
/** IDs stay reactive when a caller replaces an explicit id; registration is instance-owned. */
|
||||
export function useFieldPart(part: FieldPart, attrs: Record<string, unknown>) {
|
||||
const field = inject(fieldContextKey, undefined);
|
||||
const generated = useId();
|
||||
const id = computed(() =>
|
||||
typeof attrs.id === "string" ? attrs.id : generated,
|
||||
);
|
||||
const ids = part === "description" ? field?.descriptionIds : field?.errorIds;
|
||||
const stop = watch(
|
||||
id,
|
||||
(current, _, cleanup) => {
|
||||
if (!ids) return;
|
||||
if (!ids.value.includes(current)) ids.value = [...ids.value, current];
|
||||
cleanup(() => {
|
||||
ids.value = ids.value.filter((value) => value !== current);
|
||||
});
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
onBeforeUnmount(stop);
|
||||
return { field, id };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
onUpdated,
|
||||
ref,
|
||||
watch,
|
||||
} from "vue";
|
||||
import { mergeIds, formContextKey } from "./context";
|
||||
import { textFieldContextKey } from "../textfield/context";
|
||||
|
||||
interface TextControlProps {
|
||||
modelValue?: string;
|
||||
defaultValue?: string;
|
||||
invalid?: boolean;
|
||||
variant?: "primary" | "secondary";
|
||||
fullWidth?: boolean;
|
||||
type?: string;
|
||||
}
|
||||
export function useTextControl(
|
||||
props: TextControlProps,
|
||||
attrs: Record<string, unknown>,
|
||||
emit: (event: "update:modelValue", value: string) => void,
|
||||
) {
|
||||
const field = inject(textFieldContextKey, undefined);
|
||||
const formContext = inject(formContextKey, undefined);
|
||||
const behavior = () =>
|
||||
field?.validationBehavior.value ?? formContext?.validationBehavior.value;
|
||||
const element = ref<HTMLInputElement | HTMLTextAreaElement>();
|
||||
const initial = props.defaultValue ?? "";
|
||||
const internal = ref(initial);
|
||||
field?.initialize(props.modelValue ?? initial);
|
||||
watch(
|
||||
() => (typeof attrs.id === "string" ? attrs.id : undefined),
|
||||
(id) => field?.setControlId(id),
|
||||
{ immediate: true },
|
||||
);
|
||||
const value = computed(
|
||||
() => props.modelValue ?? field?.value.value ?? internal.value,
|
||||
);
|
||||
const attrBoolean = (value: unknown) => value != null && value !== false;
|
||||
const disabled = () =>
|
||||
attrBoolean(attrs.disabled) || Boolean(field?.disabled.value);
|
||||
const readOnly = () =>
|
||||
attrBoolean(attrs.readonly ?? attrs.readOnly) ||
|
||||
Boolean(field?.readOnly.value);
|
||||
const required = () =>
|
||||
behavior() !== "aria" &&
|
||||
!readOnly() &&
|
||||
(attrBoolean(attrs.required) || Boolean(field?.required.value));
|
||||
const invalid = () =>
|
||||
Boolean(
|
||||
props.invalid ||
|
||||
field?.invalid.value ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true",
|
||||
);
|
||||
const variant = computed(() => props.variant ?? field?.variant.value);
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(next) => {
|
||||
if (next !== undefined) field?.syncValue(next);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
watch(element, (next) => field?.setControl(next), { flush: "post" });
|
||||
function update(event: Event) {
|
||||
const next = (event.target as HTMLInputElement).value;
|
||||
if (!disabled() && !readOnly()) {
|
||||
internal.value = next;
|
||||
field?.setValue(next);
|
||||
emit("update:modelValue", next);
|
||||
}
|
||||
void nextTick(() => {
|
||||
if (element.value) {
|
||||
element.value.value = value.value;
|
||||
if (props.modelValue !== undefined) field?.syncValue(value.value);
|
||||
}
|
||||
});
|
||||
}
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
internal.value = initial;
|
||||
field?.onReset();
|
||||
if (props.modelValue !== undefined) field?.syncValue(props.modelValue);
|
||||
if (element.value) element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
let form: HTMLFormElement | null = null;
|
||||
function bindForm() {
|
||||
const next = element.value?.form ?? null;
|
||||
if (next === form) return;
|
||||
form?.removeEventListener("reset", reset);
|
||||
form = next;
|
||||
form?.addEventListener("reset", reset);
|
||||
}
|
||||
onMounted(bindForm);
|
||||
onUpdated(bindForm);
|
||||
onBeforeUnmount(() => {
|
||||
form?.removeEventListener("reset", reset);
|
||||
field?.setControl(undefined);
|
||||
});
|
||||
return {
|
||||
inheritedAttrs: () => field?.controlAttrs() ?? {},
|
||||
element,
|
||||
value,
|
||||
update,
|
||||
variant,
|
||||
invalid,
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
id: () =>
|
||||
typeof attrs.id === "string" ? attrs.id : field?.controlId.value,
|
||||
name: () =>
|
||||
typeof attrs.name === "string" ? attrs.name : field?.name.value,
|
||||
type: () => props.type ?? field?.type.value ?? "text",
|
||||
describedBy: () =>
|
||||
mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
field?.describedBy(),
|
||||
),
|
||||
onInvalid: (event: Event) => field?.onInvalid(event),
|
||||
validationBehavior: behavior,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, provide, ref, useAttrs } from "vue";
|
||||
import {
|
||||
formContextKey,
|
||||
type ValidationBehavior,
|
||||
type ValidationErrors,
|
||||
} from "../field/context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
validationBehavior?: ValidationBehavior;
|
||||
validationErrors?: ValidationErrors;
|
||||
}>(),
|
||||
{ validationBehavior: "native", validationErrors: () => ({}) },
|
||||
);
|
||||
const attrs = useAttrs();
|
||||
provide(formContextKey, {
|
||||
validationBehavior: computed(() => props.validationBehavior),
|
||||
validationErrors: computed(() => props.validationErrors),
|
||||
});
|
||||
const element = ref<HTMLFormElement>();
|
||||
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();
|
||||
}
|
||||
return !first;
|
||||
}
|
||||
function submit(event: Event) {
|
||||
const submitter = (event as SubmitEvent).submitter as
|
||||
HTMLButtonElement | HTMLInputElement | null;
|
||||
const skip =
|
||||
attrs.novalidate === "" ||
|
||||
attrs.novalidate === true ||
|
||||
attrs.noValidate === true;
|
||||
if (!skip && !submitter?.formNoValidate && !checkValidity(true)) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
}
|
||||
}
|
||||
// Native auto-validation is disabled so per-field aria/native modes can coexist.
|
||||
// The submit guard still uses each native control's Constraint Validation API.
|
||||
defineExpose({
|
||||
element,
|
||||
checkValidity: () => checkValidity(),
|
||||
reportValidity: () => checkValidity(true),
|
||||
reset: () => element.value?.reset(),
|
||||
});
|
||||
</script>
|
||||
<template>
|
||||
<form ref="element" @submit.capture="submit" v-bind="attrs" novalidate>
|
||||
<slot />
|
||||
</form>
|
||||
</template>
|
||||
@@ -1,13 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { useAttrs } from "vue";
|
||||
import { inputVariants, type InputVariants } from "@heroui-vue/styles";
|
||||
import {
|
||||
computed,
|
||||
ref,
|
||||
onMounted,
|
||||
onBeforeUnmount,
|
||||
nextTick,
|
||||
useAttrs,
|
||||
} from "vue";
|
||||
import { useTextControl } from "../field/useTextControl";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = defineProps<{
|
||||
modelValue?: string;
|
||||
@@ -17,57 +11,31 @@ const props = defineProps<{
|
||||
fullWidth?: boolean;
|
||||
type?: string;
|
||||
}>();
|
||||
const attrs = useAttrs();
|
||||
const invalidState = computed(
|
||||
() =>
|
||||
props.invalid ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true",
|
||||
);
|
||||
const emit = defineEmits<{ "update:modelValue": [value: string] }>();
|
||||
const internal = ref(props.defaultValue ?? "");
|
||||
const value = computed(() => props.modelValue ?? internal.value);
|
||||
const element = ref<HTMLInputElement>();
|
||||
function update(event: Event) {
|
||||
const next = (event.target as HTMLInputElement).value;
|
||||
internal.value = next;
|
||||
emit("update:modelValue", next);
|
||||
void nextTick(() => {
|
||||
if (element.value && element.value.value !== value.value)
|
||||
element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
internal.value = props.defaultValue ?? "";
|
||||
if (element.value) element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
let form: HTMLFormElement | null = null;
|
||||
onMounted(() => {
|
||||
form = element.value?.form ?? null;
|
||||
form?.addEventListener("reset", reset);
|
||||
});
|
||||
onBeforeUnmount(() => form?.removeEventListener("reset", reset));
|
||||
const attrs = useAttrs();
|
||||
const control = useTextControl(props, attrs, emit);
|
||||
const { element, value, variant } = control;
|
||||
defineExpose({ focus: () => element.value?.focus(), element });
|
||||
</script>
|
||||
<template>
|
||||
<input
|
||||
ref="element"
|
||||
v-bind="$attrs"
|
||||
v-bind="{ ...control.inheritedAttrs(), ...attrs }"
|
||||
:value="value"
|
||||
:id="control.id()"
|
||||
:name="control.name()"
|
||||
:type="control.type()"
|
||||
:disabled="control.disabled()"
|
||||
:readonly="control.readOnly()"
|
||||
:required="control.required()"
|
||||
:class="inputVariants({ variant, fullWidth })"
|
||||
:type="type ?? 'text'"
|
||||
:data-invalid="invalidState || undefined"
|
||||
:aria-invalid="invalidState || undefined"
|
||||
:aria-readonly="
|
||||
$attrs.readonly === '' ||
|
||||
$attrs.readonly === true ||
|
||||
$attrs.readOnly === true ||
|
||||
undefined
|
||||
"
|
||||
:data-invalid="control.invalid() || undefined"
|
||||
:aria-invalid="control.invalid() || undefined"
|
||||
:aria-readonly="control.readOnly() || undefined"
|
||||
:aria-describedby="control.describedBy()"
|
||||
:data-validation-behavior="control.validationBehavior()"
|
||||
data-slot="input"
|
||||
@input="update"
|
||||
@input="control.update"
|
||||
@invalid="control.onInvalid"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { inject, useAttrs } from "vue";
|
||||
import { switchKey } from "../switch/context";
|
||||
const ctx = inject(switchKey, undefined);
|
||||
import { fieldContextKey } from "../field/context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const field = inject(fieldContextKey, undefined);
|
||||
const attrs = useAttrs();
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
isRequired?: boolean;
|
||||
isDisabled?: boolean;
|
||||
isInvalid?: boolean;
|
||||
@@ -11,12 +12,16 @@ defineProps<{
|
||||
</script>
|
||||
<template>
|
||||
<component
|
||||
:is="ctx && !attrs.for ? 'span' : 'label'"
|
||||
:is="field?.kind === 'toggle' && !attrs.for ? 'span' : 'label'"
|
||||
v-bind="attrs"
|
||||
:for="
|
||||
attrs.for ?? (field?.kind === 'text' ? field.controlId.value : undefined)
|
||||
"
|
||||
class="hv-label"
|
||||
:class="{
|
||||
'hv-label--required': isRequired,
|
||||
'hv-label--disabled': isDisabled,
|
||||
'hv-label--invalid': isInvalid,
|
||||
'hv-label--required': props.isRequired || field?.required.value,
|
||||
'hv-label--disabled': props.isDisabled || field?.disabled.value,
|
||||
'hv-label--invalid': props.isInvalid || field?.invalid.value,
|
||||
}"
|
||||
data-slot="label"
|
||||
>
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { inject, onBeforeUnmount, useId } from "vue";
|
||||
import { switchKey } from "./context";
|
||||
const ctx = inject(switchKey, undefined);
|
||||
const id = useId();
|
||||
if (ctx) ctx.errorIds.value = [...ctx.errorIds.value, id];
|
||||
onBeforeUnmount(() => {
|
||||
if (ctx)
|
||||
ctx.errorIds.value = ctx.errorIds.value.filter((value) => value !== id);
|
||||
});
|
||||
</script>
|
||||
<template>
|
||||
<p
|
||||
v-if="!ctx || ctx.invalid.value"
|
||||
:id="id"
|
||||
data-slot="field-error"
|
||||
class="hv-field-error"
|
||||
role="alert"
|
||||
>
|
||||
<slot :validation-errors="ctx?.error.value ? [ctx.error.value] : []">
|
||||
{{ ctx?.error.value }}
|
||||
</slot>
|
||||
</p>
|
||||
</template>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
provide,
|
||||
ref,
|
||||
useId,
|
||||
@@ -14,6 +15,11 @@ import {
|
||||
import { switchVariants, type SwitchVariants } from "@heroui-vue/styles";
|
||||
import { Primitive } from "reka-ui";
|
||||
import { switchKey } from "./context";
|
||||
import {
|
||||
fieldContextKey,
|
||||
formContextKey,
|
||||
errorMessages,
|
||||
} from "../field/context";
|
||||
import SwitchContent from "./SwitchContent.vue";
|
||||
import SwitchControl from "./SwitchControl.vue";
|
||||
import SwitchThumb from "./SwitchThumb.vue";
|
||||
@@ -51,6 +57,13 @@ const emit = defineEmits<{
|
||||
change: [value: boolean];
|
||||
}>();
|
||||
const attrs = useAttrs();
|
||||
const formContext = inject(formContextKey, undefined);
|
||||
const validationMode = computed(
|
||||
() =>
|
||||
props.validationBehavior ??
|
||||
formContext?.validationBehavior.value ??
|
||||
"native",
|
||||
);
|
||||
const rootAttrs = () =>
|
||||
Object.fromEntries(
|
||||
Object.entries(attrs).filter(
|
||||
@@ -74,6 +87,13 @@ const hovered = ref(false),
|
||||
focusVisible = ref(false);
|
||||
const error = ref("");
|
||||
const showError = ref(false);
|
||||
const dismissedErrors = ref<object>();
|
||||
const serverMessages = computed(() => {
|
||||
const source = formContext?.validationErrors.value;
|
||||
return source && source !== dismissedErrors.value && props.name
|
||||
? errorMessages(source[props.name])
|
||||
: [];
|
||||
});
|
||||
const checked = computed(
|
||||
() => props.isSelected ?? props.checked ?? internal.value,
|
||||
);
|
||||
@@ -88,6 +108,7 @@ const descriptionIds = ref<string[]>([]);
|
||||
const errorIds = ref<string[]>([]);
|
||||
function update(value: boolean) {
|
||||
if (disabled.value || readOnly.value) return;
|
||||
dismissedErrors.value = formContext?.validationErrors.value;
|
||||
internal.value = value;
|
||||
emit("update:checked", value);
|
||||
emit("update:isSelected", value);
|
||||
@@ -97,6 +118,17 @@ watch([disabled, readOnly], () => {
|
||||
hovered.value = false;
|
||||
pressed.value = false;
|
||||
});
|
||||
provide(fieldContextKey, {
|
||||
controlId: computed(() => props.id ?? generated),
|
||||
kind: "toggle",
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
invalid,
|
||||
errors: computed(() => (error.value ? [error.value] : [])),
|
||||
descriptionIds,
|
||||
errorIds,
|
||||
});
|
||||
provide(switchKey, {
|
||||
hovered,
|
||||
pressed,
|
||||
@@ -114,7 +146,9 @@ provide(switchKey, {
|
||||
update,
|
||||
});
|
||||
watchEffect(() => {
|
||||
const result = props.validate?.(checked.value);
|
||||
const result = serverMessages.value.length
|
||||
? serverMessages.value
|
||||
: props.validate?.(checked.value);
|
||||
error.value =
|
||||
typeof result === "string"
|
||||
? result
|
||||
@@ -123,9 +157,10 @@ watchEffect(() => {
|
||||
: required.value && !checked.value
|
||||
? "请开启此选项。"
|
||||
: "";
|
||||
if (props.validationBehavior === "aria") showError.value = true;
|
||||
if (validationMode.value === "aria" || serverMessages.value.length)
|
||||
showError.value = true;
|
||||
input.value?.setCustomValidity(
|
||||
props.validationBehavior === "aria" || disabled.value || readOnly.value
|
||||
validationMode.value === "aria" || disabled.value || readOnly.value
|
||||
? ""
|
||||
: error.value,
|
||||
);
|
||||
@@ -138,6 +173,7 @@ function onInvalid(event: Event) {
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
dismissedErrors.value = formContext?.validationErrors.value;
|
||||
internal.value = initial;
|
||||
showError.value = false;
|
||||
if (input.value) input.value.checked = checked.value;
|
||||
@@ -188,13 +224,14 @@ defineExpose({
|
||||
ref="input"
|
||||
class="hv-switch__input"
|
||||
type="checkbox"
|
||||
:data-validation-behavior="validationMode"
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
:name="name"
|
||||
:value="value ?? 'on'"
|
||||
:checked="checked"
|
||||
:disabled="disabled"
|
||||
:required="required && !readOnly && validationBehavior !== 'aria'"
|
||||
:required="required && !readOnly && validationMode !== 'aria'"
|
||||
@invalid="onInvalid"
|
||||
@change="update(($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
computed,
|
||||
ref,
|
||||
onMounted,
|
||||
onBeforeUnmount,
|
||||
nextTick,
|
||||
useAttrs,
|
||||
} from "vue";
|
||||
import { useAttrs } from "vue";
|
||||
import { textAreaVariants, type TextAreaVariants } from "@heroui-vue/styles";
|
||||
|
||||
import { useTextControl } from "../field/useTextControl";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue?: string;
|
||||
defaultValue?: string;
|
||||
@@ -18,62 +10,30 @@ const props = defineProps<{
|
||||
variant?: TextAreaVariants["variant"];
|
||||
fullWidth?: boolean;
|
||||
}>();
|
||||
|
||||
const attrs = useAttrs();
|
||||
const invalidState = computed(
|
||||
() =>
|
||||
props.invalid ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true",
|
||||
);
|
||||
const emit = defineEmits<{ "update:modelValue": [value: string] }>();
|
||||
const internal = ref(props.defaultValue ?? "");
|
||||
const value = computed(() => props.modelValue ?? internal.value);
|
||||
const element = ref<HTMLTextAreaElement>();
|
||||
|
||||
function update(event: Event) {
|
||||
const next = (event.target as HTMLTextAreaElement).value;
|
||||
internal.value = next;
|
||||
emit("update:modelValue", next);
|
||||
void nextTick(() => {
|
||||
if (element.value && element.value.value !== value.value)
|
||||
element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
internal.value = props.defaultValue ?? "";
|
||||
if (element.value) element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
|
||||
let form: HTMLFormElement | null = null;
|
||||
onMounted(() => {
|
||||
form = element.value?.form ?? null;
|
||||
form?.addEventListener("reset", reset);
|
||||
});
|
||||
onBeforeUnmount(() => form?.removeEventListener("reset", reset));
|
||||
|
||||
const attrs = useAttrs();
|
||||
const control = useTextControl(props, attrs, emit);
|
||||
const { element, value, variant } = control;
|
||||
defineExpose({ focus: () => element.value?.focus(), element });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<textarea
|
||||
ref="element"
|
||||
v-bind="$attrs"
|
||||
v-bind="{ ...control.inheritedAttrs(), ...attrs }"
|
||||
:value="value"
|
||||
:id="control.id()"
|
||||
:name="control.name()"
|
||||
:disabled="control.disabled()"
|
||||
:readonly="control.readOnly()"
|
||||
:required="control.required()"
|
||||
:class="textAreaVariants({ variant, fullWidth })"
|
||||
:data-invalid="invalidState || undefined"
|
||||
:aria-invalid="invalidState || undefined"
|
||||
:aria-readonly="
|
||||
$attrs.readonly === '' ||
|
||||
$attrs.readonly === true ||
|
||||
$attrs.readOnly === true ||
|
||||
undefined
|
||||
"
|
||||
:data-invalid="control.invalid() || undefined"
|
||||
:aria-invalid="control.invalid() || undefined"
|
||||
:aria-readonly="control.readOnly() || undefined"
|
||||
:aria-describedby="control.describedBy()"
|
||||
:data-validation-behavior="control.validationBehavior()"
|
||||
data-slot="textarea"
|
||||
@input="update"
|
||||
@input="control.update"
|
||||
@invalid="control.onInvalid"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Comment,
|
||||
Fragment,
|
||||
cloneVNode,
|
||||
computed,
|
||||
defineComponent,
|
||||
h,
|
||||
inject,
|
||||
isVNode,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
useId,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import {
|
||||
fieldContextKey,
|
||||
formContextKey,
|
||||
errorMessages,
|
||||
mergeIds,
|
||||
type ValidateResult,
|
||||
type ValidationBehavior,
|
||||
} from "../field/context";
|
||||
import { textFieldContextKey, type TextFieldContext } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "TextField",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
modelValue: String,
|
||||
defaultValue: String,
|
||||
name: String,
|
||||
id: String,
|
||||
type: String,
|
||||
minLength: Number,
|
||||
maxLength: Number,
|
||||
pattern: String,
|
||||
autoComplete: String,
|
||||
inputMode: String,
|
||||
form: String,
|
||||
isDisabled: Boolean,
|
||||
isReadOnly: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
fullWidth: Boolean,
|
||||
variant: String as PropType<"primary" | "secondary">,
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
validate: Function as PropType<(value: string) => ValidateResult>,
|
||||
},
|
||||
emits: { "update:modelValue": (_value: string) => true },
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const form = inject(formContextKey, undefined);
|
||||
const generated = useId();
|
||||
const leafId = ref<string>();
|
||||
const controlId = computed(() => leafId.value ?? props.id ?? generated);
|
||||
const internal = ref(props.defaultValue ?? "");
|
||||
let initialized =
|
||||
props.modelValue !== undefined || props.defaultValue !== undefined;
|
||||
let initialValue = props.defaultValue ?? "";
|
||||
const value = computed(() => props.modelValue ?? internal.value);
|
||||
const control = shallowRef<HTMLInputElement | HTMLTextAreaElement>();
|
||||
const touched = ref(false),
|
||||
nativeError = ref("");
|
||||
const dismissed = shallowRef<object>();
|
||||
const descriptionIds = ref<string[]>([]),
|
||||
errorIds = ref<string[]>([]);
|
||||
// Pre-plan direct/native-wrapped parts before rendering controls, so SSR has
|
||||
// complete ID associations even when Description follows Input.
|
||||
const plannedDescriptions = ref<string[]>([]),
|
||||
plannedErrors = ref<string[]>([]);
|
||||
let lastPlan = "";
|
||||
const behavior = computed(
|
||||
() =>
|
||||
props.validationBehavior ?? form?.validationBehavior.value ?? "native",
|
||||
);
|
||||
const disabled = computed(() => props.isDisabled),
|
||||
readOnly = computed(() => props.isReadOnly);
|
||||
const required = computed(() => props.isRequired);
|
||||
const serverErrors = computed(() => {
|
||||
const source = form?.validationErrors.value;
|
||||
return source && source !== dismissed.value && props.name
|
||||
? errorMessages(source[props.name])
|
||||
: [];
|
||||
});
|
||||
const customErrors = computed(() =>
|
||||
errorMessages(props.validate?.(value.value)),
|
||||
);
|
||||
const errors = computed(() => [
|
||||
...serverErrors.value,
|
||||
...(touched.value || behavior.value === "aria" ? customErrors.value : []),
|
||||
...((touched.value || behavior.value === "aria") && nativeError.value
|
||||
? [nativeError.value]
|
||||
: []),
|
||||
]);
|
||||
const invalid = computed(
|
||||
() =>
|
||||
props.isInvalid ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true" ||
|
||||
errors.value.length > 0,
|
||||
);
|
||||
function setValue(next: string) {
|
||||
if (disabled.value || readOnly.value) return;
|
||||
internal.value = next;
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
nativeError.value = "";
|
||||
emit("update:modelValue", next);
|
||||
}
|
||||
function initialize(next: string) {
|
||||
if (!initialized) {
|
||||
internal.value = next;
|
||||
initialValue = next;
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
const field: TextFieldContext = {
|
||||
controlId,
|
||||
kind: "text",
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
invalid,
|
||||
errors,
|
||||
descriptionIds,
|
||||
errorIds,
|
||||
value,
|
||||
name: computed(() => props.name),
|
||||
type: computed(() => props.type),
|
||||
variant: computed(() => props.variant),
|
||||
validationBehavior: behavior,
|
||||
controlAttrs: () => ({
|
||||
minlength: props.minLength,
|
||||
maxlength: props.maxLength,
|
||||
pattern: props.pattern,
|
||||
autocomplete: props.autoComplete,
|
||||
inputmode: props.inputMode,
|
||||
form: props.form,
|
||||
...Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => key.startsWith("aria-")),
|
||||
),
|
||||
}),
|
||||
describedBy: () =>
|
||||
mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
descriptionIds.value,
|
||||
plannedDescriptions.value,
|
||||
invalid.value ? [...errorIds.value, ...plannedErrors.value] : [],
|
||||
),
|
||||
setControlId: (id) => {
|
||||
leafId.value = id;
|
||||
},
|
||||
initialize,
|
||||
setValue,
|
||||
syncValue: (next) => {
|
||||
internal.value = next;
|
||||
},
|
||||
setControl: (next) => {
|
||||
control.value = next;
|
||||
},
|
||||
onInvalid(event) {
|
||||
if (behavior.value === "aria") return;
|
||||
touched.value = true;
|
||||
const element = event.target as HTMLInputElement | HTMLTextAreaElement;
|
||||
nativeError.value =
|
||||
customErrors.value.length || serverErrors.value.length
|
||||
? ""
|
||||
: element.validationMessage;
|
||||
},
|
||||
onReset() {
|
||||
internal.value = initialValue;
|
||||
touched.value = false;
|
||||
nativeError.value = "";
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
},
|
||||
};
|
||||
provide(fieldContextKey, field);
|
||||
provide(textFieldContextKey, field);
|
||||
watchEffect(
|
||||
() => {
|
||||
const currentValue = value.value;
|
||||
control.value?.setCustomValidity(
|
||||
behavior.value === "native" && !disabled.value && !readOnly.value
|
||||
? [...serverErrors.value, ...customErrors.value].join(" ")
|
||||
: "",
|
||||
);
|
||||
if (behavior.value === "native" && touched.value)
|
||||
nativeError.value =
|
||||
customErrors.value.length || serverErrors.value.length
|
||||
? ""
|
||||
: (control.value?.validationMessage ?? "");
|
||||
if (behavior.value === "aria")
|
||||
nativeError.value =
|
||||
disabled.value || readOnly.value
|
||||
? ""
|
||||
: required.value && !currentValue
|
||||
? "请填写此字段。"
|
||||
: (control.value?.validationMessage ?? "");
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
expose({ focus: () => control.value?.focus(), element: control });
|
||||
function prepare(
|
||||
nodes: VNodeChild[],
|
||||
found: { description: string[]; error: string[]; controlId?: string },
|
||||
path = "",
|
||||
): VNodeChild[] {
|
||||
return nodes.map((node, index) => {
|
||||
if (!isVNode(node) || node.type === Comment) return node;
|
||||
const position = `${path}-${index}`;
|
||||
const type = node.type as { name?: string; __name?: string };
|
||||
const name = type?.name ?? type?.__name;
|
||||
if (name === "Input" || name === "TextArea")
|
||||
found.controlId = node.props?.id;
|
||||
if (name === "Description" || name === "FieldError") {
|
||||
const kind = name === "Description" ? "description" : "error";
|
||||
const id = node.props?.id ?? `${generated}-${kind}${position}`;
|
||||
found[kind].push(String(id));
|
||||
return cloneVNode(node, { id });
|
||||
}
|
||||
if (
|
||||
(typeof node.type === "string" || node.type === Fragment) &&
|
||||
Array.isArray(node.children)
|
||||
) {
|
||||
const clone = cloneVNode(node);
|
||||
clone.children = prepare(
|
||||
node.children as VNodeChild[],
|
||||
found,
|
||||
position,
|
||||
) as VNode[];
|
||||
return clone;
|
||||
}
|
||||
return node;
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
const found: {
|
||||
description: string[];
|
||||
error: string[];
|
||||
controlId?: string;
|
||||
} = { description: [], error: [] };
|
||||
const children = prepare(
|
||||
slots.default?.({
|
||||
isDisabled: disabled.value,
|
||||
isReadOnly: readOnly.value,
|
||||
isRequired: required.value,
|
||||
isInvalid: invalid.value,
|
||||
validationErrors: errors.value,
|
||||
}) ?? [],
|
||||
found,
|
||||
);
|
||||
if (found.controlId !== undefined && leafId.value !== found.controlId)
|
||||
leafId.value = found.controlId;
|
||||
const nextPlan = JSON.stringify(found);
|
||||
if (lastPlan !== nextPlan) {
|
||||
lastPlan = nextPlan;
|
||||
plannedDescriptions.value = found.description;
|
||||
plannedErrors.value = found.error;
|
||||
}
|
||||
return h(
|
||||
"div",
|
||||
{
|
||||
...Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => !key.startsWith("aria-")),
|
||||
),
|
||||
class: [
|
||||
"hv-textfield",
|
||||
props.fullWidth && "hv-textfield--full-width",
|
||||
attrs.class,
|
||||
],
|
||||
"data-slot": "textfield",
|
||||
"data-invalid": invalid.value || undefined,
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"data-required": required.value || undefined,
|
||||
"data-readonly": readOnly.value || undefined,
|
||||
},
|
||||
children,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ComputedRef, InjectionKey } from "vue";
|
||||
import type { FieldContext, ValidationBehavior } from "../field/context";
|
||||
export interface TextFieldContext extends FieldContext {
|
||||
value: ComputedRef<string>;
|
||||
name: ComputedRef<string | undefined>;
|
||||
type: ComputedRef<string | undefined>;
|
||||
variant: ComputedRef<"primary" | "secondary" | undefined>;
|
||||
validationBehavior: ComputedRef<ValidationBehavior>;
|
||||
controlAttrs: () => Record<string, unknown>;
|
||||
describedBy: () => string | undefined;
|
||||
setControlId: (id: string | undefined) => void;
|
||||
initialize: (value: string) => void;
|
||||
setValue: (value: string) => void;
|
||||
syncValue: (value: string) => void;
|
||||
setControl: (
|
||||
control: HTMLInputElement | HTMLTextAreaElement | undefined,
|
||||
) => void;
|
||||
onInvalid: (event: Event) => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
export const textFieldContextKey: InjectionKey<TextFieldContext> = Symbol(
|
||||
"HeroUIVue.TextField",
|
||||
);
|
||||
@@ -87,7 +87,7 @@ export type {
|
||||
export { tv, cn, type VariantProps } from "@heroui-vue/styles";
|
||||
|
||||
export { default as SwitchGroup } from "./components/switch/SwitchGroup.vue";
|
||||
export { default as FieldError } from "./components/switch/FieldError.vue";
|
||||
export { default as FieldError } from "./components/field/FieldError.vue";
|
||||
|
||||
export { default as Surface } from "./components/surface/Surface.vue";
|
||||
export {
|
||||
@@ -157,3 +157,27 @@ export {
|
||||
type AlertSlots,
|
||||
type AlertStatus,
|
||||
} from "./components/alert/context";
|
||||
|
||||
export { default as TextField } from "./components/textfield/TextField.vue";
|
||||
export { default as Form } from "./components/form/Form.vue";
|
||||
export {
|
||||
fieldContextKey,
|
||||
formContextKey,
|
||||
mergeIds,
|
||||
type FieldContext,
|
||||
type FormContext,
|
||||
type ValidationBehavior,
|
||||
type ValidationErrors,
|
||||
type ValidateResult,
|
||||
} from "./components/field/context";
|
||||
export {
|
||||
textFieldContextKey,
|
||||
type TextFieldContext,
|
||||
} from "./components/textfield/context";
|
||||
export { useFieldPart } from "./components/field/useFieldPart";
|
||||
export type {
|
||||
TextFieldProps,
|
||||
FormProps,
|
||||
DescriptionProps,
|
||||
FieldErrorProps,
|
||||
} from "./types";
|
||||
|
||||
@@ -72,3 +72,12 @@ export type AlertTitleProps = InstanceType<typeof AlertTitle>["$props"];
|
||||
export type AlertDescriptionProps = InstanceType<
|
||||
typeof AlertDescription
|
||||
>["$props"];
|
||||
|
||||
import type TextField from "./components/textfield/TextField.vue";
|
||||
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 DescriptionProps = InstanceType<typeof Description>["$props"];
|
||||
export type FieldErrorProps = InstanceType<typeof FieldError>["$props"];
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, h, nextTick, ref } from "vue";
|
||||
import {
|
||||
TextField,
|
||||
Form,
|
||||
Input,
|
||||
TextArea,
|
||||
Label,
|
||||
Description,
|
||||
FieldError,
|
||||
Switch,
|
||||
SwitchContent,
|
||||
SwitchControl,
|
||||
SwitchThumb,
|
||||
} from "../packages/vue/src";
|
||||
|
||||
function textField(props = {}, control = Input) {
|
||||
return h(TextField, props, () => [
|
||||
h(Label, {}, () => "Name"),
|
||||
h(control),
|
||||
h(Description, {}, () => "Hint"),
|
||||
h(FieldError),
|
||||
]);
|
||||
}
|
||||
const settle = async () => {
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
describe("shared text fields", () => {
|
||||
it.each([Input, TextArea])(
|
||||
"associates labels descriptions errors and unique IDs",
|
||||
async (control) => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h("div", [
|
||||
textField({ isInvalid: true }, control),
|
||||
textField({}, control),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
const fields = w.findAll("[data-slot=textfield]");
|
||||
const a = fields[0].get("input,textarea"),
|
||||
b = fields[1].get("input,textarea");
|
||||
expect(a.attributes("id")).not.toBe(b.attributes("id"));
|
||||
expect(fields[0].get("label").attributes("for")).toBe(a.attributes("id"));
|
||||
const ids = a.attributes("aria-describedby")!.split(" ");
|
||||
for (const id of ids)
|
||||
expect(fields[0].find(`[id="${id}"]`).exists()).toBe(true);
|
||||
expect(fields[1].find("[data-slot=field-error]").exists()).toBe(false);
|
||||
w.unmount();
|
||||
},
|
||||
);
|
||||
it("keeps external description IDs and updates explicit description IDs and unmount", async () => {
|
||||
const id = ref("first"),
|
||||
show = ref(true);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(TextField, {}, () => [
|
||||
h(Input, { "aria-describedby": "external" }),
|
||||
show.value ? h(Description, { id: id.value }, () => "hint") : null,
|
||||
]),
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
expect(w.get("input").attributes("aria-describedby")).toContain("first");
|
||||
id.value = "next";
|
||||
await settle();
|
||||
expect(w.get("input").attributes("aria-describedby")).toBe("external next");
|
||||
show.value = false;
|
||||
await settle();
|
||||
expect(w.get("input").attributes("aria-describedby")).toBe("external");
|
||||
w.unmount();
|
||||
});
|
||||
it.each([Input, TextArea])(
|
||||
"submits and resets native values, disabled omitted and readonly kept",
|
||||
async (control) => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, {}, () => [
|
||||
textField({ name: "title", defaultValue: "start" }, control),
|
||||
textField(
|
||||
{ name: "disabled", defaultValue: "no", isDisabled: true },
|
||||
control,
|
||||
),
|
||||
textField(
|
||||
{ name: "read", defaultValue: "yes", isReadOnly: true },
|
||||
control,
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
const input = w.findAll("input,textarea")[0];
|
||||
await input.setValue("changed");
|
||||
expect(
|
||||
Object.fromEntries(
|
||||
new FormData(w.get("form").element as HTMLFormElement),
|
||||
),
|
||||
).toEqual({ title: "changed", read: "yes" });
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await settle();
|
||||
expect((input.element as HTMLInputElement).value).toBe("start");
|
||||
w.unmount();
|
||||
},
|
||||
);
|
||||
it("respects canceled reset and root controlled rejection", async () => {
|
||||
const value = ref("fixed");
|
||||
const update = vi.fn();
|
||||
const cancel = ref(true);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(
|
||||
Form,
|
||||
{
|
||||
onReset: (e: Event) => {
|
||||
if (cancel.value) e.preventDefault();
|
||||
},
|
||||
},
|
||||
() => [
|
||||
textField({
|
||||
modelValue: value.value,
|
||||
"onUpdate:modelValue": update,
|
||||
name: "x",
|
||||
}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await w.get("input").setValue("rejected");
|
||||
await settle();
|
||||
expect((w.get("input").element as HTMLInputElement).value).toBe("fixed");
|
||||
expect(update).toHaveBeenCalledWith("rejected");
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await settle();
|
||||
expect((w.get("input").element as HTMLInputElement).value).toBe("fixed");
|
||||
w.unmount();
|
||||
const canceled = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, { onReset: (e: Event) => e.preventDefault() }, () => [
|
||||
textField({ defaultValue: "a" }),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await canceled.get("input").setValue("b");
|
||||
(canceled.get("form").element as HTMLFormElement).reset();
|
||||
await settle();
|
||||
expect((canceled.get("input").element as HTMLInputElement).value).toBe("b");
|
||||
canceled.unmount();
|
||||
});
|
||||
it("supports a controlled leaf within an uncontrolled TextField", async () => {
|
||||
const value = ref("leaf");
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(
|
||||
TextField,
|
||||
{
|
||||
validate: (v: string) => (v === "leaf" ? null : "bad"),
|
||||
validationBehavior: "aria",
|
||||
},
|
||||
() => [h(Input, { modelValue: value.value }), h(FieldError)],
|
||||
),
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
|
||||
await w.get("input").setValue("refused");
|
||||
await settle();
|
||||
expect((w.get("input").element as HTMLInputElement).value).toBe("leaf");
|
||||
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
|
||||
w.unmount();
|
||||
});
|
||||
it("inherits disabled required readonly and variants while preserving explicit native attrs", async () => {
|
||||
const w = mount(TextField, {
|
||||
props: { isDisabled: true, isRequired: true, variant: "secondary" },
|
||||
slots: {
|
||||
default: () => [h(Label, {}, () => "X"), h(Input), h(TextArea)],
|
||||
},
|
||||
});
|
||||
expect(w.get("input").attributes("disabled")).toBeDefined();
|
||||
expect(w.get("textarea").classes()).toContain("hv-textarea--secondary");
|
||||
expect(w.get("label").classes()).toContain("hv-label--required");
|
||||
await w.setProps({ isDisabled: false, isReadOnly: true });
|
||||
expect(w.get("input").attributes("readonly")).toBeDefined();
|
||||
expect(w.get("input").attributes("required")).toBeUndefined();
|
||||
w.unmount();
|
||||
});
|
||||
it("shows native required errors on submit and blocks submit callbacks", async () => {
|
||||
const submit = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, { onSubmit: submit }, () => [
|
||||
textField({ name: "email", type: "email", isRequired: true }),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
const form = w.get("form").element as HTMLFormElement;
|
||||
const event = new Event("submit", { cancelable: true, bubbles: true });
|
||||
form.dispatchEvent(event);
|
||||
await settle();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
expect(w.get("input").attributes("aria-invalid")).toBe("true");
|
||||
expect(w.get("[data-slot=field-error]").text().length).toBeGreaterThan(0);
|
||||
await w.get("input").setValue("a@example.com");
|
||||
await settle();
|
||||
form.dispatchEvent(
|
||||
new Event("submit", { cancelable: true, bubbles: true }),
|
||||
);
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
w.unmount();
|
||||
});
|
||||
it("reports aria constraints but allows submission and supports field-level mode override", async () => {
|
||||
const submit = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(
|
||||
Form,
|
||||
{
|
||||
onSubmit: (e: Event) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
},
|
||||
},
|
||||
() => [
|
||||
textField({
|
||||
name: "email",
|
||||
type: "email",
|
||||
isRequired: true,
|
||||
validationBehavior: "aria",
|
||||
}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await settle();
|
||||
expect(w.get("input").attributes("aria-invalid")).toBe("true");
|
||||
await w.get("form").trigger("submit");
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
await w.get("input").setValue("bad-email");
|
||||
await settle();
|
||||
expect(w.get("[data-slot=field-error]").text().length).toBeGreaterThan(0);
|
||||
w.unmount();
|
||||
});
|
||||
it("custom validation uses actual value; latest server errors replace dismissed errors", async () => {
|
||||
const errors = ref<Record<string, string | string[]>>({
|
||||
name: ["Taken", "Try again"],
|
||||
});
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Form, { validationErrors: errors.value }, () => [
|
||||
textField({
|
||||
name: "name",
|
||||
validate: (v: string) => (v.length > 3 ? "Too long" : null),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await settle();
|
||||
expect(w.get("[data-slot=field-error]").text()).toContain("Taken");
|
||||
expect(
|
||||
(w.get("input").element as HTMLInputElement).validationMessage,
|
||||
).toContain("Taken");
|
||||
await w.get("input").setValue("ok");
|
||||
await settle();
|
||||
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
|
||||
errors.value = { name: "New server error" };
|
||||
await settle();
|
||||
expect(w.get("[data-slot=field-error]").text()).toContain(
|
||||
"New server error",
|
||||
);
|
||||
await w.get("input").setValue("longer");
|
||||
await w.get("form").trigger("submit");
|
||||
await settle();
|
||||
expect(w.get("[data-slot=field-error]").text()).toContain("Too long");
|
||||
w.unmount();
|
||||
});
|
||||
it("isolates nested Switch parts from outer text field and inherits Form validation mode", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, { validationBehavior: "aria" }, () =>
|
||||
h(TextField, {}, () => [
|
||||
h(Input),
|
||||
h(Switch, { name: "notify", isRequired: true }, () => [
|
||||
h(SwitchContent, {}, () => [
|
||||
h(SwitchControl, {}, () => h(SwitchThumb)),
|
||||
h(Label, {}, () => "notify"),
|
||||
h(Description, {}, () => "switch hint"),
|
||||
h(FieldError),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
expect(w.get("[role=switch]").attributes("aria-describedby")).toContain(
|
||||
w.get("[data-slot=description]").attributes("id"),
|
||||
);
|
||||
expect(
|
||||
w.get("input[data-slot=input]").attributes("aria-describedby"),
|
||||
).toBeUndefined();
|
||||
expect(w.find("[data-slot=field-error]").exists()).toBe(true);
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("hydrates standard field composition without ID or attribute mismatch", async () => {
|
||||
const { createSSRApp } = await import("vue");
|
||||
const { renderToString } = await import("@vue/server-renderer");
|
||||
const app = { render: () => textField({ name: "ssr", isInvalid: true }) };
|
||||
const html = await renderToString(createSSRApp(app));
|
||||
const container = document.createElement("div");
|
||||
container.innerHTML = html;
|
||||
document.body.append(container);
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {}),
|
||||
error = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = createSSRApp(app);
|
||||
client.mount(container);
|
||||
await settle();
|
||||
expect(warn.mock.calls.flat().join(" ")).not.toMatch(/hydration/i);
|
||||
expect(error.mock.calls.flat().join(" ")).not.toMatch(/hydration/i);
|
||||
const control = container.querySelector("input")!;
|
||||
for (const id of control.getAttribute("aria-describedby")!.split(" "))
|
||||
expect(container.querySelector(`[id="${id}"]`)).not.toBeNull();
|
||||
client.unmount();
|
||||
container.remove();
|
||||
warn.mockRestore();
|
||||
error.mockRestore();
|
||||
});
|
||||
|
||||
it("labels an explicit control id and follows dynamic changes", async () => {
|
||||
const id = ref("custom");
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(TextField, {}, () => [
|
||||
h(Label, {}, () => "Name"),
|
||||
h(Input, { id: id.value }),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
expect(w.get("label").attributes("for")).toBe("custom");
|
||||
id.value = "changed";
|
||||
await settle();
|
||||
expect(w.get("label").attributes("for")).toBe("changed");
|
||||
w.unmount();
|
||||
});
|
||||
it("honors formnovalidate and disabled constraints", async () => {
|
||||
const submit = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, { onSubmit: submit }, () => [
|
||||
textField({ isRequired: true, isDisabled: true }),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await settle();
|
||||
await w.get("form").trigger("submit");
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
w.unmount();
|
||||
const skip = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, { novalidate: true, onSubmit: submit }, () => [
|
||||
textField({ isRequired: true }),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await skip.get("form").trigger("submit");
|
||||
expect(submit).toHaveBeenCalledTimes(2);
|
||||
skip.unmount();
|
||||
});
|
||||
it("Switch consumes server errors through the shared Form context", async () => {
|
||||
const errors = ref<Record<string, string>>({ accept: "Please accept" });
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Form, { validationErrors: errors.value }, () =>
|
||||
h(Switch, { name: "accept" }, () => [
|
||||
h(SwitchContent, {}, () => [
|
||||
h(SwitchControl, {}, () => h(SwitchThumb)),
|
||||
h(Label, {}, () => "Accept"),
|
||||
]),
|
||||
h(FieldError),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await settle();
|
||||
expect(w.get("[data-slot=field-error]").text()).toContain("Please accept");
|
||||
await w.get("[role=switch]").trigger("click");
|
||||
await settle();
|
||||
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
|
||||
errors.value = { accept: "New" };
|
||||
await settle();
|
||||
expect(w.get("[data-slot=field-error]").text()).toBe("New");
|
||||
w.unmount();
|
||||
});
|
||||
it("routes root ARIA and native constraints to the control and guards capture submit", async () => {
|
||||
const submit = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, { onSubmitCapture: submit }, () =>
|
||||
textField({
|
||||
minLength: 3,
|
||||
pattern: "[A-Z]+",
|
||||
"aria-label": "Account",
|
||||
"aria-describedby": "external",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
const input = w.get("input");
|
||||
expect(input.attributes("aria-label")).toBe("Account");
|
||||
expect(input.attributes("aria-describedby")).toContain("external");
|
||||
expect(input.attributes("minlength")).toBe("3");
|
||||
expect(
|
||||
w.get("[data-slot=textfield]").attributes("aria-label"),
|
||||
).toBeUndefined();
|
||||
await input.setValue("lowercase");
|
||||
await w.get("form").trigger("submit");
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("Form aria defaults also apply to standalone and raw native controls", async () => {
|
||||
const submit = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, { validationBehavior: "aria", onSubmit: submit }, () => [
|
||||
h(Input, { required: true, type: "email" }),
|
||||
h("input", { required: true }),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await w.get("form").trigger("submit");
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("native Switch overrides an aria Form and blocks invalid submission", async () => {
|
||||
const submit = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Form, { validationBehavior: "aria", onSubmit: submit }, () =>
|
||||
h(Switch, {
|
||||
validationBehavior: "native",
|
||||
name: "accept",
|
||||
isRequired: true,
|
||||
"aria-label": "Accept",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await settle();
|
||||
await w.get("form").trigger("submit");
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
expect(w.get("[role=switch]").attributes("aria-invalid")).toBe("true");
|
||||
w.unmount();
|
||||
});
|
||||
@@ -36,3 +36,38 @@ it("renders the initial components without browser globals", async () => {
|
||||
expect(html).toContain('role="status"');
|
||||
expect(html).toContain('data-slot="textarea"');
|
||||
});
|
||||
|
||||
it("renders complete field associations without browser globals", async () => {
|
||||
const { TextField, Label, Description, FieldError, Form } =
|
||||
await import("../packages/vue/src");
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h(Form, {}, () => [
|
||||
h(
|
||||
TextField,
|
||||
{ name: "email", defaultValue: "a@example.com", isInvalid: true },
|
||||
() => [
|
||||
h(Label, {}, () => "Email"),
|
||||
h(Input),
|
||||
h(Description, {}, () => "Hint"),
|
||||
h(FieldError, {}, () => "Error"),
|
||||
],
|
||||
),
|
||||
h(TextField, { name: "notes" }, () => [
|
||||
h(Label, {}, () => "Notes"),
|
||||
h(TextArea),
|
||||
h(Description, {}, () => "Other hint"),
|
||||
]),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
const ids = [...html.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1]);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
const refs = [
|
||||
...html.matchAll(/(?:for|aria-describedby)="([^"]+)"/g),
|
||||
].flatMap((match) => match[1].split(" "));
|
||||
expect(refs.length).toBeGreaterThan(3);
|
||||
for (const id of refs) expect(ids).toContain(id);
|
||||
expect(html).toContain('value="a@example.com"');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user