Compare commits
2 Commits
27cc62e36f
...
aac93db658
| Author | SHA1 | Date | |
|---|---|---|---|
| aac93db658 | |||
| 2d7e3d4e1e |
@@ -212,3 +212,7 @@ FieldError 组件通过以下方式确保无障碍性:
|
||||
## 相关组件
|
||||
|
||||
[TextField 文本输入框](./text-field) · [Input 输入框](./input) · [TextArea 多行文本框](./textarea)
|
||||
|
||||
### validationDetails
|
||||
|
||||
作用域插槽还提供 `validationDetails?: ValidityState`。TextField/SearchField 使用真实控件的原生快照,OTP 可显式传入详情(优先)或读取其提交代理快照;其他尚未接入详情的字段为 undefined。可读取 `valueMissing`、`patternMismatch`、`typeMismatch`、`customError` 等原生标志,而不复制字段状态。详情本身不替代 `isInvalid` 或错误文本。
|
||||
|
||||
@@ -82,7 +82,7 @@ InputOTP 组件支持两种视觉变体:
|
||||
|
||||
<ComponentPreview name="input-otp-on-complete" />
|
||||
|
||||
`@complete` 在**首次填满**时触发一次;替换已满值、重复同值或父级同步同一值不会重复触发。示例使用模拟验证(定时器),不发送真实验证码。
|
||||
`@complete` 在已接受值**从未满变为满值**时触发一次;替换已满值、重复同值或父级同步同一值不会重复触发。示例使用模拟验证(定时器),不发送真实验证码。
|
||||
|
||||
### 表单示例
|
||||
|
||||
@@ -94,7 +94,7 @@ InputOTP 组件支持两种视觉变体:
|
||||
|
||||
<ComponentPreview name="input-otp-with-pattern" />
|
||||
|
||||
`pattern` 过滤单字符输入,可使用导出的正则常量。
|
||||
`pattern` 检查整个候选字符串,可使用导出的正则常量;不匹配时拒绝整次编辑。
|
||||
|
||||
### 表单验证
|
||||
|
||||
@@ -177,25 +177,29 @@ InputOTP 组件使用以下 CSS 类([查看源码样式](https://github.com/he
|
||||
|
||||
### InputOTP / InputOTPRoot
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| ------------------ | -------------------------- | ----------- | ---------------------------------------------------------------- |
|
||||
| `modelValue` | `string` | - | 受控字符串值;下标对应槽位 |
|
||||
| `defaultValue` | `string` | `''` | 非受控初始值 |
|
||||
| `maxLength` | `number` | 必填 | 槽位数量 / 最大长度 |
|
||||
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 外观变体 |
|
||||
| `isDisabled` | `boolean` | `false` | 禁用 |
|
||||
| `isInvalid` | `boolean` | `false` | 无效展示状态 |
|
||||
| `validationErrors` | `string[]` | `[]` | 校验错误消息 |
|
||||
| `inputClassName` | `string` | - | 附加到真实 input 的类 |
|
||||
| `name` | `string` | - | 表单字段名(隐藏 input 提交一份完整值) |
|
||||
| `required` | `boolean` | `false` | 原生必填 |
|
||||
| `pattern` | `string \| RegExp` | - | 字符过滤正则 |
|
||||
| `mask` | `boolean` | `false` | 密码样式(Reka `mask`) |
|
||||
| `otp` | `boolean` | `false` | 一次性验证码自动填充(`autocomplete="one-time-code"`) |
|
||||
| `placeholder` | `string` | `''` | 空位占位符 |
|
||||
| `id` | `string` | 自动 | 提交桥 id;真实输入派生为 id-slot-index,内部 Label 自动关联首格 |
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| ------------------- | ------------------------------- | ------------ | ---------------------------------------------------------------- |
|
||||
| `modelValue` | `string` | - | 受控字符串值;下标对应槽位 |
|
||||
| `defaultValue` | `string` | `''` | 非受控初始值 |
|
||||
| `maxLength` | `number` | 必填 | 槽位数量 / 最大长度 |
|
||||
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 外观变体 |
|
||||
| `isDisabled` | `boolean` | `false` | 禁用 |
|
||||
| `isInvalid` | `boolean` | `false` | 无效展示状态 |
|
||||
| `validationErrors` | `string[]` | `[]` | 校验错误消息 |
|
||||
| `autoFocus` | `boolean` | `false` | 挂载后聚焦真实 input |
|
||||
| `pasteTransformer` | `(text: string) => string` | - | 粘贴转换先于正则检查 |
|
||||
| `textAlign` | `'left' \| 'center' \| 'right'` | `'left'` | 真实 input 对齐 |
|
||||
| `validationDetails` | `ValidityState` | 原生代理快照 | 显式校验标志优先,供 FieldError 读取 |
|
||||
| `inputClassName` | `string` | - | 附加到真实 input 的类 |
|
||||
| `name` | `string` | - | 表单字段名(隐藏 input 提交一份完整值) |
|
||||
| `required` | `boolean` | `false` | 原生必填 |
|
||||
| `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
|
||||
|
||||
@@ -213,17 +217,17 @@ InputOTP 组件使用以下 CSS 类([查看源码样式](https://github.com/he
|
||||
|
||||
### 上游差异
|
||||
|
||||
| 上游 React 能力 | Vue 实现 |
|
||||
| ------------------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| `input-otp` 单隐藏 input | Reka PinInput 多 input + 隐藏提交 input |
|
||||
| `value` / `onChange` 字符串 | `v-model` / `update:modelValue` / `change` |
|
||||
| `onComplete` 跨过长度阈值 | `complete` 仅在首次填满触发 |
|
||||
| `pattern` 整串校验 | 单字符过滤(同样接受导出常量) |
|
||||
| `render` / `OTPInputContext` | 具名插槽部件;槽位状态经上下文 |
|
||||
| `pushPasswordManagerStrategy` | 未提供;`otp` 覆盖 one-time-code 自动填充 |
|
||||
| `validationDetails`(ValidityState) | 未提供;校验结果为 `string \| string[]` 文本 |
|
||||
| `textAlign` / `pasteTransformer` | 未提供(能力缺口,见 HD 队列后续能力卡) |
|
||||
| `autoFocus` / `containerClassName` | 未提供专门 prop;`containerClassName` 被上游公共类型显式 Omit,`autoFocus` 属能力缺口 |
|
||||
| 上游 React 能力 | Vue 实现 |
|
||||
| ------------------------------------ | ------------------------------------------------------------------------- |
|
||||
| `input-otp` 单隐藏 input | Reka PinInput 多 input + 隐藏提交 input |
|
||||
| `value` / `onChange` 字符串 | `v-model` / `update:modelValue` / `change` |
|
||||
| `onComplete` 跨过长度阈值 | `complete` 在已接受值从未满变满时触发;满值替换不重复触发 |
|
||||
| `pattern` 整串校验 | 整个候选字符串按 pattern 检查,拒绝整次不匹配编辑 |
|
||||
| `render` / `OTPInputContext` | 具名插槽部件;槽位状态经上下文 |
|
||||
| `pushPasswordManagerStrategy` | 未提供;`otp` 覆盖 one-time-code 自动填充 |
|
||||
| `validationDetails`(ValidityState) | 作为 prop 传入并通过共享 FieldError 插槽暴露;缺省读取原生校验代理 |
|
||||
| `textAlign` / `pasteTransformer` | 均已提供;转换后的整值再做 pattern 检查 |
|
||||
| `autoFocus` / `containerClassName` | 提供 autoFocus;containerClassName 被上游公共类型显式 Omit,不新增该 prop |
|
||||
|
||||
## 字段与表单
|
||||
|
||||
@@ -243,3 +247,16 @@ Slot 的 keydown/paste 用户处理器在底座编辑前的 capture 边界协调
|
||||
## 相关组件
|
||||
|
||||
[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 不改变值。
|
||||
|
||||
@@ -217,6 +217,7 @@ SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议
|
||||
|
||||
| 属性 | 类型 | 默认值 | 描述 |
|
||||
| ------------------------------------- | -------------------------------------------------------------------- | ---------------------- | ------------------------------------------------- |
|
||||
| `validationErrors` | `string \| string[]` | - | 字段级外部错误,与 Form 同名错误合并 |
|
||||
| `modelValue` / `defaultValue` | `string` | - | 受控值 / 非受控初始值 |
|
||||
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 根与 Group 的视觉变体 |
|
||||
| `fullWidth` | `boolean` | `false` | 根与 Group 全宽 |
|
||||
@@ -232,7 +233,7 @@ SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议
|
||||
| `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)
|
||||
|
||||
## 字段级错误与焦点
|
||||
|
||||
`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 标志快照,不是第二套字段值。
|
||||
|
||||
@@ -153,6 +153,8 @@ TextField 会根据状态自动管理以下 data 属性:
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| ------------------------------------- | -------------------------------------------------------------------- | -------------------------- | -------------------------------------------------- |
|
||||
| 默认插槽 | `Component` | - | 子组件(Label、Input、Description、FieldError 等) |
|
||||
| `validationErrors` | `string \| string[]` | - | 字段级外部错误,与 Form 同名错误合并 |
|
||||
| `autoFocus` | `boolean` | `false` | 挂载后聚焦真实文本控件 |
|
||||
| `modelValue` | `string` | - | 当前值(受控;`v-model`) |
|
||||
| `defaultValue` | `string` | - | 默认值(非受控) |
|
||||
| `name` | `string` | - | 用于 HTML 表单提交的 input 名称 |
|
||||
@@ -172,7 +174,7 @@ TextField 会根据状态自动管理以下 data 属性:
|
||||
| `form` | `string` | - | 关联外部 form 的 id(下发到真实控件) |
|
||||
| `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` | 是否无效 |
|
||||
| `validationErrors` | `string[]` | 当前错误列表 |
|
||||
|
||||
与上游 `TextFieldRenderProps` 的差异:Vue 使用作用域插槽而非 render prop;无 `isFocusWithin` / `isFocusVisible`(聚焦状态由控件自身管理)。
|
||||
Vue 使用类型可解析的作用域插槽;`TextFieldRenderProps` 包含 `value`、`isFocusWithin`、`isFocusVisible` 与 `validationDetails`。组内焦点移动保持 focus-within,移出整个字段才清除。
|
||||
|
||||
## 相关组件
|
||||
|
||||
[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 标志快照,不是第二套字段值。
|
||||
|
||||
@@ -3,6 +3,13 @@ import { defineAsyncComponent } from "vue";
|
||||
|
||||
// Keep regression URLs stable; load only the selected harness.
|
||||
const labs = [
|
||||
{
|
||||
key: "field-otp",
|
||||
title: "字段与验证码",
|
||||
component: defineAsyncComponent(
|
||||
() => import("../../../tests/fixtures/field-otp.vue"),
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "link-focus",
|
||||
title: "链接与日期焦点",
|
||||
|
||||
@@ -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)。
|
||||
- **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 水合、独立安装仍未验收。
|
||||
|
||||
@@ -299,3 +299,8 @@ HD-01(2026-10-28):按钮/切换组与导航示例已恢复固定cn基线
|
||||
## 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)。
|
||||
|
||||
|
||||
## 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)。
|
||||
|
||||
@@ -31,3 +31,7 @@
|
||||
- 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-07-FIELD-OTP执行中:分支task/hd-07-field-otp,实际起点27cc62e36f16bc16843ccf25f202340eeac38871;本会话亲自补字段focus/autoFocus/错误数组与ValidityState、SearchField槽value,以及OTP autoFocus/pasteTransformer/textAlign和固定1.5.0的pattern/complete契约,完成后按用户授权合并push。
|
||||
|
||||
- HD-07 已完成验收:实施2d7e3d4e1e12403bb90e92e393bc7fb798a5a2ba;字段共享autoFocus/focus/validationErrors/ValidityState、SearchField槽value、OTP四项props与固定1.5.0整值pattern/accepted complete全部核销,见results/HD-07-FIELD-OTP.md。全量111文件1654项、类型、最终docs/playground构建、四组tarball与真实浏览器通过。按用户授权合入main并push origin/main;工作区释放,下一项HD-08未启动,保留5173/5174。
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!-- 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":"accepted","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 公共能力补齐
|
||||
|
||||
@@ -7,10 +7,10 @@
|
||||
|
||||
## 执行范围
|
||||
|
||||
- [ ] 补 TextField 自动聚焦、isFocusWithin/isFocusVisible 与相应 data 状态;支持 TextField/SearchField 字段级 validationErrors 并明确与 Form 错误的合并、清除和优先级;补 SearchField 插槽 value。
|
||||
- [ ] OTP 补 autoFocus、pasteTransformer、textAlign 的等价公共能力;validationDetails/FieldError 的必要校验信息复用现有字段协议,避免另建状态源。
|
||||
- [ ] 对固定 input-otp 依赖核验 pattern 和 complete:满值替换、重复值、清空重填、受控拒绝、粘贴转换后过滤均需行为证据,再修契约。不能仅依据报告把两个不同语义直接替换。
|
||||
- [ ] containerClassName 被上游公共类型 Omit 排除,不补;保留 PinInput、多真实 input、透明覆盖层和字符串/数组转换。密码管理器策略无等价能力时明确记录限制。
|
||||
- [x] 补 TextField 自动聚焦、isFocusWithin/isFocusVisible 与相应 data 状态;支持 TextField/SearchField 字段级 validationErrors 并明确与 Form 错误的合并、清除和优先级;补 SearchField 插槽 value。
|
||||
- [x] OTP 补 autoFocus、pasteTransformer、textAlign 的等价公共能力;validationDetails/FieldError 的必要校验信息复用现有字段协议,避免另建状态源。
|
||||
- [x] 对固定 input-otp 依赖核验 pattern 和 complete:满值替换、重复值、清空重填、受控拒绝、粘贴转换后过滤均需行为证据,再修契约。不能仅依据报告把两个不同语义直接替换。
|
||||
- [x] containerClassName 被上游公共类型 Omit 排除,不补;保留 PinInput、多真实 input、透明覆盖层和字符串/数组转换。密码管理器策略无等价能力时明确记录限制。
|
||||
|
||||
## 用户可见通过条件
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# HD-07-FIELD-OTP 结果与验收
|
||||
|
||||
- 日期:2026-10-29;本会话亲自实施与验收,用户已授权完成后合并 push。
|
||||
- 分支 `task/hd-07-field-otp`,实际起点 `27cc62e36f16bc16843ccf25f202340eeac38871`;实现 **`2d7e3d4e1e12403bb90e92e393bc7fb798a5a2ba`**。
|
||||
- 固定 HeroUI `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`;依赖语义核对锁定的 input-otp **1.5.0** npm 源码映射中的原始 input.tsx,不使用滚动版本。不安装或运行 React,不新增依赖。
|
||||
|
||||
## 范围核销
|
||||
|
||||
| 项 | 处理与证据 |
|
||||
| --- | --- |
|
||||
| TextField 自动聚焦与焦点 | 共享 useTextField 挂载后聚焦真实 input/textarea,禁用不聚焦;根输出 data-focus-within/data-focus-visible,槽暴露同源状态。组内焦点移动保留 within,离开根清除;visible 使用实际 :focus-visible。SearchField 改用同一焦点状态,保留组/清空按钮协议。 |
|
||||
| 字段错误数组 | TextField/SearchField 支持 string 或 string[],本地错误在前、Form 同名服务端错误在后、重复消息去重;validate/原生消息沿用原有 touched/validationBehavior 规则。改变值的编辑提案或 reset 忽略当前字段/Form 响应,新的数组/对象重新显示;不原地修改调用方错误。 |
|
||||
| 字段校验详情 | FieldContext 增量可选 validationDetails,FieldError 槽读取同一协议。TextField/SearchField 快照真实控件的11个 ValidityState 标志;value 与动态 type/minLength/maxLength/pattern/required 改变后更新。默认槽新增公开 TextFieldRenderProps/SearchFieldRenderProps,SearchField value 来自同一字段值。 |
|
||||
| OTP 四项公共能力 | autoFocus 聚焦首个真实槽输入;pasteTransformer 先转换文本再限长、校验;textAlign 默认 left 并作用于实际透明 input;validationDetails 显式值优先,否则读取已有原生提交代理,通过共享 FieldError 槽暴露,不另建字段内核。 |
|
||||
| pattern | 固定1.5.0对整个候选字符串做 RegExp.test,空串可清空。原来逐字符筛选改为非法整次编辑拒绝;capture 边界在 PinInput 改值/前进焦点前恢复当前字符。保留现有全局/粘滞正则的无 lastIndex 副作用处理。带分隔符文本由显式 transformer 转换,不隐式挑出合法字符。 |
|
||||
| complete | 固定1.5.0仅在已接受值改变且旧长度不足、新长度等于 maxLength 时触发;不在初始满值挂载、满值替换、同值回写或受控拒绝提案时触发。删除/清空后重新填满再次通知,父级主动接受的新值遵循同一规则。 |
|
||||
| 底座与提交 | 保留 PinInput 多真实 input、索引空位、一次字符串 FormData、受控拒绝恢复/可重试、reset 与取消 reset;完整代码粘贴从首格替换,短粘贴从当前格替换,成功后聚焦末格或下一格并选择字符。禁用/只读不转换或修改,消费方 preventDefault 取消粘贴。 |
|
||||
| 无需增加 | containerClassName 在固定 HeroUI 公共类型中被 Omit 排除,不补;不换单 input 底座,不加入密码管理器策略。可感知边界见下节与组件文档。 |
|
||||
|
||||
同步更新 TextField、SearchField、InputOTP、FieldError 文档、compatibility 与移植来源。修复库自有 InputGroup/SearchFieldGroup 原始默认槽返回单 VNode 时 prepare 假定数组的既有缺陷;不执行未知组件 setup/render 探测。
|
||||
|
||||
## 验证
|
||||
|
||||
- `node scripts/task-check.mjs HD-07-FIELD-OTP` 通过;卡内补入最终 tarball 检查。
|
||||
- 最终全量 `pnpm exec vitest run`:**111文件 / 1654项通过**;`pnpm typecheck`通过。相对前置增加13项(字段4、SearchField1、OTP8)。保留原有索引删除、一次提交、表单重置、取消事件等断言,无删除/skip。
|
||||
- 新字段用例验证本地/Form顺序、编辑/reset/新响应、真实自动聚焦、组内焦点、原生 required 与动态 pattern 的 validity 快照。OTP 用例验证转换/整值拒绝/取消/只读禁用、textAlign、受控拒绝与接受、重复/已满替换/清空重填 complete、显式与原生 validity。
|
||||
- 最终 `node scripts/check-package.mjs field-otp m30-m32 shared-styles api-root-aliases` 通过:独立最终 tarball 的 ESM/CSS 与 bundler/NodeNext 类型正反例全部通过;新 props/具名槽类型可消费,错误对象、非法对齐、非字符串转换器、不完整 ValidityState 被拒绝。
|
||||
- `pnpm build:docs`、`pnpm --filter @heroui-vue/playground build`通过;动态约束补修后,使用最终产物再次构建 docs 与 playground通过。文档仅既有 chunk 大小提示。
|
||||
- 修改代码 Prettier 与 `git diff --check`通过。
|
||||
- 一次与库/文档构建并发运行的全量中 choice-demos 单例超过默认5秒;停止构建并串行重跑后全部通过。未放宽超时或更改该测试,将其记录为本次运行竞争现象,不据此宣布既有组件缺陷。
|
||||
|
||||
## 真实浏览器(5174/?field-otp)
|
||||
|
||||
复用夹具 `tests/fixtures/field-otp.vue`,实际原生键盘、剪贴板和控件操作;不通过脚本补发浏览器事件。
|
||||
|
||||
1. 挂载 TextField 后焦点在实际 input,槽内 within/visible 均 true;点击内部按钮 within 保持 true、鼠标 visible=false。输入 Alice 后本地/Form错误消失,新响应按“新字段错误|新Form错误”显示,reset 清值并清除当前响应;SearchField 输入 query 后槽 value 同步。
|
||||
2. 点击挂载 OTP 自动聚焦首格;空值提交显示原生“请填写此字段。”,FieldError valueMissing=true。真实粘贴 `12-34` 得到接受值1234、一次complete、焦点末格且选区[0,1],原生错误消除。设置right后4个真实输入的computed textAlign均right。
|
||||
3. 已满时粘贴 `56-78` 替换为5678,complete不增加。关闭父级接受后粘贴 `90-12` 记录提案9012,实际值恢复5678且不complete。只读时粘贴不生成提案;受控reset保留父值5678。
|
||||
4. 末格 BackSpace 得到567,按9填满5679再次complete;按非法a保持5679且焦点不前进。清空后粘贴 `12-34` 再次complete,结果顺序为1234、5679、1234。
|
||||
5. 5173的InputOTP正式文档确认新增4属性、整值pattern、accepted complete与差异说明实际渲染,原中文全部演示保留。
|
||||
|
||||
## 边界与交接
|
||||
|
||||
- 多 input 结构保留,不承诺单 input 的任意跨格选区或 pushPasswordManagerStrategy 徽标避让;视觉 slot 字符按移植CSS居中,textAlign用于真实透明输入。短信/密码管理器自动填充、真机IME/触屏、完整读屏未在本轮验收。
|
||||
- 原生代理 required 保持底座“非空”规则,不额外发明必须满长才满足 required;完整长度业务规则仍由应用校验。显式 validationDetails 不自动改变 isInvalid。
|
||||
- OTP显式 validationErrors 由调用方管理;Form 当前错误响应在有效编辑提案/reset时忽略。受控值的拒绝恢复与错误响应忽略是两个独立的既有协议,文档已说明。
|
||||
- 仅浏览器客户端,未执行SSR/水合/Nuxt服务端或逐像素专项。
|
||||
- 无本卡未完成项。按用户授权 accepted,合入main并push origin/main;保留5173/5174。下一项HD-08未自动启动。
|
||||
@@ -366,3 +366,8 @@ Button/ButtonGroup/ToggleButton/ToggleButtonGroup与指定Accordion/Disclosure
|
||||
### 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。
|
||||
|
||||
|
||||
### 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
|
||||
:validation-errors="field?.errors.value ?? []"
|
||||
:is-invalid="field?.invalid.value ?? false"
|
||||
:validation-details="field?.validationDetails?.value"
|
||||
>
|
||||
{{ field?.errors.value.join(" ") }}
|
||||
</slot>
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface FieldContext {
|
||||
required: ComputedRef<boolean>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
errors: ComputedRef<string[]>;
|
||||
validationDetails?: ComputedRef<ValidityState | undefined>;
|
||||
labelIds?: Ref<string[]>;
|
||||
descriptionIds: Ref<string[]>;
|
||||
errorIds: Ref<string[]>;
|
||||
|
||||
@@ -12,12 +12,15 @@ import {
|
||||
shallowRef,
|
||||
useId,
|
||||
watchEffect,
|
||||
onMounted,
|
||||
nextTick,
|
||||
type PropType,
|
||||
type ExtractPropTypes,
|
||||
type Slots,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { validitySnapshot } from "./validation";
|
||||
import { textFieldVariants } from "@heroui-vue/styles";
|
||||
import {
|
||||
fieldContextKey,
|
||||
@@ -34,6 +37,18 @@ import {
|
||||
|
||||
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 = {
|
||||
modelValue: String,
|
||||
defaultValue: String,
|
||||
@@ -50,6 +65,8 @@ export const textFieldProps = {
|
||||
isReadOnly: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
autoFocus: Boolean,
|
||||
validationErrors: [String, Array] as PropType<string | string[]>,
|
||||
fullWidth: Boolean,
|
||||
variant: String as PropType<"primary" | "secondary">,
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
@@ -89,6 +106,10 @@ export function useTextField(
|
||||
const touched = ref(false),
|
||||
nativeError = ref("");
|
||||
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[]>([]),
|
||||
errorIds = ref<string[]>([]);
|
||||
// Pre-plan direct/native-wrapped parts before rendering controls, so SSR has
|
||||
@@ -109,11 +130,19 @@ export function useTextField(
|
||||
? 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(() =>
|
||||
errorMessages(props.validate?.(value.value)),
|
||||
);
|
||||
const errors = computed(() => [
|
||||
...serverErrors.value,
|
||||
...externalErrors.value,
|
||||
...(touched.value || behavior.value === "aria" ? customErrors.value : []),
|
||||
...((touched.value || behavior.value === "aria") && nativeError.value
|
||||
? [nativeError.value]
|
||||
@@ -128,8 +157,11 @@ export function useTextField(
|
||||
);
|
||||
function setValue(next: string) {
|
||||
if (disabled.value || readOnly.value) return;
|
||||
if (next !== value.value) {
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
dismissedLocal.value = props.validationErrors;
|
||||
}
|
||||
internal.value = next;
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
nativeError.value = "";
|
||||
emit("update:modelValue", next);
|
||||
}
|
||||
@@ -148,6 +180,7 @@ export function useTextField(
|
||||
required,
|
||||
invalid,
|
||||
errors,
|
||||
validationDetails: computed(() => details.value),
|
||||
descriptionIds,
|
||||
errorIds,
|
||||
value,
|
||||
@@ -189,7 +222,7 @@ export function useTextField(
|
||||
touched.value = true;
|
||||
const element = event.target as HTMLInputElement | HTMLTextAreaElement;
|
||||
nativeError.value =
|
||||
customErrors.value.length || serverErrors.value.length
|
||||
customErrors.value.length || externalErrors.value.length
|
||||
? ""
|
||||
: element.validationMessage;
|
||||
},
|
||||
@@ -198,6 +231,7 @@ export function useTextField(
|
||||
touched.value = false;
|
||||
nativeError.value = "";
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
dismissedLocal.value = props.validationErrors;
|
||||
},
|
||||
};
|
||||
provide(fieldContextKey, field);
|
||||
@@ -205,16 +239,28 @@ export function useTextField(
|
||||
watchEffect(
|
||||
() => {
|
||||
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(
|
||||
behavior.value === "native" && !disabled.value && !readOnly.value
|
||||
? [...serverErrors.value, ...customErrors.value].join(" ")
|
||||
? [...externalErrors.value, ...customErrors.value].join(" ")
|
||||
: "",
|
||||
);
|
||||
if (behavior.value === "native" && touched.value)
|
||||
nativeError.value =
|
||||
customErrors.value.length || serverErrors.value.length
|
||||
customErrors.value.length || externalErrors.value.length
|
||||
? ""
|
||||
: (control.value?.validationMessage ?? "");
|
||||
const snapshot = validitySnapshot(control.value?.validity);
|
||||
if (JSON.stringify(snapshot) !== JSON.stringify(details.value))
|
||||
details.value = snapshot;
|
||||
if (behavior.value === "aria")
|
||||
nativeError.value =
|
||||
disabled.value || readOnly.value
|
||||
@@ -225,9 +271,30 @@ export function useTextField(
|
||||
},
|
||||
{ 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 });
|
||||
function prepare(
|
||||
nodes: VNodeChild[],
|
||||
nodes: VNodeChild,
|
||||
found: {
|
||||
description: string[];
|
||||
error: string[];
|
||||
@@ -237,7 +304,7 @@ export function useTextField(
|
||||
},
|
||||
path = "",
|
||||
): VNodeChild[] {
|
||||
return nodes.map((node, index) => {
|
||||
return (Array.isArray(nodes) ? nodes : [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 };
|
||||
@@ -267,7 +334,7 @@ export function useTextField(
|
||||
node.children &&
|
||||
typeof node.children === "object"
|
||||
) {
|
||||
const groupSlots = node.children as { default?: () => VNodeChild[] };
|
||||
const groupSlots = node.children as { default?: () => VNodeChild };
|
||||
if (typeof groupSlots.default === "function") {
|
||||
const prepared = prepare(groupSlots.default(), found, position);
|
||||
const clone = cloneVNode(node);
|
||||
@@ -305,6 +372,10 @@ export function useTextField(
|
||||
isRequired: required.value,
|
||||
isInvalid: invalid.value,
|
||||
validationErrors: errors.value,
|
||||
validationDetails: details.value,
|
||||
value: value.value,
|
||||
isFocusWithin: focused.value,
|
||||
isFocusVisible: focusVisible.value,
|
||||
...options.slotState?.(),
|
||||
}) ?? [],
|
||||
found,
|
||||
@@ -330,6 +401,10 @@ export function useTextField(
|
||||
textFieldVariants({ fullWidth: props.fullWidth }),
|
||||
attrs.class,
|
||||
],
|
||||
onFocusin: focusIn,
|
||||
onFocusout: focusOut,
|
||||
"data-focus-within": focused.value || undefined,
|
||||
"data-focus-visible": focusVisible.value || undefined,
|
||||
"data-slot": options.rootSlot ?? "textfield",
|
||||
"data-invalid": invalid.value || undefined,
|
||||
"data-disabled": disabled.value || undefined,
|
||||
@@ -341,5 +416,5 @@ export function useTextField(
|
||||
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,
|
||||
useId,
|
||||
watch,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { validitySnapshot } from "../field/validation";
|
||||
import { PinInputRoot } from "reka-ui";
|
||||
import { inputOTPVariants, type InputOTPVariants } from "@heroui-vue/styles";
|
||||
import { useInheritedDisabled } from "../field/disabled";
|
||||
@@ -43,11 +45,11 @@ function attrBoolean(value: unknown): boolean {
|
||||
return value != null && value !== false;
|
||||
}
|
||||
|
||||
/** Match one character without leaking lastIndex on global/sticky regexes. */
|
||||
function charAllowed(re: RegExp, char: string): boolean {
|
||||
if (!char) return true;
|
||||
/** Test the whole candidate without leaking lastIndex on global/sticky regexes. */
|
||||
function valueAllowed(re: RegExp, value: string): boolean {
|
||||
if (!value) return true;
|
||||
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({
|
||||
@@ -83,6 +85,13 @@ export default defineComponent({
|
||||
type: Boolean,
|
||||
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: {
|
||||
type: Array as PropType<string[]>,
|
||||
default: undefined,
|
||||
@@ -113,7 +122,7 @@ export default defineComponent({
|
||||
type: String,
|
||||
default: "",
|
||||
},
|
||||
/** Character filter, e.g. REGEXP_ONLY_DIGITS. */
|
||||
/** Whole-value predicate, e.g. REGEXP_ONLY_DIGITS. */
|
||||
pattern: {
|
||||
type: [String, RegExp] as PropType<string | RegExp>,
|
||||
default: undefined,
|
||||
@@ -179,19 +188,23 @@ export default defineComponent({
|
||||
: EMPTY_ERRORS;
|
||||
});
|
||||
|
||||
const nativeError = ref("");
|
||||
const invalid = computed(
|
||||
() =>
|
||||
props.isInvalid ||
|
||||
(props.validationErrors?.length ?? 0) > 0 ||
|
||||
serverErrors.value.length > 0 ||
|
||||
Boolean(nativeError.value) ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true",
|
||||
);
|
||||
const errors = computed(() => [
|
||||
...(props.validationErrors ?? EMPTY_ERRORS),
|
||||
...serverErrors.value,
|
||||
...(nativeError.value ? [nativeError.value] : []),
|
||||
]);
|
||||
|
||||
const nativeDetails = shallowRef<ValidityState>(validitySnapshot());
|
||||
const resolvedId = computed(() => props.id ?? autoId);
|
||||
/** Stable id per real focusable input; Label `for` uses index 0. */
|
||||
function inputId(index: number): string {
|
||||
@@ -206,6 +219,9 @@ export default defineComponent({
|
||||
required: computed(() => props.required),
|
||||
invalid,
|
||||
errors,
|
||||
validationDetails: computed(
|
||||
() => props.validationDetails ?? nativeDetails.value,
|
||||
),
|
||||
labelIds,
|
||||
descriptionIds,
|
||||
errorIds,
|
||||
@@ -261,18 +277,25 @@ export default defineComponent({
|
||||
const raw = next[i];
|
||||
return raw == null ? "" : String(raw);
|
||||
});
|
||||
const proposed = stringFromChars(clamped);
|
||||
const re = pattern.value;
|
||||
if (re) {
|
||||
for (let i = 0; i < clamped.length; i++) {
|
||||
const char = clamped[i];
|
||||
if (char && !charAllowed(re, char)) clamped[i] = "";
|
||||
}
|
||||
if (re && !valueAllowed(re, proposed)) {
|
||||
// Force the primitive and native inputs back to the accepted slots.
|
||||
const accepted = [...slotChars.value];
|
||||
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 prevFilled = slotChars.value.filter(Boolean).length;
|
||||
const nextFilled = clamped.filter(Boolean).length;
|
||||
slotChars.value = clamped;
|
||||
const proposed = stringFromChars(clamped);
|
||||
const currentPublic = isControlled.value
|
||||
? (props.modelValue ?? "")
|
||||
: previous;
|
||||
@@ -282,6 +305,7 @@ export default defineComponent({
|
||||
lastEmitted = proposed;
|
||||
// Effective edit dismisses the current server-error response.
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
nativeError.value = "";
|
||||
emit("update:modelValue", proposed);
|
||||
emit("change", proposed);
|
||||
void nextTick(() => {
|
||||
@@ -294,15 +318,27 @@ export default defineComponent({
|
||||
}
|
||||
});
|
||||
}
|
||||
if (
|
||||
prevFilled < length.value &&
|
||||
nextFilled === length.value &&
|
||||
length.value > 0
|
||||
) {
|
||||
emit("complete", proposed);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
applyChars(Array.isArray(value) ? value : []);
|
||||
}
|
||||
@@ -327,6 +363,7 @@ export default defineComponent({
|
||||
slotChars.value = charsFromString(incoming, length.value);
|
||||
}
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
nativeError.value = "";
|
||||
});
|
||||
}
|
||||
|
||||
@@ -349,7 +386,46 @@ export default defineComponent({
|
||||
formEl = next;
|
||||
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);
|
||||
onBeforeUnmount(() => {
|
||||
formEl?.removeEventListener("reset", reset);
|
||||
@@ -369,12 +445,78 @@ export default defineComponent({
|
||||
chars,
|
||||
mask: computed(() => props.mask),
|
||||
inputClassName: computed(() => props.inputClassName),
|
||||
textAlign: computed(() => props.textAlign),
|
||||
handlePaste,
|
||||
guardInput,
|
||||
describedBy,
|
||||
inputId,
|
||||
labelledBy,
|
||||
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(
|
||||
nodes: VNodeChild[],
|
||||
ids: string[],
|
||||
@@ -405,6 +547,19 @@ export default defineComponent({
|
||||
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() {
|
||||
const labels: string[] = [];
|
||||
const children = prepareLabels(slots.default?.() ?? [], labels);
|
||||
@@ -413,6 +568,7 @@ export default defineComponent({
|
||||
return h(
|
||||
PinInputRoot,
|
||||
{
|
||||
...attrs,
|
||||
ref: setRoot,
|
||||
modelValue: chars.value,
|
||||
disabled: disabled.value,
|
||||
@@ -423,7 +579,14 @@ export default defineComponent({
|
||||
required: props.required,
|
||||
id: resolvedId.value,
|
||||
"onUpdate:modelValue": handlePinUpdate,
|
||||
...attrs,
|
||||
onInvalidCapture: [
|
||||
...(Array.isArray(attrs.onInvalidCapture)
|
||||
? attrs.onInvalidCapture
|
||||
: attrs.onInvalidCapture
|
||||
? [attrs.onInvalidCapture]
|
||||
: []),
|
||||
invalidCapture,
|
||||
],
|
||||
class: [variantSlots.value.base(), attrs.class],
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"data-invalid": invalid.value ? "true" : undefined,
|
||||
|
||||
@@ -93,6 +93,7 @@ export default defineComponent({
|
||||
onKeydownCapture: userKeydownCapture,
|
||||
onPaste: userPaste,
|
||||
onPasteCapture: userPasteCapture,
|
||||
onInputCapture: userInputCapture,
|
||||
...rest
|
||||
} = attrs as Record<string, unknown>;
|
||||
|
||||
@@ -110,6 +111,7 @@ export default defineComponent({
|
||||
...toHandlerArray(userPasteCapture),
|
||||
...toHandlerArray(userPaste),
|
||||
stopIfPrevented,
|
||||
(event) => context?.handlePaste(event as ClipboardEvent, props.index),
|
||||
];
|
||||
|
||||
return h(
|
||||
@@ -117,6 +119,10 @@ export default defineComponent({
|
||||
{
|
||||
...rest,
|
||||
class: [slotClass, cls],
|
||||
onInputCapture: [
|
||||
...toHandlerArray(userInputCapture),
|
||||
(event: InputEvent) => context?.guardInput(event, props.index),
|
||||
],
|
||||
onKeydownCapture: keydownCapture,
|
||||
onPasteCapture: pasteCapture,
|
||||
"data-active": isActive.value || undefined,
|
||||
@@ -151,6 +157,7 @@ export default defineComponent({
|
||||
disabled: isDisabled.value,
|
||||
readonly: isReadOnly.value || undefined,
|
||||
class: inputClass,
|
||||
style: { textAlign: context?.textAlign.value },
|
||||
id: context?.inputId(props.index),
|
||||
"data-slot": "input-otp-input",
|
||||
autocomplete: "one-time-code",
|
||||
|
||||
@@ -14,6 +14,9 @@ export interface InputOTPContextValue {
|
||||
chars: ComputedRef<string[]>;
|
||||
mask: ComputedRef<boolean>;
|
||||
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>;
|
||||
labelledBy: ComputedRef<string | undefined>;
|
||||
accessibleLabel: ComputedRef<string | undefined>;
|
||||
|
||||
@@ -4,21 +4,24 @@ import {
|
||||
defineComponent,
|
||||
getCurrentInstance,
|
||||
nextTick,
|
||||
onMounted,
|
||||
provide,
|
||||
ref,
|
||||
type SlotsType,
|
||||
type VNode,
|
||||
} from "vue";
|
||||
import { searchFieldVariants } from "@heroui-vue/styles";
|
||||
import { textFieldProps, useTextField } from "../field/useTextField";
|
||||
import { searchFieldContextKey } from "./context";
|
||||
import { searchFieldContextKey, type SearchFieldRenderProps } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "SearchField",
|
||||
inheritAttrs: false,
|
||||
slots: Object as SlotsType<{
|
||||
default: (state: SearchFieldRenderProps) => VNode[];
|
||||
}>,
|
||||
props: {
|
||||
...textFieldProps,
|
||||
type: { type: String, default: "search" },
|
||||
autoFocus: Boolean,
|
||||
},
|
||||
emits: {
|
||||
"update:modelValue": (_value: string) => true,
|
||||
@@ -27,32 +30,34 @@ export default defineComponent({
|
||||
},
|
||||
setup(props, context) {
|
||||
const instance = getCurrentInstance();
|
||||
const hovered = ref(false),
|
||||
focused = ref(false),
|
||||
focusVisible = ref(false);
|
||||
const hovered = ref(false);
|
||||
const slots = computed(() =>
|
||||
searchFieldVariants({
|
||||
variant: props.variant,
|
||||
fullWidth: props.fullWidth,
|
||||
}),
|
||||
);
|
||||
const { field, element, render } = useTextField(props, context, {
|
||||
rootSlot: "search-field",
|
||||
rootClass: () => slots.value.base(),
|
||||
rootAttrs: () => ({
|
||||
onKeydown: keydown,
|
||||
"data-empty": !field.value.value || undefined,
|
||||
"data-focus-within": focused.value || undefined,
|
||||
"data-focus-visible": focusVisible.value || undefined,
|
||||
"data-hovered": (!field.disabled.value && hovered.value) || undefined,
|
||||
}),
|
||||
slotState: () => ({
|
||||
isEmpty: !field.value.value,
|
||||
isHovered: !field.disabled.value && hovered.value,
|
||||
isFocusWithin: focused.value,
|
||||
isFocusVisible: focusVisible.value,
|
||||
}),
|
||||
});
|
||||
const { field, element, render, focused, focusVisible } = useTextField(
|
||||
props,
|
||||
context,
|
||||
{
|
||||
rootSlot: "search-field",
|
||||
rootClass: () => slots.value.base(),
|
||||
rootAttrs: () => ({
|
||||
onKeydown: keydown,
|
||||
"data-empty": !field.value.value || undefined,
|
||||
"data-focus-within": focused.value || undefined,
|
||||
"data-focus-visible": focusVisible.value || undefined,
|
||||
"data-hovered": (!field.disabled.value && hovered.value) || undefined,
|
||||
}),
|
||||
slotState: () => ({
|
||||
isEmpty: !field.value.value,
|
||||
isHovered: !field.disabled.value && hovered.value,
|
||||
isFocusWithin: focused.value,
|
||||
isFocusVisible: focusVisible.value,
|
||||
}),
|
||||
},
|
||||
);
|
||||
function clear(event?: Event) {
|
||||
const input = element.value;
|
||||
if (
|
||||
@@ -112,9 +117,7 @@ export default defineComponent({
|
||||
clear,
|
||||
keydown,
|
||||
});
|
||||
onMounted(() => {
|
||||
if (props.autoFocus && !field.disabled.value) element.value?.focus();
|
||||
});
|
||||
|
||||
return render;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { ComputedRef, InjectionKey, Ref } from "vue";
|
||||
import type { searchFieldVariants } from "@heroui-vue/styles";
|
||||
import type { TextFieldContext } from "../textfield/context";
|
||||
import type { TextFieldRenderProps } from "../field/useTextField";
|
||||
export interface SearchFieldRenderProps extends TextFieldRenderProps {
|
||||
isEmpty: boolean;
|
||||
isHovered: boolean;
|
||||
}
|
||||
export interface SearchFieldContext {
|
||||
field: TextFieldContext;
|
||||
slots: ComputedRef<ReturnType<typeof searchFieldVariants>>;
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent } from "vue";
|
||||
import { textFieldProps, useTextField } from "../field/useTextField";
|
||||
import { defineComponent, type SlotsType, type VNode } from "vue";
|
||||
import {
|
||||
textFieldProps,
|
||||
useTextField,
|
||||
type TextFieldRenderProps,
|
||||
} from "../field/useTextField";
|
||||
export default defineComponent({
|
||||
name: "TextField",
|
||||
inheritAttrs: false,
|
||||
props: textFieldProps,
|
||||
slots: Object as SlotsType<{
|
||||
default: (state: TextFieldRenderProps) => VNode[];
|
||||
}>,
|
||||
emits: { "update:modelValue": (_value: string) => true },
|
||||
setup(props, context) {
|
||||
return useTextField(props, context).render;
|
||||
|
||||
@@ -1510,3 +1510,6 @@ export type {
|
||||
TooltipRootProps,
|
||||
TypographyRootProps,
|
||||
} from "./types";
|
||||
|
||||
export type { TextFieldRenderProps } from "./components/field/useTextField";
|
||||
export type { SearchFieldRenderProps } from "./components/search-field/context";
|
||||
|
||||
@@ -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");
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
|
||||
Vendored
+134
@@ -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
@@ -219,7 +219,7 @@ describe("InputOTP value model", () => {
|
||||
});
|
||||
|
||||
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_CHARS).toBe("^[a-zA-Z]+$");
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -871,5 +871,20 @@
|
||||
".hv-date-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"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
Reference in New Issue
Block a user