feat: establish shared color channel and text input protocols

This commit is contained in:
maoyingjie
2026-10-25 14:20:12 +08:00
parent 6b8501456d
commit a042f5c44c
19 changed files with 1389 additions and 3 deletions
+6
View File
@@ -502,3 +502,9 @@ DateField/DateInputGroup 已公开,先读[DATE-02 报告](docs/migrations/DATE
Area 覆盖所有有序轴和 RTL;稳定 Root 捕获指针,内容区/边框/分别缩放与抓取偏移一起验。左右 X、上下 Y、Home/End X 页步长、PageUp/Down Y 页步长,依据通道元数据移动对应原生焦点;两个真实 range 保持单一 Tab 入口,step=any 不应破坏键盘步长。xName/yName/form 和受控 reset 后真实 input.value 不遗漏。
后续可按 [COLOR-02](docs/migrations/COLOR-02-area-swatch-prompt.md) 交接公开 Area/Swatch 与 14 例,只消费共享内核;真实缺口交失败用例给集成人。Color 辅助 API 不冒充 RAC 全接口,全 locale/感知色名、物理触屏、读屏、Nuxt 等验收边界保留说明。
## COLOR-03 输入协议接续(2026-10-25)
先读 [COLOR-03](docs/migrations/COLOR-03-input-foundation.md)。通道数值和文本草稿共用接受值 owner;禁止用 Reka 的乐观 ColorSlider ref 或 ColorField 的 hex 回传再建颜色模型。alpha 显示百分数、模型小数;未编辑的格式化草稿不得反向量化原始模型。IME、严格 locale 解析、拒绝/重试和取消原生事件分别回归。
同一真实 input 只绑定当前模式的控制器/reset,inactive 控制器不得覆盖文本。字段校验与 reset 复用 choice/Form;夹具的 hex/原始通道提交不是最终公开格式。native range 验证不等于自定义 Track/Thumb 的方向/几何/捕获通过,正式 Slider/Field/Picker 仍由集成人完成高风险接入后再交普通收尾。
+6 -1
View File
@@ -1,5 +1,9 @@
<script setup lang="ts">
import { ref } from "vue";
import ColorInputFoundationLab from "./ColorInputFoundationLab.vue";
const colorInputFoundation =
typeof window !== "undefined" &&
new URLSearchParams(window.location.search).has("color-input-foundation");
import ColorFoundationLab from "./ColorFoundationLab.vue";
const colorFoundation =
typeof window !== "undefined" &&
@@ -39,7 +43,8 @@ function save() {
}
</script>
<template>
<ColorFoundationLab v-if="colorFoundation" />
<ColorInputFoundationLab v-if="colorInputFoundation" />
<ColorFoundationLab v-else-if="colorFoundation" />
<RangeCalendarFoundationLab v-else-if="rangeFoundation" />
<SelectLifecycle v-else-if="selectLifecycle" />
<ScrollTabsLab v-else-if="scrollTabsLab" />
@@ -0,0 +1,144 @@
<script setup lang="ts">
import { shallowRef } from "vue";
import Picker from "../../../packages/vue/tests/fixtures/ColorPickerFoundation.vue";
import Area from "../../../packages/vue/tests/fixtures/ColorAreaFoundation.vue";
import Input from "../../../packages/vue/tests/fixtures/ColorInputFoundation.vue";
import { Button } from "@heroui-vue/components";
const changes = shallowRef(0),
ends = shallowRef(0),
rejected = shallowRef(0);
</script>
<template>
<main class="color-input-lab">
<h1>颜色输入协议 · 私有基建</h1>
<p>
原生滑条用于验证事务和接受值;正式 ColorSlider 的轨道、Thumb
和视觉仍待接入。
</p>
<div class="color-input-grid">
<section id="shared-input">
<h2>共享颜色 / 保留灰色色相</h2>
<form>
<Picker
default-value="hsb(270,0%,50%,.125)"
v-slot="{ value }"
@change="changes++"
@change-end="ends++"
>
<Area aria-label="Shared area" />
<label>
色相
<Input mode="range" channel="hue" aria-label="Hue" />
</label>
<label>
透明度(de-DE)
<Input
channel="alpha"
name="alpha"
locale="de-DE"
aria-label="Alpha"
/>
</label>
<label>
Hex
<Input name="hex" aria-label="Hex" />
</label>
<output>{{ value?.toString("hsba") }}</output>
</Picker>
<output>change {{ changes }} / changeEnd {{ ends }}</output>
<Button type="reset" variant="secondary">重置</Button>
</form>
</section>
<section id="rejected-input">
<h2>受控拒绝 / 相同提案可重试</h2>
<Picker
model-value="hsb(270,0%,50%,.125)"
v-slot="{ value }"
@change="rejected++"
>
<label>
色相
<Input mode="range" channel="hue" aria-label="Rejected hue" />
</label>
<label>
透明度
<Input channel="alpha" aria-label="Rejected alpha" />
</label>
<label>
Hex
<Input aria-label="Rejected hex" />
</label>
<output>{{ value?.toString("hsba") }}</output>
</Picker>
<output>提案 {{ rejected }}</output>
</section>
<section id="validated-input">
<h2>原生表单 / 必填 / 重置</h2>
<form @submit.prevent>
<Input name="color" aria-label="Required color" is-required />
<div class="color-input-actions">
<Button type="submit">校验</Button>
<Button type="reset" variant="secondary">重置</Button>
</div>
</form>
</section>
</div>
</main>
</template>
<style>
.color-input-lab {
padding: 32px;
min-height: 100vh;
background: var(--background);
color: var(--foreground);
font-family: Inter, sans-serif;
}
.color-input-lab h1 {
font-size: 24px;
font-weight: 600;
margin-bottom: 8px;
}
.color-input-lab p {
color: var(--muted);
margin-bottom: 24px;
}
.color-input-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 24px;
}
.color-input-grid section {
padding: 24px;
border: 1px solid var(--border);
border-radius: 20px;
}
.color-input-grid h2 {
font-size: 16px;
font-weight: 600;
margin-bottom: 16px;
}
.color-input-grid label,
.color-input-grid output {
display: block;
margin: 12px 0;
}
.color-input-grid input[type="text"] {
width: 100%;
padding: 8px 12px;
background: var(--field-background);
border: 1px solid var(--border);
border-radius: 12px;
}
.color-input-grid input[type="range"] {
width: 100%;
accent-color: var(--accent);
}
.color-input-grid [data-field-error] {
color: var(--danger);
}
.color-input-actions {
display: flex;
gap: 12px;
margin-top: 16px;
}
</style>
+4
View File
@@ -222,3 +222,7 @@ Toast 11/11 与 Table 13/13 预览、各部件 Props、文档和默认源样式
## COLOR-01 颜色基建
颜色值、接受值/继承 owner、二维交互与梯度已由私有夹具验证;不表示公开组件或 React Stately Color 全 API 完成。范围和限制见 [COLOR-01](migrations/COLOR-01-foundation.md),可交接的 Area/Swatch 公共迁移见 [COLOR-02](migrations/COLOR-02-area-swatch-prompt.md)。
## COLOR-03 颜色输入基建
共享通道解析、原生 range 事务及文本草稿/IME/locale/校验/reset 已由私有夹具验证,没有公开 ColorSlider/Field/InputGroup/Picker。自定义轨道、正式字段提交格式和 Picker 组合仍待接续;准确范围见 [COLOR-03](migrations/COLOR-03-input-foundation.md)。
+4
View File
@@ -52,3 +52,7 @@ Area 的 xName/yName/form 使用两个真实 range 提交,消费既有 useChoi
ColorAreaFoundation / ColorPickerFoundation 是 tests/fixtures 下的私有集成证明。后者用同一 owner 联动 Area、色相、文本、预览、Popover 和一个可选隐藏提交值;隐藏值显式采用 hexa,属于八位序列化,不能声称它保留任意浮点 alpha,也不是公开 ColorField/Picker 的最终序列化契约。未来字段仍核对基线并复用本库 field/Form。
ColorArea CSS 已从基线准备,hv- 命名空间及 Apache 声明保留;未公开 ColorArea/ColorPicker/parseColor。完整 props/slots、variants、locale 文案、色名、文档/预览和产物契约在公开迁移时单独验收。真实浏览器只验桌面关键操作;没有完成物理触屏、全读屏、全浏览器、Nuxt 或自动像素对比。
## COLOR-03 输入协议接续(2026-10-25)
通道解析/空间选择、原生 range 事务和文本草稿已作为私有层接入同一接受值 owner,详见 [COLOR-03](../migrations/COLOR-03-input-foundation.md)。不使用 Reka ColorSlider 的内部乐观颜色缓存或 ColorField 的 hex 发值作为本库状态源。草稿不参与提交,未修改的格式化输入不量化模型,alpha 显示/模型尺度明确转换。当前 native range 不是最终 Track 几何实现;私有夹具的提交格式不提前成为公共 API。
+4
View File
@@ -334,3 +334,7 @@ DateField 七部件与 DateInputGroup 六部件、17 例已落地,范围和差
不能让子控件各持 hex 副本;灰色 hue、alpha、父拒绝后的坐标/原生值、原 owner token 和兄弟禁用隔离要一起验。不要照搬 Reka 默认键盘、alpha 单位或渐变 fallback;也不要从文档表格漏掉 xName/yName/form。原生 range 不能将模型浮点值擅自对齐成整数,单步/pageSize 与显示格式分别管理。
公共任务只声明已实现的 Color 方法/格式;感知自动色名/全 locale 字典有明确差异。ColorSlider/Field/InputGroup/Picker/SwatchPicker 继续按输入协议与依赖关系接续,私有组合夹具不能作为公共完成证明。
### COLOR-03 私有输入协议(2026-10-25)
[报告](migrations/COLOR-03-input-foundation.md) 已验证共享通道、文本草稿、IME、locale、受控拒绝/重试与现有 Form/reset。禁止把安装版 hex 回传作为颜色状态源,也不要让 inactive range 控制器改文本 input。alpha 显示百分数、模型小数;未编辑草稿保留高精度接受值。当前没有公共 Slider/Field/Picker,native range 不代替自定义轨道验收;集成人继续几何/Picker/公共提交协议,COLOR-02 Area/Swatch 范围不变。
@@ -0,0 +1,33 @@
# COLOR-03:颜色通道与文本输入基建
日期:2026-10-25。从 main `6b85014` 新建 `feat/color-input-foundation`。本轮继续集成人负责的复杂共享协议,没有新增公共 ColorSlider、ColorField、ColorInputGroup 或 ColorPicker,也不替代 COLOR-02 的 Area/Swatch 任务。
## 已实现的私有协议
- `color/channel.ts` 统一颜色空间选择、数值、范围、步长和 locale 标签。专属通道修正到对应空间;hue/saturation 优先当前 polar 空间;alpha 直接保留原空间,不经 RGB/hex 往返。
- `color/native-channel.ts` 是真实 native range 与 AT 输入桥接,复用 COLOR-01 接受值和 token。连续键盘按下共用事务,完成时报告最后提案;取消、窗口失焦、禁用、外部替换、引用变化和卸载清理。左右键遵循 RTL,上下键增减,Home/End 到边界,Page/Shift 使用通道页步长;真实 input 使用 step=any 保留已接受分数。
- `color/text.ts` 维护文本草稿,Enter/blur 提交,Escape 恢复。草稿和接受颜色分开,拒绝后恢复原生 input.value,相同提案下一次可重试;取消原生事件不触发内部提交。空文本提议 null,非法/不完整文本恢复接受值。
- 默认 hex 编辑范围为可选 # 的三/六位,不接受透明 hex 或任意 CSS 文本。这是字段输入契约,不缩小私有 parseColor 的解析范围。未修改的 hex 不抹掉原有 gray hue/alpha;未修改的格式化数值不反向量化高精度模型。
- 通道草稿使用 locale 的数字、负号和小数点;拒绝指数、分组和尾部垃圾。接受百分数通道的 %、hue 的 °;alpha 显示 0–100,模型保持 0–1。IME 候选 Enter 不提交,composition 中 blur 放弃草稿。
- 私有 `ColorInputFoundation.vue` 接入现有 `useChoiceField` / `useChoiceForm`,验证 required、自定义/服务端错误、aria 验证模式、disabled/readonly、取消 reset、外部 form。文本和 range 模式只为活动真实输入绑定控制器/reset,不能两个控制器轮流改同一输入。
- Picker/Area/通道/文本只通过一个接受值 owner 共享,字段自行提供 model/default 时成为独立 owner。子控件卸载或禁用不能取消兄弟事务。
## 底座与来源
固定 HeroUI ce90ea3 的 ColorSlider、ColorField、ColorInputGroup 源码、中文文档及演示用于范围核对。本轮不移植其 CSS 或 React hook。安装版 Reka 2.11 的公开组件探针证明:ColorField polar 通道更新发出八位 hex,任意 alpha 被八位量化;ColorSlider 父拒绝后仍呈现内部乐观值。因此仅消费现有纯颜色转换,输入直接适配共享 owner。
[Adobe 当日 useColorFieldState](https://github.com/adobe/react-spectrum/blob/main/packages/react-stately/src/color/useColorFieldState.ts) 仅辅助核对 hex 的草稿/提交和整数增减语义,不代替固定 HeroUI 的最终公共 API。通道输入及原生提交格式仍需在公共组件迁移前完成基线逐项审计。
## 验证
- 新增 26 项行为/集成/实际 jsdom 水合,2 项安装版探针和 2 项真实 Node SSR。最终全库 **81 文件 / 992 项通过**。
- 类型正反例覆盖通道必填、未知通道和未知空间;vue-tsc、库/样式/文档 SSR 构建通过,文档原有大 chunk 提示保留。
- 真浏览器 `5176/?color-input-foundation`:native track 点击/键盘增减与灰色 hue 同步;德语 alpha 输入 `33,25%` 接受为 `.3325`;同一拒绝提案重复两次,接受颜色不变;真实拒绝拖动后滑条回到 270;必填错误聚焦字段;原生 reset 同时恢复 Area/滑条/文本且不新增 change。
- 私有验收截图 `/private/tmp/heroui-color-input-foundation-review.png` 不参与构建。没有新增依赖,没有改公共包根契约;本轮未重复执行独立 tarball 安装,不冒充公共颜色组件产物验收。
## 下一步仍由集成人处理
1. ColorSlider 自定义 Track/Thumb 的内容区几何、边框/缩放/抓取偏移、方向、捕获/取消、梯度和边帽。native range 的浏览器验证不证明自定义轨道已完成。
2. ColorPicker 的正式 owner/字段/弹层组合及唯一原生提交层。原有私有 Picker 的八位 hexa 提交仍只是证明,不能成为精度承诺。
3. 公共 ColorField 的名称提交格式、标签/描述/错误插槽与独立 ColorInputGroup 协议,逐项核对固定基线后交普通样式/示例收尾;当前私有隐藏字段按 hex 或原始通道数值(alpha 为 0–1)提交,是验收夹具选择,不提前声明最终公开格式。
4. 几何与公共契约稳定后,再交接 Slider/Field/Group 的样式、公开部件/类型及完整正式演示。物理触屏、完整读屏、全浏览器、逐像素和 Nuxt 均未验收。
+4
View File
@@ -210,3 +210,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生
## COLOR-01 颜色基建(2026-10-25)
固定 ce90ea3 的 color-area/picker、颜色系列组件/API、同名 CSS/tv、中文 Area/Swatch 各 7 例。ColorArea CSS 加 hv- 前缀,保留 Apache-2.0 声明。Reka 2.11 公开纯颜色转换用于私有适配,未复制其源码或修改安装包;Adobe 官方 ColorArea/Color 的当日语义审计仅作辅助,不替代固定基线。数学适配、元数据、来源链接和实际限制见 [颜色决策](decisions/color-foundation.md) 与 [COLOR-01](migrations/COLOR-01-foundation.md)。
## COLOR-03 颜色输入基建(2026-10-25)
核对固定 ce90ea3 ColorSlider/Field/InputGroup、中文文档及示例;安装版 Reka 2.11 的 Field/Slider 公开探针记录 hex 量化/乐观值差异。仅新增本库私有输入适配,未复制底座 hook/CSS。Adobe 当日 useColorFieldState 的草稿/整数步进语义为辅助参考,链接与边界见 [COLOR-03](migrations/COLOR-03-input-foundation.md)。
+6
View File
@@ -925,3 +925,9 @@ Button/PopoverTrigger/Link/ToggleButtonGroup 源码及几何复核后,移除
- 真浏览器 5176 `?color-foundation` 验证 224×224、抓取偏移拖至 75%/75%、多次 change / 一次 changeEnd、受控父拒绝保持 50%/50%、灰色 hue/alpha、交换轴/RTL、Y hue 梯度、二维按键和单一 Tab 入口、原生 reset,以及 Teleport 内外共享值/Esc/焦点恢复。最终截图为临时 `/private/tmp/heroui-color-foundation-review.png`,不依赖该文件构建。
- 最终 tarball 安装在 `/private/tmp/heroui-color-foundation-consumer`,无源码 alias:新 ColorArea CSS 存在、无公共占位导出;Calendar/DateField/Select 的 Node ESM/SSR/CSS 与 strict NodeNext/bundler 类型正反例回归通过。私有颜色类型的正反例在工作区执行,不将其冒充颜色公共产物验收。
- 实际边界:Color 接口/格式是明确子集,不继承全 RAC;自动感知色名/全部 locale 文案未迁移。私有 Picker 的 hexa 隐藏值是八位序列化证明,完整公共字段格式/校验协议仍待接续。未完成物理触屏、完整读屏/全浏览器、逐像素和 Nuxt;完整 ColorArea/Swatch 公共迁移可按 [COLOR-02](migrations/COLOR-02-area-swatch-prompt.md) 交接。
## COLOR-03 私有颜色输入(2026-10-25)
- 从 main `6b85014` 新建 feat/color-input-foundation;26 项行为/集成/实际水合 + 2 安装版 Reka 探针 + 2 真实 Node SSR,全库 81 文件 / 992 项通过。范围及未完成项见 [COLOR-03](migrations/COLOR-03-input-foundation.md)。
- vue-tsc 含通道必填/无效通道/空间类型反例、库/样式/文档 SSR 构建通过;既有文档大 chunk 提示保留。无新增依赖或公共导出,未重复本轮 tarball 安装验收。
- 浏览器 5176 `?color-input-foundation` 已验共享灰色 hue、德语 alpha、拒绝重复提案/原生拖动复位、必填错误焦点及跨视图 reset;原生 range 不是最终自定义轨道,不声称公共 Slider/Field/Picker 迁移完成。物理触屏、完整 AT、逐像素及 Nuxt 未验。
+2 -2
View File
@@ -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",
"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",
"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",
"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",
"format": "prettier --check .",
"format:fix": "prettier --write .",
"dev:playground": "pnpm build && pnpm --filter @heroui-vue/playground dev"
@@ -0,0 +1,63 @@
import { computed } from "vue";
import { useConfig } from "../../providers/context";
import { Color, type ColorChannel, type ColorSpace } from "./value";
import type { ColorState } from "./model";
export interface ColorChannelOptions {
channel: ColorChannel;
colorSpace?: ColorSpace;
locale?: string;
}
/** Resolve a channel once for fields and sliders, without an optimistic color cache. */
export function colorChannel(
color: Color,
channel: ColorChannel,
space?: ColorSpace,
) {
const required: Partial<Record<ColorChannel, ColorSpace>> = {
red: "rgb",
green: "rgb",
blue: "rgb",
lightness: "hsl",
brightness: "hsb",
};
const working =
channel === "alpha"
? color.getColorSpace()
: (required[channel] ??
(space === "rgb"
? "hsl"
: (space ??
(color.getColorSpace() === "rgb"
? "hsl"
: color.getColorSpace()))));
const value = color.toFormat(working);
return {
color: value,
channel,
range: value.getChannelRange(channel),
value: value.getChannelValue(channel),
};
}
export function useColorChannel(state: ColorState, props: ColorChannelOptions) {
const config = useConfig();
const locale = computed(
() => props.locale ?? config?.locale.value ?? "en-US",
);
const descriptor = computed(() =>
colorChannel(
state.value.value ??
new Color({ space: "hsl", h: 0, s: 100, l: 50, alpha: 1 }),
props.channel,
props.colorSpace,
),
);
const value = computed(() => descriptor.value.value);
const range = computed(() => descriptor.value.range);
const label = computed(() =>
descriptor.value.color.formatChannelValue(props.channel, locale.value),
);
const withValue = (next: number) =>
descriptor.value.color.withChannelValue(props.channel, next);
return { descriptor, value, range, label, locale, withValue };
}
@@ -0,0 +1,147 @@
import { nextTick, onBeforeUnmount, watch, type ShallowRef } from "vue";
import { useChoiceForm } from "../choice/shared";
import { useConfig } from "../../providers/context";
import { useColorChannel, type ColorChannelOptions } from "./channel";
import type { ColorState } from "./model";
/** Native range/AT bridge. A public custom track must supply its own geometry adapter. */
export function useColorNativeChannel(
state: ColorState,
props: ColorChannelOptions & {
dir?: "ltr" | "rtl";
},
input: ShallowRef<HTMLInputElement | undefined>,
) {
const channel = useColorChannel(state, props);
const config = useConfig();
const token = Symbol("color-native-channel");
const keys = new Set<string>();
let ownerWindow: Window | null | undefined;
const windowBlur = () => stop();
const restore = () => {
if (input.value) input.value.value = String(channel.value.value);
};
function stop(commit = false) {
ownerWindow?.removeEventListener("blur", windowBlur);
ownerWindow = undefined;
keys.clear();
if (commit) state.end(token);
else state.cancel(token);
void nextTick(restore);
}
function begin() {
const started = state.active.value === token || state.begin(token);
if (started && !ownerWindow) {
ownerWindow = input.value?.ownerDocument.defaultView;
ownerWindow?.addEventListener("blur", windowBlur);
}
return started;
}
function propose(next: number) {
if (Number.isFinite(next) && begin())
state.request(channel.withValue(next), token);
void nextTick(restore);
}
function onInput(event: Event) {
if (!event.defaultPrevented)
propose(Number((event.target as HTMLInputElement).value));
else void nextTick(restore);
}
function keydown(event: KeyboardEvent) {
if (
event.defaultPrevented ||
event.isComposing ||
event.ctrlKey ||
event.metaKey ||
event.altKey ||
state.disabled.value ||
state.readOnly.value
)
return;
if (event.key === "Escape") {
if (state.active.value === token) {
event.preventDefault();
stop();
}
return;
}
const { minValue, maxValue, step, pageSize } = channel.range.value;
const sign = (props.dir ?? config?.dir.value) === "rtl" ? -1 : 1;
const delta = event.shiftKey ? pageSize : step;
let next = channel.value.value;
switch (event.key) {
case "ArrowRight":
next += delta * sign;
break;
case "ArrowLeft":
next -= delta * sign;
break;
case "ArrowUp":
next += delta;
break;
case "ArrowDown":
next -= delta;
break;
case "PageUp":
next += pageSize;
break;
case "PageDown":
next -= pageSize;
break;
case "Home":
next = minValue;
break;
case "End":
next = maxValue;
break;
default:
return;
}
event.preventDefault();
keys.add(event.key);
propose(Number(next.toFixed(12)));
}
function keyup(event: KeyboardEvent) {
if (!keys.delete(event.key)) return;
if (event.defaultPrevented) stop();
else if (!keys.size) stop(true);
}
watch(
[
state.disabled,
state.readOnly,
() => props.channel,
() => props.colorSpace,
() => props.dir,
() => config?.dir.value,
input,
],
() => stop(),
{ flush: "sync" },
);
watch(state.active, (active) => {
if (active !== token) {
ownerWindow?.removeEventListener("blur", windowBlur);
ownerWindow = undefined;
keys.clear();
void nextTick(restore);
}
});
useChoiceForm(
input,
() => {
stop();
state.reset();
},
restore,
);
onBeforeUnmount(() => stop());
return {
...channel,
input: onInput,
keydown,
keyup,
commit: () => stop(true),
cancel: () => stop(),
};
}
+290
View File
@@ -0,0 +1,290 @@
import {
computed,
nextTick,
onBeforeUnmount,
shallowRef,
watch,
type ShallowRef,
} from "vue";
import { useConfig } from "../../providers/context";
import { useChoiceForm } from "../choice/shared";
import { colorChannel } from "./channel";
import {
colorKey,
parseColor,
type ColorChannel,
type ColorSpace,
} from "./value";
import type { ColorState } from "./model";
export interface ColorTextOptions {
channel?: ColorChannel;
colorSpace?: ColorSpace;
locale?: string;
}
/** Strict localized decimal parsing; grouping, exponents and trailing garbage are rejected. */
export function parseColorNumber(
text: string,
locale: string,
channel: ColorChannel,
): number | 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++)
raw = raw.split(formatter.format(i)).join(String(i));
const decimal =
formatter.formatToParts(1.1).find((p) => p.type === "decimal")?.value ??
".";
const minus =
formatter.formatToParts(-1).find((p) => p.type === "minusSign")?.value ??
"-";
if (decimal !== "." && raw.includes(".")) return;
raw = raw.split(decimal).join(".").split(minus).join("-");
const percent = /[%\u066a]$/.test(raw);
if (percent) {
if (!["alpha", "saturation", "lightness", "brightness"].includes(channel))
return;
raw = raw.slice(0, -1).trim();
}
if (channel === "hue") raw = raw.replace(/°$/, "").trim();
if (!/^[+-]?(?:\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)
? channel === "alpha"
? value / 100
: value
: undefined;
}
/** Drafts are text only. The shared owner remains the sole accepted color model. */
export function useColorText(
state: ColorState,
props: ColorTextOptions,
input: ShallowRef<HTMLInputElement | undefined>,
options: {
edit?: () => void;
reset?: () => void;
} = {},
) {
const config = useConfig();
const locale = computed(
() => props.locale ?? config?.locale.value ?? "en-US",
);
const descriptor = computed(() =>
props.channel && state.value.value
? colorChannel(state.value.value, props.channel, props.colorSpace)
: undefined,
);
const formatted = computed(() => {
if (!state.value.value) return "";
if (!props.channel) return state.value.value.toString("hex");
const value =
descriptor.value!.value * (props.channel === "alpha" ? 100 : 1);
return new Intl.NumberFormat(locale.value, {
useGrouping: false,
maximumFractionDigits: 10,
}).format(value);
});
const draft = shallowRef(formatted.value);
const composing = shallowRef(false);
const token = Symbol("color-text");
let compositionRevision = 0;
function restore() {
draft.value = formatted.value;
if (input.value) input.value.value = draft.value;
}
function cancel() {
state.cancel(token);
composing.value = false;
compositionRevision++;
restore();
}
function parse() {
const text = draft.value.trim();
if (!text) return null;
if (!props.channel) {
if (!/^#?(?:[\da-f]{3}|[\da-f]{6})$/i.test(text)) return undefined;
return parseColor(text.startsWith("#") ? text : `#${text}`);
}
if (text === formatted.value && state.value.value)
return state.value.value.clone();
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);
}
function commit(event?: Event) {
if (composing.value) return;
if (
!event?.defaultPrevented &&
!state.disabled.value &&
!state.readOnly.value
) {
const next = parse();
if (next !== undefined && state.begin(token)) {
// Typing the same hex must not erase a gray hue or an existing alpha.
if (!(
next &&
state.value.value &&
!props.channel &&
next.toString("hex") === state.value.value.toString("hex")
))
state.request(next, token);
state.end(token);
}
}
restore();
void nextTick(restore);
}
function onInput(event: Event) {
if (
event.defaultPrevented ||
state.disabled.value ||
state.readOnly.value
) {
restore();
return;
}
draft.value = (event.target as HTMLInputElement).value;
options.edit?.();
}
function keydown(event: KeyboardEvent) {
if (
event.defaultPrevented ||
event.isComposing ||
composing.value ||
event.ctrlKey ||
event.metaKey ||
event.altKey ||
state.disabled.value ||
state.readOnly.value
)
return;
if (event.key === "Enter") {
event.preventDefault();
commit();
return;
}
if (event.key === "Escape") {
event.preventDefault();
cancel();
return;
}
const direction =
event.key === "ArrowUp" || event.key === "PageUp"
? 1
: event.key === "ArrowDown" || event.key === "PageDown"
? -1
: 0;
if (!direction && event.key !== "Home" && event.key !== "End") return;
event.preventDefault();
const parsed = parse();
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"
? d.range.minValue
: event.key === "End"
? d.range.maxValue
: d.value + direction * step;
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 int =
event.key === "Home"
? 0
: event.key === "End"
? 0xffffff
: Math.min(0xffffff, Math.max(0, value + direction * step));
next = parseColor(`#${int.toString(16).padStart(6, "0")}`);
}
options.edit?.();
if (state.begin(token)) {
state.request(next, token);
state.end(token);
}
restore();
void nextTick(restore);
}
function compositionstart() {
composing.value = true;
compositionRevision++;
}
function compositionend() {
const revision = ++compositionRevision;
// The Enter used to select an IME candidate must not also submit/commit.
void nextTick(() => {
if (revision === compositionRevision) composing.value = false;
});
}
watch(
() => colorKey(state.value.value),
() => {
composing.value = false;
compositionRevision++;
restore();
},
{ flush: "sync" },
);
watch(
[
() => props.channel,
() => props.colorSpace,
locale,
state.disabled,
state.readOnly,
],
cancel,
{ flush: "sync" },
);
useChoiceForm(
input,
() => {
cancel();
state.reset();
options.reset?.();
},
restore,
);
onBeforeUnmount(() => {
state.cancel(token);
compositionRevision++;
});
const submission = computed(() =>
!state.value.value
? ""
: props.channel
? String(descriptor.value!.value)
: state.value.value.toString("hex"),
);
return {
draft,
formatted,
submission,
descriptor,
locale,
composing,
input: onInput,
commit,
blur: (event?: Event) => {
if (composing.value) cancel();
else commit(event);
},
cancel,
keydown,
compositionstart,
compositionend,
};
}
+156
View File
@@ -0,0 +1,156 @@
<script setup lang="ts">
import {
computed,
reactive,
shallowRef,
toRefs,
useAttrs,
watchEffect,
} from "vue";
import {
useColorState,
type ColorModelProps,
} from "../../src/components/color/model";
import {
useColorText,
type ColorTextOptions,
} from "../../src/components/color/text";
import { useColorNativeChannel } from "../../src/components/color/native-channel";
import {
useChoiceField,
type ChoiceFieldProps,
} from "../../src/components/choice/shared";
import { type Color } from "../../src/components/color/value";
import type { ValidateResult } from "../../src/components/field/context";
defineOptions({ inheritAttrs: false });
const props = defineProps<
ColorModelProps &
ColorTextOptions &
ChoiceFieldProps & {
mode?: "text" | "range";
dir?: "ltr" | "rtl";
validate?: (value: Color | null) => ValidateResult;
}
>();
const emit = defineEmits<{
"update:modelValue": [Color | null];
change: [Color | null];
changeEnd: [Color | null];
}>();
const attrs = useAttrs();
const state = useColorState(props, {
fallback: () => null,
inherit: true,
change: (value) => {
emit("update:modelValue", value);
emit("change", value);
},
changeEnd: (value) => emit("changeEnd", value),
});
const fieldProps = reactive({
...toRefs(props),
isDisabled: state.disabled,
isReadOnly: state.readOnly,
});
const field = useChoiceField(fieldProps, attrs, {
kind: "group",
value: state.value,
validate: (value) => props.validate?.(value),
satisfied: () => state.value.value !== null,
requiredMessage: "请选择颜色。",
});
const input = shallowRef<HTMLInputElement>();
const text = useColorText(
state,
props,
computed(() => (props.mode === "range" ? undefined : input.value)),
{
edit: field.edit,
reset: field.reset,
},
);
const scalar = useColorNativeChannel(
state,
reactive({
channel: computed(() => props.channel ?? "hue"),
colorSpace: computed(() => props.colorSpace),
locale: computed(() => props.locale),
dir: computed(() => props.dir),
}),
computed(() => (props.mode === "range" ? input.value : undefined)),
);
const value = computed(() =>
props.mode === "range" ? scalar.value.value : text.draft.value,
);
const disabled = state.disabled,
readonly = state.readOnly;
const invalid = field.field.invalid;
watchEffect(() => field.validity(input.value));
function inputEvent(event: Event) {
if (props.mode === "range") {
if (
!event.defaultPrevented &&
!state.disabled.value &&
!state.readOnly.value
)
field.edit();
scalar.input(event);
} else text.input(event);
}
function keydown(event: KeyboardEvent) {
if (props.mode === "range") scalar.keydown(event);
else text.keydown(event);
}
function blur(event: FocusEvent) {
if (props.mode === "range") scalar.commit();
else text.blur(event);
}
const submission = computed(() =>
props.mode === "range" ? String(scalar.value.value) : text.submission.value,
);
defineExpose({ state });
</script>
<template>
<div data-color-input-foundation :data-invalid="invalid || undefined">
<input
ref="input"
data-color-input
v-bind="attrs"
:id="field.field.controlId.value"
:type="mode === 'range' ? 'range' : 'text'"
:value="value"
:disabled="disabled"
:readonly="mode !== 'range' && readonly"
:aria-readonly="readonly || undefined"
:aria-invalid="invalid || undefined"
:aria-required="isRequired || undefined"
:aria-describedby="field.describedBy()"
:aria-labelledby="field.labelledBy()"
:form="form"
:min="mode === 'range' ? scalar.range.value.minValue : undefined"
:max="mode === 'range' ? scalar.range.value.maxValue : undefined"
:step="mode === 'range' ? 'any' : undefined"
:aria-valuetext="mode === 'range' ? scalar.label.value : undefined"
:dir="dir"
@input="inputEvent"
@keydown="keydown"
@keyup="mode === 'range' && scalar.keyup($event)"
@change="mode === 'range' && scalar.commit()"
@blur="blur"
@pointercancel="mode === 'range' && scalar.cancel()"
@compositionstart="text.compositionstart"
@compositionend="text.compositionend"
@invalid="field.invalidEvent($event, () => input?.focus())"
/>
<input
type="hidden"
:name="name"
:form="form"
:value="state.value.value ? submission : ''"
:disabled="disabled"
/>
<output data-field-error v-if="invalid">
{{ field.field.errors.value.join(" ") }}
</output>
</div>
</template>
+5
View File
@@ -1,5 +1,10 @@
// Installed-version probes use only public exports, resolved from the component package.
export {
ColorFieldRoot,
ColorFieldInput,
ColorSliderRoot,
ColorSliderTrack,
ColorSliderThumb,
ColorAreaRoot,
ColorAreaArea,
ColorAreaThumb,
+39
View File
@@ -0,0 +1,39 @@
// @vitest-environment node
import { describe, it, expect } from "vitest";
import { createSSRApp, defineComponent } from "vue";
import { renderToString } from "@vue/server-renderer";
import Input from "../packages/vue/tests/fixtures/ColorInputFoundation.vue";
import Picker from "../packages/vue/tests/fixtures/ColorPickerFoundation.vue";
describe("private color inputs actual Node SSR", () => {
it("renders localized text and exact fractional native channel without browser globals", async () => {
const html = await renderToString(
createSSRApp(
defineComponent({
components: { Input, Picker },
template:
'<Picker default-value="hsb(270,0%,50%,.12345)" v-slot><Input channel="alpha" locale="de-DE" name="alpha"/><Input mode="range" channel="hue" name="hue"/></Picker>',
}),
),
);
expect(html).toContain('value="12,345"');
expect(html).toContain('value="0.12345"');
expect(html).toContain('value="270"');
expect(html).toContain('aria-valuetext="270°"');
expect(html.match(/name="alpha"/g)).toHaveLength(1);
expect(html).not.toContain("NaN");
});
it("renders empty fields and native validation association deterministically", async () => {
const html = await renderToString(
createSSRApp(
defineComponent({
components: { Input },
template:
'<Input name="color" form="external" is-required aria-label="Required color"/>',
}),
),
);
expect(html).toContain('aria-required="true"');
expect(html).toContain('form="external"');
expect(html).toContain('value=""');
});
});
+400
View File
@@ -0,0 +1,400 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, shallowRef, createSSRApp } from "vue";
import Input from "../packages/vue/tests/fixtures/ColorInputFoundation.vue";
import Picker from "../packages/vue/tests/fixtures/ColorPickerFoundation.vue";
import Area from "../packages/vue/tests/fixtures/ColorAreaFoundation.vue";
import { Color, parseColor } from "../packages/vue/src/components/color/value";
import { colorChannel } from "../packages/vue/src/components/color/channel";
import { parseColorNumber } from "../packages/vue/src/components/color/text";
import { renderToString } from "@vue/server-renderer";
import { Form } from "../packages/vue/src/index";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
vi.restoreAllMocks();
});
function fixture(
template = '<Input name="color" default-value="#123456" aria-label="Color"/>',
setup = () => ({}),
) {
const w = mount(
defineComponent({
components: { Input, Picker, Area, Form },
setup,
template: `<form>${template}</form>`,
}),
{ attachTo: document.body },
);
wrappers.push(w);
return w;
}
const input = (w: ReturnType<typeof mount>) =>
w.get<HTMLInputElement>("[data-color-input]");
const changes = (w: ReturnType<typeof mount>, component = Input) =>
(w.getComponent(component).emitted("change") ?? []).map(
([v]) => v as Color | null,
);
async function enter(w: ReturnType<typeof mount>, text: string) {
await input(w).setValue(text);
await input(w).trigger("keydown", { key: "Enter" });
await flushPromises();
}
async function key(w: ReturnType<typeof mount>, key: string, extra = {}) {
await input(w).trigger("keydown", { key, ...extra });
await input(w).trigger("keyup", { key, ...extra });
await flushPromises();
}
const data = (w: ReturnType<typeof mount>) =>
new FormData(w.get("form").element as HTMLFormElement).getAll("color");
describe("color channel boundary", () => {
it("resolves space-specific channels and preserves HSB hue and alpha", () => {
const c = parseColor("hsb(270,0%,50%,.12345)");
expect(colorChannel(c, "hue").color.equals(c)).toBe(true);
expect(colorChannel(c, "red", "hsl").color.getColorSpace()).toBe("rgb");
expect(colorChannel(c, "saturation", "rgb").color.getColorSpace()).toBe(
"hsl",
);
expect(colorChannel(c, "alpha", "rgb").color.equals(c)).toBe(true);
});
it("parses localized channel numbers strictly and uses percent alpha", () => {
expect(parseColorNumber("١٢٫٥", "ar-EG", "alpha")).toBe(0.125);
expect(parseColorNumber("12,5 %", "de-DE", "saturation")).toBe(12.5);
expect(parseColorNumber("270°", "en-US", "hue")).toBe(270);
for (const t of ["1e2", "12junk", "1,234", "NaN", "--1"])
expect(parseColorNumber(t, "en-US", "red")).toBeUndefined();
expect(parseColorNumber("25%", "en-US", "red")).toBeUndefined();
});
});
describe("color text draft protocol", () => {
it("keeps partial drafts out of the model and commits normalized hex once", async () => {
const w = fixture();
await input(w).setValue("#f");
expect(changes(w)).toHaveLength(0);
expect(data(w)).toEqual(["#123456"]);
await enter(w, "abc");
expect(input(w).element.value).toBe("#AABBCC");
expect(changes(w)).toHaveLength(1);
expect(w.getComponent(Input).emitted("changeEnd")).toHaveLength(1);
expect(data(w)).toEqual(["#AABBCC"]);
});
it("rejects incomplete/malformed/alpha hex without changing accepted color", async () => {
const w = fixture();
for (const t of ["#f", "oops", "#12345678", "rgb(1,2,3)"]) {
await enter(w, t);
expect(input(w).element.value).toBe("#123456");
}
expect(changes(w)).toHaveLength(0);
});
it("restores rejected text and allows an identical proposal on the next commit", async () => {
const w = fixture('<Input model-value="#123456" name="color"/>');
await enter(w, "abc");
await enter(w, "abc");
expect(changes(w)).toHaveLength(2);
expect(w.getComponent(Input).emitted("changeEnd")).toHaveLength(2);
expect(input(w).element.value).toBe("#123456");
expect(data(w)).toEqual(["#123456"]);
});
it("preserves a gray hue and alpha when committing an unchanged hex", async () => {
const w = fixture('<Input default-value="hsb(270,0%,50%,.12345)"/>');
await enter(w, "808080");
expect(changes(w)).toHaveLength(0);
expect(
w.getComponent(Input).vm.state.value.value?.getChannelValue("hue"),
).toBe(270);
});
it("clears to null, keeps required validation, and reset restores captured defaults", async () => {
const w = fixture(
'<Input name="color" default-value="#123456" is-required/>',
);
await enter(w, "");
expect(changes(w).at(-1)).toBeNull();
expect(input(w).element.checkValidity()).toBe(false);
await flushPromises();
expect(w.text()).toContain("请选择颜色。");
(w.get("form").element as HTMLFormElement).reset();
await flushPromises();
expect(input(w).element.value).toBe("#123456");
expect(input(w).element.checkValidity()).toBe(true);
expect(changes(w)).toHaveLength(1);
});
it("uses draft numeric values for stepping and clamps channel commits", async () => {
const w = fixture(
'<Input name="color" channel="saturation" color-space="hsb" default-value="hsb(270,50%,50%,.12345)"/>',
);
await input(w).setValue("67");
await key(w, "ArrowUp");
expect(input(w).element.value).toBe("68");
expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270);
expect(changes(w).at(-1)?.getChannelValue("alpha")).toBe(0.12345);
await enter(w, "200");
expect(input(w).element.value).toBe("100");
await key(w, "Home");
expect(input(w).element.value).toBe("0");
await key(w, "End");
expect(data(w)).toEqual(["100"]);
});
it("formats locale decimal alpha, accepts percent, and submits model scale", async () => {
const w = fixture(
'<Input name="color" locale="de-DE" channel="alpha" default-value="hsb(270,0%,50%,.125)"/>',
);
expect(input(w).element.value).toBe("12,5");
await enter(w, "33,25%");
expect(data(w)).toEqual(["0.3325"]);
await key(w, "ArrowUp");
expect(input(w).element.value).toBe("34,25");
expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270);
});
it("cancels drafts on escape and external accepted replacement", async () => {
const value = shallowRef<Color | null>(parseColor("#123456"));
const w = fixture('<Input :model-value="value"/>', () => ({ value }));
await input(w).setValue("#abc");
await key(w, "Escape");
expect(input(w).element.value).toBe("#123456");
await input(w).setValue("#def");
value.value = parseColor("#654321");
await flushPromises();
expect(input(w).element.value).toBe("#654321");
expect(changes(w)).toHaveLength(0);
});
it("does not commit the Enter used to finish IME composition", async () => {
const w = fixture();
await input(w).trigger("compositionstart");
await input(w).setValue("abc");
await input(w).trigger("keydown", { key: "Enter" });
expect(changes(w)).toHaveLength(0);
await input(w).trigger("compositionend");
await flushPromises();
await input(w).trigger("keydown", { key: "Enter" });
expect(changes(w)).toHaveLength(1);
});
it("honors canceled events, readonly and disabled", async () => {
const ro = shallowRef(false),
off = shallowRef(false);
const w = fixture(
'<Input :is-read-only="ro" :is-disabled="off" default-value="#123456" @keydown="$event.preventDefault()"/>',
() => ({ ro, off }),
);
await enter(w, "abc");
expect(changes(w)).toHaveLength(0);
ro.value = true;
await flushPromises();
await enter(w, "abc");
expect(changes(w)).toHaveLength(0);
off.value = true;
await flushPromises();
expect(input(w).element.disabled).toBe(true);
});
it("resets actual controlled text even when parent value never changes", async () => {
const w = fixture('<Input model-value="#123456" name="color"/>');
await input(w).setValue("#abc");
(w.get("form").element as HTMLFormElement).reset();
await flushPromises();
expect(input(w).element.value).toBe("#123456");
expect(data(w)).toEqual(["#123456"]);
expect(changes(w)).toHaveLength(0);
});
it("honors canceled reset and external form association", async () => {
const external = document.createElement("form");
external.id = "external";
document.body.append(external);
const w = fixture(
'<Input form="external" name="color" default-value="#123456"/>',
);
await enter(w, "abc");
const form = external;
form.addEventListener("reset", (e) => e.preventDefault(), { once: true });
form.reset();
await flushPromises();
expect(input(w).element.value).toBe("#AABBCC");
form.reset();
await flushPromises();
expect(input(w).element.value).toBe("#123456");
});
});
describe("native channel shared transaction bridge", () => {
it("groups held keys, uses channel page steps and RTL, restores accepted fractions", async () => {
const w = fixture(
'<Input mode="range" channel="alpha" name="color" default-value="hsb(270,0%,50%,.12345)" dir="rtl"/>',
);
await input(w).trigger("keydown", { key: "ArrowLeft" });
await input(w).trigger("keydown", { key: "ArrowLeft", repeat: true });
await input(w).trigger("keyup", { key: "ArrowLeft" });
expect(changes(w)).toHaveLength(2);
expect(w.getComponent(Input).emitted("changeEnd")).toHaveLength(1);
expect(Number(input(w).element.value)).toBeCloseTo(0.14345);
await key(w, "PageUp");
expect(Number(input(w).element.value)).toBeCloseTo(0.24345);
expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270);
});
it("keeps rejected native input and submission at the accepted value", async () => {
const w = fixture(
'<Input mode="range" channel="hue" name="color" model-value="hsb(270,0%,50%)"/>',
);
await input(w).setValue("120");
await flushPromises();
expect(input(w).element.value).toBe("270");
expect(data(w)).toEqual(["270"]);
await input(w).setValue("120");
await flushPromises();
expect(changes(w)).toHaveLength(2);
});
it("emits final proposal after rejection, and cancel does not emit completion", async () => {
const w = fixture(
'<Input mode="range" channel="hue" model-value="hsb(270,0%,50%)"/>',
);
await input(w).trigger("keydown", { key: "ArrowUp" });
await input(w).trigger("keyup", { key: "ArrowUp" });
expect(
(
w.getComponent(Input).emitted("changeEnd")?.[0]?.[0] as Color
).getChannelValue("hue"),
).toBe(271);
await input(w).trigger("keydown", { key: "ArrowUp" });
await key(w, "Escape");
expect(w.getComponent(Input).emitted("changeEnd")).toHaveLength(1);
});
it("shares one owner across area, native channel and text", async () => {
const w = fixture(
'<Picker name="owner" default-value="hsb(270,0%,50%,.12345)" v-slot><Area/><Input mode="range" channel="hue"/><Input channel="alpha" name="color"/></Picker>',
);
const fields = w.findAll<HTMLInputElement>("[data-color-input]");
await fields[0]!.trigger("keydown", { key: "ArrowUp" });
await fields[0]!.trigger("keyup", { key: "ArrowUp" });
await fields[1]!.setValue("25");
await fields[1]!.trigger("keydown", { key: "Enter" });
const c = changes(w, Picker).at(-1)!;
expect(c.getChannelValue("hue")).toBe(271);
expect(c.getChannelValue("alpha")).toBe(0.25);
expect(
w.getComponent(Area).get('[data-axis="x"]').attributes("aria-valuetext"),
).toContain("0");
expect(changes(w)).toHaveLength(0);
expect(data(w)).toEqual(["0.25"]);
});
});
describe("color input lifecycle integration", () => {
it("does not let inactive input controllers overwrite the current mode", async () => {
const mode = shallowRef<"text" | "range">("text");
const w = fixture(
'<Input :mode="mode" channel="hue" default-value="hsb(270,0%,50%)"/>',
() => ({ mode }),
);
await flushPromises();
expect(input(w).element.value).toBe("270");
mode.value = "range";
await flushPromises();
await key(w, "ArrowUp");
expect(input(w).element.value).toBe("271");
mode.value = "text";
await flushPromises();
expect(input(w).element.value).toBe("271");
});
it("cancels an unfinished native transaction on disable, external replacement and window blur", async () => {
const off = shallowRef(false),
value = shallowRef(parseColor("hsb(270,0%,50%)"));
const w = fixture(
'<Input mode="range" channel="hue" :model-value="value" :is-disabled="off"/>',
() => ({ off, value }),
);
await input(w).trigger("keydown", { key: "ArrowUp" });
off.value = true;
await flushPromises();
await input(w).trigger("keyup", { key: "ArrowUp" });
expect(w.getComponent(Input).emitted("changeEnd")).toBeUndefined();
off.value = false;
await flushPromises();
await input(w).trigger("keydown", { key: "ArrowUp" });
value.value = parseColor("hsb(90,0%,50%)");
await flushPromises();
await input(w).trigger("keyup", { key: "ArrowUp" });
expect(input(w).element.value).toBe("90");
expect(w.getComponent(Input).emitted("changeEnd")).toBeUndefined();
await input(w).trigger("keydown", { key: "ArrowUp" });
window.dispatchEvent(new Event("blur"));
await input(w).trigger("keyup", { key: "ArrowUp" });
expect(w.getComponent(Input).emitted("changeEnd")).toBeUndefined();
});
it("clears unfinished composition on blur and prevents stale drafts after unmount", async () => {
const w = fixture();
await input(w).trigger("compositionstart");
await input(w).setValue("abc");
await input(w).trigger("blur");
expect(input(w).element.value).toBe("#123456");
expect(changes(w)).toHaveLength(0);
});
it("uses existing Form server errors and dismisses them on a text edit", async () => {
const w = mount(
defineComponent({
components: { Input, Form },
template:
'<Form :validation-errors="{color:\'颜色不可用\'}"><Input name="color" default-value="#123456"/></Form>',
}),
{ attachTo: document.body },
);
wrappers.push(w);
expect(w.text()).toContain("颜色不可用");
await input(w).setValue("abc");
expect(w.text()).not.toContain("颜色不可用");
});
it("keeps aria validation out of native form blocking and applies custom validation to accepted values", async () => {
const w = fixture(
'<Input name="color" default-value="#123456" validation-behavior="aria" :validate="()=>\'错误颜色\'"/>',
);
expect(input(w).attributes("aria-invalid")).toBe("true");
expect(input(w).element.checkValidity()).toBe(true);
});
it("preserves separate child owners and leaves sibling transactions alone on unmount", async () => {
const show = shallowRef(true);
const w = fixture(
'<Picker default-value="hsb(270,0%,50%)" v-slot><Input mode="range" channel="hue"/><Input v-if="show" default-value="#123456"/></Picker>',
() => ({ show }),
);
const first = w.findAll("[data-color-input]")[0]!;
await first.trigger("keydown", { key: "ArrowUp" });
show.value = false;
await flushPromises();
await first.trigger("keyup", { key: "ArrowUp" });
expect(w.getComponent(Picker).emitted("changeEnd")).toHaveLength(1);
});
});
describe("color inputs hydration and precision", () => {
it("does not quantize an untouched formatted alpha draft", async () => {
const w = fixture(
'<Input channel="alpha" default-value="hsb(270,0%,50%,.123456789012345)"/>',
);
await input(w).trigger("keydown", { key: "Enter" });
expect(changes(w)).toHaveLength(0);
});
it("hydrates stable actual inputs, native values and IDs", async () => {
const App = defineComponent({
components: { Input, Picker },
template:
'<main><Picker default-value="hsb(270,0%,50%,.125)" v-slot><Input channel="alpha" locale="de-DE"/><Input mode="range" channel="hue"/></Picker><Input default-value="#123456"/></main>',
});
const container = document.createElement("div");
container.innerHTML = await renderToString(createSSRApp(App));
document.body.append(container);
const nodes = [...container.querySelectorAll("[data-color-input]")];
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const app = createSSRApp(App);
app.mount(container);
await flushPromises();
expect([...container.querySelectorAll("[data-color-input]")]).toEqual(
nodes,
);
expect(nodes.map((n) => (n as HTMLInputElement).value)).toEqual([
"12,5",
"270",
"#123456",
]);
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();
});
});
+57
View File
@@ -0,0 +1,57 @@
import { describe, it, expect, afterEach, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent } from "vue";
import {
ColorFieldRoot,
ColorFieldInput,
ColorSliderRoot,
ColorSliderTrack,
ColorSliderThumb,
} from "../packages/vue/tests/fixtures/color-probe";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
vi.unstubAllGlobals();
});
describe("installed Reka color input audit, not public component acceptance", () => {
it("emits hex for a polar channel edit", async () => {
const w = mount(
defineComponent({
components: { ColorFieldRoot, ColorFieldInput },
template:
'<ColorFieldRoot default-value="hsb(270,0%,50%,.12345)" channel="hue" color-space="hsb"><ColorFieldInput/></ColorFieldRoot>',
}),
);
wrappers.push(w);
await w.get("input").setValue("271");
await w.get("input").trigger("blur");
expect(
w.getComponent(ColorFieldRoot).emitted("update:modelValue")?.[0]?.[0],
).toBe("#8080801f");
});
it("keeps optimistic slider state after a controlled parent rejection", async () => {
vi.stubGlobal(
"ResizeObserver",
class {
observe() {}
unobserve() {}
disconnect() {}
},
);
const w = mount(
defineComponent({
components: { ColorSliderRoot, ColorSliderTrack, ColorSliderThumb },
template:
'<ColorSliderRoot model-value="hsb(270,0%,50%)" channel="hue" color-space="hsb"><ColorSliderTrack><ColorSliderThumb/></ColorSliderTrack></ColorSliderRoot>',
}),
);
wrappers.push(w);
await w.get('[role="slider"]').trigger("keydown", { key: "ArrowRight" });
expect(
w.getComponent(ColorSliderRoot).emitted("update:modelValue")?.[0]?.[0],
).toMatch(/^#/);
expect(w.get('[role="slider"]').attributes("aria-valuenow")).not.toBe(
"270",
);
});
});
+19
View File
@@ -22,3 +22,22 @@ const alpha: ColorAreaOptions = { xChannel: "alpha" };
const foreign: ColorValue = { space: "rgb", r: 0, g: 0, b: 0, alpha: 1 };
void alpha;
void foreign;
import type { ColorChannelOptions } from "../../packages/vue/src/components/color/channel";
import type { ColorTextOptions } from "../../packages/vue/src/components/color/text";
const alphaField: ColorTextOptions = { channel: "alpha", locale: "de-DE" };
const hueSlider: ColorChannelOptions = { channel: "hue", colorSpace: "hsb" };
// @ts-expect-error slider channel is required
const missingChannel: ColorChannelOptions = {};
// @ts-expect-error unknown field channel
const invalidChannel: ColorTextOptions = { channel: "opacity" };
const invalidSpace: ColorChannelOptions = {
channel: "hue",
// @ts-expect-error no arbitrary color space
colorSpace: "oklch",
};
void alphaField;
void hueSlider;
void missingChannel;
void invalidChannel;
void invalidSpace;