feat: migrate ListBox with virtual collection and accessible parts

This commit is contained in:
maoyingjie
2026-10-23 15:02:30 +08:00
parent dea5ded716
commit 65db60a7ac
39 changed files with 2694 additions and 12 deletions
+7
View File
@@ -418,3 +418,10 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V
- key 区分数字和字符串,空字符串有效;内部适配编码不进入 FormData。父拒绝后相同提案可以重试,程序化父值与用户改选权限分开。 - key 区分数字和字符串,空字符串有效;内部适配编码不进入 FormData。父拒绝后相同提案可以重试,程序化父值与用户改选权限分开。
- Reka 已实测支持禁用项跳过/全选;Listbox reset、索引表单名,以及 Select 多选原生提交/关闭态 SSR 存在适配需求。不能只检查可见文字或读局部源码猜能力。 - Reka 已实测支持禁用项跳过/全选;Listbox reset、索引表单名,以及 Select 多选原生提交/关闭态 SSR 存在适配需求。不能只检查可见文字或读局部源码猜能力。
- 已挂载 registry 不等于虚拟化完整集合。公共 Item 的 Label/Description 与外层字段隔离,使用既有字段/reset/弹层设施;9/19 个基线预览和公共验收仍待完成。 - 已挂载 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 修复。
+1
View File
@@ -100,6 +100,7 @@ const groups = [
{ title: "Toolbar 工具栏", url: "/components/toolbar" }, { title: "Toolbar 工具栏", url: "/components/toolbar" },
{ title: "NumberField 数字输入框", url: "/components/number-field" }, { title: "NumberField 数字输入框", url: "/components/number-field" },
{ title: "Slider 滑块", url: "/components/slider" }, { title: "Slider 滑块", url: "/components/slider" },
{ title: "ListBox 列表框", url: "/components/list-box" },
{ title: "Tooltip 工具提示", url: "/components/tooltip" }, { title: "Tooltip 工具提示", url: "/components/tooltip" },
{ {
title: "ToggleButton 切换按钮", title: "ToggleButton 切换按钮",
+236
View File
@@ -0,0 +1,236 @@
---
title: ListBox 列表框
description: 列表框展示一组选项,并允许用户选择一个或多个。
component: list-box
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Label,
} from "@heroui-vue/components";
</script>
```
<ComponentPreview name="list-box-default" />
## 组件结构
```vue
<script setup lang="ts">
import {
ListBox,
ListBoxItem,
ListBoxItemIndicator,
ListBoxSection,
Label,
Description,
Header,
} from "@heroui-vue/components";
</script>
<template>
<ListBox aria-label="选项">
<ListBoxItem id="first" text-value="第一项">
<div>
<Label>第一项</Label>
<Description>选项说明</Description>
</div>
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxSection>
<Header>分组</Header>
<ListBoxItem id="second" text-value="第二项">
<Label>第二项</Label>
</ListBoxItem>
</ListBoxSection>
</ListBox>
</template>
```
## 示例
### 含禁用项
<ComponentPreview name="list-box-with-disabled-items" />
### 分组选项
<ComponentPreview name="list-box-with-sections" />
### 多选
<ComponentPreview name="list-box-multi-select" />
### 受控组件
使用 `v-model` 控制 key 数组。单选也使用数组,空选择为 `[]`。数字 `1` 与字符串 `"1"` 是不同的 key。父组件未接受更新时,可见选中状态保持父值。
<ComponentPreview name="list-box-controlled" />
### 虚拟滚动
ListBox 通过 `virtualized` 仅渲染视口附近的行,高效展示大数据集。下面保留基线的 1000 条数据、50px 固定行高和 400px 视口。完整数据传给 `items`,首字母导航、全选和范围选择使用完整集合。
Vue 使用现有 VueUse 虚拟列表适配,不导出 React 的 `Virtualizer` / `ListLayout`。当前支持竖向固定行高列表;可变行高、虚拟分组标题和拖放布局尚未支持。
<ComponentPreview name="list-box-virtualization" />
### 自定义勾选图标
<ComponentPreview name="list-box-custom-check-icon" />
### 渲染函数
Vue 使用 `as` 修改原生标签,普通和作用域插槽组合内容;状态属性和事件保留在实际 role 节点上。
<ComponentPreview name="list-box-render-function" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="list-box-custom-styles" />
### 全局 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。
+67
View File
@@ -0,0 +1,67 @@
<script setup lang="ts">
import {
Avatar,
AvatarImage,
AvatarFallback,
Description,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Surface,
} from "@heroui-vue/components";
import { IconCheck } from "@tabler/icons-vue";
import { ref } from "vue";
import type { ListBoxKey } from "@heroui-vue/components";
const selected = ref<ListBoxKey[]>(["1"]);
const users = [
{
id: "1",
name: "Bob",
email: "bob@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
},
{
id: "2",
name: "Fred",
email: "fred@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
},
{
id: "3",
name: "Martha",
email: "martha@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
},
];
</script>
<template>
<div class="space-y-4">
<Surface class="w-[256px] rounded-3xl shadow-surface">
<ListBox
:items="users"
v-slot="{ item: user }"
aria-label="用户"
selection-mode="multiple"
v-model="selected"
>
<ListBoxItem :id="user.id" :text-value="user.name">
<Avatar size="sm">
<AvatarImage :alt="user.name" :src="user.src" />
<AvatarFallback>{{ user.name[0] }}</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<Label>{{ user.name }}</Label>
<Description>{{ user.email }}</Description>
</div>
<ListBoxItemIndicator v-slot="{ isSelected }">
<IconCheck v-if="isSelected" class="size-4 text-accent" />
</ListBoxItemIndicator>
</ListBoxItem>
</ListBox>
</Surface>
<p class="text-sm text-muted">
已选:{{ selected.length ? selected.join("、") : "无" }}
</p>
</div>
</template>
@@ -0,0 +1,58 @@
<script setup lang="ts">
import {
Avatar,
AvatarImage,
AvatarFallback,
Description,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Surface,
} from "@heroui-vue/components";
import { IconCheck } from "@tabler/icons-vue";
const users = [
{
id: "1",
name: "Bob",
email: "bob@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
},
{
id: "2",
name: "Fred",
email: "fred@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
},
{
id: "3",
name: "Martha",
email: "martha@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
},
];
</script>
<template>
<Surface class="w-[256px] rounded-3xl shadow-surface">
<ListBox
:items="users"
v-slot="{ item: user }"
aria-label="用户"
selection-mode="multiple"
>
<ListBoxItem :id="user.id" :text-value="user.name">
<Avatar size="sm">
<AvatarImage :alt="user.name" :src="user.src" />
<AvatarFallback>{{ user.name[0] }}</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<Label>{{ user.name }}</Label>
<Description>{{ user.email }}</Description>
</div>
<ListBoxItemIndicator v-slot="{ isSelected }">
<IconCheck v-if="isSelected" class="size-4 text-accent" />
</ListBoxItemIndicator>
</ListBoxItem>
</ListBox>
</Surface>
</template>
@@ -0,0 +1,58 @@
<script setup lang="ts">
import {
Avatar,
AvatarImage,
AvatarFallback,
Description,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Surface,
} from "@heroui-vue/components";
const users = [
{
id: "1",
name: "Bob",
email: "bob@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
},
{
id: "2",
name: "Fred",
email: "fred@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
},
{
id: "3",
name: "Martha",
email: "martha@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
},
];
</script>
<template>
<ListBox
:items="users.slice(0, 2)"
v-slot="{ item: user }"
aria-label="负责人"
selection-mode="single"
class="w-56 rounded-xl border border-border/80 bg-surface p-1 shadow-sm"
>
<ListBoxItem
:id="user.id"
:text-value="user.name"
class="rounded-lg data-[focused=true]:bg-accent/10 data-[selected=true]:bg-accent/5"
>
<Avatar size="sm">
<AvatarImage :alt="user.name" :src="user.src" />
<AvatarFallback>{{ user.name[0] }}</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<Label>{{ user.name }}</Label>
<Description>{{ user.email }}</Description>
</div>
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</template>
+54
View File
@@ -0,0 +1,54 @@
<script setup lang="ts">
import {
Avatar,
AvatarImage,
AvatarFallback,
Description,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Surface,
} from "@heroui-vue/components";
const users = [
{
id: "1",
name: "Bob",
email: "bob@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
},
{
id: "2",
name: "Fred",
email: "fred@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
},
{
id: "3",
name: "Martha",
email: "martha@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
},
];
</script>
<template>
<ListBox
:items="users"
v-slot="{ item: user }"
aria-label="用户"
selection-mode="single"
class="w-[220px]"
>
<ListBoxItem :id="user.id" :text-value="user.name">
<Avatar size="sm">
<AvatarImage :alt="user.name" :src="user.src" />
<AvatarFallback>{{ user.name[0] }}</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<Label>{{ user.name }}</Label>
<Description>{{ user.email }}</Description>
</div>
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</template>
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
import {
Avatar,
AvatarImage,
AvatarFallback,
Description,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Surface,
} from "@heroui-vue/components";
const users = [
{
id: "1",
name: "Bob",
email: "bob@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
},
{
id: "2",
name: "Fred",
email: "fred@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
},
{
id: "3",
name: "Martha",
email: "martha@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
},
];
</script>
<template>
<Surface class="w-[256px] rounded-3xl shadow-surface">
<ListBox
:items="users"
v-slot="{ item: user }"
aria-label="用户"
selection-mode="multiple"
>
<ListBoxItem :id="user.id" :text-value="user.name">
<Avatar size="sm">
<AvatarImage :alt="user.name" :src="user.src" />
<AvatarFallback>{{ user.name[0] }}</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<Label>{{ user.name }}</Label>
<Description>{{ user.email }}</Description>
</div>
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</Surface>
</template>
@@ -0,0 +1,61 @@
<script setup lang="ts">
import {
Avatar,
AvatarImage,
AvatarFallback,
Description,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Surface,
} from "@heroui-vue/components";
const users = [
{
id: "1",
name: "Bob",
email: "bob@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
},
{
id: "2",
name: "Fred",
email: "fred@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
},
{
id: "3",
name: "Martha",
email: "martha@heroui.com",
src: "https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
},
];
</script>
<template>
<ListBox
:items="users"
v-slot="{ item: user }"
aria-label="用户"
selection-mode="single"
class="w-[220px]"
as="div"
data-custom="true"
>
<ListBoxItem
:id="user.id"
:text-value="user.name"
as="span"
:data-custom="{ '1': 'foo', '2': 'bar', '3': 'baz' }[user.id]"
>
<Avatar size="sm">
<AvatarImage :alt="user.name" :src="user.src" />
<AvatarFallback>{{ user.name[0] }}</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<Label>{{ user.name }}</Label>
<Description>{{ user.email }}</Description>
</div>
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</template>
@@ -0,0 +1,82 @@
<script setup lang="ts">
import {
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Label,
Description,
} from "@heroui-vue/components";
const firstNames = [
"Emma",
"Liam",
"Olivia",
"Noah",
"Ava",
"James",
"Sophia",
"Oliver",
"Isabella",
"Lucas",
"Mia",
"Ethan",
"Charlotte",
"Mason",
"Amelia",
"Logan",
"Harper",
"Alexander",
"Ella",
"Benjamin",
];
const lastNames = [
"Smith",
"Johnson",
"Williams",
"Brown",
"Jones",
"Garcia",
"Miller",
"Davis",
"Rodriguez",
"Martinez",
"Anderson",
"Taylor",
"Thomas",
"Jackson",
"White",
"Harris",
"Clark",
"Lewis",
"Robinson",
"Walker",
];
const users = Array.from({ length: 1000 }, (_, index) => {
const first = firstNames[index % firstNames.length];
const last =
lastNames[Math.floor(index / firstNames.length) % lastNames.length];
return {
id: index + 1,
name: `${first} ${last}`,
textValue: `${first} ${last}`,
email: `${first.toLowerCase()}.${last.toLowerCase()}@acme.com`,
};
});
</script>
<template>
<ListBox
:items="users"
virtualized
:row-height="50"
aria-label="包含 1000 项的虚拟化列表"
class="h-[400px] w-[300px] overflow-y-auto"
v-slot="{ item }"
>
<ListBoxItem :id="item.id" :text-value="item.name" class="h-full">
<div class="flex flex-col">
<Label>{{ item.name }}</Label>
<Description>{{ item.email }}</Description>
</div>
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</template>
@@ -0,0 +1,88 @@
<script setup lang="ts">
import { ref } from "vue";
import { IconPencil, IconSquarePlus, IconTrash } from "@tabler/icons-vue";
import {
Description,
Header,
Kbd,
KbdAbbr,
KbdContent,
Label,
ListBox,
ListBoxItem,
ListBoxSection,
Separator,
Surface,
} from "@heroui-vue/components";
const message = ref("");
const actions = [
{
id: "new-file",
title: "新建文件",
description: "创建新文件",
shortcut: "N",
icon: IconSquarePlus,
},
{
id: "edit-file",
title: "编辑文件",
description: "进行修改",
shortcut: "E",
icon: IconPencil,
},
];
</script>
<template>
<div class="space-y-3">
<Surface class="w-[256px] rounded-3xl shadow-surface">
<ListBox
aria-label="文件操作"
class="w-full p-2"
selection-mode="none"
@action="message = `已选项目:${$event}`"
:disabled-keys="['delete-file']"
>
<ListBoxSection>
<Header>操作</Header>
<ListBoxItem
v-for="action in actions"
:key="action.id"
:id="action.id"
:text-value="action.title"
>
<div class="flex h-8 items-start justify-center pt-px">
<component :is="action.icon" class="size-4 shrink-0 text-muted" />
</div>
<div class="flex flex-col">
<Label>{{ action.title }}</Label>
<Description>{{ action.description }}</Description>
</div>
<Kbd class="ms-auto" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>{{ action.shortcut }}</KbdContent>
</Kbd>
</ListBoxItem>
</ListBoxSection>
<Separator />
<ListBoxSection>
<Header>危险区域</Header>
<ListBoxItem id="delete-file" text-value="删除文件" variant="danger">
<div class="flex h-8 items-start justify-center pt-px">
<IconTrash class="size-4 shrink-0 text-danger" />
</div>
<div class="flex flex-col">
<Label>删除文件</Label>
<Description>移至废纸篓</Description>
</div>
<Kbd class="ms-auto" variant="light">
<KbdAbbr key-value="command" />
<KbdAbbr key-value="shift" />
<KbdContent>D</KbdContent>
</Kbd>
</ListBoxItem>
</ListBoxSection>
</ListBox>
</Surface>
<p v-if="message" role="status" class="text-sm text-muted">{{ message }}</p>
</div>
</template>
@@ -0,0 +1,87 @@
<script setup lang="ts">
import { ref } from "vue";
import { IconPencil, IconSquarePlus, IconTrash } from "@tabler/icons-vue";
import {
Description,
Header,
Kbd,
KbdAbbr,
KbdContent,
Label,
ListBox,
ListBoxItem,
ListBoxSection,
Separator,
Surface,
} from "@heroui-vue/components";
const message = ref("");
const actions = [
{
id: "new-file",
title: "新建文件",
description: "创建新文件",
shortcut: "N",
icon: IconSquarePlus,
},
{
id: "edit-file",
title: "编辑文件",
description: "进行修改",
shortcut: "E",
icon: IconPencil,
},
];
</script>
<template>
<div class="space-y-3">
<Surface class="w-[256px] rounded-3xl shadow-surface">
<ListBox
aria-label="文件操作"
class="w-full p-2"
selection-mode="none"
@action="message = `已选项目:${$event}`"
>
<ListBoxSection>
<Header>操作</Header>
<ListBoxItem
v-for="action in actions"
:key="action.id"
:id="action.id"
:text-value="action.title"
>
<div class="flex h-8 items-start justify-center pt-px">
<component :is="action.icon" class="size-4 shrink-0 text-muted" />
</div>
<div class="flex flex-col">
<Label>{{ action.title }}</Label>
<Description>{{ action.description }}</Description>
</div>
<Kbd class="ms-auto" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>{{ action.shortcut }}</KbdContent>
</Kbd>
</ListBoxItem>
</ListBoxSection>
<Separator />
<ListBoxSection>
<Header>危险区域</Header>
<ListBoxItem id="delete-file" text-value="删除文件" variant="danger">
<div class="flex h-8 items-start justify-center pt-px">
<IconTrash class="size-4 shrink-0 text-danger" />
</div>
<div class="flex flex-col">
<Label>删除文件</Label>
<Description>移至废纸篓</Description>
</div>
<Kbd class="ms-auto" variant="light">
<KbdAbbr key-value="command" />
<KbdAbbr key-value="shift" />
<KbdContent>D</KbdContent>
</Kbd>
</ListBoxItem>
</ListBoxSection>
</ListBox>
</Surface>
<p v-if="message" role="status" class="text-sm text-muted">{{ message }}</p>
</div>
</template>
+4 -4
View File
@@ -70,9 +70,9 @@
| radio-group | 验证中(基线实现) | 标量模型、roving Tab/方向键/dir/loop、原生提交/校验/reset;12 个基线预览 | | 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/读屏未真机验证 | | input-otp | 验证中(M32) | Root/Group/Slot/Separator + 3 正则常量;Reka PinInput 底座;字符串+索引数组;reset/Fieldset/Form/ARIA/mask 已接入;11/11 例;自动填充/IME/读屏未真机验证 |
| alert | 验证中(最小实现) | status 五态;默认图标随 status;自定义 Indicator 空内容回退;内部 Surface 重置为 default | | alert | 验证中(最小实现) | status 五态;默认图标随 status;自定义 Indicator 空内容回退;内部 Surface 重置为 default |
| list-box | 基建中(未公开) | 私有 typed key、接受值状态、挂载成员协议及 Reka 审计已实现;公共组件/9 与 19 个基线预览尚未迁移,见 COLLECTION-01 | | list-box | 验证中(LISTBOX-01) | 四部件、9/9 基线例;typed key/数组模型、none/single/multiple、键盘/范围/全选、1000 项固定行高虚拟化;差异见 LISTBOX-01 |
| list-box-item | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | list-box-item | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 |
| list-box-section | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | list-box-section | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 |
| dropdown | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | dropdown | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| menu | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | menu | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| menu-item | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | 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 | | 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 可覆盖 | | pagination | 验证中(M30) | 组合式 nav 容器(无 total/page 状态机);11 具名部件;9/9 基线例;onPress→@click;显式 aria-current 可覆盖 |
| number-field | 验证中(NUMBER-01) | 五部件与 17/17 基线例;Reka 数值内核;受控/只读/表单 reset、SSR/水合;差异见 NUMBER-01 报告 | | 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 | | meter | 验证中(M20) | Meter/Output/Track/Fill;6/6 基线例;role=meter progressbar;无 isIndeterminate;测量语义独立于 Progress |
| slider | 验证中(SLIDER-01) | 六部件、9/9 基线例;原生 range/局部指针适配,单值/范围、受控/reset/SSR/水合;差异见 SLIDER-01 | | slider | 验证中(SLIDER-01) | 六部件、9/9 基线例;原生 range/局部指针适配,单值/范围、受控/reset/SSR/水合;差异见 SLIDER-01 |
| table | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | table | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
+8
View File
@@ -63,3 +63,11 @@
公共实际 DOM 和 FormData、受控拒绝/重试、单多选空值、禁用/只读/Fieldset、required 和 Form 错误响应、取消 reset / form 归属、名称优先级、动态增删/重排/禁用项、键盘/IME/typeahead、范围/全选、Select 清空/关闭、异步值标签、虚拟滚动、嵌套弹层、node SSR 与实际水合、独立产物类型正反例。浏览器在 5174 只重点验几何、滚动、焦点和动效。 公共实际 DOM 和 FormData、受控拒绝/重试、单多选空值、禁用/只读/Fieldset、required 和 Form 错误响应、取消 reset / form 归属、名称优先级、动态增删/重排/禁用项、键盘/IME/typeahead、范围/全选、Select 清空/关闭、异步值标签、虚拟滚动、嵌套弹层、node SSR 与实际水合、独立产物类型正反例。浏览器在 5174 只重点验几何、滚动、焦点和动效。
当前状态层及底座探针不覆盖上面这些公共组件验收,也没有逐像素、读屏、触屏或 Nuxt 结论。 当前状态层及底座探针不覆盖上面这些公共组件验收,也没有逐像素、读屏、触屏或 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 或删除反例规避。
+4
View File
@@ -257,3 +257,7 @@ Modal / Popover / Tooltip 公共迁移与全部 26 个基线预览已接入,
## 集合基建实施中(COLLECTION-01) ## 集合基建实施中(COLLECTION-01)
集成人负责独立分支的 [ListBox/Select 集合基建](decisions/collection-foundation.md),其他 AI 继续 AlertDialog/Drawer。typed key、接受值选择状态和挂载成员注册为私有设施,暂不交给其他 AI 扩展或视为公共组件已完成。Reka 的多选显示与表单提交必须分别验;虚拟化全集与挂载 registry 必须区分。公共迁移、字段/标签作用域、SSR 元数据和 9/19 个基线预览按决策文档接续。 集成人负责独立分支的 [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 展示元数据、清除和嵌套定位仍归集成人实施。
+33
View File
@@ -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 水合与真实浏览器的结论分别记录,不互相替代。
+4
View File
@@ -166,3 +166,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生
- 固定 ce90ea3 的 ListBox / ListBoxItem / ListBoxSection / Select 源码、CSS/tv、中文正文和 9/19 预览作为后续公共实现清单。本轮未复制这些组件 CSS 或演示。 - 固定 ce90ea3 的 ListBox / ListBoxItem / ListBoxSection / Select 源码、CSS/tv、中文正文和 9/19 预览作为后续公共实现清单。本轮未复制这些组件 CSS 或演示。
- 直接使用安装版 Reka 2.11.0(MIT)公开导出构造测试夹具;未修改 node_modules、未复制内部 Collection/Select 实现。私有 key、状态和成员层为 Vue 实现。 - 直接使用安装版 Reka 2.11.0(MIT)公开导出构造测试夹具;未修改 node_modules、未复制内部 Collection/Select 实现。私有 key、状态和成员层为 Vue 实现。
- 依据、实际缺口及阶段边界见 [集合基建决策](decisions/collection-foundation.md)。 - 依据、实际缺口及阶段边界见 [集合基建决策](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)。
+8
View File
@@ -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` 通过。 - 新增 19 项 key/接受值/成员协议回归、8 项安装版 Reka Listbox/Select jsdom 探针、4 项真正 node SSR 探针,共 31 项。完整 `pnpm test`:42 文件 / 624 项通过;`pnpm typecheck`、`pnpm build` 通过。
- 断言包括 typed key、受控拒绝重试、禁用初值改选、不可变快照、DOM 重排、动态碰撞、清理/实例隔离、焦点、实际 FormData 和 SSR 缺口。底座缺陷的审计断言不代表公共组件已修复。 - 断言包括 typed key、受控拒绝重试、禁用初值改选、不可变快照、DOM 重排、动态碰撞、清理/实例隔离、焦点、实际 FormData 和 SSR 缺口。底座缺陷的审计断言不代表公共组件已修复。
- 本轮无公共导出或页面改动,未进行浏览器/文档视觉、实际水合、独立产物消费或完整 ListBox/Select 验收。详细边界和 9/19 基线清单见 [集合基建决策](decisions/collection-foundation.md)。 - 本轮无公共导出或页面改动,未进行浏览器/文档视觉、实际水合、独立产物消费或完整 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 公共组件未完成。
+2 -2
View File
@@ -15,8 +15,8 @@
"build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build", "build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build",
"typecheck": "vue-tsc --noEmit", "typecheck": "vue-tsc --noEmit",
"test": "vitest run", "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: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", "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": "prettier --check .",
"format:fix": "prettier --write .", "format:fix": "prettier --write .",
"dev:playground": "pnpm build && pnpm --filter @heroui-vue/playground dev" "dev:playground": "pnpm build && pnpm --filter @heroui-vue/playground dev"
@@ -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;
}
}
@@ -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;
}
+26
View File
@@ -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%];
}
}
+4
View File
@@ -141,3 +141,7 @@
@import "./components/number-field.css"; @import "./components/number-field.css";
@import "./components/slider.css" layer(components); @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);
+25
View File
@@ -1273,3 +1273,28 @@ export const sliderVariants = tv({
}, },
}); });
export type SliderVariants = VariantProps<typeof sliderVariants>; export type SliderVariants = VariantProps<typeof sliderVariants>;
// 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<typeof listboxVariants>;
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<typeof listboxItemVariants>;
export const listboxSectionVariants = tv({ base: "hv-list-box-section" });
export type ListBoxSectionVariants = VariantProps<
typeof listboxSectionVariants
>;
@@ -10,10 +10,12 @@ export interface CollectionMember {
/** One registry per collection provider. No document queries or global IDs. /** One registry per collection provider. No document queries or global IDs.
* Read order at interaction time: Vue can reorder nodes without changing refs. */ * Read order at interaction time: Vue can reorder nodes without changing refs. */
export function useCollectionRegistry() { export function useCollectionRegistry<
const members = shallowRef<readonly CollectionMember[]>([]); T extends CollectionMember = CollectionMember,
>() {
const members = shallowRef<readonly T[]>([]);
function ordered(): CollectionMember[] { function ordered(): T[] {
const seen = new Set<CollectionKey>(); const seen = new Set<CollectionKey>();
for (const member of members.value) { for (const member of members.value) {
const key = member.key(); const key = member.key();
@@ -32,7 +34,7 @@ export function useCollectionRegistry() {
}); });
} }
function register(member: CollectionMember): () => void { function register(member: T): () => void {
assertKey(member.key()); assertKey(member.key());
if (ordered().some((item) => item.key() === member.key())) { if (ordered().some((item) => item.key() === member.key())) {
throw new Error(`Duplicate collection key: ${member.key()}`); throw new Error(`Duplicate collection key: ${member.key()}`);
@@ -52,7 +54,7 @@ export function useCollectionRegistry() {
key: CollectionKey | undefined, key: CollectionKey | undefined,
intent: "first" | "last" | "next" | "previous", intent: "first" | "last" | "next" | "previous",
loop = false, loop = false,
): CollectionMember | undefined { ): T | undefined {
const items = available(); const items = available();
if (intent === "first") return items[0]; if (intent === "first") return items[0];
if (intent === "last") return items.at(-1); if (intent === "last") return items.at(-1);
@@ -0,0 +1,496 @@
<script setup lang="ts" generic="T extends ListBoxDataItem = ListBoxDataItem">
import {
computed,
getCurrentInstance,
mergeProps,
nextTick,
onBeforeUpdate,
onBeforeUnmount,
onMounted,
provide,
ref,
useAttrs,
} from "vue";
import { useVirtualList } from "@vueuse/core";
import { listboxVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
import { useCollectionSelection } from "../collection/selection";
import { useCollectionRegistry } from "../collection/registry";
import { assertKey } from "../collection/keys";
import {
listBoxKey,
type ListBoxDataItem,
type ListBoxOptions,
type ListBoxKey,
type ListBoxMember,
} from "./context";
defineOptions({ name: "ListBox", inheritAttrs: false });
const props = withDefaults(defineProps<ListBoxOptions<T>>(), {
selectionMode: "single",
selectionBehavior: "toggle",
orientation: "vertical",
variant: "default",
as: "div",
rowHeight: 50,
overscan: 5,
});
const emit = defineEmits<{
"update:modelValue": [keys: ListBoxKey[]];
selectionChange: [keys: ListBoxKey[]];
action: [key: ListBoxKey];
}>();
defineSlots<{
default?: (props: { item: T; index: number }) => unknown;
empty?: () => unknown;
}>();
const attrs = useAttrs();
const instance = getCurrentInstance()!;
const modelPresence = () =>
["modelValue", "model-value"].some((key) =>
Object.hasOwn(instance.vnode.props ?? {}, key),
);
const selectedPresence = () =>
["selectedKeys", "selected-keys"].some((key) =>
Object.hasOwn(instance.vnode.props ?? {}, key),
);
const controlled = ref(modelPresence() || selectedPresence());
const hasModel = ref(modelPresence());
onBeforeUpdate(() => {
hasModel.value = modelPresence();
controlled.value = hasModel.value || selectedPresence();
});
const config = useConfig();
const disabled = useInheritedDisabled(() => props.isDisabled);
provide(disabledContextKey, disabled);
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
const registry = useCollectionRegistry<ListBoxMember>();
const mounted = ref(false);
onMounted(() => {
mounted.value = true;
});
const data = computed(() => {
const seen = new Set<ListBoxKey>();
return props.items?.map((item) => {
assertKey(item.id);
if (seen.has(item.id))
throw new Error(`Duplicate collection key: ${item.id}`);
seen.add(item.id);
return {
key: item.id,
disabled: !!item.isDisabled || !!props.disabledKeys?.includes(item.id),
text: item.textValue ?? "",
};
});
});
const keyDisabled = (key: ListBoxKey) =>
disabled.value ||
!!props.disabledKeys?.includes(key) ||
!!data.value?.find((item) => item.key === key)?.disabled;
const known = () => {
const members = registry.ordered();
return (
data.value?.map((item) => ({
...item,
text:
item.text ||
members.find((member) => member.key() === item.key)?.textValue() ||
"",
disabled:
item.disabled ||
!!members.find((member) => member.key() === item.key)?.disabled(),
})) ??
members.map((member) => ({
key: member.key(),
disabled: member.disabled(),
text: member.textValue(),
}))
);
};
const eligible = () => known().filter((item) => !item.disabled);
const blockedKeys = computed(() =>
known()
.filter((item) => item.disabled)
.map((item) => item.key),
);
const selection = useCollectionSelection({
mode: () => props.selectionMode,
controlled: () => controlled.value,
value: () => (hasModel.value ? props.modelValue : props.selectedKeys),
defaultValue: props.defaultValue ?? props.defaultSelectedKeys,
disabled: () => disabled.value,
readOnly: () => props.isReadOnly,
disabledKeys: () => blockedKeys.value,
disallowEmptySelection: () => props.disallowEmptySelection,
onChange: (keys) => {
emit("update:modelValue", [...keys]);
emit("selectionChange", [...keys]);
},
});
const focused = ref<ListBoxKey>();
const lastFocused = ref<ListBoxKey>();
const pressed = ref<ListBoxKey>();
const keyboard = ref(true);
const active = computed(() => {
if (!mounted.value) return undefined;
const items = eligible();
return (
items.find((item) => item.key === lastFocused.value)?.key ??
items.find(
(item) => props.selectionMode !== "none" && selection.selected(item.key),
)?.key ??
items[0]?.key
);
});
const source = computed(() => (props.items ? [...props.items] : []));
// VueUse owns measurement, scroll range and cleanup; one logical collection
// remains available for select-all/typeahead even while most rows are unmounted.
const {
list: windowItems,
containerProps,
wrapperProps,
scrollTo,
} = useVirtualList(source, {
itemHeight: () => props.rowHeight,
overscan: props.overscan,
});
const root = containerProps.ref;
let restoringFocus = false;
function restoreFocus() {
restoringFocus = true;
root.value?.focus({ preventScroll: true });
restoringFocus = false;
}
let focusRequest = 0;
let disposing = false;
onBeforeUnmount(() => {
disposing = true;
focusRequest++;
});
async function focus(key: ListBoxKey) {
if (
disposing ||
disabled.value ||
!eligible().some((item) => item.key === key)
)
return;
const request = ++focusRequest;
lastFocused.value = key;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
scrollTo(index);
}
await nextTick();
if (disposing || request !== focusRequest || disabled.value) return;
const element = registry
.available()
.find((member) => member.key() === key)
?.element();
element?.focus({ preventScroll: true });
element?.scrollIntoView?.({ block: "nearest" });
}
let anchor: ListBoxKey | undefined;
function activate(key: ListBoxKey, event: MouseEvent | KeyboardEvent) {
const item = known().find((entry) => entry.key === key);
if (
event.defaultPrevented ||
disabled.value ||
props.isReadOnly ||
!item ||
item.disabled
)
return;
if (props.selectionMode === "multiple" && event.shiftKey) {
anchor ??= selection.keys.value[0] ?? active.value ?? key;
selectRange(anchor, key);
} else if (
props.selectionBehavior === "replace" &&
!event.ctrlKey &&
!event.metaKey
)
selection.replace(key);
else selection.toggle(key);
if (!event.shiftKey) anchor = key;
emit("action", key);
}
function selectRange(startKey: ListBoxKey, endKey: ListBoxKey) {
const items = eligible();
const start = items.findIndex((item) => item.key === startKey),
end = items.findIndex((item) => item.key === endKey);
if (start < 0 || end < 0) return;
selection.request([
...selection.keys.value.filter(selection.disabled),
...items
.slice(Math.min(start, end), Math.max(start, end) + 1)
.map((item) => item.key),
]);
}
let search = "",
lastSearch = 0;
let pendingSpace: ListBoxKey | undefined;
function keydown(event: KeyboardEvent) {
if (
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
disabled.value ||
(event.target as Element).closest("[data-hv-listbox]") !== root.value
)
return;
keyboard.value = true;
const items = eligible();
if (!items.length) return;
if (
(event.ctrlKey || event.metaKey) &&
event.key.toLowerCase() === "a" &&
props.selectionMode === "multiple"
) {
event.preventDefault();
selection.selectAll(items.map((item) => item.key));
return;
}
if (event.altKey) return;
if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) return;
const index = items.findIndex((item) => item.key === active.value);
let target: number | undefined;
const backward =
props.orientation === "vertical"
? "ArrowUp"
: dir.value === "rtl"
? "ArrowRight"
: "ArrowLeft";
const forward =
props.orientation === "vertical"
? "ArrowDown"
: dir.value === "rtl"
? "ArrowLeft"
: "ArrowRight";
if (event.key === "Home") target = 0;
else if (event.key === "End") target = items.length - 1;
else if (event.key === "PageUp" || event.key === "PageDown") {
const current = registry
.ordered()
.find((member) => member.key() === active.value)
?.element();
const height = props.virtualized
? props.rowHeight
: current?.getBoundingClientRect().height || props.rowHeight;
const page = Math.max(
1,
Math.floor((root.value?.clientHeight ?? 0) / height),
);
target = index + (event.key === "PageDown" ? page : -page);
} else if (event.key === backward) target = index - 1;
else if (event.key === forward) target = index + 1;
if (target !== undefined) {
event.preventDefault();
target = props.loop
? (target + items.length) % items.length
: Math.max(0, Math.min(target, items.length - 1));
const key = items[target].key;
if (event.shiftKey && props.selectionMode === "multiple") {
anchor ??= active.value;
if (anchor !== undefined) selectRange(anchor, key);
} else if (
props.selectionBehavior === "replace" &&
!event.ctrlKey &&
!event.metaKey
) {
selection.replace(key);
anchor = key;
}
void focus(key);
return;
}
if (
event.key === "Enter" ||
(event.key === " " && (Date.now() - lastSearch > 1000 || !search))
) {
if (event.repeat) {
event.preventDefault();
return;
}
if (props.isReadOnly) {
event.preventDefault();
return;
}
pressed.value = active.value;
if (event.key === " ") {
pendingSpace = active.value;
event.preventDefault();
return;
}
if (active.value !== undefined)
registry
.ordered()
.find((member) => member.key() === active.value)
?.activate(event);
event.preventDefault();
return;
}
if (event.ctrlKey || event.metaKey || event.key.length !== 1) return;
const now = Date.now();
search = now - lastSearch > 1000 ? event.key : search + event.key;
lastSearch = now;
const query = [...search].every((char) => char === search[0])
? search[0]
: search;
const collator = new Intl.Collator(config?.locale.value, {
usage: "search",
sensitivity: "base",
});
const searchItems =
query.length > 1 && items[index]
? [items[index], ...items.slice(index + 1), ...items.slice(0, index)]
: [...items.slice(index + 1), ...items.slice(0, index + 1)];
const match = searchItems.find(
(item) => collator.compare(item.text.slice(0, query.length), query) === 0,
);
if (match) {
event.preventDefault();
void focus(match.key);
}
}
function keyup(event: KeyboardEvent) {
if (event.key !== " ") return;
const key = pendingSpace;
pendingSpace = undefined;
if (
!event.defaultPrevented &&
key !== undefined &&
contextOwnsEvent(event) &&
focused.value === key
) {
registry
.ordered()
.find((member) => member.key() === key)
?.activate(event);
event.preventDefault();
}
}
function contextOwnsEvent(event: KeyboardEvent) {
return (event.target as Element).closest("[data-hv-listbox]") === root.value;
}
provide(listBoxKey, {
mode: computed(() => props.selectionMode),
readOnly: computed(() => props.isReadOnly),
keyboard,
focused,
noteFocus: (key) => {
lastFocused.value = key;
focused.value = key;
},
pressed,
active,
selected: (key) => props.selectionMode !== "none" && selection.selected(key),
disabled: keyDisabled,
register: registry.register,
activate,
focus,
virtualized: () => props.virtualized,
restoreFocus,
position: (key) =>
props.virtualized && data.value
? {
index: data.value.findIndex((item) => item.key === key) + 1,
size: data.value.length,
}
: undefined,
});
function rootAttrs() {
if (props.selectionMode === "single" && selection.keys.value.length > 1)
throw new TypeError("Single ListBox accepts at most one selected key.");
if (
props.virtualized &&
(!props.items || props.orientation !== "vertical" || props.rowHeight <= 0)
)
throw new Error(
"Virtualized ListBox requires items, vertical orientation and a positive rowHeight.",
);
// Force duplicate validation even when a scoped item renderer is absent.
void data.value;
return mergeProps(attrs, {
class: listboxVariants({ variant: props.variant }),
role: "listbox",
dir: dir.value,
"data-slot": "list-box",
"data-hv-listbox": "",
"data-disabled": disabled.value || undefined,
"aria-disabled": disabled.value || undefined,
"aria-readonly": props.isReadOnly || undefined,
"aria-orientation": props.orientation,
"aria-multiselectable":
props.selectionMode === "none"
? undefined
: props.selectionMode === "multiple",
tabindex:
disabled.value ||
(mounted.value &&
registry.available().some((member) => member.key() === active.value))
? -1
: 0,
onKeydown: keydown,
onKeyup: keyup,
onKeyupCapture: () => {
pressed.value = undefined;
},
onFocusout: (event: FocusEvent) => {
if (!root.value?.contains(event.relatedTarget as Node | null)) {
pressed.value = undefined;
pendingSpace = undefined;
}
},
onPointerdownCapture: () => {
keyboard.value = false;
},
onFocus: (event: FocusEvent) => {
if (
!restoringFocus &&
event.target === root.value &&
active.value !== undefined
)
void focus(active.value);
},
onScroll: props.virtualized ? containerProps.onScroll : undefined,
});
}
defineExpose({
element: root,
focus: (key?: ListBoxKey) =>
key === undefined ? root.value?.focus() : focus(key),
selectAll: () => selection.selectAll(eligible().map((item) => item.key)),
});
</script>
<template>
<component :is="as" ref="root" v-bind="rootAttrs()">
<slot v-if="!items" :item="undefined!" :index="-1" />
<slot v-else-if="!items.length" name="empty" />
<div
v-else-if="virtualized"
v-bind="wrapperProps"
role="presentation"
data-slot="list-box-virtual-content"
>
<div
v-for="entry in windowItems"
:key="entry.data.id"
role="presentation"
:style="{ height: `${rowHeight}px` }"
>
<slot :item="entry.data" :index="entry.index" />
</div>
</div>
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
</template>
</component>
</template>
@@ -0,0 +1,212 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
mergeProps,
onBeforeUnmount,
provide,
ref,
type PropType,
type SlotsType,
type VNodeChild,
watchEffect,
} from "vue";
import { listboxItemVariants } from "@heroui-vue/styles";
import { useChoiceField } from "../choice/shared";
import {
listBoxItemKey,
useListBox,
type ListBoxKey,
type ListBoxItemState,
} from "./context";
import { mergeIds } from "../field/context";
export default defineComponent({
name: "ListBoxItem",
inheritAttrs: false,
slots: Object as SlotsType<{
default: (state: ListBoxItemState) => VNodeChild[];
}>,
props: {
/** Collection identity, distinct from the generated DOM id. */
id: { type: [String, Number] as PropType<ListBoxKey>, required: true },
textValue: String,
isDisabled: Boolean,
variant: {
type: String as PropType<"default" | "danger">,
default: "default",
},
as: { type: String, default: "div" },
},
emits: {
select: (
_event: CustomEvent<{
key: ListBoxKey;
originalEvent: MouseEvent | KeyboardEvent;
}>,
) => true,
},
setup(props, { attrs, slots, emit, expose }) {
const context = useListBox();
const element = ref<HTMLElement>();
const hovered = ref(false),
pressed = ref(false);
const disabled = computed(
() => props.isDisabled || context.disabled(props.id),
);
// Isolate option labels/descriptions from a surrounding Select/Form field.
const text = useChoiceField(
{
get isDisabled() {
return disabled.value;
},
},
{},
{
kind: "group",
value: computed(() => props.id),
satisfied: () => true,
requiredMessage: "",
},
);
const state = () => ({
isSelected: context.selected(props.id),
isDisabled: disabled.value,
isFocused: context.focused.value === props.id,
isFocusVisible:
context.focused.value === props.id &&
(context.keyboard.value || !!element.value?.matches(":focus-visible")),
isPressed:
(pressed.value || context.pressed.value === props.id) &&
!disabled.value,
isHovered: hovered.value && !disabled.value,
});
provide(listBoxItemKey, state);
const remove = context.register({
key: () => props.id,
element: () => element.value,
textValue: () =>
props.textValue ??
element.value
?.querySelector('[data-slot="label"]')
?.textContent?.trim() ??
element.value?.textContent?.trim() ??
"",
disabled: () => disabled.value,
activate: click,
});
onBeforeUnmount(() => {
const hadFocus =
element.value?.ownerDocument.activeElement === element.value;
remove();
if (hadFocus) {
if (context.virtualized()) context.restoreFocus();
else {
context.focused.value = undefined;
const key = context.active.value;
if (key !== undefined) void context.focus(key);
else context.restoreFocus();
}
}
});
watchEffect((cleanup) => {
if (!pressed.value || !element.value) return;
const document = element.value.ownerDocument;
const release = () => {
pressed.value = false;
};
document.addEventListener("pointerup", release, true);
document.addEventListener("pointercancel", release, true);
cleanup(() => {
document.removeEventListener("pointerup", release, true);
document.removeEventListener("pointercancel", release, true);
});
});
watchEffect(() => {
if (
disabled.value &&
element.value?.ownerDocument.activeElement === element.value
) {
const key = context.active.value;
if (key !== undefined && key !== props.id) void context.focus(key);
else context.restoreFocus();
}
});
function click(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value || context.readOnly.value)
return;
const select = new CustomEvent("select", {
cancelable: true,
detail: { key: props.id, originalEvent: event },
});
emit("select", select);
if (select.defaultPrevented) return;
context.activate(props.id, event);
void context.focus(props.id);
}
expose({ element, focus: () => context.focus(props.id) });
return () => {
const current = state();
const position = context.position(props.id);
const children = text.prepare(slots.default?.(current) ?? [], true);
return h(
props.as,
mergeProps(attrs, {
ref: element,
id: text.field.controlId.value,
role: "option",
class: listboxItemVariants({
variant: props.variant,
}).item(),
tabindex:
!disabled.value && context.active.value === props.id ? 0 : -1,
"aria-selected":
context.mode.value === "none" ? undefined : current.isSelected,
"aria-disabled": disabled.value || undefined,
"aria-posinset": attrs["aria-posinset"] ?? position?.index,
"aria-setsize": attrs["aria-setsize"] ?? position?.size,
"aria-labelledby":
attrs["aria-labelledby"] ??
(attrs["aria-label"] ? undefined : text.labelledBy()),
"aria-describedby": mergeIds(
attrs["aria-describedby"] as string | undefined,
text.describedBy(),
),
"data-slot": "list-box-item",
"data-disabled": disabled.value || undefined,
"data-selected": current.isSelected || undefined,
"data-focused": current.isFocused || undefined,
"data-focus-visible": current.isFocusVisible || undefined,
"data-hovered": current.isHovered || undefined,
"data-pressed": current.isPressed || undefined,
onClick: click,
onFocus: () => {
if (!disabled.value) context.noteFocus(props.id);
},
onBlur: () => {
if (context.focused.value === props.id)
context.focused.value = undefined;
pressed.value = false;
},
onPointerenter: () => {
hovered.value = true;
},
onPointerleave: () => {
hovered.value = false;
},
onPointerdown: (event: PointerEvent) => {
if (
!event.defaultPrevented &&
!disabled.value &&
event.button === 0
)
pressed.value = true;
},
}),
children,
);
};
},
});
</script>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { inject } from "vue";
import { listboxItemVariants } from "@heroui-vue/styles";
import { listBoxItemKey, type ListBoxItemState } from "./context";
defineOptions({ inheritAttrs: false });
defineProps<{ as?: string }>();
defineSlots<{ default?: (state: ListBoxItemState) => unknown }>();
const state = inject(listBoxItemKey);
if (!state) throw new Error("ListBoxItemIndicator requires ListBoxItem.");
</script>
<template>
<component
:is="as ?? 'span'"
v-bind="$attrs"
:class="[listboxItemVariants().indicator(), $attrs.class]"
aria-hidden="true"
data-slot="list-box-item-indicator"
:data-visible="state().isSelected || undefined"
>
<slot v-bind="state()">
<!-- HeroUI ce90ea3 licensed checkmark; see third-party/HEROUI-LICENSE. -->
<svg
aria-hidden="true"
role="presentation"
fill="none"
stroke="currentColor"
stroke-dasharray="22"
:stroke-dashoffset="state().isSelected ? 44 : 66"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 17 18"
data-slot="list-box-item-indicator--checkmark"
>
<polyline points="1 9 7 14 15 4" />
</svg>
</slot>
</component>
</template>
@@ -0,0 +1,61 @@
<script lang="ts">
import {
cloneVNode,
defineComponent,
Fragment,
h,
isVNode,
mergeProps,
useId,
type VNodeChild,
} from "vue";
import { listboxSectionVariants } from "@heroui-vue/styles";
export default defineComponent({
name: "ListBoxSection",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { attrs, slots }) {
const id = useId();
return () => {
const headers: string[] = [];
function prepare(nodes: VNodeChild[], path = ""): VNodeChild[] {
return nodes.map((node, index) => {
if (!isVNode(node)) return node;
const type = node.type as { name?: string; __name?: string };
const at = `${path}-${index}`;
if ((type.name ?? type.__name) === "HeaderRoot") {
const headerId = String(node.props?.id ?? `${id}-heading${at}`);
headers.push(headerId);
return cloneVNode(node, { id: headerId });
}
if (
(typeof node.type === "string" || node.type === Fragment) &&
Array.isArray(node.children)
) {
const clone = cloneVNode(node);
clone.children = prepare(
node.children as VNodeChild[],
at,
) as typeof clone.children;
return clone;
}
return node;
});
}
const children = prepare(slots.default?.() ?? []);
return h(
props.as,
mergeProps(attrs, {
role: "group",
class: listboxSectionVariants(),
"data-slot": "list-box-section",
"aria-labelledby":
attrs["aria-labelledby"] ??
(attrs["aria-label"] ? undefined : headers.join(" ") || undefined),
}),
children,
);
};
},
});
</script>
@@ -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<T extends ListBoxDataItem = ListBoxDataItem> {
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<CollectionSelectionMode>;
readOnly: ComputedRef<boolean>;
keyboard: Ref<boolean>;
focused: Ref<ListBoxKey | undefined>;
noteFocus: (key: ListBoxKey) => void;
pressed: Ref<ListBoxKey | undefined>;
active: ComputedRef<ListBoxKey | undefined>;
selected: (key: ListBoxKey) => boolean;
disabled: (key: ListBoxKey) => boolean;
register: (member: ListBoxMember) => () => void;
activate: (key: ListBoxKey, event: MouseEvent | KeyboardEvent) => void;
focus: (key: ListBoxKey) => Promise<void>;
virtualized: () => boolean;
restoreFocus: () => void;
position: (key: ListBoxKey) => { index: number; size: number } | undefined;
}
export const listBoxKey: InjectionKey<ListBoxContext> = 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;
}
+28
View File
@@ -630,3 +630,31 @@ export type {
SliderOutputProps, SliderOutputProps,
SliderMarksProps, SliderMarksProps,
} from "./types"; } 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";
+29
View File
@@ -16,6 +16,35 @@ import type AvatarGroupCount from "./components/avatar/AvatarGroupCount.vue";
import type Skeleton from "./components/skeleton/Skeleton.vue"; import type Skeleton from "./components/skeleton/Skeleton.vue";
export type ButtonProps = InstanceType<typeof Button>["$props"]; export type ButtonProps = InstanceType<typeof Button>["$props"];
export type ListBoxProps<
T extends import("./components/list-box/context").ListBoxDataItem =
import("./components/list-box/context").ListBoxDataItem,
> = import("./components/list-box/context").ListBoxOptions<T> &
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<T>;
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<typeof Card>["$props"]; export type CardProps = InstanceType<typeof Card>["$props"];
export type InputProps = InstanceType<typeof Input>["$props"]; export type InputProps = InstanceType<typeof Input>["$props"];
export type SwitchProps = InstanceType<typeof Switch>["$props"]; export type SwitchProps = InstanceType<typeof Switch>["$props"];
+9 -1
View File
@@ -10,6 +10,7 @@ withDefaults(
multiple?: boolean; multiple?: boolean;
disabled?: boolean; disabled?: boolean;
name?: string; name?: string;
cancelNavigation?: boolean;
}>(), }>(),
{ modelValue: undefined, defaultValue: undefined }, { modelValue: undefined, defaultValue: undefined },
); );
@@ -26,7 +27,14 @@ const emit = defineEmits<{ "update:modelValue": [value: unknown] }>();
:name="name" :name="name"
@update:model-value="emit('update:modelValue', $event)" @update:model-value="emit('update:modelValue', $event)"
> >
<ListboxContent aria-label="Audit choices"> <ListboxContent
aria-label="Audit choices"
@keydown="
(event: KeyboardEvent) => {
if (cancelNavigation) event.preventDefault();
}
"
>
<ListboxItem :value="0">Numeric zero</ListboxItem> <ListboxItem :value="0">Numeric zero</ListboxItem>
<ListboxItem value="0">String zero</ListboxItem> <ListboxItem value="0">String zero</ListboxItem>
<ListboxItem value="disabled" disabled>Disabled</ListboxItem> <ListboxItem value="disabled" disabled>Disabled</ListboxItem>
+8
View File
@@ -95,6 +95,14 @@ function fixture(props: Record<string, unknown> = {}) {
} }
describe("installed Reka Listbox audit — not public component acceptance", () => { 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 () => { it("distinguishes numeric and string zero and toggles multiple values", async () => {
const wrapper = fixture({ multiple: true, defaultValue: [0] }); const wrapper = fixture({ multiple: true, defaultValue: [0] });
await flushPromises(); await flushPromises();
+70
View File
@@ -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);
});
});
+473
View File
@@ -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<typeof mount>[] = [];
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 =
'<ListBoxItem :id="0" text-value="Émma"><Label>Emma</Label><Description>emma@example.com</Description><ListBoxItemIndicator/></ListBoxItem><ListBoxItem id="0" text-value="Fred"><Label>Fred</Label><ListBoxItemIndicator/></ListBoxItem><ListBoxItem id="disabled" is-disabled><Label>Disabled</Label></ListBoxItem><ListBoxItem id="last" text-value="Martha"><Label>Martha</Label></ListBoxItem>';
const option = (wrapper: ReturnType<typeof mount>, index: number) =>
wrapper.findAll<HTMLElement>('[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(
`<div><ListBox>${options}</ListBox><button>Outside</button></div>`,
);
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(
`<ListBox selection-mode="none" variant="danger" :default-value="['last']">${options}</ListBox>`,
);
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(
`<ListBox @keyup="cancelled && $event.preventDefault()">${options}</ListBox>`,
() => ({ 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(
'<ListBox><ListBoxItem id="a" text-value="Liam Smith">Liam Smith</ListBoxItem><ListBoxItem id="b" text-value="Liam Jones">Liam Jones</ListBoxItem><ListBoxItem id="c" text-value="Emma">Emma</ListBoxItem></ListBox>',
);
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(
`<ListBox :default-selected-keys="[0]" selection-mode="multiple" aria-label="People">${options}</ListBox>`,
);
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(
`<ListBox :model-value="[0]" selection-mode="multiple">${options}</ListBox>`,
);
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(
`<ListBox :model-value="undefined" :selected-keys="[0]">${options}</ListBox>`,
);
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(
`<ListBox :default-value="[0]" :disallow-empty-selection="locked">${options}</ListBox>`,
() => ({ 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(
`<ListBox selection-mode="none">${options}</ListBox>`,
);
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(
`<ListBox orientation="horizontal" dir="rtl">${options}</ListBox>`,
);
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(
`<ListBox selection-mode="multiple" :is-read-only="readonly">${options}</ListBox>`,
() => ({ 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(
`<ListBox selection-mode="multiple" selection-behavior="replace">${options}</ListBox>`,
);
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(`<ListBox>${options}</ListBox>`);
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(
`<ListBox @keydown.prevent><ListBoxItem id="a" :onClick="handlers">A</ListBoxItem><ListBoxItem id="b">B</ListBoxItem></ListBox>`,
() => ({
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(
'<ListBox><ListBoxItem id="a" @select="select">A</ListBoxItem></ListBox>',
() => ({ 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(
`<Fieldset disabled><legend><ListBox>${options}</ListBox></legend><ListBox>${options}</ListBox></Fieldset>`,
);
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(
'<ListBox><ListBoxSection><Header>Team</Header><ListBoxItem id="a"><Label>A</Label><Description>Detail A</Description></ListBoxItem><ListBoxItem id="b" aria-label="Explicit"><Label>B</Label><Description>Detail B</Description></ListBoxItem></ListBoxSection></ListBox>',
);
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<string[]>([]);
const wrapper = fixture(
'<ListBox :disabled-keys="blocked"><ListBoxItem v-for="item in items" :key="item.id" :id="item.id" :text-value="item.textValue">{{ item.textValue }}</ListBoxItem></ListBox>',
() => ({ 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(
'<ListBox :items="items" virtualized selection-mode="multiple" style="height:400px" v-slot="{ item }"><ListBoxItem :id="item.id" :text-value="item.textValue">{{ item.textValue }}</ListBoxItem></ListBox>',
() => ({ 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(
`<div><ListBox>${options}</ListBox><ListBox>${options}</ListBox><ListBox :items="[]"><template #empty>No results</template></ListBox></div>`,
);
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<typeof defineComponent>),
),
),
}),
{
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);
});
});
+2
View File
@@ -15,3 +15,5 @@ pnpm exec tsc --noEmit --strict --skipLibCheck --module esnext --moduleResolutio
SLIDER-01 已在 `/private/tmp/heroui-slider-consumer` 完成上述检查,临时契约文件名为 `contract.ts`。默认工作区 typecheck 仍使用源码 alias,所以不能代替此独立产物检查。 SLIDER-01 已在 `/private/tmp/heroui-slider-consumer` 完成上述检查,临时契约文件名为 `contract.ts`。默认工作区 typecheck 仍使用源码 alias,所以不能代替此独立产物检查。
M30–M32 增加 consume-m30-m32.mjs 和 m30-m32-contract.ts。将它们复制到同一个独立消费工程,执行运行脚本,并将契约文件加入上述两种 tsc 命令。合并后的产物还应同时通过原 NumberField/Slider 消费检查,避免只验证新加组件。 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 提取后退化,非法模型/模式反例与事件参数推断必须保留。
+52
View File
@@ -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.",
);
+38
View File
@@ -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,
];