diff --git a/AGENTS.md b/AGENTS.md index e002b40..7173c49 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -514,3 +514,11 @@ Area 覆盖所有有序轴和 RTL;稳定 Root 捕获指针,内容区/边框/ 先读 [COLOR-04](docs/migrations/COLOR-04-slider-picker-foundation.md)。颜色自定义 Track 和 native-channel 共用一个 token/原生 range;显示色与接受色分开,hue 的完整色环不得改变灰色 hue/alpha。完整精度序列化是私有 owner 证明,不提前承诺公开字段格式。退出观察弹层已接受的 open 状态,不能按被拒绝的关闭提案取消颜色事务;可选布尔 open 显式保留 undefined。 草稿 Escape 与弹层 Escape 分层,无草稿不拦截关闭。Popover 的 available-height 必须在真实长面板上核对,Dialog 内滚动同时保留外层箭头,不靠 docs 定位补丁。下一批公开 Slider 的依赖/范围见 [COLOR-05](docs/migrations/COLOR-05-slider-prompt.md);Picker/字段协议仍由集成人维护。 + +## COLOR-06 字段正式协议(2026-10-25) + +先读 [COLOR-06](docs/migrations/COLOR-06-field-protocol.md)。固定 npm 发布版本 RAC1.21.1/Stately3.50.0/Aria3.52.1 的通道字段继承 NumberField,不能用简表或旧夹具猜原生协议。自然步长显示/提交与完整接受颜色分开,percent 50% 提交0.5;未编辑不改颜色精度。Hex 为实际命名可见 input,合法部分草稿可进入程序化 FormData;Enter 先 commit 并保留原生提交。 + +Root/Group/Input 复用 choice/Form;Group 独立时是普通文本,不能污染外层 TextField。元数据预读不能冻结 Group 实际作用域插槽状态,也不执行未知组件 setup/render;未知包装的关键属性放 Root。输入事件在真实节点合并一次、先尊重可取消事件。内部组合与样式已有验证,尚未公开;Area/Swatch 后按 [COLOR-07](docs/migrations/COLOR-07-field-group-prompt.md) 交接13例和公共收尾,Picker 正式接口仍由集成人维护。 + +字段 Root 的 useAttrs 不当作可 watch 的响应式状态;仅 ARIA 或事件回调变化也要让真实 Input 更新。元数据预读与实际 Group scoped slot 渲染分开验证,不能因 SSR 标签规划而冻结 hover/focus 插槽。 diff --git a/apps/playground/src/App.vue b/apps/playground/src/App.vue index 26396d7..bf9fa61 100644 --- a/apps/playground/src/App.vue +++ b/apps/playground/src/App.vue @@ -1,5 +1,9 @@ - + + diff --git a/apps/playground/src/ColorFieldProtocolLab.vue b/apps/playground/src/ColorFieldProtocolLab.vue new file mode 100644 index 0000000..3db8d3c --- /dev/null +++ b/apps/playground/src/ColorFieldProtocolLab.vue @@ -0,0 +1,153 @@ + + + + 颜色字段正式协议 · 内部验收 + + 组合部件、原生关联、格式化通道、提交和共享颜色;公开导出与正式文档尚未接入。 + + + + 受控 Hex / 原生 Enter + + + 品牌颜色 + + # + + + 帮助 + + + Enter 提交已接受的颜色。 + + + + 提交 + 重置 + + {{ submitted }} + 接受值:{{ value?.toString("hex") ?? "empty" }} + + + + 百分数显示 / 小数提交 + + + 饱和度 + + 50% 提交为 0.5;聚焦后可滚轮增减。 + + + 提交通道 + {{ channelSubmitted }} + + + + 空值 / 必填 / 错误关联 + + + 必填颜色 + + 支持浅色和深色主题。 + + + + 校验 + 重置 + + + + + 独立输入组 + + Text + + suffix + + + + 正式字段接入 Picker + + + 重置 Picker + + + + + + diff --git a/docs/compatibility.md b/docs/compatibility.md index 76f5e99..3b1821f 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -230,3 +230,7 @@ Toast 11/11 与 Table 13/13 预览、各部件 Props、文档和默认源样式 ## COLOR-04 颜色轨道与 Picker 组合 私有 ColorSlider 自定义轨道、捕获/取消、方向/渐变与 Picker 共享 owner/Popover/唯一提交证明已通过重点验证,尚未公开这些组件。公共 Popover 已补可用高度与 Dialog 滚动;实际范围与待办见 [COLOR-04](migrations/COLOR-04-slider-picker-foundation.md)。 + +## COLOR-06 颜色字段组合协议 + +ColorField/ColorInputGroup 内部 Root/Input/前后缀、校验/关联、独立文本组及正式字段显示/提交协议已验证;未公开包根、variants 或正式13例。通道字段以自然步长提交归一化数字,Hex 使用命名可见输入,完整接受颜色独立保留精度。原始底座修正和实际差异见 [COLOR-06](migrations/COLOR-06-field-protocol.md)。 diff --git a/docs/decisions/color-foundation.md b/docs/decisions/color-foundation.md index 2f4962f..3a33b82 100644 --- a/docs/decisions/color-foundation.md +++ b/docs/decisions/color-foundation.md @@ -60,3 +60,7 @@ ColorArea CSS 已从基线准备,hv- 命名空间及 Apache 声明保留;未 ## COLOR-04 轨道与组合接续(2026-10-25) 自定义 Slider Track 通过 native-channel 私有 transaction 桥接复用同一 token;指针捕获/抓取偏移/步长和位置只从接受值派生。显示色单独计算,不改变模型。私有 Picker 在现有 Popover/Teleport 上证明共享 owner、单一完整精度序列化与接受关闭后取消;正式公开表单格式仍待核对。详见 [COLOR-04](../migrations/COLOR-04-slider-picker-foundation.md),普通公开 Slider 收尾可按 COLOR-05 交接。 + +## COLOR-06 字段组合接续(2026-10-25) + +正式字段使用 Root 颜色 owner + choice 文本字段上下文 + 唯一连接 Input;Group 独立时只使用已有 text control。固定发布版本审计发现通道继承 NumberField 的格式、步长、百分数提交及原生 Enter/wheel 协议,已与旧单输入夹具分开。接受颜色不由格式化反写,Hex 原生文本与通道隐藏数字的提交层分别管理;差异与交接见 [COLOR-06](../migrations/COLOR-06-field-protocol.md)。 diff --git a/docs/migration-handoff.md b/docs/migration-handoff.md index 7e856c1..8b48d75 100644 --- a/docs/migration-handoff.md +++ b/docs/migration-handoff.md @@ -342,3 +342,7 @@ DateField 七部件与 DateInputGroup 六部件、17 例已落地,范围和差 ### COLOR-04 轨道与弹层组合(2026-10-25) [COLOR-04](migrations/COLOR-04-slider-picker-foundation.md) 已验证自定义 Track 几何/捕获/方向/拒绝、显示色渐变与 Picker 共享 owner/关闭协议。不要再建拖动颜色缓存;同一 native range/token 覆盖指针/键盘/AT。Boolean open 省略时保持 undefined;仅接受的关闭取消手势;无文本草稿时 Escape 留给弹层。公共 Popover 高度约束在组件层修正,Dialog 滚动不应裁外层箭头。Area/Swatch 集成后可按 [COLOR-05](migrations/COLOR-05-slider-prompt.md) 交接 Slider 四部件/9例;正式字段提交/Picker 仍由集成人核对。 + +### COLOR-06 字段组合接续(2026-10-25) + +[COLOR-06](migrations/COLOR-06-field-protocol.md) 已实现内部 Root/Group/Input/前后缀、真实标签关联、Form/校验/reset、原生 Enter/wheel 与独立文本组。固定版本审计后,通道显示/提交按自然步长,percent 归一化,完整颜色接受值保留精度;Hex 实际命名 input 与旧夹具隐藏值不同。不要用最新 GitHub main 或演示简表代替继承协议,也不要把 Group 元数据预读变成静态作用域插槽。组件尚未从包根公开;普通13例/variants/Props/完整消费收尾见 [COLOR-07](migrations/COLOR-07-field-group-prompt.md),Picker 仍由集成人接续。 diff --git a/docs/migrations/COLOR-06-field-protocol.md b/docs/migrations/COLOR-06-field-protocol.md new file mode 100644 index 0000000..4fa3731 --- /dev/null +++ b/docs/migrations/COLOR-06-field-protocol.md @@ -0,0 +1,43 @@ +# COLOR-06:颜色字段组合与原生协议 + +2026-10-25,从同步后的 main `a41517a` 新建 `feat/color-field-protocol`。本轮完成 ColorField、ColorInputGroup、Input、Prefix、Suffix 的内部组合实现和协议验证;尚未从包根导出、生成 variants 或迁移正式组件页/13 例,不以私有完成推断公共组件已经验收。 + +## 固定版本审计 + +除固定 HeroUI ce90ea3 组件/CSS/中文文档外,直接读取其锁定的 npm 官方 tarball:React Aria Components **1.21.1**、React Stately **3.50.0**、React Aria **3.52.1**。源文件只审计,不安装或执行 React,也不复制 React hook。不能拿当日 GitHub main 或中文 API 简表代替安装基线的继承协议。 + +发布来源:[ColorField](https://unpkg.com/react-aria-components@1.21.1/dist/private/ColorField.mjs)、[通道字段状态](https://unpkg.com/react-stately@3.50.0/dist/private/color/useColorChannelFieldState.mjs)、[通道原生适配](https://unpkg.com/react-aria@3.52.1/dist/private/color/useColorChannelField.mjs)、[Hex 原生适配](https://unpkg.com/react-aria@3.52.1/dist/private/color/useColorField.mjs)。本地临时 `/private/tmp/heroui-color-field-source` 不是构建依赖。 + +| 层次 | 正式字段协议 | 与此前夹具的区别 | +| ---------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| 接受颜色 | 唯一不可变 Color owner;保留灰色色相和原始数值精度 | 不通过字段格式化写回颜色 | +| 通道显示 | 按自然步长吸附后格式化;percent/degree 含单位 | COLOR-03 的单输入夹具仍保留无单位草稿模式 | +| 通道原生值 | 唯一 hidden 输入提交吸附后的数值;saturation/lightness/brightness 除100,alpha 原本为0–1 | 50% 提交0.5;alpha .125 显示13%、提交.13,完整颜色仍保留.125 | +| Hex 原生值 | 实际可见 input 命名,提交当前文本;Enter/blur 规范化,拒绝时恢复父值 | 编辑中的合法部分文本可被程序化 FormData 读取,这是固定源码的原生结构;不能再宣称始终提交接受色 | +| Enter | 先提交/验证草稿,保留原生默认提交 | 不用 preventDefault 永久阻止表单提交 | +| 滚轮 | 仅实际输入聚焦且可编辑时处理纵向滚轮;deltaY>0 增加 | isWheelDisabled、取消事件、横向滚动保留 | + +格式化数字采用 Intl locale;严格解析不接受分组、指数和尾部垃圾。非空非法输入在 beforeinput/输入回退层拦截,合法部分草稿保留;IME 暂时容纳候选文本,结束后不合法则回到组合前草稿。Page/Shift 仍使用本库通道页步长,未承诺与 RAC 所有继承快捷键逐项相同。 + +## 组合与共享设施 + +- `color-field/useColorField.ts` 复用 `useColorState`、`useColorText` 与 `useChoiceField`。Choice 允许 text 语义并暴露 commitValidation,不新建 Form/error/reset 队列。Label 是真实原生 label,Description/FieldError IDs 与输入关联。 +- 已知 Group 只做初始 VNode 元数据预读,不挂载/执行用户组件 setup 或 render。实际 Group 插槽仍使用自己的动态 hover/focus 状态,不能把元数据预览当成 UI。slots 是纯渲染函数;未知自定义包装内部不会被任意执行,内部 Input 的关键 id/name/form/状态请放在 Root(必要时显式 aria-label),避免 SSR 渲染顺序差异。Label/Description/Error 放在 Root 或原生包装内,Group 内用于 Input/前后缀。 +- 一个 ColorField 连接一个真实 Input;注册/更新/卸载各自持有 token。已知组合可预先解析叶 input 的显式 id,保证位于前面的 label 在 SSR 就指向正确节点;动态 ID/name/form 和替换 Input 也回归。 +- 模型/validate 属于 ColorField Root;Input 与 Group 不另建颜色模型。Field 在 Picker 下省略自己的值时继承唯一 owner,自带值时独立。普通 TextField 不被颜色字段反向初始化或改写。 +- Root 与 Input 的原生事件合并到真实输入,外部处理器各执行一次且先于内部处理;Root 的 class/style/data 保留容器归属,控制 ARIA 路由到输入。disabled、readonly、required、Fieldset/首个 legend 语义复用现有设施;外部 form、取消 reset 和控制拒绝后原生值恢复复用 choice。 +- useAttrs 本身不能被当作可 watch 的响应式对象;Root 在更新前同步控制 ARIA/原生监听器快照,只有这些 fallthrough 属性变化时真实输入和 Group 也必须更新,不能缓存旧回调。 +- 独立 ColorInputGroupInput 使用已有 useTextControl,不要求 ColorField、Color 或 Picker,保留普通文本模型和原生属性。共享 useTextControl 补上对可取消输入事件 defaultPrevented 的检查;普通不可取消 input 事件仍遵循浏览器原生语义。 +- ColorField/Group CSS 从固定来源移植并加 hv- 前缀,保留主题数值和 Apache 声明。还没有公共 variants,也没有把这些内部实现冒充完整公开 Props/slots 或正式文档迁移。 + +## 有意保留的修正与边界 + +固定 RAC 通道 hidden 输入没有 disabled,且颜色 validate 没有完整传到 NumberField 路径;Vue 实现按原生表单要求排除禁用字段,并统一对接受的 Color/null 运行 validate。完整精度没有通过通道显示/提交往返;完整颜色提交证明仍由 Picker owner 的单一序列化层负责。 + +额外保持受控值高精度,而字段展示/数值提交遵循自然步长;不把变更完成信号或格式化草稿当作父已接受值。多输入并列在一个字段下、未知包装的叶属性预读、全 locale 分组数字、感知色名、全 RAC 状态对象与所有继承快捷键均未承诺。 + +## 验证与后续 + +新增27项行为/集成/实际水合、3项真实 Node SSR;全库与产物结果见 `docs/verification.md`。私有 Picker 已换成这套组合字段,原有10项 owner/Teleport/关闭/精度回归保留。 + +真实浏览器 `5176/?color-field-protocol` 核对原生 Enter 提交受控 Hex 与德语通道、聚焦滚轮、必填错误/焦点、命名唯一性和 Picker 字段同步。颜色字段正式 API 的普通收尾可以按 COLOR-07 交接;ColorPicker 公共接口与其余重要基建仍由集成人接续。没有完成公共颜色字段产物验收、完整读屏、物理触屏、逐像素或 Nuxt。 diff --git a/docs/migrations/COLOR-07-field-group-prompt.md b/docs/migrations/COLOR-07-field-group-prompt.md new file mode 100644 index 0000000..16dd7c6 --- /dev/null +++ b/docs/migrations/COLOR-07-field-group-prompt.md @@ -0,0 +1,13 @@ +# COLOR-07:其他 AI 的颜色字段公开收尾提示词 + +在 COLOR-02 Area/Swatch 及公共 Color/parseColor 已经合入 main 后执行。可由同一个 AI 在完成 COLOR-05 Slider 后顺序接续,避免多人并行改包根/样式入口。尚未完成原任务时不要擅自扩大范围。 + +请同步最新 main 后新开 `feat/color-07-field-group`。先读 AGENTS.md、迁移说明、COLOR-03/04/06;固定 HeroUI ce90ea3。消费 `color-field/` 内部组合实现与共享 color/field/choice 协议,不另建颜色/字段/reset 状态。不自行改内核以迎合演示;缺口交最小失败用例给集成人。 + +完成 ColorField/ColorFieldRoot、ColorInputGroup/ColorInputGroupRoot、Input/Prefix/Suffix 的公开命名部件/全部 Props/作用域插槽与包根导出,补 colorFieldVariants/colorInputGroupVariants 及样式导出。Group 保持独立普通输入能力;ColorField 使用真实 label/input 与已有 Description/FieldError/Form,字段值由 Root 管理。原始 CSS 已暂存,不改设计数值;通道格式/提交依据 COLOR-06,不能用旧单输入夹具的无单位草稿/原始通道提交作为正式契约。 + +按固定中文文档完成 basic、variants、on-surface、with-description、required、disabled、full-width、invalid、channel-editing、controlled、form-example、render-function、custom-styles 全13例。保留原文标题/顺序/API/主题;预览、高亮、复制来自同一 SFC,图标用 Tabler Vue,表格满宽换行。独立 ColorInputGroup 有公共导出,基线没有独立中文页面,不制造假官方页面。ColorPicker 不在本任务内。 + +公开前核对完整原生属性归属、事件取消/合并、表单 Enter、wheel、粘贴与 IME、模型优先级、required/disabled/readonly、Form 服务端错误、唯一 name 与外部 form/reset;未知包装的 SSR metadata 限制、自然步长显示/提交与原始颜色精度、Page/Shift 差异如实写入兼容矩阵。每个公开部件 Props 从包根可取,错误模型/通道/变体/validate 参数的类型反例必须真的失败。 + +运行行为/SSR/实际水合、13例共存/交互、文档/消费构建与独立 tarball 的 ESM/SSR/CSS、strict NodeNext/bundler 正反类型验收。浏览器只重点检查提交、焦点、滚轮和组合风险;不要逐页机械点。同步 compatibility/upstream/verification/本轮验收;完成后交集成人检查,不擅自合入 main。 diff --git a/docs/upstream.md b/docs/upstream.md index 13c40ff..e284d42 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -218,3 +218,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生 ## COLOR-04 颜色轨道与组合(2026-10-25) 固定 ce90ea3 ColorSlider/Picker、ColorSlider CSS/tv 及演示;CSS 加 hv- 前缀并保留 Apache 声明,单色渐变端帽改合法双色标并补透明棋盘。Adobe 当日 ColorSlider 的显示色和梯度语义仅作辅助审计,不复制 React hook;来源链接与公共 Popover 高度适配见 [COLOR-04](migrations/COLOR-04-slider-picker-foundation.md)。 + +## COLOR-06 字段组合(2026-10-25) + +固定 ce90ea3 ColorField/ColorInputGroup、对应 CSS/tv、中文文档与13例;CSS 加 hv- 前缀并保留 Apache 声明。直接审计 npm 官方 RAC1.21.1、Stately3.50.0、Aria3.52.1 tarball 中 ColorField、ColorChannelFieldState、ColorField/NumberField 原生协议,未安装/执行 React、未移植其 hook。发布文件链接、通道尺度与禁用/validate 修正见 [COLOR-06](migrations/COLOR-06-field-protocol.md)。 diff --git a/docs/verification.md b/docs/verification.md index 4d326c2..a1f02ac 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -938,3 +938,11 @@ Button/PopoverTrigger/Link/ToggleButtonGroup 源码及几何复核后,移除 - 库/样式/文档 SSR 与 playground 构建、Prettier 和 diff 空白检查通过;原有文档大 chunk 提示保留。独立 `/private/tmp/heroui-color-slider-consumer` 安装最终两份 tarball,新增暂存 Slider CSS/合法端帽/Popover 高度约束与无公开占位导出检查,并保留 Calendar/DateField/Select 的 ESM/SSR/CSS 与 strict NodeNext/bundler 类型正反例。 - 真实浏览器证明自定义横向/竖向/RTL/缩放边框/抓取偏移、拒绝后 Thumb 位置、8 change/1 changeEnd、Teleport 共享 owner/唯一命名提交、reset 与 Escape/恢复焦点。公共 Popover 从 top=-30 改为12,长 Dialog 内滚动后底部焦点字段保持可见;详见报告的实际数值与截图位置。 - 显示色与接受色分离、原节点捕获释放和接受关闭后取消均有回归。辅助全精度序列化不成为公开表单格式承诺;未验真机触屏、全 AT、多浏览器、逐像素、Nuxt。ColorSlider 的普通公开收尾可在 Area/Swatch 集成后交接 COLOR-05,字段/Picker 正式契约仍待集成人核对。 + +## COLOR-06 颜色字段组合协议(2026-10-25) + +- 从 main `a41517a` 新建 feat/color-field-protocol。新增 **27** 项字段/输入组行为与实际水合、**3** 项真实 Node SSR;最终全库 **86 文件 / 1051 项通过**。内部组合与限制见 [COLOR-06](migrations/COLOR-06-field-protocol.md),没有公共导出/variants/正式13例完成声明。 +- vue-tsc(含错误颜色模型/validate 参数与作用域插槽类型)、库/样式/文档 SSR、playground 构建通过;全仓 Prettier 与 diff 检查通过,原有文档大 chunk 提示保留。私有 Picker 已接入组合字段,原有10项 owner/Teleport/关闭/精度回归保留。 +- 最终 tarball 在 `/private/tmp/heroui-color-field-consumer` 独立安装,无源码 alias:新增字段/输入组 CSS 和没有提前公开占位的检查;Calendar/DateField/Select 的 ESM/SSR/CSS 与 strict NodeNext/bundler 类型正反例保留。这不证明私有字段的公共类型/产物已经验收,公开批次仍需单独的完整契约。 +- 真浏览器 5176 `?color-field-protocol` 验证受控 Hex 原生 Enter 提交 `#DDEEFF`、德语 `33,25%` 提交0.33、聚焦纵向滚轮50%→51%、必填错误聚焦/描述切换,以及 Picker 文本25%同步 Slider/完整颜色且只有一个 name=color。验收截图 `/private/tmp/heroui-color-field-protocol-review.png` 不参与构建。 +- 固定 RAC1.21.1/Stately3.50.0/Aria3.52.1 发布源码仅审计,未安装/执行 React;通道步长/百分数/Hex 原生草稿语义已与旧单输入夹具分开。Group 实际作用域插槽状态、Root attrs-only 更新、独立文本组和字段 owner 隔离均有回归。完整读屏、物理触屏、逐像素/全主题和 Nuxt 未验收。 diff --git a/package.json b/package.json index b8c2379..63b076e 100644 --- a/package.json +++ b/package.json @@ -15,8 +15,8 @@ "build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build", "typecheck": "vue-tsc --noEmit", "test": "vitest run", - "test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/calendar-view.test.ts tests/calendar.test.ts tests/calendar-demos.test.ts tests/range-calendar-foundation.test.ts tests/color-foundation.test.ts tests/color-foundation-probes.test.ts tests/color-input-foundation.test.ts tests/color-input-probes.test.ts tests/color-slider-foundation.test.ts tests/color-picker-composition.test.ts", - "test:ssr": "vitest run tests/ssr.test.ts tests/input-otp-ssr.test.ts tests/slider-foundation-ssr.test.ts tests/slider-ssr.test.ts tests/collection-foundation-ssr.test.ts tests/list-box-ssr.test.ts tests/select-ssr.test.ts tests/date-foundation-ssr.test.ts tests/date-field-ssr.test.ts tests/m35-m36-ssr.test.ts tests/calendar-ssr.test.ts tests/range-calendar-foundation-ssr.test.ts tests/color-foundation-ssr.test.ts tests/color-input-foundation-ssr.test.ts tests/color-slider-foundation-ssr.test.ts", + "test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/calendar-view.test.ts tests/calendar.test.ts tests/calendar-demos.test.ts tests/range-calendar-foundation.test.ts tests/color-foundation.test.ts tests/color-foundation-probes.test.ts tests/color-input-foundation.test.ts tests/color-input-probes.test.ts tests/color-slider-foundation.test.ts tests/color-picker-composition.test.ts tests/color-field-protocol.test.ts", + "test:ssr": "vitest run tests/ssr.test.ts tests/input-otp-ssr.test.ts tests/slider-foundation-ssr.test.ts tests/slider-ssr.test.ts tests/collection-foundation-ssr.test.ts tests/list-box-ssr.test.ts tests/select-ssr.test.ts tests/date-foundation-ssr.test.ts tests/date-field-ssr.test.ts tests/m35-m36-ssr.test.ts tests/calendar-ssr.test.ts tests/range-calendar-foundation-ssr.test.ts tests/color-foundation-ssr.test.ts tests/color-input-foundation-ssr.test.ts tests/color-slider-foundation-ssr.test.ts tests/color-field-protocol-ssr.test.ts", "format": "prettier --check .", "format:fix": "prettier --write .", "dev:playground": "pnpm build && pnpm --filter @heroui-vue/playground dev" diff --git a/packages/styles/components/color-field.css b/packages/styles/components/color-field.css new file mode 100644 index 0000000..98b9592 --- /dev/null +++ b/packages/styles/components/color-field.css @@ -0,0 +1,25 @@ +/* Adapted from HeroUI ce90ea3, Apache-2.0; see third-party/HEROUI-LICENSE. */ +/* ========================================================================== + ColorField - Form field for editing hex colors or individual color channels + ========================================================================== */ + +/* Base styles */ +.hv-color-field { + @apply flex flex-col gap-1; + + &[data-invalid="true"], + &[aria-invalid="true"] { + [data-slot="description"] { + @apply hidden; + } + } + + [data-slot="label"] { + @apply w-fit; + } +} + +/* Full width modifier */ +.hv-color-field--full-width { + @apply w-full; +} diff --git a/packages/styles/components/color-input-group.css b/packages/styles/components/color-input-group.css new file mode 100644 index 0000000..5c97f5a --- /dev/null +++ b/packages/styles/components/color-input-group.css @@ -0,0 +1,136 @@ +/* Adapted from HeroUI ce90ea3, Apache-2.0; see third-party/HEROUI-LICENSE. */ +/* ========================================================================== + ColorInputGroup - Input group for color field with prefix/suffix support + ========================================================================== */ + +/* Base styles */ +.hv-color-input-group { + @apply inline-flex h-9 items-center overflow-hidden rounded-field border bg-field text-sm text-field-foreground shadow-field outline-none; + border-width: var(--border-width-field); + border-color: var(--field-border); + + /** + * Transitions + * CRITICAL: motion-reduce must be AFTER transition for correct override specificity + */ + transition: + background-color 150ms var(--ease-smooth), + border-color 150ms var(--ease-smooth), + box-shadow 150ms var(--ease-out); + @apply motion-reduce:transition-none; + + /* Hover state */ + @media (hover: hover) { + &:hover:not(:focus-within), + &[data-hovered="true"]:not([data-focus-within="true"]) { + @apply bg-field-hover; + border-color: var(--field-border-hover); + } + } + + /* Focus within state */ + &[data-focus-within="true"], + &:focus-within { + @apply status-focused-field; + } + + /* Invalid state */ + &[data-invalid="true"] { + @apply status-invalid-field; + background-color: var(--field-focus); + border-color: var(--color-field-border-invalid); + } + + /* Disabled state */ + &[data-disabled="true"], + &[aria-disabled="true"] { + @apply status-disabled; + } +} + +/* ========================================================================== + Elements + ========================================================================== */ + +.hv-color-input-group__input { + @apply flex h-full flex-1 cursor-text items-center rounded-none border-0 bg-transparent px-3 py-2 text-base shadow-none outline-none sm:text-sm; + + /* Placeholder styling */ + &::placeholder { + @apply text-field-placeholder; + } + + /* Remove border radius on left side when prefix is present */ + .hv-color-input-group:has([data-slot="color-input-group-prefix"]) & { + @apply rounded-s-none ps-2; + } + + /* Remove border radius on right side when suffix is present */ + .hv-color-input-group:has([data-slot="color-input-group-suffix"]) & { + @apply rounded-e-none pe-2; + } + + /* Focus state - handled by group */ + &:focus, + &:focus-visible { + @apply outline-none; + } +} + +.hv-color-input-group__prefix { + @apply shrink-0 text-field-placeholder; + @apply ms-3 me-0 flex items-center; +} + +.hv-color-input-group__suffix { + @apply shrink-0 text-field-placeholder; + @apply me-3 flex items-center; +} + +/* ========================================================================== + Variant modifiers + ========================================================================== */ + +.hv-color-input-group--primary { + /* Default styles - primary variant uses the base field styling */ +} + +.hv-color-input-group--secondary { + @apply shadow-none; + background-color: var(--color-input-group-bg); + + --color-input-group-bg: var(--default); + --color-input-group-bg-hover: var(--default-hover); + --color-input-group-bg-focus: var(--default); + + @media (hover: hover) { + &:hover:not(:focus-within), + &[data-hovered="true"]:not([data-focus-within="true"]) { + background-color: var(--color-input-group-bg-hover); + } + } + + &:focus-within, + &[data-focus-within="true"] { + background-color: var(--color-input-group-bg-focus); + } + + /* Invalid state */ + &[data-invalid="true"] { + @apply status-invalid-field; + border-color: var(--color-field-border-invalid); + background-color: var(--color-input-group-bg-focus); + } + + [data-slot="color-input-group-input"] { + @apply bg-transparent; + } +} + +/* ========================================================================== + Full width modifier + ========================================================================== */ + +.hv-color-input-group--full-width { + @apply w-full; +} diff --git a/packages/styles/index.css b/packages/styles/index.css index 57ce2b5..d85b480 100644 --- a/packages/styles/index.css +++ b/packages/styles/index.css @@ -165,3 +165,6 @@ @import "./components/color-area.css" layer(components); @import "./components/color-slider.css" layer(components); + +@import "./components/color-field.css" layer(components); +@import "./components/color-input-group.css" layer(components); diff --git a/packages/vue/src/components/choice/shared.ts b/packages/vue/src/components/choice/shared.ts index 12e5bca..13f4f27 100644 --- a/packages/vue/src/components/choice/shared.ts +++ b/packages/vue/src/components/choice/shared.ts @@ -85,7 +85,7 @@ export function useChoiceField( props: ChoiceFieldProps, attrs: Record, options: { - kind: "group" | "toggle"; + kind: "text" | "group" | "toggle"; value: ComputedRef; validate?: (value: T) => ValidateResult; satisfied: () => boolean; @@ -271,6 +271,9 @@ export function useChoiceField( reset, invalidEvent, validity, + commitValidation: () => { + touched.value = true; + }, prepare, }; } diff --git a/packages/vue/src/components/color-field/ColorField.vue b/packages/vue/src/components/color-field/ColorField.vue new file mode 100644 index 0000000..ab7211c --- /dev/null +++ b/packages/vue/src/components/color-field/ColorField.vue @@ -0,0 +1,117 @@ + + + + + + + diff --git a/packages/vue/src/components/color-field/ColorInputGroup.vue b/packages/vue/src/components/color-field/ColorInputGroup.vue new file mode 100644 index 0000000..9eda339 --- /dev/null +++ b/packages/vue/src/components/color-field/ColorInputGroup.vue @@ -0,0 +1,78 @@ + + + + + + diff --git a/packages/vue/src/components/color-field/ColorInputGroupInput.vue b/packages/vue/src/components/color-field/ColorInputGroupInput.vue new file mode 100644 index 0000000..04798c3 --- /dev/null +++ b/packages/vue/src/components/color-field/ColorInputGroupInput.vue @@ -0,0 +1,127 @@ + + + element?.focus()) + : standalone?.onInvalid($event) + " + /> + diff --git a/packages/vue/src/components/color-field/ColorInputGroupPrefix.vue b/packages/vue/src/components/color-field/ColorInputGroupPrefix.vue new file mode 100644 index 0000000..92ba79b --- /dev/null +++ b/packages/vue/src/components/color-field/ColorInputGroupPrefix.vue @@ -0,0 +1,12 @@ + + + + + + diff --git a/packages/vue/src/components/color-field/ColorInputGroupSuffix.vue b/packages/vue/src/components/color-field/ColorInputGroupSuffix.vue new file mode 100644 index 0000000..a0c516a --- /dev/null +++ b/packages/vue/src/components/color-field/ColorInputGroupSuffix.vue @@ -0,0 +1,12 @@ + + + + + + diff --git a/packages/vue/src/components/color-field/context.ts b/packages/vue/src/components/color-field/context.ts new file mode 100644 index 0000000..90fa60f --- /dev/null +++ b/packages/vue/src/components/color-field/context.ts @@ -0,0 +1,53 @@ +import { + inject, + type ComputedRef, + type InjectionKey, + type ShallowRef, +} from "vue"; +import type { useChoiceField, ChoiceFieldProps } from "../choice/shared"; +import type { ColorModelProps, ColorState } from "../color/model"; +import type { ColorTextOptions, useColorText } from "../color/text"; +import type { Color } from "../color/value"; +import type { ValidateResult } from "../field/context"; +export interface ColorFieldProps + extends ColorModelProps, ColorTextOptions, ChoiceFieldProps { + as?: string; + fullWidth?: boolean; + autoFocus?: boolean; + autoComplete?: string; + isWheelDisabled?: boolean; + validate?: (value: Color | null) => ValidateResult; +} +export interface ColorFieldRenderState { + value: Color | null; + isDisabled: boolean; + isReadOnly: boolean; + isRequired: boolean; + isInvalid: boolean; + isFocused: boolean; + isFocusWithin: boolean; + isFocusVisible: boolean; + validationErrors: string[]; +} +export interface ColorFieldContext { + state: ColorState; + field: ReturnType>; + text: ReturnType; + input: ShallowRef; + channel: ComputedRef; + id: ComputedRef; + name: ComputedRef; + form: ComputedRef; + autoFocus: ComputedRef; + autoComplete: ComputedRef; + register: (token: symbol, attrs: Record) => void; + unregister: (token: symbol) => void; + connect: (token: symbol, input: HTMLInputElement | undefined) => void; + nativeAttrs: (attrs: Record) => Record; + wheel: (event: WheelEvent) => void; +} +export const colorFieldKey: InjectionKey = + Symbol("hv-color-field"); +export function useColorFieldContext() { + return inject(colorFieldKey, undefined); +} diff --git a/packages/vue/src/components/color-field/tree.ts b/packages/vue/src/components/color-field/tree.ts new file mode 100644 index 0000000..a5267d6 --- /dev/null +++ b/packages/vue/src/components/color-field/tree.ts @@ -0,0 +1,82 @@ +import { + cloneVNode, + Fragment, + isVNode, + type VNodeChild, + type VNode, +} from "vue"; +const metadata = [ + "id", + "name", + "form", + "disabled", + "readonly", + "readOnly", + "required", + "autofocus", + "autoFocus", + "autocomplete", + "autoComplete", + "aria-invalid", +] as const; +export function colorInputMetadata(props: Record) { + return Object.fromEntries( + metadata.filter((key) => key in props).map((key) => [key, props[key]]), + ); +} +/** Plan initial input metadata through known Group slots without mounting components. */ +export function prepareColorFieldTree( + nodes: VNodeChild[], + state: Record, +) { + let input: Record | undefined; + let hasLabel = false; + function walk(children: VNodeChild[]): VNodeChild[] { + return children.map((node) => { + if (!isVNode(node)) return node; + const type = node.type as { name?: string; __name?: string }; + const name = type.name ?? type.__name; + if (name === "Label") hasLabel = true; + if (name === "ColorInputGroupInput") + input = colorInputMetadata(node.props ?? {}); + if (name === "ColorInputGroup" || name === "ColorInputGroupRoot") { + const slots = node.children as + | { + default?: ( + state: Record, + ) => VNodeChild | VNodeChild[]; + } + | undefined; + if (slots?.default) { + const initial = { + isDisabled: state.isDisabled, + isInvalid: state.isInvalid, + isFocusWithin: false, + isHovered: false, + }; + const raw = slots.default(initial); + walk(Array.isArray(raw) ? raw : [raw]); + const clone = cloneVNode(node); + // Keep the real Group's reactive render state; a metadata preview is not its UI. + clone.children = { + ...slots, + default: (groupState: Record) => + slots.default!(groupState), + }; + return clone; + } + } + if ( + (node.type === Fragment || typeof node.type === "string") && + Array.isArray(node.children) + ) { + const clone = cloneVNode(node); + clone.children = walk(node.children as VNodeChild[]) as VNode[]; + return clone; + } + return node; + }); + } + const prepared = walk(nodes); + return { nodes: prepared, input, hasLabel }; +} diff --git a/packages/vue/src/components/color-field/useColorField.ts b/packages/vue/src/components/color-field/useColorField.ts new file mode 100644 index 0000000..3c12e99 --- /dev/null +++ b/packages/vue/src/components/color-field/useColorField.ts @@ -0,0 +1,213 @@ +import { + computed, + onBeforeUpdate, + provide, + reactive, + shallowRef, + toRefs, + watchEffect, + type VNodeChild, +} from "vue"; +import { useColorState } from "../color/model"; +import { useColorText } from "../color/text"; +import { useChoiceField } from "../choice/shared"; +import { disabledContextKey } from "../field/disabled"; +import { + colorFieldKey, + type ColorFieldProps, + type ColorFieldContext, +} from "./context"; +import { colorInputMetadata, prepareColorFieldTree } from "./tree"; +import type { Color } from "../color/value"; +import { useConfig } from "../../providers/context"; +const bool = (value: unknown) => value != null && value !== false; +/** Shared field owner and one connected input, with no second form/reset model. */ +export function useColorField( + props: ColorFieldProps, + attrs: Record, + change: (value: Color | null) => void, +) { + const planned = shallowRef>({}), + registered = shallowRef>({}); + const nativeEvents = new Set([ + "onBeforeinput", + "onKeydown", + "onKeyup", + "onInput", + "onBlur", + "onFocus", + "onWheel", + "onCompositionstart", + "onCompositionend", + "onPaste", + ]); + const pickNative = () => + Object.fromEntries( + Object.entries(attrs).filter( + ([key]) => key.startsWith("aria-") || nativeEvents.has(key), + ), + ); + const rootNative = shallowRef(pickNative()); + onBeforeUpdate(() => { + const next = pickNative(), + previous = rootNative.value; + if ( + Object.keys(next).length !== Object.keys(previous).length || + Object.keys(next).some((key) => next[key] !== previous[key]) + ) + rootNative.value = next; + }); + const leaf = computed(() => ({ ...planned.value, ...registered.value })); + let owner: symbol | undefined; + const input = shallowRef(); + const hasLabel = shallowRef(false), + config = useConfig(); + const metadata = reactive({ + ...toRefs(props), + isDisabled: computed( + () => !!props.isDisabled || !!props.disabled || bool(leaf.value.disabled), + ), + isReadOnly: computed( + () => + !!props.isReadOnly || bool(leaf.value.readonly ?? leaf.value.readOnly), + ), + }); + const state = useColorState(metadata, { + fallback: () => null, + inherit: true, + provide: true, + change, + }); + const effective = reactive({ + ...toRefs(props), + id: computed(() => + typeof leaf.value.id === "string" ? leaf.value.id : props.id, + ), + name: computed(() => + typeof leaf.value.name === "string" ? leaf.value.name : props.name, + ), + form: computed(() => + typeof leaf.value.form === "string" ? leaf.value.form : props.form, + ), + isRequired: computed(() => !!props.isRequired || bool(leaf.value.required)), + isDisabled: state.disabled, + isReadOnly: state.readOnly, + isInvalid: computed( + () => + !!props.isInvalid || + rootNative.value["aria-invalid"] === true || + rootNative.value["aria-invalid"] === "true" || + leaf.value["aria-invalid"] === true || + leaf.value["aria-invalid"] === "true", + ), + }); + const field = useChoiceField(effective, attrs, { + kind: "text", + value: state.value, + satisfied: () => state.value.value !== null, + requiredMessage: "请选择颜色。", + validate: (value) => props.validate?.(value), + }); + const text = useColorText(state, props, input, { + channelFormat: "unit", + submitOnEnter: true, + edit: field.edit, + reset: field.reset, + commitValidation: field.commitValidation, + }); + const context: ColorFieldContext = { + state, + field, + text, + input, + channel: computed(() => props.channel), + id: field.field.controlId, + name: computed(() => effective.name), + form: computed(() => effective.form), + autoFocus: computed( + () => + !!props.autoFocus || bool(leaf.value.autofocus ?? leaf.value.autoFocus), + ), + autoComplete: computed(() => + String( + leaf.value.autocomplete ?? + leaf.value.autoComplete ?? + props.autoComplete ?? + "off", + ), + ), + register(token, attrs) { + if (owner && owner !== token) + throw new Error("ColorField supports one ColorInputGroupInput."); + owner = token; + const next = colorInputMetadata(attrs); + if (JSON.stringify(next) !== JSON.stringify(registered.value)) + registered.value = next; + }, + unregister(token) { + if (owner !== token) return; + owner = undefined; + input.value = undefined; + registered.value = {}; + text.cancel(); + }, + connect(token, node) { + if (owner === token) input.value = node; + }, + nativeAttrs(own) { + const forwarded = rootNative.value; + const names: Record = { + hue: "色相", + saturation: "饱和度", + lightness: "明度", + brightness: "亮度", + red: "红色", + green: "绿色", + blue: "蓝色", + alpha: "透明度", + }; + const locale = props.locale ?? config?.locale.value ?? "en-US"; + return { + ...forwarded, + "aria-label": + own["aria-label"] ?? + attrs["aria-label"] ?? + (!hasLabel.value && + !own["aria-labelledby"] && + !attrs["aria-labelledby"] && + props.channel + ? locale.startsWith("zh") + ? names[props.channel] + : props.channel + : undefined), + }; + }, + wheel, + }; + provide(colorFieldKey, context); + provide(disabledContextKey, state.disabled); + watchEffect(() => field.validity(input.value), { flush: "sync" }); + function prepare(nodes: VNodeChild[], slotState: Record) { + const tree = prepareColorFieldTree(nodes, slotState); + hasLabel.value = tree.hasLabel; + const next = tree.input ?? {}; + if (JSON.stringify(next) !== JSON.stringify(planned.value)) + planned.value = next; + return field.prepare(tree.nodes); + } + function wheel(event: WheelEvent) { + if ( + event.defaultPrevented || + !input.value || + props.isWheelDisabled || + state.disabled.value || + state.readOnly.value || + input.value?.ownerDocument.activeElement !== input.value || + Math.abs(event.deltaY) <= Math.abs(event.deltaX) + ) + return; + event.preventDefault(); + text.adjust(event.deltaY > 0 ? 1 : -1); + } + return { ...context, prepare, wheel }; +} diff --git a/packages/vue/src/components/color/text.ts b/packages/vue/src/components/color/text.ts index 99cd291..dd5a331 100644 --- a/packages/vue/src/components/color/text.ts +++ b/packages/vue/src/components/color/text.ts @@ -23,11 +23,11 @@ export interface ColorTextOptions { locale?: string; } /** Strict localized decimal parsing; grouping, exponents and trailing garbage are rejected. */ -export function parseColorNumber( +function colorNumberText( text: string, locale: string, channel: ColorChannel, -): number | undefined { +): string | undefined { const formatter = new Intl.NumberFormat(locale, { useGrouping: false }); let raw = text.trim().replace(/[\u061c\u200e\u200f]/g, ""); for (let i = 0; i < 10; i++) @@ -47,7 +47,15 @@ export function parseColorNumber( raw = raw.slice(0, -1).trim(); } if (channel === "hue") raw = raw.replace(/°$/, "").trim(); - if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(raw)) return; + return raw; +} +export function parseColorNumber( + text: string, + locale: string, + channel: ColorChannel, +): number | undefined { + const raw = colorNumberText(text, locale, channel); + if (raw === undefined || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(raw)) return; const value = Number(raw); // Channel text displays alpha on the familiar 0–100 scale, independent of model alpha 0–1. return Number.isFinite(value) @@ -65,6 +73,9 @@ export function useColorText( options: { edit?: () => void; reset?: () => void; + channelFormat?: "plain" | "unit"; + submitOnEnter?: boolean; + commitValidation?: () => void; } = {}, ) { const config = useConfig(); @@ -76,9 +87,20 @@ export function useColorText( ? colorChannel(state.value.value, props.channel, props.colorSpace) : undefined, ); + const nativeChannelValue = computed(() => { + const d = descriptor.value; + if (!d) return undefined; + return options.channelFormat === "unit" + ? Number((Math.round(d.value / d.range.step) * d.range.step).toFixed(12)) + : d.value; + }); const formatted = computed(() => { if (!state.value.value) return ""; if (!props.channel) return state.value.value.toString("hex"); + if (options.channelFormat === "unit") + return descriptor + .value!.color.withChannelValue(props.channel, nativeChannelValue.value!) + .formatChannelValue(props.channel, locale.value); const value = descriptor.value!.value * (props.channel === "alpha" ? 100 : 1); return new Intl.NumberFormat(locale.value, { @@ -90,6 +112,28 @@ export function useColorText( const composing = shallowRef(false); const token = Symbol("color-text"); let compositionRevision = 0; + let compositionDraft = draft.value; + function validDraft(text: string) { + if (!props.channel) return /^#?[\da-f]{0,6}$/i.test(text); + const raw = colorNumberText(text, locale.value, props.channel); + return raw !== undefined && /^[+-]?\d*(?:\.\d*)?$/.test(raw); + } + function beforeinput(event: InputEvent) { + if ( + event.defaultPrevented || + event.isComposing || + composing.value || + options.channelFormat !== "unit" || + event.data == null + ) + return; + const target = event.target as HTMLInputElement; + const next = + target.value.slice(0, target.selectionStart ?? target.value.length) + + event.data + + target.value.slice(target.selectionEnd ?? target.value.length); + if (!validDraft(next)) event.preventDefault(); + } function restore() { draft.value = formatted.value; if (input.value) input.value.value = draft.value; @@ -100,7 +144,7 @@ export function useColorText( compositionRevision++; restore(); } - function parse() { + function parse(snap = true) { const text = draft.value.trim(); if (!text) return null; if (!props.channel) { @@ -112,11 +156,16 @@ export function useColorText( const value = parseColorNumber(text, locale.value, props.channel); if (value === undefined) return undefined; const base = state.value.value ?? parseColor("#000000"); - return colorChannel( - base, - props.channel, - props.colorSpace, - ).color.withChannelValue(props.channel, value); + const native = colorChannel(base, props.channel, props.colorSpace); + const number = + options.channelFormat === "unit" && snap + ? Number( + (Math.round(value / native.range.step) * native.range.step).toFixed( + 12, + ), + ) + : value; + return native.color.withChannelValue(props.channel, number); } function commit(event?: Event) { if (composing.value) return; @@ -150,7 +199,16 @@ export function useColorText( restore(); return; } - draft.value = (event.target as HTMLInputElement).value; + const target = event.target as HTMLInputElement; + if ( + options.channelFormat === "unit" && + !composing.value && + !validDraft(target.value) + ) { + target.value = draft.value; + return; + } + draft.value = target.value; options.edit?.(); } function keydown(event: KeyboardEvent) { @@ -166,8 +224,9 @@ export function useColorText( ) return; if (event.key === "Enter") { - event.preventDefault(); + if (!options.submitOnEnter) event.preventDefault(); commit(); + options.commitValidation?.(); return; } if (event.key === "Escape") { @@ -185,29 +244,52 @@ export function useColorText( : 0; if (!direction && event.key !== "Home" && event.key !== "End") return; event.preventDefault(); - const parsed = parse(); + adjust( + direction, + event.shiftKey || event.key.startsWith("Page"), + event.key === "Home" ? "min" : event.key === "End" ? "max" : undefined, + ); + } + function adjust(direction: number, page = false, boundary?: "min" | "max") { + if (state.disabled.value || state.readOnly.value || composing.value) return; + const parsed = parse(false); const base = parsed ?? state.value.value ?? parseColor("#000000"); let next; if (props.channel) { const d = colorChannel(base, props.channel, props.colorSpace); - const step = - event.shiftKey || event.key.startsWith("Page") - ? d.range.pageSize - : d.range.step; - const value = - event.key === "Home" + if ( + options.channelFormat === "unit" && + draft.value.trim() === formatted.value + ) + d.value = nativeChannelValue.value ?? d.value; + const step = page ? d.range.pageSize : d.range.step; + let value = + boundary === "min" ? d.range.minValue - : event.key === "End" + : boundary === "max" ? d.range.maxValue : d.value + direction * step; + if (options.channelFormat === "unit" && !boundary) { + const snapped = Number((Math.round(d.value / step) * step).toFixed(12)); + value = + direction > 0 + ? snapped > d.value + ? snapped + : snapped + step + : snapped < d.value + ? snapped + : snapped - step; + if (!state.value.value && !draft.value.trim()) + value = direction > 0 ? d.range.minValue : d.range.maxValue; + } next = d.color.withChannelValue(props.channel, Number(value.toFixed(12))); } else { const value = Number.parseInt(base.toString("hex").slice(1), 16); - const step = event.shiftKey || event.key.startsWith("Page") ? 10 : 1; + const step = page ? 10 : 1; const int = - event.key === "Home" + boundary === "min" ? 0 - : event.key === "End" + : boundary === "max" ? 0xffffff : Math.min(0xffffff, Math.max(0, value + direction * step)); next = parseColor(`#${int.toString(16).padStart(6, "0")}`); @@ -219,8 +301,10 @@ export function useColorText( } restore(); void nextTick(restore); + options.commitValidation?.(); } function compositionstart() { + compositionDraft = draft.value; composing.value = true; compositionRevision++; } @@ -228,7 +312,13 @@ export function useColorText( const revision = ++compositionRevision; // The Enter used to select an IME candidate must not also submit/commit. void nextTick(() => { - if (revision === compositionRevision) composing.value = false; + if (revision === compositionRevision) { + composing.value = false; + if (options.channelFormat === "unit" && !validDraft(draft.value)) { + draft.value = compositionDraft; + if (input.value) input.value.value = draft.value; + } + } }); } watch( @@ -268,7 +358,13 @@ export function useColorText( !state.value.value ? "" : props.channel - ? String(descriptor.value!.value) + ? String( + nativeChannelValue.value! / + (options.channelFormat === "unit" && + ["saturation", "lightness", "brightness"].includes(props.channel) + ? 100 + : 1), + ) : state.value.value.toString("hex"), ); return { @@ -279,6 +375,7 @@ export function useColorText( locale, composing, input: onInput, + beforeinput, commit, blur: (event?: Event) => { if (composing.value) cancel(); @@ -286,6 +383,7 @@ export function useColorText( }, cancel, keydown, + adjust, compositionstart, compositionend, }; diff --git a/packages/vue/src/components/field/useTextControl.ts b/packages/vue/src/components/field/useTextControl.ts index 2197422..a1bf23c 100644 --- a/packages/vue/src/components/field/useTextControl.ts +++ b/packages/vue/src/components/field/useTextControl.ts @@ -72,7 +72,7 @@ export function useTextControl( watch(element, (next) => field?.setControl(next), { flush: "post" }); function update(event: Event) { const next = (event.target as HTMLInputElement).value; - if (!disabled() && !readOnly()) { + if (!event.defaultPrevented && !disabled() && !readOnly()) { internal.value = next; field?.setValue(next); emit("update:modelValue", next); diff --git a/packages/vue/tests/fixtures/ColorPickerComposition.vue b/packages/vue/tests/fixtures/ColorPickerComposition.vue index 9588e32..8906d0d 100644 --- a/packages/vue/tests/fixtures/ColorPickerComposition.vue +++ b/packages/vue/tests/fixtures/ColorPickerComposition.vue @@ -17,7 +17,9 @@ import { import Boundary from "./ColorPickerBoundary"; import Area from "./ColorAreaFoundation.vue"; import Slider from "./ColorSliderFoundation.vue"; -import Input from "./ColorInputFoundation.vue"; +import ColorField from "../../src/components/color-field/ColorField.vue"; +import ColorInputGroup from "../../src/components/color-field/ColorInputGroup.vue"; +import ColorInputGroupInput from "../../src/components/color-field/ColorInputGroupInput.vue"; const props = withDefaults( defineProps< ColorModelProps & { @@ -90,8 +92,12 @@ defineExpose({ state }); - - + + + + + + @@ -113,11 +119,4 @@ defineExpose({ state }); flex-direction: column; gap: 16px; } -.color-picker-composition-panel [data-color-input] { - width: 100%; - padding: 8px 12px; - border: 1px solid var(--border); - border-radius: 12px; - background: var(--field-background); -} diff --git a/tests/color-field-protocol-ssr.test.ts b/tests/color-field-protocol-ssr.test.ts new file mode 100644 index 0000000..391e428 --- /dev/null +++ b/tests/color-field-protocol-ssr.test.ts @@ -0,0 +1,50 @@ +// @vitest-environment node +import { describe, it, expect } from "vitest"; +import { createSSRApp, defineComponent } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import ColorField from "../packages/vue/src/components/color-field/ColorField.vue"; +import ColorInputGroup from "../packages/vue/src/components/color-field/ColorInputGroup.vue"; +import ColorInputGroupInput from "../packages/vue/src/components/color-field/ColorInputGroupInput.vue"; +import { Label, Description, FieldError } from "../packages/vue/src/index"; +const components = { + ColorField, + ColorInputGroup, + ColorInputGroupInput, + Label, + Description, + FieldError, +}; +async function html(template: string) { + return renderToString( + createSSRApp(defineComponent({ components, template })), + ); +} +describe("composed color field actual Node SSR", () => { + it("plans an explicit leaf id before the preceding native label and field descriptions", async () => { + const result = await html( + 'ColorHint', + ); + expect(result).toContain('for="native"'); + expect(result).toContain('id="native"'); + expect(result).toContain("aria-describedby="); + expect(result.match(/name="color"/g)).toHaveLength(1); + expect(result).toContain('value="#123456"'); + }); + it("uses percent display and numeric form scale with one name, without browser globals", async () => { + const result = await html( + '', + ); + expect(result).toContain('value="50%"'); + expect(result).toContain('value="0.5"'); + expect(result.match(/name="saturation"/g)).toHaveLength(1); + expect(result).toContain('aria-label="saturation"'); + }); + it("keeps standalone group native attributes and excludes disabled channel submission", async () => { + const result = await html( + '', + ); + expect(result).toContain('value="plain"'); + expect(result).toContain('autocomplete="username"'); + expect(result).toContain('name="alpha" disabled'); + }); +}); diff --git a/tests/color-field-protocol.test.ts b/tests/color-field-protocol.test.ts new file mode 100644 index 0000000..8345c7a --- /dev/null +++ b/tests/color-field-protocol.test.ts @@ -0,0 +1,526 @@ +import { afterEach, describe, it, expect, vi } from "vitest"; +import { mount, flushPromises } from "@vue/test-utils"; +import { createSSRApp, defineComponent, shallowRef } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import ColorField from "../packages/vue/src/components/color-field/ColorField.vue"; +import ColorInputGroup from "../packages/vue/src/components/color-field/ColorInputGroup.vue"; +import ColorInputGroupInput from "../packages/vue/src/components/color-field/ColorInputGroupInput.vue"; +import Prefix from "../packages/vue/src/components/color-field/ColorInputGroupPrefix.vue"; +import Suffix from "../packages/vue/src/components/color-field/ColorInputGroupSuffix.vue"; +import { + Label, + Description, + FieldError, + Form, + TextField, + Fieldset, + Button, +} from "../packages/vue/src/index"; +import Picker from "../packages/vue/tests/fixtures/ColorPickerFoundation.vue"; +import { + parseColor, + type Color, +} from "../packages/vue/src/components/color/value"; +const components = { + ColorField, + ColorInputGroup, + ColorInputGroupInput, + Prefix, + Suffix, + Label, + Description, + FieldError, + Form, + TextField, + Fieldset, + Button, + Picker, +}; +const wrappers: ReturnType[] = []; +afterEach(() => { + wrappers.splice(0).forEach((w) => w.unmount()); + document.body.innerHTML = ""; + vi.restoreAllMocks(); +}); +function view(body: string, setup = () => ({})) { + const w = mount( + defineComponent({ + components, + setup, + template: body.trim().startsWith("${body}`, + }), + { attachTo: document.body }, + ); + wrappers.push(w); + return w; +} +function field(attrs = "", inputAttrs = "", extra = "") { + return `Color label#${extra}Color description`; +} +const input = (w: ReturnType) => + w.get("[data-slot=color-input-group-input]"); +const changes = (w: ReturnType) => + (w.getComponent(ColorField).emitted("change") ?? []).map( + ([v]) => v as Color | null, + ); +const data = (w: ReturnType) => + new FormData(w.get("form").element as HTMLFormElement).getAll("color"); +async function edit(w: ReturnType, value: string) { + await input(w).setValue(value); + await input(w).trigger("keydown", { key: "Enter" }); + await flushPromises(); +} +describe("color field composed protocol", () => { + it("associates a native label, description and exact input override before rendering", async () => { + const w = view(field('default-value="#123456"', 'id="leaf"')); + expect(w.get("label").attributes("for")).toBe("leaf"); + expect(input(w).attributes("id")).toBe("leaf"); + expect(input(w).attributes("aria-describedby")).toBe( + w.get("[data-slot=description]").attributes("id"), + ); + expect(w.get("[data-slot=color-input-group]").attributes("role")).toBe( + "presentation", + ); + expect(input(w).attributes("aria-label")).toBeUndefined(); + expect(data(w)).toEqual(["#123456"]); + }); + it("uses localized channel units and the upstream percent submission scale", async () => { + const w = view( + field( + 'channel="saturation" color-space="hsb" locale="de-DE" default-value="hsb(270,50%,50%)"', + ), + ); + expect(input(w).element.value).toBe("50 %"); + expect(data(w)).toEqual(["0.5"]); + await edit(w, "33,25%"); + expect(input(w).element.value).toBe("33 %"); + expect(data(w)).toEqual(["0.33"]); + expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270); + expect(w.findAll("input[name=color]")).toHaveLength(1); + }); + it("uses alpha percentage text but fractional submission, and hue degrees", async () => { + const w = view( + field('channel="alpha" default-value="hsba(270,0%,50%,.125)"'), + ); + expect(input(w).element.value).toBe("13%"); + expect(data(w)).toEqual(["0.13"]); + await edit(w, "25%"); + expect(data(w)).toEqual(["0.25"]); + expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270); + const hue = view( + field('channel="hue" color-space="hsb" default-value="hsb(270,0%,50%)"'), + ); + expect(input(hue).element.value).toBe("270°"); + await edit(hue, "271°"); + expect(data(hue)).toEqual(["271"]); + }); + it("preserves unedited precision despite a rounded localized presentation", async () => { + const w = view( + field( + 'channel="alpha" default-value="hsba(270,0%,50%,.123456789012345)"', + ), + ); + await input(w).trigger("keydown", { key: "Enter" }); + expect(changes(w)).toHaveLength(0); + expect(data(w)).toEqual(["0.12"]); + }); + it("restores rejected text and retries identical proposals", async () => { + const w = view( + field( + 'channel="saturation" color-space="hsb" model-value="hsb(270,50%,50%)"', + ), + ); + await edit(w, "70%"); + await edit(w, "70%"); + expect(changes(w)).toHaveLength(2); + expect(input(w).element.value).toBe("50%"); + expect(data(w)).toEqual(["0.5"]); + }); + it("keeps native hex drafts out of the accepted color until commit and restores on Escape", async () => { + const w = view(field('default-value="#123456"')); + await input(w).setValue("#ab"); + expect(data(w)).toEqual(["#ab"]); + expect(changes(w)).toHaveLength(0); + await input(w).trigger("keydown", { key: "Escape" }); + expect(input(w).element.value).toBe("#123456"); + await edit(w, "abc"); + expect(data(w)).toEqual(["#AABBCC"]); + }); + it("allows native Enter submission after committing while caller cancellation wins", async () => { + const cancel = shallowRef(true); + const w = view( + field( + 'default-value="#123456" @keydown="cancel&&$event.preventDefault()"', + ), + () => ({ cancel }), + ); + await input(w).setValue("abc"); + let e = new KeyboardEvent("keydown", { + key: "Enter", + bubbles: true, + cancelable: true, + }); + input(w).element.dispatchEvent(e); + await flushPromises(); + expect(changes(w)).toHaveLength(0); + cancel.value = false; + await flushPromises(); + e = new KeyboardEvent("keydown", { + key: "Enter", + bubbles: true, + cancelable: true, + }); + input(w).element.dispatchEvent(e); + await flushPromises(); + expect(e.defaultPrevented).toBe(false); + expect(data(w)).toEqual(["#AABBCC"]); + }); + it("chains root and input native event handlers exactly once before internal behavior", async () => { + const root = vi.fn(), + leaf = vi.fn((e: Event) => e.preventDefault()); + const w = view( + field('default-value="#123456" @keydown="root"', '@keydown="leaf"'), + () => ({ root, leaf }), + ); + await edit(w, "abc"); + expect(root).toHaveBeenCalledOnce(); + expect(leaf).toHaveBeenCalledOnce(); + expect(changes(w)).toHaveLength(0); + }); + it("wheels only a focused enabled field, respects horizontal scroll and isWheelDisabled", async () => { + const off = shallowRef(false); + const w = view( + field('default-value="#123456" :is-wheel-disabled="off"'), + () => ({ off }), + ); + await input(w).trigger("wheel", { deltaY: 1, deltaX: 0 }); + expect(changes(w)).toHaveLength(0); + input(w).element.focus(); + await input(w).trigger("wheel", { deltaY: 1, deltaX: 2 }); + expect(changes(w)).toHaveLength(0); + await input(w).trigger("wheel", { deltaY: 1, deltaX: 0 }); + expect(data(w)).toEqual(["#123457"]); + off.value = true; + await flushPromises(); + await input(w).trigger("wheel", { deltaY: 1, deltaX: 0 }); + expect(changes(w)).toHaveLength(1); + }); + it("required native/aria validation attaches visible error and resets without emitting", async () => { + const w = view(field("is-required")); + expect(input(w).element.required).toBe(true); + expect(input(w).element.checkValidity()).toBe(false); + await flushPromises(); + expect(w.get("[data-slot=field-error]").text()).toBe("请选择颜色。"); + const error = w.get("[data-slot=field-error]").attributes("id"); + expect(input(w).attributes("aria-describedby")).toContain(error); + await edit(w, "abc"); + expect(input(w).element.checkValidity()).toBe(true); + (w.get("form").element as HTMLFormElement).reset(); + await flushPromises(); + expect(input(w).element.value).toBe(""); + expect(w.find("[data-slot=field-error]").exists()).toBe(false); + expect(changes(w)).toHaveLength(1); + const aria = view(field('is-required validation-behavior="aria"')); + expect(input(aria).element.required).toBe(false); + expect(input(aria).attributes("aria-required")).toBe("true"); + expect(input(aria).element.checkValidity()).toBe(true); + expect(input(aria).attributes("aria-invalid")).toBe("true"); + }); + it("uses existing Form server errors and color validation, with generic field isolation", async () => { + const validate = vi.fn((value: Color | null) => + value?.toString("hex") === "#AABBCC" ? "不允许此颜色" : true, + ); + const w = view( + `${field('default-value="#123456" :validate="validate"')}`, + () => ({ validate }), + ); + expect(w.get("[data-slot=field-error]").text()).toBe("服务端错误"); + await edit(w, "abc"); + expect(w.get("[data-slot=field-error]").text()).toBe("不允许此颜色"); + expect(validate.mock.calls.at(-1)?.[0]).toBeInstanceOf(Object); + expect(input(w).element.checkValidity()).toBe(false); + }); + it("honors root/leaf and Fieldset disabled, readonly and later programmatic values", async () => { + const off = shallowRef(true), + value = shallowRef(parseColor("#123456")); + const w = view( + `${field(':model-value="value"')}`, + () => ({ off, value }), + ); + expect(input(w).element.disabled).toBe(true); + expect(data(w)).toEqual([]); + value.value = parseColor("#654321"); + await flushPromises(); + expect(input(w).element.value).toBe("#654321"); + off.value = false; + await flushPromises(); + expect(data(w)).toEqual(["#654321"]); + const ro = view(field('default-value="#123456"', "readonly")); + await edit(ro, "abc"); + expect(changes(ro)).toHaveLength(0); + expect(input(ro).element.readOnly).toBe(true); + }); + it("updates native leaf name/form/ID dynamically and respects canceled reset", async () => { + const external = document.createElement("form"); + external.id = "external"; + document.body.append(external); + const id = shallowRef("first"), + name = shallowRef("color"); + const w = view( + field('default-value="#123456"', ':id="id" :name="name" form="external"'), + () => ({ id, name }), + ); + id.value = "second"; + name.value = "other"; + await flushPromises(); + expect(w.get("label").attributes("for")).toBe("second"); + expect(new FormData(external).getAll("other")).toEqual(["#123456"]); + await edit(w, "abc"); + external.addEventListener("reset", (e) => e.preventDefault(), { + once: true, + }); + external.reset(); + await flushPromises(); + expect(input(w).element.value).toBe("#AABBCC"); + external.reset(); + await flushPromises(); + expect(input(w).element.value).toBe("#123456"); + }); + it("shares a Picker owner and does not mutate an enclosing TextField", async () => { + const outer = shallowRef("outer"); + const w = view( + `${field('channel="hue" color-space="hsb"')}`, + () => ({ outer }), + ); + await edit(w, "271°"); + expect(w.getComponent(Picker).emitted("change")).toHaveLength(1); + expect(changes(w)).toHaveLength(0); + expect(outer.value).toBe("outer"); + }); + it("keeps an independent group a regular text control and respects controlled rejection/reset", async () => { + const w = view( + 'Textsuffix', + ); + expect(w.get("[data-slot=color-input-group]").attributes("role")).toBe( + "group", + ); + await input(w).setValue("rejected"); + await flushPromises(); + expect(input(w).element.value).toBe("accepted"); + expect(data(w)).toEqual(["accepted"]); + (w.get("form").element as HTMLFormElement).reset(); + await flushPromises(); + expect(input(w).element.value).toBe("accepted"); + }); + it("focuses the input from plain affixes but keeps interactive suffix focus and focus-within state", async () => { + const w = view( + field( + 'default-value="#123456"', + "", + 'Action', + ), + ); + await w.get("[data-slot=color-input-group-prefix]").trigger("click"); + expect(document.activeElement).toBe(input(w).element); + const button = w.get("button").element; + button.focus(); + await w.get("button").trigger("click"); + expect(document.activeElement).toBe(button); + expect( + w.get("[data-slot=color-input-group]").attributes("data-focus-within"), + ).toBe("true"); + }); + it("hydrates prepared leaf ID and all real associations without replacing nodes", async () => { + const App = defineComponent({ + components, + template: `${field('default-value="#123456"', 'id="leaf"')}${field('channel="saturation" color-space="hsb" default-value="hsb(270,50%,50%)"', 'id="percent"')}`, + }); + const container = document.createElement("div"); + container.innerHTML = await renderToString(createSSRApp(App)); + document.body.append(container); + expect(container.querySelector("label")?.htmlFor).toBe("leaf"); + const nodes = [...container.querySelectorAll("input")]; + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}), + error = vi.spyOn(console, "error").mockImplementation(() => {}); + const app = createSSRApp(App); + app.mount(container); + await flushPromises(); + expect([...container.querySelectorAll("input")]).toEqual(nodes); + const ids = [...container.querySelectorAll("[id]")].map((n) => n.id); + expect(new Set(ids).size).toBe(ids.length); + expect(warn).not.toHaveBeenCalled(); + expect(error).not.toHaveBeenCalled(); + app.unmount(); + }); +}); +describe("color field ownership and native boundaries", () => { + it("switches channel/name mode with only one successful named input", async () => { + const channel = shallowRef<"saturation" | undefined>("saturation"); + const w = view( + field( + ':channel="channel" color-space="hsb" default-value="hsb(270,50%,50%)"', + ), + () => ({ channel }), + ); + expect(data(w)).toEqual(["0.5"]); + channel.value = undefined; + await flushPromises(); + expect(data(w)).toEqual(["#604080"]); + expect(w.findAll("input[name=color]")).toHaveLength(1); + channel.value = "saturation"; + await flushPromises(); + expect(data(w)).toEqual(["0.5"]); + }); + it("keeps boolean HTML attributes present, supports autofocus and joins explicit ARIA relationships", async () => { + const w = view( + field( + 'default-value="#123456"', + 'autofocus readonly="false" aria-labelledby="external-label" aria-describedby="external-description"', + ), + ); + expect(document.activeElement).toBe(input(w).element); + expect(input(w).element.readOnly).toBe(true); + expect(input(w).attributes("aria-labelledby")).toBe("external-label"); + expect(input(w).attributes("aria-describedby")).toContain( + "external-description", + ); + }); + it("restores raw controlled native input after canceled reset and a rejected clear", async () => { + const w = view(field('model-value="#123456"')); + await edit(w, ""); + expect(input(w).element.value).toBe("#123456"); + await input(w).setValue("#ab"); + const form = w.get("form").element as HTMLFormElement; + form.addEventListener("reset", (e) => e.preventDefault(), { once: true }); + form.reset(); + await flushPromises(); + expect(input(w).element.value).toBe("#ab"); + form.reset(); + await flushPromises(); + expect(input(w).element.value).toBe("#123456"); + expect(changes(w)).toHaveLength(1); + }); + it("does not submit disabled channel fields and still validates channel Color callbacks", async () => { + const off = shallowRef(false); + const validate = vi.fn(() => "通道错误"); + const w = view( + field( + 'channel="saturation" color-space="hsb" default-value="hsb(270,50%,50%)" :is-disabled="off" validation-behavior="aria" :validate="validate"', + ), + () => ({ off, validate }), + ); + expect(w.get("[data-slot=field-error]").text()).toBe("通道错误"); + expect(validate.mock.calls.length).toBeGreaterThan(0); + off.value = true; + await flushPromises(); + expect(data(w)).toEqual([]); + expect(input(w).element.disabled).toBe(true); + expect(w.find("[data-slot=field-error]").exists()).toBe(false); + }); + it("keeps standalone native attributes and honors canceled input in the shared text control", async () => { + const w = view( + '', + ); + expect(input(w).attributes("autocomplete")).toBe("current-password"); + expect(input(w).attributes("type")).toBe("password"); + expect(input(w).attributes("spellcheck")).toBe("true"); + input(w).element.value = "blocked"; + input(w).element.dispatchEvent( + new Event("input", { bubbles: true, cancelable: true }), + ); + await flushPromises(); + expect(input(w).element.value).toBe("original"); + expect( + w.getComponent(ColorInputGroupInput).emitted("update:modelValue"), + ).toBeUndefined(); + }); + it("does not commit during IME and replaces the input without stale ownership", async () => { + const show = shallowRef(true); + const w = view( + field('default-value="#123456"', ":key=\"show?'first':'second'\""), + () => ({ show }), + ); + await input(w).trigger("compositionstart"); + await input(w).setValue("abc"); + await input(w).trigger("keydown", { key: "Enter" }); + expect(changes(w)).toHaveLength(0); + const old = input(w).element; + show.value = false; + await flushPromises(); + expect(input(w).element).not.toBe(old); + expect(input(w).element.value).toBe("#123456"); + await edit(w, "abc"); + expect(data(w)).toEqual(["#AABBCC"]); + }); +}); + +describe("color field draft validation and step grid", () => { + it("filters invalid input without discarding the previous partial draft", async () => { + const w = view(field('default-value="#123456"')); + await input(w).setValue("#ab"); + await input(w).setValue("#abZ"); + expect(input(w).element.value).toBe("#ab"); + expect(changes(w)).toHaveLength(0); + await input(w).trigger("compositionstart"); + await input(w).setValue("颜色"); + await input(w).trigger("compositionend"); + await flushPromises(); + expect(input(w).element.value).toBe("#ab"); + const node = input(w).element; + node.setSelectionRange(3, 3); + const event = new InputEvent("beforeinput", { + bubbles: true, + cancelable: true, + data: "Z", + inputType: "insertText", + }); + node.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + }); + it("steps from accepted fractions onto the natural grid and starts empty channel values at the boundary", async () => { + const w = view( + field('channel="alpha" default-value="hsba(270,0%,50%,.125)"'), + ); + await input(w).trigger("keydown", { key: "ArrowUp" }); + expect(data(w)).toEqual(["0.14"]); + await input(w).trigger("keydown", { key: "ArrowDown" }); + expect(data(w)).toEqual(["0.13"]); + const empty = view(field('channel="saturation" color-space="hsb"')); + await input(empty).trigger("keydown", { key: "ArrowUp" }); + expect(data(empty)).toEqual(["0"]); + }); +}); +it("keeps Group scoped slot state reactive while planning the native label before SSR", async () => { + const w = view( + "Hover color{{isHovered?'hover':'rest'}}", + ); + expect(w.get("label").attributes("for")).toBe("rest-input"); + expect(w.get("[data-slot=color-input-group-suffix]").text()).toBe("rest"); + await w.get("[data-slot=color-input-group]").trigger("pointerenter"); + expect(w.get("[data-slot=color-input-group-suffix]").text()).toBe("hover"); + expect(input(w).attributes("id")).toBe("hover-input"); + expect(w.get("label").attributes("for")).toBe("hover-input"); +}); +it("refreshes root ARIA and native listeners even when only fallthrough attrs change", async () => { + const invalid = shallowRef(false), + label = shallowRef("first label"), + handler = shallowRef((event: Event) => event.preventDefault()); + const w = view( + field( + 'default-value="#123456" :aria-invalid="invalid" :aria-label="label" @keydown="handler"', + ), + () => ({ invalid, label, handler }), + ); + expect(input(w).attributes("aria-label")).toBe("first label"); + invalid.value = true; + label.value = "second label"; + handler.value = () => {}; + await flushPromises(); + expect(input(w).attributes("aria-invalid")).toBe("true"); + expect(input(w).attributes("aria-label")).toBe("second label"); + expect( + w.get("[data-slot=color-input-group]").attributes("data-invalid"), + ).toBe("true"); + await edit(w, "abc"); + expect(changes(w)).toHaveLength(1); +}); diff --git a/tests/package/README.md b/tests/package/README.md index 92e2b06..d963638 100644 --- a/tests/package/README.md +++ b/tests/package/README.md @@ -33,3 +33,5 @@ DATE-04 提取共享 Calendar 视图并完成私有范围内核,公共 RangeCa COLOR-01 增加 `consume-color-foundation.mjs`:只验证准备好的 Area CSS 和没有提前暴露公共占位。独立目录 `/private/tmp/heroui-color-foundation-consumer` 同时运行旧 Calendar/DateField/Select 的运行与双解析模式类型回归。新颜色实现目前私有,其正反类型在 `tests/types/color-foundation.ts` 执行;公开批次必须另加自己的完整 ESM/SSR/Props/events/slots 产物契约。 COLOR-04 增加 `consume-color-slider-foundation.mjs`,在 `/private/tmp/heroui-color-slider-consumer` 用最终两份 tarball 验证暂存 Slider CSS、端帽变量、公共 Popover 高度/滚动约束与无公共颜色占位导出,同时保留 Calendar/DateField/Select 的 ESM/SSR/CSS 和 strict NodeNext/bundler 正反类型回归。私有 Slider/Picker 的实际交互/SSR/水合在工作区验收,公开组件仍需另写完整产物契约。 + +COLOR-06 增加 `consume-color-field-protocol.mjs`,在 `/private/tmp/heroui-color-field-consumer` 验证两份最终 tarball 的字段/输入组暂存 CSS 与没有提前公开占位;同时保留 Calendar/DateField/Select 的 ESM/SSR/CSS 和 strict NodeNext/bundler 类型正反例。组合字段当前内部实现,其 Props/slots 行为与 SSR/水合在工作区测试;COLOR-07 公共批次须补完整产物契约。 diff --git a/tests/package/consume-color-field-protocol.mjs b/tests/package/consume-color-field-protocol.mjs new file mode 100644 index 0000000..266efbf --- /dev/null +++ b/tests/package/consume-color-field-protocol.mjs @@ -0,0 +1,21 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import * as ui from "@heroui-vue/components"; +const css = fs.readFileSync( + new URL(import.meta.resolve("@heroui-vue/styles/css")), + "utf8", +); +for (const name of [ + ".hv-color-field", + ".hv-color-input-group", + ".hv-color-input-group__input", + ".hv-color-input-group--secondary", + ".hv-color-input-group__prefix", + ".hv-color-input-group__suffix", +]) + assert.ok(css.includes(name), name); +for (const name of ["ColorField", "ColorInputGroup", "ColorPicker"]) + assert.equal(name in ui, false); +console.log( + "Color field protocol styles present; unfinished public contracts stay private.", +); diff --git a/tests/types/color-foundation.ts b/tests/types/color-foundation.ts index 7ae39e1..c85e39a 100644 --- a/tests/types/color-foundation.ts +++ b/tests/types/color-foundation.ts @@ -55,3 +55,20 @@ const invalidOrientation: ColorSliderOptions = { }; void verticalSlider; void invalidOrientation; + +import type { ColorFieldProps } from "../../packages/vue/src/components/color-field/context"; +const field: ColorFieldProps = { + modelValue: color, + channel: "alpha", + validate: (value) => + value?.getChannelValue("alpha") === 0 ? "transparent" : true, +}; +const wrongValidator: ColorFieldProps = { + // @ts-expect-error invalid validation argument type + validate: (value: number) => (value > 0 ? true : "invalid"), +}; +// @ts-expect-error no numeric color models +const wrongFieldModel: ColorFieldProps = { modelValue: 123 }; +void field; +void wrongValidator; +void wrongFieldModel;
+ 组合部件、原生关联、格式化通道、提交和共享颜色;公开导出与正式文档尚未接入。 +