diff --git a/AGENTS.md b/AGENTS.md index d3f9af2..2c0d3df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -418,3 +418,10 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V - key 区分数字和字符串,空字符串有效;内部适配编码不进入 FormData。父拒绝后相同提案可以重试,程序化父值与用户改选权限分开。 - Reka 已实测支持禁用项跳过/全选;Listbox reset、索引表单名,以及 Select 多选原生提交/关闭态 SSR 存在适配需求。不能只检查可见文字或读局部源码猜能力。 - 已挂载 registry 不等于虚拟化完整集合。公共 Item 的 Label/Description 与外层字段隔离,使用既有字段/reset/弹层设施;9/19 个基线预览和公共验收仍待完成。 + +## LISTBOX-01 公共集合协议(2026-10-23) + +- ListBox 四部件与 9 个预览已经接入,见 [报告](docs/migrations/LISTBOX-01-list-box.md);Select 的 19 个预览仍待迁移。其他 AI 不自行改写 collection / ListBox 共享模型。 +- 逻辑数据全集与挂载 registry 分开。虚拟导航先滚动再等 DOM 聚焦,异步焦点请求可被新请求或卸载取消;用户滚动卸载焦点行时不跳回首行。全选/范围/搜索不能只看可见窗口。 +- 连续 typeahead 在当前项仍匹配时保留它;重复首字母才循环下一项。空 key / 数字 0 不得被真值判断排除;none 模式不显示遗留的选中状态。 +- Root 与公开 Props 共用 ListBoxOptions 明确 schema,泛型 SFC 的 Parameters 提取曾让反例失效。后续泛型组件也必须做产物类型正反例,不能用 any 修复。 diff --git a/apps/docs/.vitepress/theme/Layout.vue b/apps/docs/.vitepress/theme/Layout.vue index ee5bf71..56509fa 100644 --- a/apps/docs/.vitepress/theme/Layout.vue +++ b/apps/docs/.vitepress/theme/Layout.vue @@ -100,6 +100,7 @@ const groups = [ { title: "Toolbar 工具栏", url: "/components/toolbar" }, { title: "NumberField 数字输入框", url: "/components/number-field" }, { title: "Slider 滑块", url: "/components/slider" }, + { title: "ListBox 列表框", url: "/components/list-box" }, { title: "Tooltip 工具提示", url: "/components/tooltip" }, { title: "ToggleButton 切换按钮", diff --git a/apps/docs/components/list-box.md b/apps/docs/components/list-box.md new file mode 100644 index 0000000..b255379 --- /dev/null +++ b/apps/docs/components/list-box.md @@ -0,0 +1,236 @@ +--- +title: ListBox 列表框 +description: 列表框展示一组选项,并允许用户选择一个或多个。 +component: list-box +group: 组件 +--- + +## 用法 + +```vue + +``` + + + +## 组件结构 + +```vue + + + + + + 第一项 + 选项说明 + + + + + 分组 + + 第二项 + + + + +``` + +## 示例 + +### 含禁用项 + + + +### 分组选项 + + + +### 多选 + + + +### 受控组件 + +使用 `v-model` 控制 key 数组。单选也使用数组,空选择为 `[]`。数字 `1` 与字符串 `"1"` 是不同的 key。父组件未接受更新时,可见选中状态保持父值。 + + + +### 虚拟滚动 + +ListBox 通过 `virtualized` 仅渲染视口附近的行,高效展示大数据集。下面保留基线的 1000 条数据、50px 固定行高和 400px 视口。完整数据传给 `items`,首字母导航、全选和范围选择使用完整集合。 + +Vue 使用现有 VueUse 虚拟列表适配,不导出 React 的 `Virtualizer` / `ListLayout`。当前支持竖向固定行高列表;可变行高、虚拟分组标题和拖放布局尚未支持。 + + + +### 自定义勾选图标 + + + +### 渲染函数 + +Vue 使用 `as` 修改原生标签,普通和作用域插槽组合内容;状态属性和事件保留在实际 role 节点上。 + + + +## 自定义样式 + +### Tailwind CSS + + + +### 全局 CSS + +若要自定义组件类,可使用 `@layer components` 指令。 + +```css +@layer components { + .hv-list-box { + @apply rounded-lg border border-border bg-surface p-2; + } + .hv-list-box-item { + @apply rounded px-2 py-1 cursor-pointer; + } + .hv-list-box-item--danger { + @apply text-danger; + } + .hv-list-box-item__indicator { + @apply text-accent; + } +} +``` + +## 样式参考 + +保留固定 HeroUI 基线的 BEM 类与视觉数值,使用 `hv-` 命名空间。 + +| CSS 类 | 描述 | +| ---------------------------------------------------------- | -------------- | +| `.hv-list-box` | ListBox 根容器 | +| `.hv-list-box--default` / `.hv-list-box--danger` | 根变体 | +| `.hv-list-box-item` | 单个列表项 | +| `.hv-list-box-item--default` / `.hv-list-box-item--danger` | 项变体 | +| `.hv-list-box-item__indicator` | 选中指示图标 | +| `.hv-list-box-section` | 分组容器 | + +### 交互状态 + +| 状态 | 属性与样式 | +| ------ | ----------------------------------------------------------- | +| 悬停 | `:hover` / `data-hovered="true"` | +| 聚焦 | `data-focused="true"`;键盘焦点 `data-focus-visible="true"` | +| 按下 | `:active` / `data-pressed="true"`,缩放至 0.98 | +| 已选中 | `aria-selected="true"` / `data-selected="true"` | +| 禁用 | `aria-disabled="true"` / `data-disabled="true"` | +| 指示器 | `data-visible="true"`;默认勾选使用源 stroke 动画 | + +## API 参考 + +### ListBox / ListBoxRoot + +| 属性 | 类型 | 默认值 | 描述 | +| -------------------------------- | ------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------ | +| `modelValue` | `readonly ListBoxKey[]` | — | 受控选择,使用 `v-model`。 | +| `selectedKeys` | `readonly ListBoxKey[]` | — | 受控选择别名;显式 `modelValue` 优先,包括 `undefined`。 | +| `defaultValue` | `readonly ListBoxKey[]` | `[]` | 非受控初始值。 | +| `defaultSelectedKeys` | `readonly ListBoxKey[]` | — | 初始值别名;`defaultValue` 优先。 | +| `selectionMode` | `"none" \| "single" \| "multiple"` | `"single"` | 不选择、单选或多选;单选最多一个 key。 | +| `selectionBehavior` | `"toggle" \| "replace"` | `"toggle"` | toggle 逐项切换;replace 点击或普通方向导航替换选择,Ctrl/Command 方向键仅移动焦点。 | +| `disabledKeys` | `readonly ListBoxKey[]` | `[]` | 禁用项;导航、范围与全选跳过这些项。 | +| `disallowEmptySelection` | `boolean` | `false` | 阻止用户清空选择,不自动选择初始项。 | +| `isDisabled` | `boolean` | `false` | 禁止交互并移除 Tab 停靠点;合并 Fieldset 禁用作用域。 | +| `isReadOnly` | `boolean` | `false` | 保留焦点导航,阻止改选与 action。 | +| `orientation` | `"vertical" \| "horizontal"` | `"vertical"` | 方向键导航方向。 | +| `dir` | `"ltr" \| "rtl"` | ConfigProvider / `"ltr"` | 横向导航方向。 | +| `loop` | `boolean` | `false` | 方向键到边界后循环。 | +| `variant` | `"default" \| "danger"` | `"default"` | 视觉变体。 | +| `as` | `string` | `"div"` | 根原生标签。 | +| `items` | `readonly T[]`,`T extends ListBoxDataItem` | — | 数据集合,具备唯一的 `id`;作用域插槽接收 `item` 和 `index`。 | +| `virtualized` | `boolean` | `false` | 开启竖向固定行高虚拟列表,必须提供 `items`。 | +| `rowHeight` | `number` | `50` | 每行高度(px),必须为正数。 | +| `overscan` | `number` | `5` | 视口外额外渲染的行数,初始化时确定。 | +| `aria-label` / `aria-labelledby` | `string` | — | 根列表框的可访问名称。 | +| `class` / `style` / DOM 事件 | Vue 原生属性 | — | 透传到根 role=listbox 节点,类增量合并。 | + +`ListBoxKey` 为 `string | number`,数字必须有限;空字符串是有效 key。Vue 数组替代 RAC 的 `Set` 和 `"all"` 哨兵;使用实例 `selectAll()` 选择当前可用全集,受控时仍由父级接受提案。成员移除不会擅自清理父模型。ListBox 本身不是表单字段,不生成有名输入;Select 的表单提交由其字段层处理。 + +| 事件 | 载荷 | 描述 | +| ------------------- | -------------- | ------------------------------------------------------------------ | +| `update:modelValue` | `ListBoxKey[]` | 用户提出新的选择;拒绝后可重复提出相同选择。 | +| `selectionChange` | `ListBoxKey[]` | 同一次选择提案,供非 v-model 使用。 | +| `action` | `ListBoxKey` | 可用项被点击或 Enter/Space 激活;与选择更新分开,none 模式也触发。 | + +| 插槽 / 实例方法 | 参数 | 描述 | +| --------------- | ------------------------------------- | -------------------------------------------- | +| 默认插槽 | 数据模式 `{ item: T, index: number }` | 静态部件模式直接放置 Item / Section。 | +| `empty` | 无 | items 为空时的内容。 | +| `focus(key?)` | `ListBoxKey?` | 聚焦根或指定可用项;虚拟项先滚动到可见范围。 | +| `selectAll()` | 无 | 多选模式下提出全选,跳过禁用项。 | +| `element` | `HTMLElement` | 根元素引用。 | + +### ListBoxItem + +| 属性 | 类型 | 默认值 | 描述 | +| ----------------------------------- | ----------------------- | ------------------- | ----------------------------------------------------------------------- | +| `id` | `ListBoxKey` | 必填 | 集合身份,不直接作为 DOM id;不同列表可复用相同 key。 | +| `textValue` | `string` | Label 文本 / 项文本 | 首字母导航文本。数据模式也应提供 items 的 textValue,支持未挂载项搜索。 | +| `isDisabled` | `boolean` | `false` | 项禁用,与根/disabledKeys 合并。 | +| `variant` | `"default" \| "danger"` | `"default"` | 视觉变体。 | +| `as` | `string` | `"div"` | 原生标签,对应 React render 的元素替换用途。 | +| `class` / `style` / ARIA / DOM 事件 | Vue 原生属性 | — | 透传实际 role=option 节点,调用方事件先执行,取消后不改选。 | + +`@select` 接收可取消的 `CustomEvent<{ key: ListBoxKey; originalEvent: MouseEvent | KeyboardEvent }>`;`preventDefault()` 阻止选择和 action。Root 的 DOM `@keydown.prevent` 同样在内部导航前生效。 + +### ListBoxItemIndicator + +| 属性 / 插槽 | 类型 | 默认值 | 描述 | +| ----------------- | ------------------ | ------------ | ----------------------------------- | +| `as` | `string` | `"span"` | 装饰性容器,aria-hidden。 | +| `class` / `style` | Vue 原生属性 | — | 增量合并。 | +| 默认插槽 | `ListBoxItemState` | 基线勾选图标 | 自定义选中图标,可使用 Tabler Vue。 | + +### ListBoxSection + +| 属性 | 类型 | 默认值 | 描述 | +| ------------------------ | ------------ | ------- | ------------------------------------------- | +| `as` | `string` | `"div"` | role=group 的原生容器。 | +| `class` / `style` / ARIA | Vue 原生属性 | — | 增量合并;显式 aria-label/labelledby 优先。 | + +默认插槽放置 Header 与 Item。直接、Fragment 或原生容器内的 Header 自动关联;任意用户组件内的 Header 请提供显式 id 与 Section 的 aria-labelledby。Item 内 Label/Description 支持同样的静态规划边界,自定义包装请显式关联。显式 aria-label 不被自动标签覆盖。 + +### 作用域插槽状态 + +Item 和 ItemIndicator 的默认插槽共享以下状态: + +| 状态 | 类型 | 描述 | +| ---------------- | --------- | ------------------ | +| `isSelected` | `boolean` | 项是否选中。 | +| `isFocused` | `boolean` | 项是否实际聚焦。 | +| `isFocusVisible` | `boolean` | 是否显示键盘焦点。 | +| `isDisabled` | `boolean` | 项是否禁用。 | +| `isPressed` | `boolean` | 是否按下。 | +| `isHovered` | `boolean` | 是否悬停。 | + +## 无障碍 + +列表使用 role=listbox / option / group,支持单一 Tab 入口、方向键、Home/End、按视口移动的 PageUp/PageDown、Enter/Space、首字母搜索与 IME 避让。多选支持 Ctrl/Command+A 和 Shift 范围选择。横向导航遵循 dir,禁用项不可激活;只读项仍可聚焦。 + +node SSR 输出选中状态、名称和描述;虚拟列表首屏为滚动容器,挂载后按测量显示可见行。读屏、触屏和完整视觉比较的已验证范围见仓库验证报告,不声明已经完整兼容 React Aria。 diff --git a/apps/docs/demos/list-box-controlled.vue b/apps/docs/demos/list-box-controlled.vue new file mode 100644 index 0000000..562eeb6 --- /dev/null +++ b/apps/docs/demos/list-box-controlled.vue @@ -0,0 +1,67 @@ + + + + + + + + + {{ user.name[0] }} + + + {{ user.name }} + {{ user.email }} + + + + + + + + + 已选:{{ selected.length ? selected.join("、") : "无" }} + + + diff --git a/apps/docs/demos/list-box-custom-check-icon.vue b/apps/docs/demos/list-box-custom-check-icon.vue new file mode 100644 index 0000000..aba581c --- /dev/null +++ b/apps/docs/demos/list-box-custom-check-icon.vue @@ -0,0 +1,58 @@ + + + + + + + + {{ user.name[0] }} + + + {{ user.name }} + {{ user.email }} + + + + + + + + diff --git a/apps/docs/demos/list-box-custom-styles.vue b/apps/docs/demos/list-box-custom-styles.vue new file mode 100644 index 0000000..052fa8c --- /dev/null +++ b/apps/docs/demos/list-box-custom-styles.vue @@ -0,0 +1,58 @@ + + + + + + + {{ user.name[0] }} + + + {{ user.name }} + {{ user.email }} + + + + + diff --git a/apps/docs/demos/list-box-default.vue b/apps/docs/demos/list-box-default.vue new file mode 100644 index 0000000..e435eaf --- /dev/null +++ b/apps/docs/demos/list-box-default.vue @@ -0,0 +1,54 @@ + + + + + + + {{ user.name[0] }} + + + {{ user.name }} + {{ user.email }} + + + + + diff --git a/apps/docs/demos/list-box-multi-select.vue b/apps/docs/demos/list-box-multi-select.vue new file mode 100644 index 0000000..4d5a0d8 --- /dev/null +++ b/apps/docs/demos/list-box-multi-select.vue @@ -0,0 +1,55 @@ + + + + + + + + {{ user.name[0] }} + + + {{ user.name }} + {{ user.email }} + + + + + + diff --git a/apps/docs/demos/list-box-render-function.vue b/apps/docs/demos/list-box-render-function.vue new file mode 100644 index 0000000..dda1cae --- /dev/null +++ b/apps/docs/demos/list-box-render-function.vue @@ -0,0 +1,61 @@ + + + + + + + {{ user.name[0] }} + + + {{ user.name }} + {{ user.email }} + + + + + diff --git a/apps/docs/demos/list-box-virtualization.vue b/apps/docs/demos/list-box-virtualization.vue new file mode 100644 index 0000000..1d13d8c --- /dev/null +++ b/apps/docs/demos/list-box-virtualization.vue @@ -0,0 +1,82 @@ + + + + + + {{ item.name }} + {{ item.email }} + + + + + diff --git a/apps/docs/demos/list-box-with-disabled-items.vue b/apps/docs/demos/list-box-with-disabled-items.vue new file mode 100644 index 0000000..ce31950 --- /dev/null +++ b/apps/docs/demos/list-box-with-disabled-items.vue @@ -0,0 +1,88 @@ + + + + + + + 操作 + + + + + + {{ action.title }} + {{ action.description }} + + + + {{ action.shortcut }} + + + + + + 危险区域 + + + + + + 删除文件 + 移至废纸篓 + + + + + D + + + + + + {{ message }} + + diff --git a/apps/docs/demos/list-box-with-sections.vue b/apps/docs/demos/list-box-with-sections.vue new file mode 100644 index 0000000..24a673f --- /dev/null +++ b/apps/docs/demos/list-box-with-sections.vue @@ -0,0 +1,87 @@ + + + + + + + 操作 + + + + + + {{ action.title }} + {{ action.description }} + + + + {{ action.shortcut }} + + + + + + 危险区域 + + + + + + 删除文件 + 移至废纸篓 + + + + + D + + + + + + {{ message }} + + diff --git a/docs/compatibility.md b/docs/compatibility.md index faecce5..1eabe6e 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -70,9 +70,9 @@ | radio-group | 验证中(基线实现) | 标量模型、roving Tab/方向键/dir/loop、原生提交/校验/reset;12 个基线预览 | | input-otp | 验证中(M32) | Root/Group/Slot/Separator + 3 正则常量;Reka PinInput 底座;字符串+索引数组;reset/Fieldset/Form/ARIA/mask 已接入;11/11 例;自动填充/IME/读屏未真机验证 | | alert | 验证中(最小实现) | status 五态;默认图标随 status;自定义 Indicator 空内容回退;内部 Surface 重置为 default | -| list-box | 基建中(未公开) | 私有 typed key、接受值状态、挂载成员协议及 Reka 审计已实现;公共组件/9 与 19 个基线预览尚未迁移,见 COLLECTION-01 | -| list-box-item | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | -| list-box-section | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | +| list-box | 验证中(LISTBOX-01) | 四部件、9/9 基线例;typed key/数组模型、none/single/multiple、键盘/范围/全选、1000 项固定行高虚拟化;差异见 LISTBOX-01 | +| list-box-item | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 | +| list-box-section | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 | | dropdown | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | menu | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | menu-item | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | @@ -80,7 +80,7 @@ | modal | 验证中(OVERLAY-02) | Root/Trigger/Backdrop/Container/Dialog/Heading/Header/Body/Footer/Icon/Close/CloseTrigger;14/14 基线例;焦点/锁/滚动/退出动画;Vue close 部件替代 React slot | | pagination | 验证中(M30) | 组合式 nav 容器(无 total/page 状态机);11 具名部件;9/9 基线例;onPress→@click;显式 aria-current 可覆盖 | | number-field | 验证中(NUMBER-01) | 五部件与 17/17 基线例;Reka 数值内核;受控/只读/表单 reset、SSR/水合;差异见 NUMBER-01 报告 | -| select | 基建中(未公开) | 私有 typed key、接受值状态、挂载成员协议及 Reka 审计已实现;公共组件/9 与 19 个基线预览尚未迁移,见 COLLECTION-01 | +| select | 基建中(未公开) | 集合状态与公开 ListBox 已落地;Select 六部件、字段/弹层/SSR 接入及 19 个基线预览仍待迁移,见 COLLECTION-01 | | meter | 验证中(M20) | Meter/Output/Track/Fill;6/6 基线例;role=meter progressbar;无 isIndeterminate;测量语义独立于 Progress | | slider | 验证中(SLIDER-01) | 六部件、9/9 基线例;原生 range/局部指针适配,单值/范围、受控/reset/SSR/水合;差异见 SLIDER-01 | | table | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | diff --git a/docs/decisions/collection-foundation.md b/docs/decisions/collection-foundation.md index 1f2a920..9291230 100644 --- a/docs/decisions/collection-foundation.md +++ b/docs/decisions/collection-foundation.md @@ -63,3 +63,11 @@ 公共实际 DOM 和 FormData、受控拒绝/重试、单多选空值、禁用/只读/Fieldset、required 和 Form 错误响应、取消 reset / form 归属、名称优先级、动态增删/重排/禁用项、键盘/IME/typeahead、范围/全选、Select 清空/关闭、异步值标签、虚拟滚动、嵌套弹层、node SSR 与实际水合、独立产物类型正反例。浏览器在 5174 只重点验几何、滚动、焦点和动效。 当前状态层及底座探针不覆盖上面这些公共组件验收,也没有逐像素、读屏、触屏或 Nuxt 结论。 + +## LISTBOX-01 公共实现接续 + +前文“尚未导出”是 COLLECTION-01 审计阶段的历史状态。ListBox 四部件和九个预览已接入,见 [LISTBOX-01 报告](../migrations/LISTBOX-01-list-box.md)。Select 公共组件与十九个预览仍未实现。 + +新增原始 Reka 探针确认:Content 的用户 keydown preventDefault 后,End 仍移动焦点。结合 none 语义、完整数据虚拟化与 textValue / 元数据需求,公共 ListBox 使用局部原生 role 节点与既有集合内核,VueUse 维护虚拟滚动测量;不修改依赖、不调用私有上下文,也不引入另一套组件底座。普通列表与虚拟列表共用唯一逻辑集合、选择和焦点状态。 + +泛型 SFC 不通过 Parameters 提取公共 Props:实测会让模型/模式反例失效。Root 和导出的 Props 复用 ListBoxOptions 明确 schema,保留消费端正反例;不能以 skipLibCheck 或删除反例规避。 diff --git a/docs/migration-handoff.md b/docs/migration-handoff.md index 10e7602..e6e4a55 100644 --- a/docs/migration-handoff.md +++ b/docs/migration-handoff.md @@ -257,3 +257,7 @@ Modal / Popover / Tooltip 公共迁移与全部 26 个基线预览已接入, ## 集合基建实施中(COLLECTION-01) 集成人负责独立分支的 [ListBox/Select 集合基建](decisions/collection-foundation.md),其他 AI 继续 AlertDialog/Drawer。typed key、接受值选择状态和挂载成员注册为私有设施,暂不交给其他 AI 扩展或视为公共组件已完成。Reka 的多选显示与表单提交必须分别验;虚拟化全集与挂载 registry 必须区分。公共迁移、字段/标签作用域、SSR 元数据和 9/19 个基线预览按决策文档接续。 + +## LISTBOX-01 接续 + +ListBox 已完成公共首轮实现,见 [报告](migrations/LISTBOX-01-list-box.md)。后续 Select / ComboBox 等可沿用 typed key、接受值模型、项内文本作用域与完整数据集合;不能把独立 ListBox 的 action/选择直接当作 Select 的关闭与表单契约。Select 的十九个预览、唯一提交层、字段名称、SSR 展示元数据、清除和嵌套定位仍归集成人实施。 diff --git a/docs/migrations/LISTBOX-01-list-box.md b/docs/migrations/LISTBOX-01-list-box.md new file mode 100644 index 0000000..8f30174 --- /dev/null +++ b/docs/migrations/LISTBOX-01-list-box.md @@ -0,0 +1,33 @@ +# LISTBOX-01:ListBox 公共迁移 + +2026-10-23,独立目录 `heroui-vue-core`,`feat/listbox-select-foundation`。固定 HeroUI 3.2.6 / ce90ea3;COLLECTION-01 私有基建从 dea5ded 接续,Select 仍待实施。 + +## 交付 + +- ListBox / ListBoxRoot、ListBoxItem、ListBoxItemIndicator、ListBoxSection;具名部件、Props、key/data/state 类型和三个 tv 导出。 +- 完整移植 list-box、list-box-item、list-box-section CSS/tv,改 hv- 命名空间,保留 36px 最小项高、12px gap、16px 圆角、缩放 0.98、250/150ms 和勾选 stroke 动画、reduced-motion;原许可证见 third-party/HEROUI-LICENSE。Item 变体独立于 Root,与源 tv 对应。 +- 中文正文九个预览按原顺序:default、with-disabled-items、with-sections、multi-select、controlled、virtualization、custom-check-icon、render-function、custom-styles。使用同份 SFC 做预览/高亮/复制,图标用 Tabler Vue,默认勾选来自源许可图形。 +- 保留头像数据、邮件、分组与快捷键、自定义 Tailwind 示例、1000 条确定数据、50px 行高、400×300 虚拟列表。action 演示将浏览器 alert 改为当前示例中的可访问状态反馈。 +- 单选/多选/none、toggle/replace、受控拒绝/重试、禁用/Fieldset/只读、方向/RTL/边界、范围/全选、typeahead/IME、取消与实际焦点、组和项的 ARIA 关联。 + +## 实现与差异 + +安装版 Reka 的能力与缺口见 [集合审计](../decisions/collection-foundation.md)。公共 ListBox 使用原生 listbox/option/group 节点和私有集合内核;使用既有 VueUse useVirtualList 测量/滚动,不另加依赖。原始探针保留 Reka Content 导航取消过晚这一事实,公共测试独立验证已修复的取消语义。 + +- Vue `v-model` / selectedKeys 是 key 数组,单选也为数组;不直接接受 RAC Set / "all"。selectAll() 选择当前已知可用全集,受控时发提案。数字 0 / 字符串 "0" / 空字符串分别保留身份,DOM id 使用实例 ID,避免同页重复。 +- 数据模式用 items + 作用域 item/index 插槽;复杂内容的未挂载项搜索需要数据 textValue。虚拟化的全选、范围和导航使用完整数据,挂载 registry 只表示可见成员。普通列表读取实际 DOM 顺序。 +- Enter 在按下时激活,Space 在松开时激活;按住重复键不重复激活。用户 DOM 处理器由 Vue 执行并先于内部行为,支持 capture、preventDefault 和数组 stopImmediatePropagation,不使用私有 invoker 标记。keyup 捕获只释放按下外观,不绕过取消执行选择。 +- action 在可用项点击或键盘激活时发出,与 selectionChange 分开;none 保持不选中。拖放、链接路由适配、RAC render 函数与框架集合对象不宣称完整等价;as / Vue 插槽承担元素和内容替换。 +- ListBox 本身不是表单字段,不生成额外隐藏输入。字段提交/reset/required 在后续 Select 层实现,沿用现有字段协议,不把 Reka Listbox 的索引提交层暴露给用户。 +- 项内复用字段 Label/Description 规划与注册;每项独立作用域,不向外层 Select/Form 注册选项标签。Section Header 自动规划;任意用户组件内的标签/标题仍需要显式 ID/ARIA,未执行其 setup 来探测内容。 +- 当前虚拟化仅竖向固定行高;可变行高、虚拟分组、ListLayout 的其他参数和拖放布局未实现。虚拟 SSR 输出容器,挂载后按测量显示行;普通列表 SSR 输出真实选中状态、ID 和标签关联。 + +## 验证 + +- 22 项公共行为/同页示例/实际 jsdom 水合测试,2 项真正 node SSR 测试,新增 1 项原始 Reka 取消探针。完整测试最终数量见 verification.md。 +- 正反例涵盖模型、非法 key、selectionMode、variant、必填 Item id 和 selectionChange 参数推断。Root/Props 共用明确 schema;泛型 SFC Parameters 提取实测会退化,已避免。 +- 5174 浏览器重点验证受控多选状态和指示器、实际 Space 按键、虚拟列表 End 到第 1000 项及 Home、连续输入 Liam 保持第二项、鼠标后 Tab 返回原项及焦点环、深浅色;末行焦点同时在列表和页面可视范围内。1000 项只挂载约 12–14 行,400px 容器的 scrollHeight 约 50008px(含源 padding)。 +- 1280×720 浏览器下九张 API/样式/状态表均 736px,scrollWidth=clientWidth;长内容换行,短表不缩小。没有逐个点击全部示例。 +- pnpm test、typecheck、build:docs、Prettier、独立 tarball ESM/SSR/CSS/NodeNext/bundler 的最终结果在完成后记录到 verification.md;构建只有既存 chunk 超过 500kB 提示。 + +未做逐像素自动视觉、完整读屏/触屏、移动视口和 Nuxt 验收。源码/构建、node SSR、jsdom 水合与真实浏览器的结论分别记录,不互相替代。 diff --git a/docs/upstream.md b/docs/upstream.md index f714f86..15caff2 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -166,3 +166,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生 - 固定 ce90ea3 的 ListBox / ListBoxItem / ListBoxSection / Select 源码、CSS/tv、中文正文和 9/19 预览作为后续公共实现清单。本轮未复制这些组件 CSS 或演示。 - 直接使用安装版 Reka 2.11.0(MIT)公开导出构造测试夹具;未修改 node_modules、未复制内部 Collection/Select 实现。私有 key、状态和成员层为 Vue 实现。 - 依据、实际缺口及阶段边界见 [集合基建决策](decisions/collection-foundation.md)。 + +## LISTBOX-01(2026-10-23) + +固定 ce90ea3 的 list-box / list-box-item / list-box-section 源码、CSS/tv,以及中文正文和九个预览。CSS/tv 按 hv- 移植,源勾选图形遵循原 Apache-2.0;文档图标用现有 Tabler Vue。原 alert 演示改为内联状态反馈,React render 改 as/插槽,Virtualizer/ListLayout 改 VueUse 固定行高虚拟化。依据、差异与限制见 [LISTBOX-01](migrations/LISTBOX-01-list-box.md)。 diff --git a/docs/verification.md b/docs/verification.md index 9bd022c..eebf067 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -639,3 +639,11 @@ typecheck、build:docs、build:playground、format、diff-check 与 dist 正反 - 新增 19 项 key/接受值/成员协议回归、8 项安装版 Reka Listbox/Select jsdom 探针、4 项真正 node SSR 探针,共 31 项。完整 `pnpm test`:42 文件 / 624 项通过;`pnpm typecheck`、`pnpm build` 通过。 - 断言包括 typed key、受控拒绝重试、禁用初值改选、不可变快照、DOM 重排、动态碰撞、清理/实例隔离、焦点、实际 FormData 和 SSR 缺口。底座缺陷的审计断言不代表公共组件已修复。 - 本轮无公共导出或页面改动,未进行浏览器/文档视觉、实际水合、独立产物消费或完整 ListBox/Select 验收。详细边界和 9/19 基线清单见 [集合基建决策](decisions/collection-foundation.md)。 + +## LISTBOX-01 公共迁移(2026-10-23) + +- 最终 `pnpm test`:44 文件 / 649 项通过;其中 ListBox 公共行为、九例同页挂载和实际 jsdom 水合 22 项,真正 node SSR 2 项。原始 Reka 取消探针单独保留,不作为公共验收替代。 +- `pnpm typecheck`、`pnpm build:docs`、Prettier 和 git diff --check 通过;库与生产文档包含完整新导出/CSS,只有既存 chunk 超过 500kB 提示。 +- 最终 tarball 在 `/private/tmp/heroui-slider-consumer` 重新安装,ListBox ESM/SSR/CSS、NodeNext / bundler 严格正反例通过;并保留 NumberField/Slider、M30–M32 消费回归。泛型 Props 的非法模型/模式反例没有被删除或放宽。 +- 5174 浏览器重点验证受控选择/Space、虚拟 End 到第 1000 项及 Home、连续 Liam 搜索、深浅色、鼠标后 Tab 返回原项与焦点环。1280×720 下九张表均为正文 736px,scrollWidth=clientWidth。 +- 普通列表 SSR 的选中/ID/名称/描述与水合已验;虚拟 SSR 是容器,挂载后测量显示固定高度行。可变行高/虚拟分组、自动逐像素、读屏/触屏、移动视口和 Nuxt 未验收。详见 [LISTBOX-01](migrations/LISTBOX-01-list-box.md)。Select 公共组件未完成。 diff --git a/package.json b/package.json index bd3ff60..aa40ab6 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", - "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", + "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", + "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", "format": "prettier --check .", "format:fix": "prettier --write .", "dev:playground": "pnpm build && pnpm --filter @heroui-vue/playground dev" diff --git a/packages/styles/components/list-box-item.css b/packages/styles/components/list-box-item.css new file mode 100644 index 0000000..c692b82 --- /dev/null +++ b/packages/styles/components/list-box-item.css @@ -0,0 +1,121 @@ +/* Adapted from HeroUI ce90ea3. Apache-2.0; see third-party/HEROUI-LICENSE. */ +/* ========================================================================== + Base list-box item styles + ========================================================================== */ + +.hv-list-box-item { + @apply relative flex min-h-9 w-full items-center justify-start gap-3 rounded-2xl px-2 py-1.5 outline-none no-highlight; + + /** + * Transitions + * CRITICAL: motion-reduce must be AFTER transition for correct override specificity + */ + transition: + transform 250ms var(--ease-out-quart), + box-shadow 150ms var(--ease-out); + + @apply motion-reduce:transition-none; + + /* Cursor */ + cursor: var(--cursor-interactive); + + [data-slot="label"] { + @apply pointer-events-none w-fit select-none; + } + + [data-slot="description"] { + @apply pointer-events-none text-wrap select-none; + } + + /* Add inline-end padding when indicator is present */ + &:has(.hv-list-box-item__indicator) { + @apply pe-7; + } + + /* Focus visible state (keyboard focus only). + React Aria always sets data-focused when it owns the item, so the native + fallback is scoped to consumers rendering this class outside React Aria. */ + &:focus-visible:not([data-focused]), + &[data-focus-visible="true"] { + @apply status-focused; + } + + /* Focus state */ + &:focus, + &[data-focus="true"] { + } + + /* Pressed state */ + &:active, + &[data-pressed="true"] { + transform: scale(0.98); + } + + /* Hover state */ + @media (hover: hover) { + &:hover, + &[data-hovered="true"] { + @apply bg-default; + } + } + + /* Selected state */ + &[aria-selected="true"], + &[data-selected="true"] { + } + + /* Disabled state */ + &[data-disabled="true"] { + @apply status-disabled; + } +} + +/* ========================================================================== + List-box item indicator + ========================================================================== */ + +.hv-list-box-item__indicator { + @apply absolute end-2 top-1/2 flex size-4 shrink-0 -translate-y-1/2 items-center justify-center text-default-foreground; + + /** + * Transitions + */ + @apply transition duration-250 motion-reduce:transition-none; + + /* Checkmark SVG indicator */ + [data-slot="list-box-item-indicator--checkmark"] { + @apply size-2.5; + + /** + * Transitions + */ + @apply transition-all duration-300 motion-reduce:transition-none; + } + + .hv-list-box-item[aria-selected="true"] + [data-slot="list-box-item-indicator--checkmark"], + .hv-list-box-item[data-selected="true"] + [data-slot="list-box-item-indicator--checkmark"] { + /** + * Transitions + * CRITICAL: motion-reduce must be AFTER transition for correct override specificity + */ + transition: stroke-dashoffset 250ms linear; + @apply motion-reduce:transition-none; + } +} + +/* Default variant */ +.hv-list-box-item--default { +} + +/* Danger variant */ +.hv-list-box-item--danger { + .hv-list-box-item__indicator { + @apply text-danger; + } + + [data-slot="label"] { + @apply text-danger; + } +} diff --git a/packages/styles/components/list-box-section.css b/packages/styles/components/list-box-section.css new file mode 100644 index 0000000..d5656b0 --- /dev/null +++ b/packages/styles/components/list-box-section.css @@ -0,0 +1,8 @@ +/* Adapted from HeroUI ce90ea3. Apache-2.0; see third-party/HEROUI-LICENSE. */ +/* ========================================================================== + Base list-box section styles + ========================================================================== */ + +.hv-list-box-section { + @apply flex flex-col items-start gap-0; +} diff --git a/packages/styles/components/list-box.css b/packages/styles/components/list-box.css new file mode 100644 index 0000000..8e1ac7b --- /dev/null +++ b/packages/styles/components/list-box.css @@ -0,0 +1,26 @@ +/* Adapted from HeroUI ce90ea3. Apache-2.0; see third-party/HEROUI-LICENSE. */ +/* ========================================================================== + Base list-box styles + ========================================================================== */ + +.hv-list-box { + @apply relative w-full overflow-clip p-1; + + /** + * Spacing between direct children. + * + * NOTE: We intentionally avoid `display: flex` + `gap` here because + * react-aria's Virtualizer renders a `position: relative` content + * div with an explicit large height (e.g. 50000px) as the only child + * of the ListBox. Flex shrinking would collapse that height and break + * scrollbar sizing during virtualized scroll. + */ + & > * + * { + @apply mt-1; + } + + /* This makes the horizontal separator take up 94% of the width and be centered */ + [data-slot="separator"][data-orientation="horizontal"] { + @apply ms-[3%] w-[94%]; + } +} diff --git a/packages/styles/index.css b/packages/styles/index.css index eb66c50..2b3d3c2 100644 --- a/packages/styles/index.css +++ b/packages/styles/index.css @@ -141,3 +141,7 @@ @import "./components/number-field.css"; @import "./components/slider.css" layer(components); + +@import "./components/list-box.css" layer(components); +@import "./components/list-box-item.css" layer(components); +@import "./components/list-box-section.css" layer(components); diff --git a/packages/styles/src/index.ts b/packages/styles/src/index.ts index abcb5bd..b0c9017 100644 --- a/packages/styles/src/index.ts +++ b/packages/styles/src/index.ts @@ -1273,3 +1273,28 @@ export const sliderVariants = tv({ }, }); export type SliderVariants = VariantProps; + +// Adapted from HeroUI ce90ea3, Apache-2.0. +export const listboxVariants = tv({ + base: "hv-list-box", + defaultVariants: { variant: "default" }, + variants: { + variant: { default: "hv-list-box--default", danger: "hv-list-box--danger" }, + }, +}); +export type ListBoxVariants = VariantProps; +export const listboxItemVariants = tv({ + slots: { item: "hv-list-box-item", indicator: "hv-list-box-item__indicator" }, + defaultVariants: { variant: "default" }, + variants: { + variant: { + default: { item: "hv-list-box-item--default" }, + danger: { item: "hv-list-box-item--danger" }, + }, + }, +}); +export type ListBoxItemVariants = VariantProps; +export const listboxSectionVariants = tv({ base: "hv-list-box-section" }); +export type ListBoxSectionVariants = VariantProps< + typeof listboxSectionVariants +>; diff --git a/packages/vue/src/components/collection/registry.ts b/packages/vue/src/components/collection/registry.ts index 864ef34..b59082b 100644 --- a/packages/vue/src/components/collection/registry.ts +++ b/packages/vue/src/components/collection/registry.ts @@ -10,10 +10,12 @@ export interface CollectionMember { /** One registry per collection provider. No document queries or global IDs. * Read order at interaction time: Vue can reorder nodes without changing refs. */ -export function useCollectionRegistry() { - const members = shallowRef([]); +export function useCollectionRegistry< + T extends CollectionMember = CollectionMember, +>() { + const members = shallowRef([]); - function ordered(): CollectionMember[] { + function ordered(): T[] { const seen = new Set(); for (const member of members.value) { const key = member.key(); @@ -32,7 +34,7 @@ export function useCollectionRegistry() { }); } - function register(member: CollectionMember): () => void { + function register(member: T): () => void { assertKey(member.key()); if (ordered().some((item) => item.key() === member.key())) { throw new Error(`Duplicate collection key: ${member.key()}`); @@ -52,7 +54,7 @@ export function useCollectionRegistry() { key: CollectionKey | undefined, intent: "first" | "last" | "next" | "previous", loop = false, - ): CollectionMember | undefined { + ): T | undefined { const items = available(); if (intent === "first") return items[0]; if (intent === "last") return items.at(-1); diff --git a/packages/vue/src/components/list-box/ListBox.vue b/packages/vue/src/components/list-box/ListBox.vue new file mode 100644 index 0000000..b2f0814 --- /dev/null +++ b/packages/vue/src/components/list-box/ListBox.vue @@ -0,0 +1,496 @@ + + + + + + + + + + + + + + + + diff --git a/packages/vue/src/components/list-box/ListBoxItem.vue b/packages/vue/src/components/list-box/ListBoxItem.vue new file mode 100644 index 0000000..f2f4b54 --- /dev/null +++ b/packages/vue/src/components/list-box/ListBoxItem.vue @@ -0,0 +1,212 @@ + diff --git a/packages/vue/src/components/list-box/ListBoxItemIndicator.vue b/packages/vue/src/components/list-box/ListBoxItemIndicator.vue new file mode 100644 index 0000000..df90808 --- /dev/null +++ b/packages/vue/src/components/list-box/ListBoxItemIndicator.vue @@ -0,0 +1,39 @@ + + + + + + + + + + + diff --git a/packages/vue/src/components/list-box/ListBoxSection.vue b/packages/vue/src/components/list-box/ListBoxSection.vue new file mode 100644 index 0000000..1663f75 --- /dev/null +++ b/packages/vue/src/components/list-box/ListBoxSection.vue @@ -0,0 +1,61 @@ + diff --git a/packages/vue/src/components/list-box/context.ts b/packages/vue/src/components/list-box/context.ts new file mode 100644 index 0000000..13b9611 --- /dev/null +++ b/packages/vue/src/components/list-box/context.ts @@ -0,0 +1,69 @@ +import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue"; +import type { CollectionKey } from "../collection/keys"; +import type { CollectionMember } from "../collection/registry"; +import type { CollectionSelectionMode } from "../collection/selection"; + +export type ListBoxKey = CollectionKey; +export interface ListBoxDataItem { + id: ListBoxKey; + textValue?: string; + isDisabled?: boolean; +} +/** Shared schema: generic SFC parameter extraction can erase its prop types. */ +export interface ListBoxOptions { + modelValue?: readonly ListBoxKey[]; + selectedKeys?: readonly ListBoxKey[]; + defaultValue?: readonly ListBoxKey[]; + defaultSelectedKeys?: readonly ListBoxKey[]; + selectionMode?: CollectionSelectionMode; + selectionBehavior?: "toggle" | "replace"; + disabledKeys?: readonly ListBoxKey[]; + isDisabled?: boolean; + isReadOnly?: boolean; + disallowEmptySelection?: boolean; + orientation?: "vertical" | "horizontal"; + dir?: "ltr" | "rtl"; + loop?: boolean; + variant?: "default" | "danger"; + as?: string; + items?: readonly T[]; + virtualized?: boolean; + rowHeight?: number; + overscan?: number; +} +export interface ListBoxItemState { + isSelected: boolean; + isDisabled: boolean; + isFocused: boolean; + isFocusVisible: boolean; + isPressed: boolean; + isHovered: boolean; +} +export interface ListBoxMember extends CollectionMember { + activate: (event: MouseEvent | KeyboardEvent) => void; +} +export interface ListBoxContext { + mode: ComputedRef; + readOnly: ComputedRef; + keyboard: Ref; + focused: Ref; + noteFocus: (key: ListBoxKey) => void; + pressed: Ref; + active: ComputedRef; + selected: (key: ListBoxKey) => boolean; + disabled: (key: ListBoxKey) => boolean; + register: (member: ListBoxMember) => () => void; + activate: (key: ListBoxKey, event: MouseEvent | KeyboardEvent) => void; + focus: (key: ListBoxKey) => Promise; + virtualized: () => boolean; + restoreFocus: () => void; + position: (key: ListBoxKey) => { index: number; size: number } | undefined; +} +export const listBoxKey: InjectionKey = Symbol("hv-list-box"); +export const listBoxItemKey: InjectionKey<() => ListBoxItemState> = + Symbol("hv-list-box-item"); +export function useListBox() { + const context = inject(listBoxKey); + if (!context) throw new Error("ListBoxItem requires ListBox."); + return context; +} diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index c0d0d5a..f01ae1c 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -630,3 +630,31 @@ export type { SliderOutputProps, SliderMarksProps, } from "./types"; + +export { + default as ListBox, + default as ListBoxRoot, +} from "./components/list-box/ListBox.vue"; +export { default as ListBoxItem } from "./components/list-box/ListBoxItem.vue"; +export { default as ListBoxItemIndicator } from "./components/list-box/ListBoxItemIndicator.vue"; +export { default as ListBoxSection } from "./components/list-box/ListBoxSection.vue"; +export type { + ListBoxKey, + ListBoxDataItem, + ListBoxItemState, +} from "./components/list-box/context"; +export type { + ListBoxProps, + ListBoxRootProps, + ListBoxItemProps, + ListBoxItemIndicatorProps, + ListBoxSectionProps, +} from "./types"; +export { + listboxVariants, + listboxItemVariants, + listboxSectionVariants, + type ListBoxVariants, + type ListBoxItemVariants, + type ListBoxSectionVariants, +} from "@heroui-vue/styles"; diff --git a/packages/vue/src/types.ts b/packages/vue/src/types.ts index 47266c0..426350a 100644 --- a/packages/vue/src/types.ts +++ b/packages/vue/src/types.ts @@ -16,6 +16,35 @@ import type AvatarGroupCount from "./components/avatar/AvatarGroupCount.vue"; import type Skeleton from "./components/skeleton/Skeleton.vue"; export type ButtonProps = InstanceType["$props"]; + +export type ListBoxProps< + T extends import("./components/list-box/context").ListBoxDataItem = + import("./components/list-box/context").ListBoxDataItem, +> = import("./components/list-box/context").ListBoxOptions & + import("vue").HTMLAttributes & { + "onUpdate:modelValue"?: ( + keys: import("./components/list-box/context").ListBoxKey[], + ) => void; + onSelectionChange?: ( + keys: import("./components/list-box/context").ListBoxKey[], + ) => void; + onAction?: ( + key: import("./components/list-box/context").ListBoxKey, + ) => void; + }; +export type ListBoxRootProps< + T extends import("./components/list-box/context").ListBoxDataItem = + import("./components/list-box/context").ListBoxDataItem, +> = ListBoxProps; +export type ListBoxItemProps = InstanceType< + typeof import("./components/list-box/ListBoxItem.vue").default +>["$props"]; +export type ListBoxItemIndicatorProps = InstanceType< + typeof import("./components/list-box/ListBoxItemIndicator.vue").default +>["$props"]; +export type ListBoxSectionProps = InstanceType< + typeof import("./components/list-box/ListBoxSection.vue").default +>["$props"]; export type CardProps = InstanceType["$props"]; export type InputProps = InstanceType["$props"]; export type SwitchProps = InstanceType["$props"]; diff --git a/packages/vue/tests/fixtures/CollectionFoundation.vue b/packages/vue/tests/fixtures/CollectionFoundation.vue index f2df54b..280b4fe 100644 --- a/packages/vue/tests/fixtures/CollectionFoundation.vue +++ b/packages/vue/tests/fixtures/CollectionFoundation.vue @@ -10,6 +10,7 @@ withDefaults( multiple?: boolean; disabled?: boolean; name?: string; + cancelNavigation?: boolean; }>(), { modelValue: undefined, defaultValue: undefined }, ); @@ -26,7 +27,14 @@ const emit = defineEmits<{ "update:modelValue": [value: unknown] }>(); :name="name" @update:model-value="emit('update:modelValue', $event)" > - + { + if (cancelNavigation) event.preventDefault(); + } + " + > Numeric zero String zero Disabled diff --git a/tests/collection-foundation.test.ts b/tests/collection-foundation.test.ts index 9100ae7..ac72a6a 100644 --- a/tests/collection-foundation.test.ts +++ b/tests/collection-foundation.test.ts @@ -95,6 +95,14 @@ function fixture(props: Record = {}) { } describe("installed Reka Listbox audit — not public component acceptance", () => { + it("records that a cancelled Content keydown still performs navigation", async () => { + const wrapper = fixture({ cancelNavigation: true }); + await flushPromises(); + await wrapper.get('[role="listbox"]').trigger("keydown", { key: "End" }); + expect(document.activeElement).toBe( + wrapper.findAll('[role="option"]')[1].element, + ); + }); it("distinguishes numeric and string zero and toggles multiple values", async () => { const wrapper = fixture({ multiple: true, defaultValue: [0] }); await flushPromises(); diff --git a/tests/list-box-ssr.test.ts b/tests/list-box-ssr.test.ts new file mode 100644 index 0000000..f7d924a --- /dev/null +++ b/tests/list-box-ssr.test.ts @@ -0,0 +1,70 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { createSSRApp, defineComponent, h } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import { + ListBox, + ListBoxItem, + ListBoxItemIndicator, + ListBoxSection, + Label, + Description, + Header, +} from "../packages/vue/src"; + +describe("ListBox public node SSR", () => { + it("renders selection, option names, descriptions and section names without browser globals", async () => { + expect(typeof window).toBe("undefined"); + const app = createSSRApp( + defineComponent({ + render: () => + h(ListBox, { defaultValue: [0], "aria-label": "People" }, () => [ + h(ListBoxSection, {}, () => [ + h(Header, {}, () => "Team"), + h(ListBoxItem, { id: 0 }, () => [ + h(Label, {}, () => "Bob"), + h(Description, {}, () => "Details"), + h(ListBoxItemIndicator), + ]), + ]), + h(ListBoxItem, { id: "0" }, () => "Fred"), + ]), + }), + ); + const html = await renderToString(app); + expect(html).toContain('aria-selected="true"'); + expect(html).toContain('aria-selected="false"'); + expect(html).toContain('role="listbox"'); + expect(html).toContain("aria-describedby="); + expect(html).toContain("aria-labelledby="); + const ids = [...html.matchAll(/ id="([^"]+)"/g)].map((match) => match[1]); + for (const match of html.matchAll( + /aria-(?:labelledby|describedby)="([^"]+)"/g, + )) + for (const id of match[1].split(" ")) expect(ids).toContain(id); + expect(new Set(ids).size).toBe(ids.length); + }); + + it("isolates keys/IDs across two lists and independent SSR requests", async () => { + const app = () => + createSSRApp({ + render: () => + h( + "main", + Array.from({ length: 2 }, () => + h(ListBox, { defaultValue: [""] }, () => + h(ListBoxItem, { id: "" }, () => + h(Label, {}, () => "Empty key"), + ), + ), + ), + ), + }); + const first = await renderToString(app()), + second = await renderToString(app()); + expect(first).toBe(second); + const ids = [...first.matchAll(/ id="([^"]+)"/g)].map((match) => match[1]); + expect(new Set(ids).size).toBe(ids.length); + expect(first.match(/aria-selected="true"/g)).toHaveLength(2); + }); +}); diff --git a/tests/list-box.test.ts b/tests/list-box.test.ts new file mode 100644 index 0000000..c348909 --- /dev/null +++ b/tests/list-box.test.ts @@ -0,0 +1,473 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { mount, flushPromises } from "@vue/test-utils"; +import { createSSRApp, defineComponent, h, ref } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import { + ListBox, + ListBoxItem, + ListBoxItemIndicator, + ListBoxSection, + Label, + Description, + Header, + Fieldset, +} from "../packages/vue/src"; + +const wrappers: ReturnType[] = []; +afterEach(() => { + wrappers.splice(0).forEach((wrapper) => wrapper.unmount()); + document.body.innerHTML = ""; +}); +function fixture(template: string, setup = () => ({})) { + const wrapper = mount( + defineComponent({ + components: { + ListBox, + ListBoxItem, + ListBoxItemIndicator, + ListBoxSection, + Label, + Description, + Header, + Fieldset, + }, + setup, + template, + }), + { attachTo: document.body }, + ); + wrappers.push(wrapper); + return wrapper; +} +const options = + 'Emmaemma@example.comFredDisabledMartha'; +const option = (wrapper: ReturnType, index: number) => + wrapper.findAll('[role="option"]')[index]; + +describe("ListBox public behavior", () => { + it("retains the last Tab entry after blur and combines native focus-visible with local modality", async () => { + const wrapper = fixture( + `${options}Outside`, + ); + await option(wrapper, 1).trigger("pointerdown", { button: 0 }); + option(wrapper, 1).element.focus(); + await flushPromises(); + wrapper.get("button").element.focus(); + await flushPromises(); + expect(option(wrapper, 1).attributes("tabindex")).toBe("0"); + expect(option(wrapper, 0).attributes("tabindex")).toBe("-1"); + expect(option(wrapper, 1).attributes("data-focused")).toBeUndefined(); + option(wrapper, 1).element.focus(); + await flushPromises(); + expect(option(wrapper, 1).element.matches(":focus-visible")).toBe(true); + expect(option(wrapper, 1).attributes("data-focus-visible")).toBe("true"); + }); + it("hides selection in none mode, keeps item variants independent and leaves modified Enter alone", async () => { + const wrapper = fixture( + `${options}`, + ); + option(wrapper, 0).element.focus(); + expect(option(wrapper, 3).attributes("data-selected")).toBeUndefined(); + expect(option(wrapper, 0).classes()).toContain("hv-list-box-item--default"); + await option(wrapper, 0).trigger("keydown", { + key: "Enter", + ctrlKey: true, + }); + expect(wrapper.getComponent(ListBox).emitted("action")).toBeUndefined(); + await option(wrapper, 0).trigger("keydown", { key: "Enter" }); + expect(wrapper.getComponent(ListBox).emitted("action")).toEqual([[0]]); + }); + it("holds keyboard pressed state, activates Space on release once and respects keyup cancellation", async () => { + const cancelled = ref(false); + const wrapper = fixture( + `${options}`, + () => ({ cancelled }), + ); + option(wrapper, 0).element.focus(); + await option(wrapper, 0).trigger("keydown", { key: " " }); + expect(option(wrapper, 0).attributes("data-pressed")).toBe("true"); + expect(wrapper.getComponent(ListBox).emitted("action")).toBeUndefined(); + await option(wrapper, 0).trigger("keydown", { key: " ", repeat: true }); + await option(wrapper, 0).trigger("keyup", { key: " " }); + expect(option(wrapper, 0).attributes("data-pressed")).toBeUndefined(); + expect(wrapper.getComponent(ListBox).emitted("action")).toEqual([[0]]); + cancelled.value = true; + await flushPromises(); + await option(wrapper, 0).trigger("keydown", { key: " " }); + await option(wrapper, 0).trigger("keyup", { key: " " }); + expect(wrapper.getComponent(ListBox).emitted("action")).toEqual([[0]]); + expect(option(wrapper, 0).attributes("data-pressed")).toBeUndefined(); + }); + it("keeps the current prefix match while typing a word and cycles repeated initials", async () => { + const wrapper = fixture( + 'Liam SmithLiam JonesEmma', + ); + option(wrapper, 2).element.focus(); + for (const key of ["l", "i", "a", "m"]) + await wrapper.get('[role="listbox"]').trigger("keydown", { key }); + expect(document.activeElement).toBe(option(wrapper, 0).element); + // A new repeated-initial search cycles, rather than searching for "ll". + vi.spyOn(Date, "now").mockReturnValue(Date.now() + 2000); + try { + await option(wrapper, 0).trigger("keydown", { key: "l" }); + expect(document.activeElement).toBe(option(wrapper, 1).element); + await option(wrapper, 1).trigger("keydown", { key: "l" }); + expect(document.activeElement).toBe(option(wrapper, 0).element); + } finally { + vi.restoreAllMocks(); + } + }); + it("keeps typed keys, selection aliases and generated DOM ids distinct", async () => { + const wrapper = fixture( + `${options}`, + ); + await flushPromises(); + expect(option(wrapper, 0).attributes("aria-selected")).toBe("true"); + expect(option(wrapper, 1).attributes("aria-selected")).toBe("false"); + await option(wrapper, 1).trigger("click"); + expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([ + [[0, "0"]], + ]); + expect(wrapper.getComponent(ListBox).emitted("selectionChange")).toEqual([ + [[0, "0"]], + ]); + expect(option(wrapper, 0).attributes("id")).not.toBe("0"); + expect(option(wrapper, 0).attributes("id")).not.toBe( + option(wrapper, 1).attributes("id"), + ); + expect(option(wrapper, 0).attributes("aria-labelledby")).toBe( + option(wrapper, 0).get('[data-slot="label"]').attributes("id"), + ); + expect(option(wrapper, 0).attributes("aria-describedby")).toBe( + option(wrapper, 0).get('[data-slot="description"]').attributes("id"), + ); + }); + + it("restores controlled selection after rejection and retries identical proposals", async () => { + const wrapper = fixture( + `${options}`, + ); + await option(wrapper, 1).trigger("click"); + await option(wrapper, 1).trigger("click"); + expect(option(wrapper, 1).attributes("aria-selected")).toBe("false"); + expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([ + [[0, "0"]], + [[0, "0"]], + ]); + }); + + it("treats explicit undefined model as controlled and gives it priority over selectedKeys", async () => { + const wrapper = fixture( + `${options}`, + ); + await option(wrapper, 0).trigger("click"); + expect(option(wrapper, 0).attributes("aria-selected")).toBe("false"); + expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([ + [[0]], + ]); + }); + + it("implements single toggle and disallow-empty selection", async () => { + const locked = ref(true); + const wrapper = fixture( + `${options}`, + () => ({ locked }), + ); + await option(wrapper, 0).trigger("click"); + expect(option(wrapper, 0).attributes("aria-selected")).toBe("true"); + locked.value = false; + await flushPromises(); + await option(wrapper, 0).trigger("click"); + expect(option(wrapper, 0).attributes("aria-selected")).toBe("false"); + await option(wrapper, 1).trigger("click"); + expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([ + [[]], + [["0"]], + ]); + }); + + it("keeps action-only collections unselected for pointer and keyboard activation", async () => { + const wrapper = fixture( + `${options}`, + ); + await option(wrapper, 0).trigger("click"); + await flushPromises(); + await option(wrapper, 0).trigger("keydown", { key: "Enter" }); + expect(wrapper.getComponent(ListBox).emitted("action")).toEqual([[0], [0]]); + expect( + wrapper.getComponent(ListBox).emitted("update:modelValue"), + ).toBeUndefined(); + expect(option(wrapper, 0).attributes("aria-selected")).toBeUndefined(); + }); + + it("uses one Tab stop, skips disabled keys and supports Home/End and RTL orientation", async () => { + const wrapper = fixture( + `${options}`, + ); + await flushPromises(); + const root = wrapper.get('[role="listbox"]'); + expect(root.attributes("tabindex")).toBe("-1"); + expect(wrapper.findAll('[role="option"][tabindex="0"]')).toHaveLength(1); + option(wrapper, 0).element.focus(); + await option(wrapper, 0).trigger("keydown", { key: "ArrowLeft" }); + expect(document.activeElement).toBe(option(wrapper, 1).element); + await option(wrapper, 1).trigger("keydown", { key: "ArrowLeft" }); + expect(document.activeElement).toBe(option(wrapper, 3).element); + await option(wrapper, 3).trigger("keydown", { key: "Home" }); + expect(document.activeElement).toBe(option(wrapper, 0).element); + await option(wrapper, 0).trigger("keydown", { key: "End" }); + expect(document.activeElement).toBe(option(wrapper, 3).element); + expect( + wrapper.getComponent(ListBox).emitted("update:modelValue"), + ).toBeUndefined(); + }); + + it("selects a range with a zero anchor, toggles all available keys and respects readonly", async () => { + const readonly = ref(false); + const wrapper = fixture( + `${options}`, + () => ({ readonly }), + ); + await option(wrapper, 0).trigger("click"); + await flushPromises(); + await option(wrapper, 0).trigger("keydown", { key: "End", shiftKey: true }); + expect(wrapper.findAll('[aria-selected="true"]')).toHaveLength(3); + expect(option(wrapper, 2).attributes("aria-selected")).toBe("false"); + readonly.value = true; + await flushPromises(); + await option(wrapper, 3).trigger("keydown", { key: "a", ctrlKey: true }); + await option(wrapper, 1).trigger("click"); + expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([ + [[0]], + [[0, "0", "last"]], + ]); + }); + + it("replace navigation selects focused options while modifier navigation only moves focus", async () => { + const wrapper = fixture( + `${options}`, + ); + await option(wrapper, 0).trigger("click"); + await flushPromises(); + await option(wrapper, 0).trigger("keydown", { key: "ArrowDown" }); + expect(option(wrapper, 1).attributes("aria-selected")).toBe("true"); + expect(option(wrapper, 0).attributes("aria-selected")).toBe("false"); + await option(wrapper, 1).trigger("keydown", { key: "End", ctrlKey: true }); + expect(document.activeElement).toBe(option(wrapper, 3).element); + expect(option(wrapper, 3).attributes("aria-selected")).toBe("false"); + }); + + it("uses textValue for accent-insensitive typeahead and leaves IME alone", async () => { + const wrapper = fixture(`${options}`); + option(wrapper, 1).element.focus(); + await option(wrapper, 1).trigger("keydown", { + key: "e", + isComposing: true, + }); + expect(document.activeElement).toBe(option(wrapper, 1).element); + await option(wrapper, 1).trigger("keydown", { key: "e" }); + expect(document.activeElement).toBe(option(wrapper, 0).element); + }); + + it("respects caller keyboard/click cancellation and DOM listener-array stop semantics", async () => { + const second = vi.fn(); + const wrapper = fixture( + `AB`, + () => ({ + handlers: [ + (event: MouseEvent) => event.stopImmediatePropagation(), + second, + ], + }), + ); + option(wrapper, 0).element.focus(); + await option(wrapper, 0).trigger("keydown", { key: "ArrowDown" }); + expect(document.activeElement).toBe(option(wrapper, 0).element); + await option(wrapper, 0).trigger("click"); + expect(second).not.toHaveBeenCalled(); + expect( + wrapper.getComponent(ListBox).emitted("update:modelValue"), + ).toBeUndefined(); + }); + + it("cancels select before activation and exposes the original keyboard event", async () => { + const select = vi.fn((event: CustomEvent) => event.preventDefault()); + const wrapper = fixture( + 'A', + () => ({ select }), + ); + option(wrapper, 0).element.focus(); + await option(wrapper, 0).trigger("keydown", { key: " " }); + await option(wrapper, 0).trigger("keyup", { key: " " }); + expect(select).toHaveBeenCalledOnce(); + expect(select.mock.calls[0][0].detail.originalEvent).toBeInstanceOf( + KeyboardEvent, + ); + expect(wrapper.getComponent(ListBox).emitted("action")).toBeUndefined(); + }); + + it("applies Fieldset disabled semantics and preserves first Legend exemption", async () => { + const wrapper = fixture( + `${options}${options}`, + ); + const lists = wrapper.findAllComponents(ListBox); + await lists[0].findAll('[role="option"]')[0].trigger("click"); + await lists[1].findAll('[role="option"]')[0].trigger("click"); + expect(lists[0].emitted("update:modelValue")).toEqual([[[0]]]); + expect(lists[1].emitted("update:modelValue")).toBeUndefined(); + expect( + lists[1].findAll('[role="option"]')[0].attributes("aria-disabled"), + ).toBe("true"); + expect(lists[1].findAll('[tabindex="0"]')).toHaveLength(0); + }); + + it("isolates option labels/descriptions, names sections and honors explicit ARIA", async () => { + const wrapper = fixture( + 'TeamADetail ABDetail B', + ); + expect(wrapper.get('[role="group"]').attributes("aria-labelledby")).toBe( + wrapper.get("header").attributes("id"), + ); + expect(option(wrapper, 0).attributes("aria-describedby")).not.toBe( + option(wrapper, 1).attributes("aria-describedby"), + ); + expect(option(wrapper, 1).attributes("aria-labelledby")).toBeUndefined(); + expect(option(wrapper, 1).attributes("aria-label")).toBe("Explicit"); + }); + + it("handles member reordering, disabled updates and removal without losing a focus entry", async () => { + const items = ref([ + { id: "a", textValue: "A" }, + { id: "b", textValue: "B" }, + { id: "c", textValue: "C" }, + ]); + const blocked = ref([]); + const wrapper = fixture( + '{{ item.textValue }}', + () => ({ items, blocked }), + ); + option(wrapper, 0).element.focus(); + items.value.reverse(); + await flushPromises(); + await option(wrapper, 2).trigger("keydown", { key: "Home" }); + expect(document.activeElement?.textContent).toBe("C"); + blocked.value = ["c"]; + await flushPromises(); + expect(document.activeElement?.textContent).toBe("B"); + items.value = items.value.filter((item) => item.id !== "b"); + await flushPromises(); + expect(document.activeElement?.textContent).toBe("A"); + expect(wrapper.findAll('[role="option"][tabindex="0"]')).toHaveLength(1); + }); + + it("renders a bounded virtual window but selects the entire logical collection", async () => { + const items = Array.from({ length: 1000 }, (_, index) => ({ + id: index, + textValue: `User ${index}`, + isDisabled: index === 999, + })); + const wrapper = fixture( + '{{ item.textValue }}', + () => ({ items }), + ); + await flushPromises(); + expect(wrapper.findAll('[role="option"]').length).toBeGreaterThan(0); + expect(wrapper.findAll('[role="option"]').length).toBeLessThan(40); + await option(wrapper, 0).trigger("keydown", { key: "a", ctrlKey: true }); + const changes = wrapper.getComponent(ListBox).emitted("update:modelValue")!; + expect(changes[0][0] as number[]).toHaveLength(999); + expect(changes[0][0] as number[]).not.toContain(999); + expect(option(wrapper, 0).attributes("aria-setsize")).toBe("1000"); + // jsdom does not verify scrolling geometry; browser verifies End/scroll/focus. + }); + + it("keeps all instances isolated and supports a supplied empty state", async () => { + const wrapper = fixture( + `${options}${options}No results`, + ); + await option(wrapper, 0).trigger("click"); + expect(wrapper.findAll('[aria-selected="true"]')).toHaveLength(1); + const ids = wrapper.findAll("[id]").map((node) => node.attributes("id")); + expect(new Set(ids).size).toBe(ids.length); + expect(wrapper.text()).toContain("No results"); + }); + + it("hydrates selected options and label relationships without mismatches", async () => { + const Component = defineComponent({ + render: () => + h(ListBox, { defaultValue: [0] }, () => + h( + ListBoxItem, + { id: 0 }, + { + default: () => [ + h(Label, {}, () => "Bob"), + h(Description, {}, () => "Details"), + ], + }, + ), + ), + }); + const host = document.createElement("div"); + host.innerHTML = await renderToString(createSSRApp(Component)); + document.body.append(host); + const before = host.querySelector('[role="option"]')!; + const beforeId = before.id; + const warnings: string[] = []; + const app = createSSRApp(Component); + app.config.warnHandler = (message) => warnings.push(message); + app.mount(host); + await flushPromises(); + try { + expect(warnings).toEqual([]); + const after = host.querySelector('[role="option"]')!; + expect(after).toBe(before); + expect(after.id).toBe(beforeId); + expect(after.getAttribute("aria-selected")).toBe("true"); + expect(after.getAttribute("aria-labelledby")).toBe( + after.querySelector('[data-slot="label"]')?.id, + ); + expect(after.getAttribute("aria-describedby")).toBe( + after.querySelector('[data-slot="description"]')?.id, + ); + } finally { + app.unmount(); + } + }); + + it("compiles and mounts all nine baseline demos together without warnings or duplicate IDs", async () => { + const demos = import.meta.glob("../apps/docs/demos/list-box-*.vue", { + eager: true, + import: "default", + }); + expect(Object.keys(demos)).toHaveLength(9); + const warnings: string[] = []; + const wrapper = mount( + defineComponent({ + render: () => + h( + "main", + Object.values(demos).map((component) => + h(component as ReturnType), + ), + ), + }), + { + attachTo: document.body, + global: { + config: { warnHandler: (message) => warnings.push(message) }, + }, + }, + ); + wrappers.push(wrapper); + await flushPromises(); + expect(warnings).toEqual([]); + expect(wrapper.findAll('[role="listbox"]')).toHaveLength(9); + expect(wrapper.findAll('[role="option"]').length).toBeLessThan(100); + const ids = wrapper.findAll("[id]").map((node) => node.attributes("id")); + expect(new Set(ids).size).toBe(ids.length); + const defaults = wrapper.findAll('[role="listbox"]')[0]; + expect(wrapper.text()).toContain("bob@heroui.com"); + expect(defaults.find('[role="option"]').exists()).toBe(true); + }); +}); diff --git a/tests/package/README.md b/tests/package/README.md index 88003db..d5279c1 100644 --- a/tests/package/README.md +++ b/tests/package/README.md @@ -15,3 +15,5 @@ pnpm exec tsc --noEmit --strict --skipLibCheck --module esnext --moduleResolutio SLIDER-01 已在 `/private/tmp/heroui-slider-consumer` 完成上述检查,临时契约文件名为 `contract.ts`。默认工作区 typecheck 仍使用源码 alias,所以不能代替此独立产物检查。 M30–M32 增加 consume-m30-m32.mjs 和 m30-m32-contract.ts。将它们复制到同一个独立消费工程,执行运行脚本,并将契约文件加入上述两种 tsc 命令。合并后的产物还应同时通过原 NumberField/Slider 消费检查,避免只验证新加组件。 + +LISTBOX-01 增加 `consume-list-box.mjs` / `list-box-contract.ts`。同样复制到独立消费者,用两份新 tarball 安装后运行脚本,并在 NodeNext / bundler 两种模式执行契约文件。Root 的泛型 Props 曾在 Parameters 提取后退化,非法模型/模式反例与事件参数推断必须保留。 diff --git a/tests/package/consume-list-box.mjs b/tests/package/consume-list-box.mjs new file mode 100644 index 0000000..1ddf818 --- /dev/null +++ b/tests/package/consume-list-box.mjs @@ -0,0 +1,52 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { createSSRApp, h } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import { + ListBox, + ListBoxItem, + ListBoxItemIndicator, + ListBoxSection, + Header, + Label, + Description, + listboxVariants, + listboxItemVariants, +} from "@heroui-vue/components"; +const html = await renderToString( + createSSRApp({ + render: () => + h(ListBox, { modelValue: [0], "aria-label": "People" }, () => [ + h(ListBoxSection, {}, () => [ + h(Header, {}, () => "Team"), + h(ListBoxItem, { id: 0 }, () => [ + h(Label, {}, () => "Bob"), + h(Description, {}, () => "Details"), + h(ListBoxItemIndicator), + ]), + ]), + h(ListBoxItem, { id: "0" }, () => "Fred"), + ]), + }), +); +assert.equal((html.match(/aria-selected="true"/g) ?? []).length, 1); +assert(html.includes('role="group"')); +assert(html.includes('aria-labelledby="')); +assert(html.includes('aria-describedby="')); +assert(listboxVariants().includes("hv-list-box")); +assert( + listboxItemVariants().indicator().includes("hv-list-box-item__indicator"), +); +const css = readFileSync( + new URL(import.meta.resolve("@heroui-vue/styles/css")), + "utf8", +); +for (const name of [ + ".hv-list-box", + ".hv-list-box-item", + ".hv-list-box-section", +]) + assert(css.includes(name)); +console.log( + "ListBox independent tarball: ESM, SSR, typed selection, labels and CSS passed.", +); diff --git a/tests/package/list-box-contract.ts b/tests/package/list-box-contract.ts new file mode 100644 index 0000000..c07afd7 --- /dev/null +++ b/tests/package/list-box-contract.ts @@ -0,0 +1,38 @@ +import { + ListBox, + ListBoxItem, + ListBoxItemIndicator, + ListBoxSection, + type ListBoxProps, + type ListBoxItemProps, +} from "@heroui-vue/components"; +const props: ListBoxProps = { + modelValue: [0, "0"], + selectionMode: "multiple", + variant: "danger", + onSelectionChange: (keys) => keys.forEach((key) => String(key)), +}; +const item: ListBoxItemProps = { id: 0, textValue: "Zero" }; +// @ts-expect-error Vue collection models are key arrays, not scalars +const scalar: ListBoxProps = { modelValue: 0 }; +// @ts-expect-error Keys cannot be objects +const badKey: ListBoxProps = { modelValue: [{}] }; +// @ts-expect-error Selection mode is constrained +const badMode: ListBoxProps = { selectionMode: "radio" }; +// @ts-expect-error Variant is constrained +const badVariant: ListBoxItemProps = { id: "a", variant: "solid" }; +// @ts-expect-error Item identity is required +const missing: ListBoxItemProps = { textValue: "Missing" }; +void [ + ListBox, + ListBoxItem, + ListBoxItemIndicator, + ListBoxSection, + props, + item, + scalar, + badKey, + badMode, + badVariant, + missing, +];
+ 已选:{{ selected.length ? selected.join("、") : "无" }} +
{{ message }}