fix: complete field and OTP public contracts (HD-07)

This commit is contained in:
maoyingjie
2026-10-29 09:30:58 +08:00
parent 27cc62e36f
commit 2d7e3d4e1e
26 changed files with 1067 additions and 100 deletions
+4
View File
@@ -212,3 +212,7 @@ FieldError 组件通过以下方式确保无障碍性:
## 相关组件 ## 相关组件
[TextField 文本输入框](./text-field) · [Input 输入框](./input) · [TextArea 多行文本框](./textarea) [TextField 文本输入框](./text-field) · [Input 输入框](./input) · [TextArea 多行文本框](./textarea)
### validationDetails
作用域插槽还提供 `validationDetails?: ValidityState`。TextField/SearchField 使用真实控件的原生快照,OTP 可显式传入详情(优先)或读取其提交代理快照;其他尚未接入详情的字段为 undefined。可读取 `valueMissing`、`patternMismatch`、`typeMismatch`、`customError` 等原生标志,而不复制字段状态。详情本身不替代 `isInvalid` 或错误文本。
+48 -31
View File
@@ -82,7 +82,7 @@ InputOTP 组件支持两种视觉变体:
<ComponentPreview name="input-otp-on-complete" /> <ComponentPreview name="input-otp-on-complete" />
`@complete` 在**首次填满**时触发一次;替换已满值、重复同值或父级同步同一值不会重复触发。示例使用模拟验证(定时器),不发送真实验证码。 `@complete` 在已接受值**从未满变为满值**时触发一次;替换已满值、重复同值或父级同步同一值不会重复触发。示例使用模拟验证(定时器),不发送真实验证码。
### 表单示例 ### 表单示例
@@ -94,7 +94,7 @@ InputOTP 组件支持两种视觉变体:
<ComponentPreview name="input-otp-with-pattern" /> <ComponentPreview name="input-otp-with-pattern" />
`pattern` 过滤单字符输入,可使用导出的正则常量。 `pattern` 检查整个候选字符串,可使用导出的正则常量;不匹配时拒绝整次编辑。
### 表单验证 ### 表单验证
@@ -177,25 +177,29 @@ InputOTP 组件使用以下 CSS 类([查看源码样式](https://github.com/he
### InputOTP / InputOTPRoot ### InputOTP / InputOTPRoot
| Prop | 类型 | 默认值 | 描述 | | Prop | 类型 | 默认值 | 描述 |
| ------------------ | -------------------------- | ----------- | ---------------------------------------------------------------- | | ------------------- | ------------------------------- | ------------ | ---------------------------------------------------------------- |
| `modelValue` | `string` | - | 受控字符串值;下标对应槽位 | | `modelValue` | `string` | - | 受控字符串值;下标对应槽位 |
| `defaultValue` | `string` | `''` | 非受控初始值 | | `defaultValue` | `string` | `''` | 非受控初始值 |
| `maxLength` | `number` | 必填 | 槽位数量 / 最大长度 | | `maxLength` | `number` | 必填 | 槽位数量 / 最大长度 |
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 外观变体 | | `variant` | `'primary' \| 'secondary'` | `'primary'` | 外观变体 |
| `isDisabled` | `boolean` | `false` | 禁用 | | `isDisabled` | `boolean` | `false` | 禁用 |
| `isInvalid` | `boolean` | `false` | 无效展示状态 | | `isInvalid` | `boolean` | `false` | 无效展示状态 |
| `validationErrors` | `string[]` | `[]` | 校验错误消息 | | `validationErrors` | `string[]` | `[]` | 校验错误消息 |
| `inputClassName` | `string` | - | 附加到真实 input 的类 | | `autoFocus` | `boolean` | `false` | 挂载后聚焦真实 input |
| `name` | `string` | - | 表单字段名(隐藏 input 提交一份完整值) | | `pasteTransformer` | `(text: string) => string` | - | 粘贴转换先于正则检查 |
| `required` | `boolean` | `false` | 原生必填 | | `textAlign` | `'left' \| 'center' \| 'right'` | `'left'` | 真实 input 对齐 |
| `pattern` | `string \| RegExp` | - | 字符过滤正则 | | `validationDetails` | `ValidityState` | 原生代理快照 | 显式校验标志优先,供 FieldError 读取 |
| `mask` | `boolean` | `false` | 密码样式(Reka `mask`) | | `inputClassName` | `string` | - | 附加到真实 input 的类 |
| `otp` | `boolean` | `false` | 一次性验证码自动填充(`autocomplete="one-time-code"`) | | `name` | `string` | - | 表单字段名(隐藏 input 提交一份完整值) |
| `placeholder` | `string` | `''` | 空位占位符 | | `required` | `boolean` | `false` | 原生必填 |
| `id` | `string` | 自动 | 提交桥 id;真实输入派生为 id-slot-index,内部 Label 自动关联首格 | | `pattern` | `string \| RegExp` | - | 整个候选字符串的正则判定 |
| `mask` | `boolean` | `false` | 密码样式(Reka `mask`) |
| `otp` | `boolean` | `false` | 一次性验证码自动填充(`autocomplete="one-time-code"`) |
| `placeholder` | `string` | `''` | 空位占位符 |
| `id` | `string` | 自动 | 提交桥 id;真实输入派生为 id-slot-index,内部 Label 自动关联首格 |
事件:`update:modelValue` / `change`(字符串)、`complete`(首次填满)。 事件:`update:modelValue` / `change`(字符串)、`complete`(已接受值从未满变满)。
### InputOTPGroup / InputOTPSeparator ### InputOTPGroup / InputOTPSeparator
@@ -213,17 +217,17 @@ InputOTP 组件使用以下 CSS 类([查看源码样式](https://github.com/he
### 上游差异 ### 上游差异
| 上游 React 能力 | Vue 实现 | | 上游 React 能力 | Vue 实现 |
| ------------------------------------ | ------------------------------------------------------------------------------------- | | ------------------------------------ | ------------------------------------------------------------------------- |
| `input-otp` 单隐藏 input | Reka PinInput 多 input + 隐藏提交 input | | `input-otp` 单隐藏 input | Reka PinInput 多 input + 隐藏提交 input |
| `value` / `onChange` 字符串 | `v-model` / `update:modelValue` / `change` | | `value` / `onChange` 字符串 | `v-model` / `update:modelValue` / `change` |
| `onComplete` 跨过长度阈值 | `complete` 仅在首次填满触发 | | `onComplete` 跨过长度阈值 | `complete` 在已接受值从未满变满时触发;满值替换不重复触发 |
| `pattern` 整串校验 | 单字符过滤(同样接受导出常量) | | `pattern` 整串校验 | 整个候选字符串按 pattern 检查,拒绝整次不匹配编辑 |
| `render` / `OTPInputContext` | 具名插槽部件;槽位状态经上下文 | | `render` / `OTPInputContext` | 具名插槽部件;槽位状态经上下文 |
| `pushPasswordManagerStrategy` | 未提供;`otp` 覆盖 one-time-code 自动填充 | | `pushPasswordManagerStrategy` | 未提供;`otp` 覆盖 one-time-code 自动填充 |
| `validationDetails`(ValidityState) | 未提供;校验结果为 `string \| string[]` 文本 | | `validationDetails`(ValidityState) | 作为 prop 传入并通过共享 FieldError 插槽暴露;缺省读取原生校验代理 |
| `textAlign` / `pasteTransformer` | 未提供(能力缺口,见 HD 队列后续能力卡) | | `textAlign` / `pasteTransformer` | 均已提供;转换后的整值再做 pattern 检查 |
| `autoFocus` / `containerClassName` | 未提供专门 prop;`containerClassName` 被上游公共类型显式 Omit,`autoFocus` 属能力缺口 | | `autoFocus` / `containerClassName` | 提供 autoFocus;containerClassName 被上游公共类型显式 Omit,不新增该 prop |
## 字段与表单 ## 字段与表单
@@ -243,3 +247,16 @@ Slot 的 keydown/paste 用户处理器在底座编辑前的 capture 边界协调
## 相关组件 ## 相关组件
[Input 输入框](./input) · [Form 表单](./form) · [Surface 表面](./surface) [Input 输入框](./input) · [Form 表单](./form) · [Surface 表面](./surface)
## 粘贴、对齐与完成事件
- `autoFocus?: boolean`:挂载后聚焦真实槽输入;保留 PinInput 的焦点导航。
- `pasteTransformer?: (pastedText: string) => string`:先转换剪贴板文本,再限制到 maxLength 并检查整个候选字符串。例如 `text => text.replaceAll('-', '')` 可接收带分隔符的验证码。不匹配的编辑整次拒绝,不从非法文本中悄悄筛出部分字符;空字符串始终可清空。
- `textAlign?: 'left' | 'center' | 'right'`(默认 left):用于各真实透明 input 的文字/选区对齐,视觉 slot 仍按移植 CSS 居中。多 input 结构不伪装为单 input。
- `validationDetails?: ValidityState`:传入全部原生 validity 标志,由 FieldError 的作用域插槽读取;显式值优先于校验代理快照。它本身不改变 isInvalid;错误文本和无效状态沿用已有字段协议。
`complete` 只跟随已接受值从长度不足变为 maxLength 的变化:父级拒绝满值提案不会触发;满值替换或重复相同值不触发;清空/删除后重新填满会再次触发。父级主动设置的已接受值也遵循同一阈值规则。禁用/只读不运行粘贴转换或编辑。
保留 PinInput 编辑约定:一份完整代码的粘贴从首格替换,短粘贴从当前格替换;完成后焦点位于末格或下一待填格,当前格字符可选择。单 input 的任意跨格文本选区与密码管理器徽标避让不承诺等价;`pushPasswordManagerStrategy` 未提供。`containerClassName` 在固定上游公共类型中已 Omit,不新增。
`validationErrors` 显式数组由调用方管理;Form 下同名服务端错误在有效编辑提案或 reset 时忽略当前响应,新响应会重新显示。原生 required/错误通过现有提交代理和共享 FieldError 关联;受控 reset 保留父值、非受控恢复 defaultValue,取消 reset 不改变值。
+10 -1
View File
@@ -217,6 +217,7 @@ SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议
| 属性 | 类型 | 默认值 | 描述 | | 属性 | 类型 | 默认值 | 描述 |
| ------------------------------------- | -------------------------------------------------------------------- | ---------------------- | ------------------------------------------------- | | ------------------------------------- | -------------------------------------------------------------------- | ---------------------- | ------------------------------------------------- |
| `validationErrors` | `string \| string[]` | - | 字段级外部错误,与 Form 同名错误合并 |
| `modelValue` / `defaultValue` | `string` | - | 受控值 / 非受控初始值 | | `modelValue` / `defaultValue` | `string` | - | 受控值 / 非受控初始值 |
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 根与 Group 的视觉变体 | | `variant` | `'primary' \| 'secondary'` | `'primary'` | 根与 Group 的视觉变体 |
| `fullWidth` | `boolean` | `false` | 根与 Group 全宽 | | `fullWidth` | `boolean` | `false` | 根与 Group 全宽 |
@@ -232,7 +233,7 @@ SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议
| `class` / `style` | Vue class / style 绑定 | - | 根节点属性;ARIA 下发到输入 | | `class` / `style` | Vue class / style 绑定 | - | 根节点属性;ARIA 下发到输入 |
| 默认插槽 | 作用域插槽 | - | 字段部件及状态 | | 默认插槽 | 作用域插槽 | - | 字段部件及状态 |
服务端错误通过 Form 的 validationErrors 按 name 映射;不提供 SearchField 独立 validationErrors 数组。validate 暂不接受 Promise;FieldError 无完整 React Aria validationDetails。 字段级 `validationErrors`(字符串或数组)与 Form 按 name 提供的错误共同接入;`validate` 暂不接受 Promise。FieldError 可读取真实控件的 `validationDetails`(ValidityState 快照)。
### 事件与暴露 ### 事件与暴露
@@ -270,3 +271,11 @@ SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议
## 相关组件 ## 相关组件
[Label 标签](./label) · [Description 描述](./description) · [FieldError 字段错误](./field-error) [Label 标签](./label) · [Description 描述](./description) · [FieldError 字段错误](./field-error)
## 字段级错误与焦点
`autoFocus?: boolean` 在挂载后聚焦真实 input/textarea(禁用控件不聚焦),不落到字段 div。默认插槽提供 `value`、`isFocusWithin`、`isFocusVisible`、`validationErrors` 和 `validationDetails`;根的 `data-focus-within` / `data-focus-visible` 与实际组内焦点和浏览器判定同步。
`validationErrors?: string | string[]` 用于字段级外部错误;显示顺序为字段错误、Form 中该 name 的错误、已触发的 validate/原生错误,字段与 Form 的重复消息去重。native 策略下外部错误写入真实控件的 customValidity,aria 策略只显示语义错误。`isInvalid` 仍只控制展示,不单独设置 customValidity。
改变值的输入事件会忽略当前字段错误响应与 Form 错误响应,reset 也会清除它们;新数组/对象引用视为新响应,重新显示。相同响应引用的原地修改不用于重新投递已忽略的错误。字段级响应只影响当前字段,Form 的其他字段错误保留。FieldError 的 `validationDetails` 是只读的原生 ValidityState 标志快照,不是第二套字段值。
+12 -2
View File
@@ -153,6 +153,8 @@ TextField 会根据状态自动管理以下 data 属性:
| Prop | 类型 | 默认值 | 描述 | | Prop | 类型 | 默认值 | 描述 |
| ------------------------------------- | -------------------------------------------------------------------- | -------------------------- | -------------------------------------------------- | | ------------------------------------- | -------------------------------------------------------------------- | -------------------------- | -------------------------------------------------- |
| 默认插槽 | `Component` | - | 子组件(Label、Input、Description、FieldError 等) | | 默认插槽 | `Component` | - | 子组件(Label、Input、Description、FieldError 等) |
| `validationErrors` | `string \| string[]` | - | 字段级外部错误,与 Form 同名错误合并 |
| `autoFocus` | `boolean` | `false` | 挂载后聚焦真实文本控件 |
| `modelValue` | `string` | - | 当前值(受控;`v-model`) | | `modelValue` | `string` | - | 当前值(受控;`v-model`) |
| `defaultValue` | `string` | - | 默认值(非受控) | | `defaultValue` | `string` | - | 默认值(非受控) |
| `name` | `string` | - | 用于 HTML 表单提交的 input 名称 | | `name` | `string` | - | 用于 HTML 表单提交的 input 名称 |
@@ -172,7 +174,7 @@ TextField 会根据状态自动管理以下 data 属性:
| `form` | `string` | - | 关联外部 form 的 id(下发到真实控件) | | `form` | `string` | - | 关联外部 form 的 id(下发到真实控件) |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | | `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
值使用 `v-model`(`update:modelValue`)。受控值由父级决定,拒绝更新时恢复实际 DOM 值。`name`、原生约束、`autoComplete` / `inputMode` / `form` 与 ARIA 落在真实 `input`/`textarea` 上。服务端/外部错误通过 Form 的 `validation-errors`(按 name 映射)接入,不是 TextField 的 `validationErrors` 数组。 值使用 `v-model`(`update:modelValue`)。受控值由父级决定,拒绝更新时恢复实际 DOM 值。`name`、原生约束、`autoComplete` / `inputMode` / `form` 与 ARIA 落在真实 `input`/`textarea` 上。服务端/外部错误既可由字段 `validationErrors`(字符串或数组)传入,也可由 Form 的 `validation-errors` 按 name 映射。
### 事件 ### 事件
@@ -234,8 +236,16 @@ const hasError = ref(false);
| `isInvalid` | `boolean` | 是否无效 | | `isInvalid` | `boolean` | 是否无效 |
| `validationErrors` | `string[]` | 当前错误列表 | | `validationErrors` | `string[]` | 当前错误列表 |
与上游 `TextFieldRenderProps` 的差异:Vue 使用作用域插槽而非 render prop;无 `isFocusWithin` / `isFocusVisible`(聚焦状态由控件自身管理)。 Vue 使用类型可解析的作用域插槽;`TextFieldRenderProps` 包含 `value`、`isFocusWithin`、`isFocusVisible` 与 `validationDetails`。组内焦点移动保持 focus-within,移出整个字段才清除。
## 相关组件 ## 相关组件
[Input 输入框](./input) · [TextArea 多行文本框](./textarea) · [Fieldset 字段组](./fieldset) [Input 输入框](./input) · [TextArea 多行文本框](./textarea) · [Fieldset 字段组](./fieldset)
## 字段级错误与焦点
`autoFocus?: boolean` 在挂载后聚焦真实 input/textarea(禁用控件不聚焦),不落到字段 div。默认插槽提供 `value`、`isFocusWithin`、`isFocusVisible`、`validationErrors` 和 `validationDetails`;根的 `data-focus-within` / `data-focus-visible` 与实际组内焦点和浏览器判定同步。
`validationErrors?: string | string[]` 用于字段级外部错误;显示顺序为字段错误、Form 中该 name 的错误、已触发的 validate/原生错误,字段与 Form 的重复消息去重。native 策略下外部错误写入真实控件的 customValidity,aria 策略只显示语义错误。`isInvalid` 仍只控制展示,不单独设置 customValidity。
改变值的输入事件会忽略当前字段错误响应与 Form 错误响应,reset 也会清除它们;新数组/对象引用视为新响应,重新显示。相同响应引用的原地修改不用于重新投递已忽略的错误。字段级响应只影响当前字段,Form 的其他字段错误保留。FieldError 的 `validationDetails` 是只读的原生 ValidityState 标志快照,不是第二套字段值。
+7
View File
@@ -3,6 +3,13 @@ import { defineAsyncComponent } from "vue";
// Keep regression URLs stable; load only the selected harness. // Keep regression URLs stable; load only the selected harness.
const labs = [ const labs = [
{
key: "field-otp",
title: "字段与验证码",
component: defineAsyncComponent(
() => import("../../../tests/fixtures/field-otp.vue"),
),
},
{ {
key: "link-focus", key: "link-focus",
title: "链接与日期焦点", title: "链接与日期焦点",
+6 -1
View File
@@ -201,7 +201,7 @@ React render 自定义根类型不支持;原生 attrs/具名部件/作用域
- **Pagination**:组合式 nav 容器(无 total/page 状态机);具名部件含 Link/Previous/Next(原生 button)、Ellipsis、图标默认 SVG。9/9 基线示例。`onPress`→`@click`。详见 [M30](component-notes.md)。 - **Pagination**:组合式 nav 容器(无 total/page 状态机);具名部件含 Link/Previous/Next(原生 button)、Ellipsis、图标默认 SVG。9/9 基线示例。`onPress`→`@click`。详见 [M30](component-notes.md)。
- **Header**:集合/分组标题,原生 `<header>`(已核对 RAC 契约)。基线无独立文档/演示;自编 3 例并标注。详见 [M31](component-notes.md)。 - **Header**:集合/分组标题,原生 `<header>`(已核对 RAC 契约)。基线无独立文档/演示;自编 3 例并标注。详见 [M31](component-notes.md)。
- **InputOTP**:Reka PinInput 底座;公开字符串 + 内部索引数组(中间空位不左移);complete 仅首次填满。11/11 示例。消费 fieldContextKey,未改共享内核。真实自动填充/IME/读屏未验证。详见 [M32](component-notes.md)。 - **InputOTP**:Reka PinInput 底座;公开字符串 + 内部索引数组(中间空位不左移);complete 已按HD-07收口为已接受值从未满变满。11/11 示例。消费 fieldContextKey,未改共享内核。真实自动填充/IME/读屏未验证。详见 [M32](component-notes.md)。
以上不构成整库完成声明;逐像素、读屏、Nuxt 水合、独立安装仍未验收。 以上不构成整库完成声明;逐像素、读屏、Nuxt 水合、独立安装仍未验收。
@@ -299,3 +299,8 @@ HD-01(2026-10-28):按钮/切换组与导航示例已恢复固定cn基线
## HD-06 链接与日期焦点(2026-10-29) ## HD-06 链接与日期焦点(2026-10-29)
禁用 Link 移除 href/target/download,包括 asChild 子节点的导航属性,保持 aria-disabled、tabindex=-1 与暴露的 focus;启用恢复,用户事件取消和子 ref 保留。Breadcrumbs 当前/禁用项原已用 span,不重复改写;新增按 ConfigProvider locale 的默认名称及 @action(key),保持 id/key 的数字0与空串身份,取消的激活不通知 action。两个日期触发器按实际 :focus-visible 更新状态标记,鼠标/Tab/关闭恢复由浏览器判定。证据见 [HD-06结果](tasks/results/HD-06-LINK-FOCUS.md)。 禁用 Link 移除 href/target/download,包括 asChild 子节点的导航属性,保持 aria-disabled、tabindex=-1 与暴露的 focus;启用恢复,用户事件取消和子 ref 保留。Breadcrumbs 当前/禁用项原已用 span,不重复改写;新增按 ConfigProvider locale 的默认名称及 @action(key),保持 id/key 的数字0与空串身份,取消的激活不通知 action。两个日期触发器按实际 :focus-visible 更新状态标记,鼠标/Tab/关闭恢复由浏览器判定。证据见 [HD-06结果](tasks/results/HD-06-LINK-FOCUS.md)。
## HD-07 字段与OTP公共能力(2026-10-29)
TextField/SearchField共享autoFocus、组内focus状态、字段级validationErrors与Form错误合并;SearchField槽value与文本值同源。FieldError按共享FieldContext可读取ValidityState快照,TextField/SearchField来自真实控件、OTP支持显式validationDetails或原生提交代理。OTP补autoFocus/pasteTransformer/textAlign,整值pattern与accepted complete对照固定input-otp1.5.0:非法整次编辑拒绝、受控拒绝不complete、满值替换不重复、清空重填再通知。PinInput索引空位与单字符串提交保留;视觉槽对齐、跨格选区、密码管理器策略等Vue边界见组件文档及[任务结果](tasks/results/HD-07-FIELD-OTP.md)。
+2
View File
@@ -31,3 +31,5 @@
- HD-06-LINK-FOCUS执行中:分支task/hd-06-link-focus,起点680a592e7b95bd52592edc19d1b8654b30b53a1c;本会话亲自实施并按用户授权验收后合并push。范围:Link禁用导航/asChild/ref、日期真实focus-visible、Breadcrumbs locale/action。5173保持,5174原已停止,本轮重新启动用于公开组合浏览器验收。 - HD-06-LINK-FOCUS执行中:分支task/hd-06-link-focus,起点680a592e7b95bd52592edc19d1b8654b30b53a1c;本会话亲自实施并按用户授权验收后合并push。范围:Link禁用导航/asChild/ref、日期真实focus-visible、Breadcrumbs locale/action。5173保持,5174原已停止,本轮重新启动用于公开组合浏览器验收。
- HD-06 已完成验收:实施68d45c66f98eeebd5872448b839ed387bf65f0f0;Link原生/asChild禁用导航及ref/取消语义、Breadcrumbs locale/action、日期真实focus-visible全部核销,见results/HD-06-LINK-FOCUS.md。全量111文件1641项、类型、文档/playground构建、四个最终tarball契约与真实浏览器通过。按用户授权合入main并push origin/main;工作区释放,下一项HD-07-FIELD-OTP未启动,保留5173及本轮重启的5174。 - HD-06 已完成验收:实施68d45c66f98eeebd5872448b839ed387bf65f0f0;Link原生/asChild禁用导航及ref/取消语义、Breadcrumbs locale/action、日期真实focus-visible全部核销,见results/HD-06-LINK-FOCUS.md。全量111文件1641项、类型、文档/playground构建、四个最终tarball契约与真实浏览器通过。按用户授权合入main并push origin/main;工作区释放,下一项HD-07-FIELD-OTP未启动,保留5173及本轮重启的5174。
- HD-07-FIELD-OTP执行中:分支task/hd-07-field-otp,实际起点27cc62e36f16bc16843ccf25f202340eeac38871;本会话亲自补字段focus/autoFocus/错误数组与ValidityState、SearchField槽value,以及OTP autoFocus/pasteTransformer/textAlign和固定1.5.0的pattern/complete契约,完成后按用户授权合并push。
+5 -5
View File
@@ -1,5 +1,5 @@
<!-- task-metadata <!-- task-metadata
{"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"pending","requires":["docs/tasks/HD-QUEUE.md"],"sources":["packages/react/src/components/input-otp/input-otp.tsx"],"checks":["pnpm exec vitest run tests/field-foundation.test.ts tests/fieldset-search-field.test.ts tests/input-otp.test.ts tests/regressions/navigation-otp/public-contracts.test.ts","pnpm typecheck"]} {"base":"db5670f4e1efe0e6ef7433002de5fb0a4a284f84","upstream":"ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960","status":"implemented","requires":["docs/tasks/HD-QUEUE.md"],"sources":["packages/react/src/components/input-otp/input-otp.tsx"],"checks":["pnpm exec vitest run tests/field-foundation.test.ts tests/fieldset-search-field.test.ts tests/input-otp.test.ts tests/regressions/navigation-otp/public-contracts.test.ts","pnpm typecheck","node scripts/check-package.mjs field-otp m30-m32 shared-styles api-root-aliases"]}
--> -->
# HD-07-FIELD-OTP:字段与 OTP 公共能力补齐 # HD-07-FIELD-OTP:字段与 OTP 公共能力补齐
@@ -7,10 +7,10 @@
## 执行范围 ## 执行范围
- [ ] 补 TextField 自动聚焦、isFocusWithin/isFocusVisible 与相应 data 状态;支持 TextField/SearchField 字段级 validationErrors 并明确与 Form 错误的合并、清除和优先级;补 SearchField 插槽 value。 - [x] 补 TextField 自动聚焦、isFocusWithin/isFocusVisible 与相应 data 状态;支持 TextField/SearchField 字段级 validationErrors 并明确与 Form 错误的合并、清除和优先级;补 SearchField 插槽 value。
- [ ] OTP 补 autoFocus、pasteTransformer、textAlign 的等价公共能力;validationDetails/FieldError 的必要校验信息复用现有字段协议,避免另建状态源。 - [x] OTP 补 autoFocus、pasteTransformer、textAlign 的等价公共能力;validationDetails/FieldError 的必要校验信息复用现有字段协议,避免另建状态源。
- [ ] 对固定 input-otp 依赖核验 pattern 和 complete:满值替换、重复值、清空重填、受控拒绝、粘贴转换后过滤均需行为证据,再修契约。不能仅依据报告把两个不同语义直接替换。 - [x] 对固定 input-otp 依赖核验 pattern 和 complete:满值替换、重复值、清空重填、受控拒绝、粘贴转换后过滤均需行为证据,再修契约。不能仅依据报告把两个不同语义直接替换。
- [ ] containerClassName 被上游公共类型 Omit 排除,不补;保留 PinInput、多真实 input、透明覆盖层和字符串/数组转换。密码管理器策略无等价能力时明确记录限制。 - [x] containerClassName 被上游公共类型 Omit 排除,不补;保留 PinInput、多真实 input、透明覆盖层和字符串/数组转换。密码管理器策略无等价能力时明确记录限制。
## 用户可见通过条件 ## 用户可见通过条件
+5
View File
@@ -366,3 +366,8 @@ Button/ButtonGroup/ToggleButton/ToggleButtonGroup与指定Accordion/Disclosure
### HD-06(2026-10-29) ### HD-06(2026-10-29)
Link/Breadcrumbs 对照固定 ce90ea3;Breadcrumbs 的34种名称移植自该上游锁文件的 react-aria 3.52.1 `dist/private/intl/breadcrumbs`,仅数据,不引入 React 运行时。Adobe Apache-2.0声明保留于第三方许可及组件包 `LICENSE.react-aria`(随 tarball发布)。Vue identity采用 id/key/index,事件为 @action。日期焦点标记适配真实 DOM :focus-visible。 Link/Breadcrumbs 对照固定 ce90ea3;Breadcrumbs 的34种名称移植自该上游锁文件的 react-aria 3.52.1 `dist/private/intl/breadcrumbs`,仅数据,不引入 React 运行时。Adobe Apache-2.0声明保留于第三方许可及组件包 `LICENSE.react-aria`(随 tarball发布)。Vue identity采用 id/key/index,事件为 @action。日期焦点标记适配真实 DOM :focus-visible。
### HD-07(2026-10-29)
固定HeroUI ce90ea3的InputOTP公开类型及锁定input-otp1.5.0(npm tarball只读source map)核对:pattern.test整值、pasteTransformer先转换、complete effect只跟随accepted value跨阈值。仅在现有Vue/Reka字段/PinInput边界适配,不安装React或增加运行时依赖;底座多input、索引空位、单字段提交保留。全局/sticky RegExp去状态化延续既有Vue行为;字符选区限单槽,非单input任意跨槽选择。字段错误与focus采用现有共享上下文,新增原生ValidityState快照。
@@ -19,6 +19,7 @@ const { field, id } = useFieldPart("error", attrs);
<slot <slot
:validation-errors="field?.errors.value ?? []" :validation-errors="field?.errors.value ?? []"
:is-invalid="field?.invalid.value ?? false" :is-invalid="field?.invalid.value ?? false"
:validation-details="field?.validationDetails?.value"
> >
{{ field?.errors.value.join(" ") }} {{ field?.errors.value.join(" ") }}
</slot> </slot>
@@ -12,6 +12,7 @@ export interface FieldContext {
required: ComputedRef<boolean>; required: ComputedRef<boolean>;
invalid: ComputedRef<boolean>; invalid: ComputedRef<boolean>;
errors: ComputedRef<string[]>; errors: ComputedRef<string[]>;
validationDetails?: ComputedRef<ValidityState | undefined>;
labelIds?: Ref<string[]>; labelIds?: Ref<string[]>;
descriptionIds: Ref<string[]>; descriptionIds: Ref<string[]>;
errorIds: Ref<string[]>; errorIds: Ref<string[]>;
@@ -12,12 +12,15 @@ import {
shallowRef, shallowRef,
useId, useId,
watchEffect, watchEffect,
onMounted,
nextTick,
type PropType, type PropType,
type ExtractPropTypes, type ExtractPropTypes,
type Slots, type Slots,
type VNode, type VNode,
type VNodeChild, type VNodeChild,
} from "vue"; } from "vue";
import { validitySnapshot } from "./validation";
import { textFieldVariants } from "@heroui-vue/styles"; import { textFieldVariants } from "@heroui-vue/styles";
import { import {
fieldContextKey, fieldContextKey,
@@ -34,6 +37,18 @@ import {
import { useInheritedDisabled } from "./disabled"; import { useInheritedDisabled } from "./disabled";
export interface TextFieldRenderProps {
value: string;
isDisabled: boolean;
isReadOnly: boolean;
isRequired: boolean;
isInvalid: boolean;
isFocusWithin: boolean;
isFocusVisible: boolean;
validationErrors: string[];
validationDetails: ValidityState;
}
export const textFieldProps = { export const textFieldProps = {
modelValue: String, modelValue: String,
defaultValue: String, defaultValue: String,
@@ -50,6 +65,8 @@ export const textFieldProps = {
isReadOnly: Boolean, isReadOnly: Boolean,
isRequired: Boolean, isRequired: Boolean,
isInvalid: Boolean, isInvalid: Boolean,
autoFocus: Boolean,
validationErrors: [String, Array] as PropType<string | string[]>,
fullWidth: Boolean, fullWidth: Boolean,
variant: String as PropType<"primary" | "secondary">, variant: String as PropType<"primary" | "secondary">,
validationBehavior: String as PropType<ValidationBehavior>, validationBehavior: String as PropType<ValidationBehavior>,
@@ -89,6 +106,10 @@ export function useTextField(
const touched = ref(false), const touched = ref(false),
nativeError = ref(""); nativeError = ref("");
const dismissed = shallowRef<object>(); const dismissed = shallowRef<object>();
const dismissedLocal = shallowRef<string | string[]>();
const focused = ref(false),
focusVisible = ref(false);
const details = shallowRef<ValidityState>(validitySnapshot());
const descriptionIds = ref<string[]>([]), const descriptionIds = ref<string[]>([]),
errorIds = ref<string[]>([]); errorIds = ref<string[]>([]);
// Pre-plan direct/native-wrapped parts before rendering controls, so SSR has // Pre-plan direct/native-wrapped parts before rendering controls, so SSR has
@@ -109,11 +130,19 @@ export function useTextField(
? errorMessages(source[props.name]) ? errorMessages(source[props.name])
: []; : [];
}); });
const localErrors = computed(() =>
props.validationErrors !== dismissedLocal.value
? errorMessages(props.validationErrors)
: [],
);
const externalErrors = computed(() => [
...new Set([...localErrors.value, ...serverErrors.value]),
]);
const customErrors = computed(() => const customErrors = computed(() =>
errorMessages(props.validate?.(value.value)), errorMessages(props.validate?.(value.value)),
); );
const errors = computed(() => [ const errors = computed(() => [
...serverErrors.value, ...externalErrors.value,
...(touched.value || behavior.value === "aria" ? customErrors.value : []), ...(touched.value || behavior.value === "aria" ? customErrors.value : []),
...((touched.value || behavior.value === "aria") && nativeError.value ...((touched.value || behavior.value === "aria") && nativeError.value
? [nativeError.value] ? [nativeError.value]
@@ -128,8 +157,11 @@ export function useTextField(
); );
function setValue(next: string) { function setValue(next: string) {
if (disabled.value || readOnly.value) return; if (disabled.value || readOnly.value) return;
if (next !== value.value) {
dismissed.value = form?.validationErrors.value;
dismissedLocal.value = props.validationErrors;
}
internal.value = next; internal.value = next;
dismissed.value = form?.validationErrors.value;
nativeError.value = ""; nativeError.value = "";
emit("update:modelValue", next); emit("update:modelValue", next);
} }
@@ -148,6 +180,7 @@ export function useTextField(
required, required,
invalid, invalid,
errors, errors,
validationDetails: computed(() => details.value),
descriptionIds, descriptionIds,
errorIds, errorIds,
value, value,
@@ -189,7 +222,7 @@ export function useTextField(
touched.value = true; touched.value = true;
const element = event.target as HTMLInputElement | HTMLTextAreaElement; const element = event.target as HTMLInputElement | HTMLTextAreaElement;
nativeError.value = nativeError.value =
customErrors.value.length || serverErrors.value.length customErrors.value.length || externalErrors.value.length
? "" ? ""
: element.validationMessage; : element.validationMessage;
}, },
@@ -198,6 +231,7 @@ export function useTextField(
touched.value = false; touched.value = false;
nativeError.value = ""; nativeError.value = "";
dismissed.value = form?.validationErrors.value; dismissed.value = form?.validationErrors.value;
dismissedLocal.value = props.validationErrors;
}, },
}; };
provide(fieldContextKey, field); provide(fieldContextKey, field);
@@ -205,16 +239,28 @@ export function useTextField(
watchEffect( watchEffect(
() => { () => {
const currentValue = value.value; const currentValue = value.value;
// Native constraints are patched by the leaf before this post effect.
// Track root props even when the value itself has not changed.
void [
props.type,
props.minLength,
props.maxLength,
props.pattern,
required.value,
];
control.value?.setCustomValidity( control.value?.setCustomValidity(
behavior.value === "native" && !disabled.value && !readOnly.value behavior.value === "native" && !disabled.value && !readOnly.value
? [...serverErrors.value, ...customErrors.value].join(" ") ? [...externalErrors.value, ...customErrors.value].join(" ")
: "", : "",
); );
if (behavior.value === "native" && touched.value) if (behavior.value === "native" && touched.value)
nativeError.value = nativeError.value =
customErrors.value.length || serverErrors.value.length customErrors.value.length || externalErrors.value.length
? "" ? ""
: (control.value?.validationMessage ?? ""); : (control.value?.validationMessage ?? "");
const snapshot = validitySnapshot(control.value?.validity);
if (JSON.stringify(snapshot) !== JSON.stringify(details.value))
details.value = snapshot;
if (behavior.value === "aria") if (behavior.value === "aria")
nativeError.value = nativeError.value =
disabled.value || readOnly.value disabled.value || readOnly.value
@@ -225,9 +271,30 @@ export function useTextField(
}, },
{ flush: "post" }, { flush: "post" },
); );
onMounted(() => {
void nextTick(() => {
if (props.autoFocus && !disabled.value) control.value?.focus();
});
});
function focusIn(event: FocusEvent) {
focused.value = true;
focusVisible.value = (event.target as HTMLElement).matches(
":focus-visible",
);
}
function focusOut(event: FocusEvent) {
if (
!(event.currentTarget as HTMLElement).contains(
event.relatedTarget as Node | null,
)
) {
focused.value = false;
focusVisible.value = false;
}
}
expose({ focus: () => control.value?.focus(), element: control }); expose({ focus: () => control.value?.focus(), element: control });
function prepare( function prepare(
nodes: VNodeChild[], nodes: VNodeChild,
found: { found: {
description: string[]; description: string[];
error: string[]; error: string[];
@@ -237,7 +304,7 @@ export function useTextField(
}, },
path = "", path = "",
): VNodeChild[] { ): VNodeChild[] {
return nodes.map((node, index) => { return (Array.isArray(nodes) ? nodes : [nodes]).map((node, index) => {
if (!isVNode(node) || node.type === Comment) return node; if (!isVNode(node) || node.type === Comment) return node;
const position = `${path}-${index}`; const position = `${path}-${index}`;
const type = node.type as { name?: string; __name?: string }; const type = node.type as { name?: string; __name?: string };
@@ -267,7 +334,7 @@ export function useTextField(
node.children && node.children &&
typeof node.children === "object" typeof node.children === "object"
) { ) {
const groupSlots = node.children as { default?: () => VNodeChild[] }; const groupSlots = node.children as { default?: () => VNodeChild };
if (typeof groupSlots.default === "function") { if (typeof groupSlots.default === "function") {
const prepared = prepare(groupSlots.default(), found, position); const prepared = prepare(groupSlots.default(), found, position);
const clone = cloneVNode(node); const clone = cloneVNode(node);
@@ -305,6 +372,10 @@ export function useTextField(
isRequired: required.value, isRequired: required.value,
isInvalid: invalid.value, isInvalid: invalid.value,
validationErrors: errors.value, validationErrors: errors.value,
validationDetails: details.value,
value: value.value,
isFocusWithin: focused.value,
isFocusVisible: focusVisible.value,
...options.slotState?.(), ...options.slotState?.(),
}) ?? [], }) ?? [],
found, found,
@@ -330,6 +401,10 @@ export function useTextField(
textFieldVariants({ fullWidth: props.fullWidth }), textFieldVariants({ fullWidth: props.fullWidth }),
attrs.class, attrs.class,
], ],
onFocusin: focusIn,
onFocusout: focusOut,
"data-focus-within": focused.value || undefined,
"data-focus-visible": focusVisible.value || undefined,
"data-slot": options.rootSlot ?? "textfield", "data-slot": options.rootSlot ?? "textfield",
"data-invalid": invalid.value || undefined, "data-invalid": invalid.value || undefined,
"data-disabled": disabled.value || undefined, "data-disabled": disabled.value || undefined,
@@ -341,5 +416,5 @@ export function useTextField(
children, children,
); );
}; };
return { field, element: control, render }; return { field, element: control, render, focused, focusVisible };
} }
@@ -0,0 +1,16 @@
/** Snapshot native readonly validity flags without retaining a live DOM object. */
export function validitySnapshot(value?: ValidityState): ValidityState {
return {
badInput: value?.badInput ?? false,
customError: value?.customError ?? false,
patternMismatch: value?.patternMismatch ?? false,
rangeOverflow: value?.rangeOverflow ?? false,
rangeUnderflow: value?.rangeUnderflow ?? false,
stepMismatch: value?.stepMismatch ?? false,
tooLong: value?.tooLong ?? false,
tooShort: value?.tooShort ?? false,
typeMismatch: value?.typeMismatch ?? false,
valid: value?.valid ?? true,
valueMissing: value?.valueMissing ?? false,
};
}
@@ -17,10 +17,12 @@ import {
useAttrs, useAttrs,
useId, useId,
watch, watch,
watchEffect,
type PropType, type PropType,
type VNode, type VNode,
type VNodeChild, type VNodeChild,
} from "vue"; } from "vue";
import { validitySnapshot } from "../field/validation";
import { PinInputRoot } from "reka-ui"; import { PinInputRoot } from "reka-ui";
import { inputOTPVariants, type InputOTPVariants } from "@heroui-vue/styles"; import { inputOTPVariants, type InputOTPVariants } from "@heroui-vue/styles";
import { useInheritedDisabled } from "../field/disabled"; import { useInheritedDisabled } from "../field/disabled";
@@ -43,11 +45,11 @@ function attrBoolean(value: unknown): boolean {
return value != null && value !== false; return value != null && value !== false;
} }
/** Match one character without leaking lastIndex on global/sticky regexes. */ /** Test the whole candidate without leaking lastIndex on global/sticky regexes. */
function charAllowed(re: RegExp, char: string): boolean { function valueAllowed(re: RegExp, value: string): boolean {
if (!char) return true; if (!value) return true;
const flags = re.flags.replace(/[gy]/g, ""); const flags = re.flags.replace(/[gy]/g, "");
return new RegExp(re.source, flags).test(char); return new RegExp(re.source, flags).test(value);
} }
export default defineComponent({ export default defineComponent({
@@ -83,6 +85,13 @@ export default defineComponent({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
autoFocus: Boolean,
pasteTransformer: Function as PropType<(pastedText: string) => string>,
textAlign: {
type: String as PropType<"left" | "center" | "right">,
default: "left",
},
validationDetails: Object as PropType<ValidityState>,
validationErrors: { validationErrors: {
type: Array as PropType<string[]>, type: Array as PropType<string[]>,
default: undefined, default: undefined,
@@ -113,7 +122,7 @@ export default defineComponent({
type: String, type: String,
default: "", default: "",
}, },
/** Character filter, e.g. REGEXP_ONLY_DIGITS. */ /** Whole-value predicate, e.g. REGEXP_ONLY_DIGITS. */
pattern: { pattern: {
type: [String, RegExp] as PropType<string | RegExp>, type: [String, RegExp] as PropType<string | RegExp>,
default: undefined, default: undefined,
@@ -179,19 +188,23 @@ export default defineComponent({
: EMPTY_ERRORS; : EMPTY_ERRORS;
}); });
const nativeError = ref("");
const invalid = computed( const invalid = computed(
() => () =>
props.isInvalid || props.isInvalid ||
(props.validationErrors?.length ?? 0) > 0 || (props.validationErrors?.length ?? 0) > 0 ||
serverErrors.value.length > 0 || serverErrors.value.length > 0 ||
Boolean(nativeError.value) ||
attrs["aria-invalid"] === true || attrs["aria-invalid"] === true ||
attrs["aria-invalid"] === "true", attrs["aria-invalid"] === "true",
); );
const errors = computed(() => [ const errors = computed(() => [
...(props.validationErrors ?? EMPTY_ERRORS), ...(props.validationErrors ?? EMPTY_ERRORS),
...serverErrors.value, ...serverErrors.value,
...(nativeError.value ? [nativeError.value] : []),
]); ]);
const nativeDetails = shallowRef<ValidityState>(validitySnapshot());
const resolvedId = computed(() => props.id ?? autoId); const resolvedId = computed(() => props.id ?? autoId);
/** Stable id per real focusable input; Label `for` uses index 0. */ /** Stable id per real focusable input; Label `for` uses index 0. */
function inputId(index: number): string { function inputId(index: number): string {
@@ -206,6 +219,9 @@ export default defineComponent({
required: computed(() => props.required), required: computed(() => props.required),
invalid, invalid,
errors, errors,
validationDetails: computed(
() => props.validationDetails ?? nativeDetails.value,
),
labelIds, labelIds,
descriptionIds, descriptionIds,
errorIds, errorIds,
@@ -261,18 +277,25 @@ export default defineComponent({
const raw = next[i]; const raw = next[i];
return raw == null ? "" : String(raw); return raw == null ? "" : String(raw);
}); });
const proposed = stringFromChars(clamped);
const re = pattern.value; const re = pattern.value;
if (re) { if (re && !valueAllowed(re, proposed)) {
for (let i = 0; i < clamped.length; i++) { // Force the primitive and native inputs back to the accepted slots.
const char = clamped[i]; const accepted = [...slotChars.value];
if (char && !charAllowed(re, char)) clamped[i] = ""; void nextTick(() => {
} slotChars.value = accepted;
rootEl.value
?.querySelectorAll<HTMLInputElement>(
'input[data-slot="input-otp-input"]',
)
.forEach((input, index) => {
input.value = accepted[index] ?? "";
});
});
return false;
} }
const previous = stringFromChars(slotChars.value); const previous = stringFromChars(slotChars.value);
const prevFilled = slotChars.value.filter(Boolean).length;
const nextFilled = clamped.filter(Boolean).length;
slotChars.value = clamped; slotChars.value = clamped;
const proposed = stringFromChars(clamped);
const currentPublic = isControlled.value const currentPublic = isControlled.value
? (props.modelValue ?? "") ? (props.modelValue ?? "")
: previous; : previous;
@@ -282,6 +305,7 @@ export default defineComponent({
lastEmitted = proposed; lastEmitted = proposed;
// Effective edit dismisses the current server-error response. // Effective edit dismisses the current server-error response.
dismissed.value = form?.validationErrors.value; dismissed.value = form?.validationErrors.value;
nativeError.value = "";
emit("update:modelValue", proposed); emit("update:modelValue", proposed);
emit("change", proposed); emit("change", proposed);
void nextTick(() => { void nextTick(() => {
@@ -294,15 +318,27 @@ export default defineComponent({
} }
}); });
} }
if ( return true;
prevFilled < length.value &&
nextFilled === length.value &&
length.value > 0
) {
emit("complete", proposed);
}
} }
// Completion follows the accepted public value, never a rejected proposal.
watch(
() =>
isControlled.value
? (props.modelValue ?? "")
: stringFromChars(slotChars.value),
(next, previous) => {
if (
next !== previous &&
previous.length < length.value &&
next.length === length.value &&
length.value > 0
)
emit("complete", next);
},
{ flush: "post" },
);
function handlePinUpdate(value: unknown) { function handlePinUpdate(value: unknown) {
applyChars(Array.isArray(value) ? value : []); applyChars(Array.isArray(value) ? value : []);
} }
@@ -327,6 +363,7 @@ export default defineComponent({
slotChars.value = charsFromString(incoming, length.value); slotChars.value = charsFromString(incoming, length.value);
} }
dismissed.value = form?.validationErrors.value; dismissed.value = form?.validationErrors.value;
nativeError.value = "";
}); });
} }
@@ -349,7 +386,46 @@ export default defineComponent({
formEl = next; formEl = next;
formEl?.addEventListener("reset", reset); formEl?.addEventListener("reset", reset);
} }
onMounted(bindForm); onMounted(() => {
bindForm();
void nextTick(() => {
if (props.autoFocus && !disabled.value)
rootEl.value
?.querySelector<HTMLInputElement>(
'input[data-slot="input-otp-input"]:not(:disabled)',
)
?.focus();
});
});
watchEffect(
() => {
// Shared FieldContext exposes the real validation proxy, with optional
// caller-supplied ValidityState taking precedence for FieldError slots.
const proxy = rootEl.value?.querySelector<HTMLInputElement>(
'input[aria-hidden="true"]',
);
if (!proxy) return;
const source = pattern.value?.source;
if (source) proxy.setAttribute("pattern", source);
else proxy.removeAttribute("pattern");
proxy.readOnly = readOnly.value;
if (disabled.value || readOnly.value) nativeError.value = "";
proxy.setCustomValidity(
disabled.value || readOnly.value
? ""
: [...(props.validationErrors ?? []), ...serverErrors.value].join(
" ",
),
);
// Track primitive value updates so native validity is read after DOM patch.
chars.value;
props.required;
const snapshot = validitySnapshot(proxy.validity);
if (JSON.stringify(snapshot) !== JSON.stringify(nativeDetails.value))
nativeDetails.value = snapshot;
},
{ flush: "post" },
);
onUpdated(bindForm); onUpdated(bindForm);
onBeforeUnmount(() => { onBeforeUnmount(() => {
formEl?.removeEventListener("reset", reset); formEl?.removeEventListener("reset", reset);
@@ -369,12 +445,78 @@ export default defineComponent({
chars, chars,
mask: computed(() => props.mask), mask: computed(() => props.mask),
inputClassName: computed(() => props.inputClassName), inputClassName: computed(() => props.inputClassName),
textAlign: computed(() => props.textAlign),
handlePaste,
guardInput,
describedBy, describedBy,
inputId, inputId,
labelledBy, labelledBy,
accessibleLabel, accessibleLabel,
}); });
function guardInput(event: InputEvent, index: number) {
if (event.isComposing) return;
if (!(event.target instanceof HTMLInputElement)) return;
const target = event.target;
const next = [...slotChars.value];
const multi = (event.data?.length ?? 0) > 1;
if (multi) {
const text = target.value;
const start = text.length >= length.value ? 0 : index;
for (
let i = start;
i < Math.min(start + text.length, length.value);
i++
)
next[i] = text[i - start]!;
} else next[index] = event.data || target.value.slice(-1);
if (
disabled.value ||
readOnly.value ||
event.defaultPrevented ||
(pattern.value && !valueAllowed(pattern.value, stringFromChars(next)))
) {
event.preventDefault();
event.stopImmediatePropagation();
target.value = slotChars.value[index] ?? "";
target.select();
}
}
function handlePaste(event: ClipboardEvent, index: number) {
if (
event.defaultPrevented ||
disabled.value ||
readOnly.value ||
!event.clipboardData
)
return;
const raw =
event.clipboardData.getData("text/plain") ||
event.clipboardData.getData("text");
const text = props.pasteTransformer ? props.pasteTransformer(raw) : raw;
event.preventDefault();
event.stopImmediatePropagation();
if (!text) return;
// Preserve PinInput's slot editing convention: a full code replaces
// all slots; a shorter paste starts at the focused slot.
const start = text.length >= length.value ? 0 : index;
const next = [...slotChars.value];
for (let i = start; i < Math.min(start + text.length, length.value); i++)
next[i] = text[i - start]!;
if (!applyChars(next)) return;
void nextTick(() => {
if (isControlled.value && props.modelValue !== stringFromChars(next))
return;
const inputs = rootEl.value?.querySelectorAll<HTMLInputElement>(
'input[data-slot="input-otp-input"]',
);
const input = inputs?.[Math.min(start + text.length, length.value - 1)];
input?.focus();
input?.select();
});
}
function prepareLabels( function prepareLabels(
nodes: VNodeChild[], nodes: VNodeChild[],
ids: string[], ids: string[],
@@ -405,6 +547,19 @@ export default defineComponent({
return node; return node;
}); });
} }
function invalidCapture(event: Event) {
const target = event.target;
if (
target instanceof HTMLInputElement &&
target.getAttribute("aria-hidden") === "true"
) {
nativeDetails.value = validitySnapshot(target.validity);
nativeError.value =
props.validationErrors?.length || serverErrors.value.length
? ""
: target.validationMessage;
}
}
function render() { function render() {
const labels: string[] = []; const labels: string[] = [];
const children = prepareLabels(slots.default?.() ?? [], labels); const children = prepareLabels(slots.default?.() ?? [], labels);
@@ -413,6 +568,7 @@ export default defineComponent({
return h( return h(
PinInputRoot, PinInputRoot,
{ {
...attrs,
ref: setRoot, ref: setRoot,
modelValue: chars.value, modelValue: chars.value,
disabled: disabled.value, disabled: disabled.value,
@@ -423,7 +579,14 @@ export default defineComponent({
required: props.required, required: props.required,
id: resolvedId.value, id: resolvedId.value,
"onUpdate:modelValue": handlePinUpdate, "onUpdate:modelValue": handlePinUpdate,
...attrs, onInvalidCapture: [
...(Array.isArray(attrs.onInvalidCapture)
? attrs.onInvalidCapture
: attrs.onInvalidCapture
? [attrs.onInvalidCapture]
: []),
invalidCapture,
],
class: [variantSlots.value.base(), attrs.class], class: [variantSlots.value.base(), attrs.class],
"data-disabled": disabled.value || undefined, "data-disabled": disabled.value || undefined,
"data-invalid": invalid.value ? "true" : undefined, "data-invalid": invalid.value ? "true" : undefined,
@@ -93,6 +93,7 @@ export default defineComponent({
onKeydownCapture: userKeydownCapture, onKeydownCapture: userKeydownCapture,
onPaste: userPaste, onPaste: userPaste,
onPasteCapture: userPasteCapture, onPasteCapture: userPasteCapture,
onInputCapture: userInputCapture,
...rest ...rest
} = attrs as Record<string, unknown>; } = attrs as Record<string, unknown>;
@@ -110,6 +111,7 @@ export default defineComponent({
...toHandlerArray(userPasteCapture), ...toHandlerArray(userPasteCapture),
...toHandlerArray(userPaste), ...toHandlerArray(userPaste),
stopIfPrevented, stopIfPrevented,
(event) => context?.handlePaste(event as ClipboardEvent, props.index),
]; ];
return h( return h(
@@ -117,6 +119,10 @@ export default defineComponent({
{ {
...rest, ...rest,
class: [slotClass, cls], class: [slotClass, cls],
onInputCapture: [
...toHandlerArray(userInputCapture),
(event: InputEvent) => context?.guardInput(event, props.index),
],
onKeydownCapture: keydownCapture, onKeydownCapture: keydownCapture,
onPasteCapture: pasteCapture, onPasteCapture: pasteCapture,
"data-active": isActive.value || undefined, "data-active": isActive.value || undefined,
@@ -151,6 +157,7 @@ export default defineComponent({
disabled: isDisabled.value, disabled: isDisabled.value,
readonly: isReadOnly.value || undefined, readonly: isReadOnly.value || undefined,
class: inputClass, class: inputClass,
style: { textAlign: context?.textAlign.value },
id: context?.inputId(props.index), id: context?.inputId(props.index),
"data-slot": "input-otp-input", "data-slot": "input-otp-input",
autocomplete: "one-time-code", autocomplete: "one-time-code",
@@ -14,6 +14,9 @@ export interface InputOTPContextValue {
chars: ComputedRef<string[]>; chars: ComputedRef<string[]>;
mask: ComputedRef<boolean>; mask: ComputedRef<boolean>;
inputClassName: ComputedRef<string | undefined>; inputClassName: ComputedRef<string | undefined>;
textAlign: ComputedRef<"left" | "center" | "right">;
guardInput: (event: InputEvent, index: number) => void;
handlePaste: (event: ClipboardEvent, index: number) => void;
describedBy: ComputedRef<string | undefined>; describedBy: ComputedRef<string | undefined>;
labelledBy: ComputedRef<string | undefined>; labelledBy: ComputedRef<string | undefined>;
accessibleLabel: ComputedRef<string | undefined>; accessibleLabel: ComputedRef<string | undefined>;
@@ -4,21 +4,24 @@ import {
defineComponent, defineComponent,
getCurrentInstance, getCurrentInstance,
nextTick, nextTick,
onMounted,
provide, provide,
ref, ref,
type SlotsType,
type VNode,
} from "vue"; } from "vue";
import { searchFieldVariants } from "@heroui-vue/styles"; import { searchFieldVariants } from "@heroui-vue/styles";
import { textFieldProps, useTextField } from "../field/useTextField"; import { textFieldProps, useTextField } from "../field/useTextField";
import { searchFieldContextKey } from "./context"; import { searchFieldContextKey, type SearchFieldRenderProps } from "./context";
export default defineComponent({ export default defineComponent({
name: "SearchField", name: "SearchField",
inheritAttrs: false, inheritAttrs: false,
slots: Object as SlotsType<{
default: (state: SearchFieldRenderProps) => VNode[];
}>,
props: { props: {
...textFieldProps, ...textFieldProps,
type: { type: String, default: "search" }, type: { type: String, default: "search" },
autoFocus: Boolean,
}, },
emits: { emits: {
"update:modelValue": (_value: string) => true, "update:modelValue": (_value: string) => true,
@@ -27,32 +30,34 @@ export default defineComponent({
}, },
setup(props, context) { setup(props, context) {
const instance = getCurrentInstance(); const instance = getCurrentInstance();
const hovered = ref(false), const hovered = ref(false);
focused = ref(false),
focusVisible = ref(false);
const slots = computed(() => const slots = computed(() =>
searchFieldVariants({ searchFieldVariants({
variant: props.variant, variant: props.variant,
fullWidth: props.fullWidth, fullWidth: props.fullWidth,
}), }),
); );
const { field, element, render } = useTextField(props, context, { const { field, element, render, focused, focusVisible } = useTextField(
rootSlot: "search-field", props,
rootClass: () => slots.value.base(), context,
rootAttrs: () => ({ {
onKeydown: keydown, rootSlot: "search-field",
"data-empty": !field.value.value || undefined, rootClass: () => slots.value.base(),
"data-focus-within": focused.value || undefined, rootAttrs: () => ({
"data-focus-visible": focusVisible.value || undefined, onKeydown: keydown,
"data-hovered": (!field.disabled.value && hovered.value) || undefined, "data-empty": !field.value.value || undefined,
}), "data-focus-within": focused.value || undefined,
slotState: () => ({ "data-focus-visible": focusVisible.value || undefined,
isEmpty: !field.value.value, "data-hovered": (!field.disabled.value && hovered.value) || undefined,
isHovered: !field.disabled.value && hovered.value, }),
isFocusWithin: focused.value, slotState: () => ({
isFocusVisible: focusVisible.value, isEmpty: !field.value.value,
}), isHovered: !field.disabled.value && hovered.value,
}); isFocusWithin: focused.value,
isFocusVisible: focusVisible.value,
}),
},
);
function clear(event?: Event) { function clear(event?: Event) {
const input = element.value; const input = element.value;
if ( if (
@@ -112,9 +117,7 @@ export default defineComponent({
clear, clear,
keydown, keydown,
}); });
onMounted(() => {
if (props.autoFocus && !field.disabled.value) element.value?.focus();
});
return render; return render;
}, },
}); });
@@ -1,6 +1,11 @@
import type { ComputedRef, InjectionKey, Ref } from "vue"; import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { searchFieldVariants } from "@heroui-vue/styles"; import type { searchFieldVariants } from "@heroui-vue/styles";
import type { TextFieldContext } from "../textfield/context"; import type { TextFieldContext } from "../textfield/context";
import type { TextFieldRenderProps } from "../field/useTextField";
export interface SearchFieldRenderProps extends TextFieldRenderProps {
isEmpty: boolean;
isHovered: boolean;
}
export interface SearchFieldContext { export interface SearchFieldContext {
field: TextFieldContext; field: TextFieldContext;
slots: ComputedRef<ReturnType<typeof searchFieldVariants>>; slots: ComputedRef<ReturnType<typeof searchFieldVariants>>;
@@ -1,10 +1,17 @@
<script lang="ts"> <script lang="ts">
import { defineComponent } from "vue"; import { defineComponent, type SlotsType, type VNode } from "vue";
import { textFieldProps, useTextField } from "../field/useTextField"; import {
textFieldProps,
useTextField,
type TextFieldRenderProps,
} from "../field/useTextField";
export default defineComponent({ export default defineComponent({
name: "TextField", name: "TextField",
inheritAttrs: false, inheritAttrs: false,
props: textFieldProps, props: textFieldProps,
slots: Object as SlotsType<{
default: (state: TextFieldRenderProps) => VNode[];
}>,
emits: { "update:modelValue": (_value: string) => true }, emits: { "update:modelValue": (_value: string) => true },
setup(props, context) { setup(props, context) {
return useTextField(props, context).render; return useTextField(props, context).render;
+3
View File
@@ -1510,3 +1510,6 @@ export type {
TooltipRootProps, TooltipRootProps,
TypographyRootProps, TypographyRootProps,
} from "./types"; } from "./types";
export type { TextFieldRenderProps } from "./components/field/useTextField";
export type { SearchFieldRenderProps } from "./components/search-field/context";
+138
View File
@@ -463,3 +463,141 @@ it("native Switch overrides an aria Form and blocks invalid submission", async (
expect(w.get("[role=switch]").attributes("aria-invalid")).toBe("true"); expect(w.get("[role=switch]").attributes("aria-invalid")).toBe("true");
w.unmount(); w.unmount();
}); });
it("TextField autoFocus and focus-within cover moves between child controls", async () => {
const w = mount(
defineComponent({
render: () =>
h(
TextField,
{ autoFocus: true },
{
default: (state: Record<string, unknown>) => [
h(Input),
h("button", { type: "button" }, "inside"),
h("output", String(state.isFocusWithin)),
],
},
),
}),
{ attachTo: document.body },
);
try {
await settle();
expect(document.activeElement).toBe(w.get("input").element);
expect(
w.get('[data-slot="textfield"]').attributes("data-focus-within"),
).toBe("true");
(w.get("button").element as HTMLButtonElement).focus();
await settle();
expect(w.get("output").text()).toBe("true");
(w.get("button").element as HTMLButtonElement).blur();
await settle();
expect(w.get("output").text()).toBe("false");
} finally {
w.unmount();
}
});
it("field and Form errors merge in order, dismiss on edit/reset, and a new response reappears", async () => {
const local = ref(["local"]),
server = ref({ name: "server" });
const w = mount(
defineComponent({
render: () =>
h(Form, { validationErrors: server.value }, () =>
h(TextField, { name: "name", validationErrors: local.value }, () => [
h(Input),
h(
FieldError,
{},
{
default: (s: {
validationErrors: string[];
validationDetails?: ValidityState;
}) =>
`${s.validationErrors.join("|")}:${s.validationDetails?.customError}`,
},
),
]),
),
}),
{ attachTo: document.body },
);
try {
await settle();
expect(w.get('[role="alert"]').text()).toBe("local|server:true");
expect((w.get("input").element as HTMLInputElement).checkValidity()).toBe(
false,
);
await w.get("input").setValue("edit");
await settle();
expect(w.find('[role="alert"]').exists()).toBe(false);
local.value = ["new local"];
server.value = { name: "new server" };
await settle();
expect(w.get('[role="alert"]').text()).toBe("new local|new server:true");
(w.get("form").element as HTMLFormElement).reset();
await settle();
expect(w.find('[role="alert"]').exists()).toBe(false);
} finally {
w.unmount();
}
});
it("TextField FieldError exposes native validity flags for required input", async () => {
const w = mount(
defineComponent({
render: () =>
h(TextField, { isRequired: true }, () => [
h(Input),
h(
FieldError,
{},
{
default: (s: { validationDetails?: ValidityState }) =>
String(s.validationDetails?.valueMissing),
},
),
]),
}),
{ attachTo: document.body },
);
try {
await settle();
(w.get("input").element as HTMLInputElement).checkValidity();
await settle();
expect(w.get('[role="alert"]').text()).toBe("true");
} finally {
w.unmount();
}
});
it("TextField validity details update when native constraints change without an edit", async () => {
const pattern = ref("[0-9]+");
const w = mount(
defineComponent({
render: () =>
h(
TextField,
{ defaultValue: "123", pattern: pattern.value },
{
default: (state: { validationDetails: ValidityState }) => [
h(Input),
h("output", String(state.validationDetails.patternMismatch)),
],
},
),
}),
);
try {
await settle();
expect(w.get("output").text()).toBe("false");
pattern.value = "[a-z]+";
await settle();
expect(w.get("output").text()).toBe("true");
pattern.value = "[0-9]+";
await settle();
expect(w.get("output").text()).toBe("false");
} finally {
w.unmount();
}
});
+37
View File
@@ -509,3 +509,40 @@ it.each(["changed-query", "x"])(
} }
}, },
); );
it("SearchField exposes value and shares field-level validation errors with Form", async () => {
const local = ref(["local search"]),
formErrors = ref({ q: "form search" });
const w = mount(
defineComponent({
render: () =>
h(Form, { validationErrors: formErrors.value }, () =>
h(
SearchField,
{ name: "q", validationErrors: local.value },
{
default: (s: { value: string }) => [
h(SearchFieldGroup, {}, () => h(SearchFieldInput)),
h(FieldError),
h("output", s.value),
],
},
),
),
}),
{ attachTo: document.body },
);
try {
await settle();
expect(w.get('[role="alert"]').text()).toBe("local search form search");
await w.get("input").setValue("query");
await settle();
expect(w.get("output").text()).toBe("query");
expect(w.find('[role="alert"]').exists()).toBe(false);
local.value = ["new search"];
await settle();
expect(w.get('[role="alert"]').text()).toBe("new search");
} finally {
w.unmount();
}
});
+134
View File
@@ -0,0 +1,134 @@
<script setup lang="ts">
import { ref } from "vue";
import {
TextField,
SearchField,
SearchFieldGroup,
SearchFieldInput,
SearchFieldClearButton,
Form,
Label,
Input,
FieldError,
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@heroui-vue/components";
const local = ref(["字段错误"]),
server = ref({ name: "Form错误" });
const mounted = ref(false),
accepted = ref(true),
disabled = ref(false),
readonly = ref(false);
const otp = ref(""),
completes = ref<string[]>([]),
proposals = ref<string[]>([]);
const align = ref<"left" | "center" | "right">("left");
const strip = (text: string) => text.replaceAll("-", "");
</script>
<template>
<main style="padding: 24px; display: grid; gap: 20px">
<Form :validation-errors="server">
<TextField
v-slot="state"
auto-focus
name="name"
:validation-errors="local"
>
<Label>姓名</Label>
<Input />
<button type="button">字段内按钮</button>
<output id="field-state">
{{
JSON.stringify({
value: state.value,
within: state.isFocusWithin,
visible: state.isFocusVisible,
})
}}
</output>
<FieldError v-slot="errors">
{{ errors.validationErrors.join("|") }} /
{{ errors.validationDetails?.customError }}
</FieldError>
</TextField>
<SearchField v-slot="state" name="query">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldInput />
<SearchFieldClearButton />
</SearchFieldGroup>
<output id="search-value">{{ state.value }}</output>
</SearchField>
<button type="reset">重置字段</button>
<button
type="button"
@click="
local = ['新字段错误'];
server = { name: '新Form错误' };
"
>
新错误响应
</button>
</Form>
<div>
<button @click="mounted = true">挂载验证码</button>
<label>
<input v-model="accepted" type="checkbox" />
接受验证码
</label>
<label>
<input v-model="disabled" type="checkbox" />
禁用验证码
</label>
<label>
<input v-model="readonly" type="checkbox" />
只读验证码
</label>
<label>
输入对齐
<select v-model="align">
<option>left</option>
<option>center</option>
<option>right</option>
</select>
</label>
</div>
<Form @submit.prevent>
<InputOTP
v-if="mounted"
:model-value="otp"
:max-length="4"
auto-focus
required
aria-label="验证码"
name="code"
:is-disabled="disabled"
:is-read-only="readonly"
:text-align="align"
:paste-transformer="strip"
pattern="^\d+$"
@update:model-value="
proposals.push($event);
accepted && (otp = $event);
"
@complete="completes.push($event)"
>
<InputOTPGroup>
<InputOTPSlot v-for="index in 4" :key="index" :index="index - 1" />
</InputOTPGroup>
<FieldError v-slot="state">
{{ state.validationErrors.join("|") }} / missing={{
state.validationDetails?.valueMissing
}}
</FieldError>
</InputOTP>
<button type="submit">校验验证码</button>
<button type="reset">重置验证码</button>
<button type="button" @click="otp = ''">清空验证码</button>
</Form>
<output id="otp-state">
{{ JSON.stringify({ value: otp, completes, proposals }) }}
</output>
</main>
</template>
+250 -1
View File
@@ -219,7 +219,7 @@ describe("InputOTP value model", () => {
}); });
describe("InputOTP pattern and states", () => { describe("InputOTP pattern and states", () => {
it("filters characters with REGEXP_ONLY_CHARS and digits constants", async () => { it("checks candidates with REGEXP_ONLY_CHARS and digits constants", async () => {
expect(REGEXP_ONLY_DIGITS).toBe("^\\d+$"); expect(REGEXP_ONLY_DIGITS).toBe("^\\d+$");
expect(REGEXP_ONLY_CHARS).toBe("^[a-zA-Z]+$"); expect(REGEXP_ONLY_CHARS).toBe("^[a-zA-Z]+$");
expect(REGEXP_ONLY_DIGITS_AND_CHARS).toBe("^[a-zA-Z0-9]+$"); expect(REGEXP_ONLY_DIGITS_AND_CHARS).toBe("^[a-zA-Z0-9]+$");
@@ -540,3 +540,252 @@ describe("InputOTP types", () => {
expect((bad as { variant?: string }).variant).toBe("ghost"); expect((bad as { variant?: string }).variant).toBe("ghost");
}); });
}); });
function pasteInto(input: Element, text: string) {
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { getData: () => text },
});
input.dispatchEvent(event);
}
const settleOtp = async () => {
await nextTick();
await nextTick();
await nextTick();
};
function enhancedOtp(
props: Record<string, unknown> = {},
slots: Record<string, unknown> = {},
) {
return mount(InputOTP, {
props: { maxLength: 4, ...props },
slots: {
default: () =>
h(InputOTPGroup, {}, () =>
[0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })),
),
...slots,
},
attachTo: document.body,
});
}
it("OTP autoFocus and textAlign reach actual inputs without leaking root props", async () => {
const w = enhancedOtp({ autoFocus: true, textAlign: "right" });
try {
await settleOtp();
expect(document.activeElement).toBe(slotInputs(w)[0].element);
expect((slotInputs(w)[0].element as HTMLInputElement).style.textAlign).toBe(
"right",
);
expect(w.attributes("textalign")).toBeUndefined();
await w.setProps({ textAlign: "center" });
expect((slotInputs(w)[3].element as HTMLInputElement).style.textAlign).toBe(
"center",
);
} finally {
w.unmount();
}
});
it.each(["isDisabled", "isReadOnly"])(
"OTP %s prevents paste transformation and edits",
async (flag) => {
const transform = vi.fn((text: string) => text.replaceAll("-", ""));
const w = enhancedOtp({
[flag]: true,
defaultValue: "12",
pasteTransformer: transform,
autoFocus: true,
});
try {
await settleOtp();
pasteInto(slotInputs(w)[0].element, "34-56");
await settleOtp();
expect(transform).not.toHaveBeenCalled();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("12");
if (flag === "isDisabled")
expect(w.element.contains(document.activeElement)).toBe(false);
} finally {
w.unmount();
}
},
);
it("OTP transforms paste before whole-value pattern checking and restores rejected DOM values", async () => {
const w = enhancedOtp({
pattern: "^12[0-9]*$",
defaultValue: "12",
pasteTransformer: (t: string) => t.replaceAll("-", ""),
});
try {
pasteInto(slotInputs(w)[0].element, "12-34");
await settleOtp();
expect(
slotInputs(w).map((i) => (i.element as HTMLInputElement).value),
).toEqual(["1", "2", "3", "4"]);
expect(document.activeElement).toBe(slotInputs(w)[3].element);
expect((slotInputs(w)[3].element as HTMLInputElement).selectionStart).toBe(
0,
);
await slotInputs(w)[2].setValue("8");
await settleOtp();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("1284");
await slotInputs(w)[0].setValue("9");
await settleOtp();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("1284");
pasteInto(slotInputs(w)[0].element, "90-12");
await settleOtp();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("1284");
} finally {
w.unmount();
}
});
it("OTP rejects an invalid paste as one edit and honors consumer cancellation", async () => {
const w = enhancedOtp({ pattern: REGEXP_ONLY_DIGITS, defaultValue: "12" });
try {
pasteInto(slotInputs(w)[0].element, "3a45");
await settleOtp();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("12");
const transform = vi.fn((t: string) => t);
await w.setProps({ pasteTransformer: transform });
const slot = w.element;
slot.addEventListener("paste", (e: Event) => e.preventDefault(), {
capture: true,
});
pasteInto(slotInputs(w)[0].element, "5678");
await settleOtp();
expect(transform).not.toHaveBeenCalled();
} finally {
w.unmount();
}
});
it("OTP complete follows accepted threshold crossings, including external updates, rather than rejected drafts", async () => {
const w = enhancedOtp({ modelValue: "12" });
try {
pasteInto(slotInputs(w)[0].element, "1234");
await settleOtp();
pasteInto(slotInputs(w)[0].element, "1234");
await settleOtp();
expect(w.emitted("update:modelValue")).toHaveLength(2);
expect(w.emitted("complete")).toBeUndefined();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("12");
await w.setProps({ modelValue: "1234" });
await settleOtp();
expect(w.emitted("complete")).toEqual([["1234"]]);
await w.setProps({ modelValue: "9876" });
await settleOtp();
pasteInto(slotInputs(w)[0].element, "9876");
await settleOtp();
expect(w.emitted("complete")).toHaveLength(1);
await w.setProps({ modelValue: "" });
await settleOtp();
await w.setProps({ modelValue: "4567" });
await settleOtp();
expect(w.emitted("complete")).toEqual([["1234"], ["4567"]]);
} finally {
w.unmount();
}
});
it("OTP passes caller ValidityState through shared FieldError without emitting it on the DOM", async () => {
const { FieldError } = await import("../packages/vue/src");
const details = {
badInput: false,
customError: true,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valid: false,
valueMissing: false,
};
const w = enhancedOtp(
{
isInvalid: true,
validationDetails: details,
validationErrors: ["server"],
},
{
default: () => [
h(InputOTPGroup, {}, () =>
[0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })),
),
h(
FieldError,
{},
{
default: (s: { validationDetails?: ValidityState }) =>
String(s.validationDetails?.customError),
},
),
],
},
);
try {
await settleOtp();
expect(w.get('[data-slot="field-error"]').text()).toBe("true");
expect(w.attributes("validationdetails")).toBeUndefined();
} finally {
w.unmount();
}
});
it("OTP native required validation shares FieldError details and clears on an effective edit", async () => {
const { FieldError } = await import("../packages/vue/src");
const w = enhancedOtp(
{ required: true },
{
default: () => [
h(InputOTPGroup, {}, () =>
[0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })),
),
h(
FieldError,
{},
{
default: (s: { validationDetails?: ValidityState }) =>
String(s.validationDetails?.valueMissing),
},
),
],
},
);
try {
await settleOtp();
const proxy = w.get('input[aria-hidden="true"]')
.element as HTMLInputElement;
expect(proxy.checkValidity()).toBe(false);
await settleOtp();
expect(w.get('[role="alert"]').text()).toBe("true");
await slotInputs(w)[0].setValue("1");
await settleOtp();
expect(w.find('[role="alert"]').exists()).toBe(false);
expect(proxy.checkValidity()).toBe(true);
} finally {
w.unmount();
}
});
+15
View File
@@ -871,5 +871,20 @@
".hv-date-picker__trigger", ".hv-date-picker__trigger",
".hv-date-range-picker__trigger" ".hv-date-range-picker__trigger"
] ]
},
"field-otp": {
"exports": [
"TextField",
"SearchField",
"FieldError",
"InputOTP",
"InputOTPSlot"
],
"css": [
".hv-textfield",
".hv-search-field",
".hv-field-error",
".hv-input-otp__input"
]
} }
} }
+51
View File
@@ -0,0 +1,51 @@
import { h } from "vue";
import {
TextField,
SearchField,
type TextFieldProps,
type SearchFieldProps,
type TextFieldRenderProps,
type SearchFieldRenderProps,
type InputOTPProps,
} from "@heroui-vue/components";
const text: TextFieldProps = { autoFocus: true, validationErrors: ["server"] };
const search: SearchFieldProps = { validationErrors: "local", autoFocus: true };
const otp: InputOTPProps = {
maxLength: 4,
autoFocus: true,
textAlign: "right",
pasteTransformer: (text) => text.replaceAll("-", ""),
};
const textSlot: NonNullable<
InstanceType<typeof TextField>["$slots"]["default"]
> = (state: TextFieldRenderProps) => [
h(
"span",
`${state.value}/${state.isFocusWithin}/${state.validationDetails.valid}`,
),
];
const searchSlot: NonNullable<
InstanceType<typeof SearchField>["$slots"]["default"]
> = (state: SearchFieldRenderProps) => [
h("span", `${state.value}/${state.isEmpty}/${state.isFocusVisible}`),
];
// @ts-expect-error errors are local text/arrays, not Form name maps
const badField: TextFieldProps = { validationErrors: { email: "wrong" } };
// @ts-expect-error text alignment is a closed union
const badAlignment: InputOTPProps = { maxLength: 4, textAlign: "bottom" };
// @ts-expect-error the paste transformer returns a string
const badPaste: InputOTPProps = { maxLength: 4, pasteTransformer: () => 42 };
const badDetails: InputOTPProps = {
maxLength: 4,
// @ts-expect-error all native validity flags are required
validationDetails: { valid: false },
};
void text;
void search;
void otp;
void textSlot;
void searchSlot;
void badField;
void badAlignment;
void badPaste;
void badDetails;