Compare commits
2 Commits
9f44ffb310
...
65db60a7ac
| Author | SHA1 | Date | |
|---|---|---|---|
| 65db60a7ac | |||
| dea5ded716 |
@@ -411,3 +411,17 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V
|
||||
- 独立产物类型至少核对 bundler 与 NodeNext。声明中的扩展名缺失可能让 skipLibCheck 下的属性退化为 any;正例能编译不足以验收,必须让错误模型/变体的反例触发诊断,并保留 validate 等参数推断。ESM 声明路径在生成时规范化,消费用例见 tests/package/。
|
||||
|
||||
- 新任务必须先读 [M30–M32 多轮返工总结](docs/migrations/M30-M32-lessons.md),将适用失败场景映射到自己的回归。迁移说明 docs/migration-handoff.md 已同步,不仅看上一轮绿色测试数量。
|
||||
|
||||
## COLLECTION-01 基建启动(2026-10-23)
|
||||
|
||||
- 集成人在独立目录、`feat/listbox-select-foundation` 分支实施;先读 [集合基建决策](docs/decisions/collection-foundation.md)。私有 key / 接受值状态 / 挂载成员注册已落地,未导出公共 ListBox 或 Select。
|
||||
- key 区分数字和字符串,空字符串有效;内部适配编码不进入 FormData。父拒绝后相同提案可以重试,程序化父值与用户改选权限分开。
|
||||
- Reka 已实测支持禁用项跳过/全选;Listbox reset、索引表单名,以及 Select 多选原生提交/关闭态 SSR 存在适配需求。不能只检查可见文字或读局部源码猜能力。
|
||||
- 已挂载 registry 不等于虚拟化完整集合。公共 Item 的 Label/Description 与外层字段隔离,使用既有字段/reset/弹层设施;9/19 个基线预览和公共验收仍待完成。
|
||||
|
||||
## LISTBOX-01 公共集合协议(2026-10-23)
|
||||
|
||||
- ListBox 四部件与 9 个预览已经接入,见 [报告](docs/migrations/LISTBOX-01-list-box.md);Select 的 19 个预览仍待迁移。其他 AI 不自行改写 collection / ListBox 共享模型。
|
||||
- 逻辑数据全集与挂载 registry 分开。虚拟导航先滚动再等 DOM 聚焦,异步焦点请求可被新请求或卸载取消;用户滚动卸载焦点行时不跳回首行。全选/范围/搜索不能只看可见窗口。
|
||||
- 连续 typeahead 在当前项仍匹配时保留它;重复首字母才循环下一项。空 key / 数字 0 不得被真值判断排除;none 模式不显示遗留的选中状态。
|
||||
- Root 与公开 Props 共用 ListBoxOptions 明确 schema,泛型 SFC 的 Parameters 提取曾让反例失效。后续泛型组件也必须做产物类型正反例,不能用 any 修复。
|
||||
|
||||
@@ -100,6 +100,7 @@ const groups = [
|
||||
{ title: "Toolbar 工具栏", url: "/components/toolbar" },
|
||||
{ title: "NumberField 数字输入框", url: "/components/number-field" },
|
||||
{ title: "Slider 滑块", url: "/components/slider" },
|
||||
{ title: "ListBox 列表框", url: "/components/list-box" },
|
||||
{ title: "Tooltip 工具提示", url: "/components/tooltip" },
|
||||
{
|
||||
title: "ToggleButton 切换按钮",
|
||||
|
||||
@@ -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。
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -70,9 +70,9 @@
|
||||
| radio-group | 验证中(基线实现) | 标量模型、roving Tab/方向键/dir/loop、原生提交/校验/reset;12 个基线预览 |
|
||||
| input-otp | 验证中(M32) | Root/Group/Slot/Separator + 3 正则常量;Reka PinInput 底座;字符串+索引数组;reset/Fieldset/Form/ARIA/mask 已接入;11/11 例;自动填充/IME/读屏未真机验证 |
|
||||
| alert | 验证中(最小实现) | status 五态;默认图标随 status;自定义 Indicator 空内容回退;内部 Surface 重置为 default |
|
||||
| list-box | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| list-box-item | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| list-box-section | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| list-box | 验证中(LISTBOX-01) | 四部件、9/9 基线例;typed key/数组模型、none/single/multiple、键盘/范围/全选、1000 项固定行高虚拟化;差异见 LISTBOX-01 |
|
||||
| list-box-item | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 |
|
||||
| list-box-section | 验证中(LISTBOX-01) | ListBox 子部件;独立标签/描述作用域、自动分组名称、原生标签替换、状态/指示器;见 LISTBOX-01 |
|
||||
| dropdown | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| menu | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| menu-item | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
@@ -80,7 +80,7 @@
|
||||
| modal | 验证中(OVERLAY-02) | Root/Trigger/Backdrop/Container/Dialog/Heading/Header/Body/Footer/Icon/Close/CloseTrigger;14/14 基线例;焦点/锁/滚动/退出动画;Vue close 部件替代 React slot |
|
||||
| pagination | 验证中(M30) | 组合式 nav 容器(无 total/page 状态机);11 具名部件;9/9 基线例;onPress→@click;显式 aria-current 可覆盖 |
|
||||
| number-field | 验证中(NUMBER-01) | 五部件与 17/17 基线例;Reka 数值内核;受控/只读/表单 reset、SSR/水合;差异见 NUMBER-01 报告 |
|
||||
| select | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| select | 基建中(未公开) | 集合状态与公开 ListBox 已落地;Select 六部件、字段/弹层/SSR 接入及 19 个基线预览仍待迁移,见 COLLECTION-01 |
|
||||
| meter | 验证中(M20) | Meter/Output/Track/Fill;6/6 基线例;role=meter progressbar;无 isIndeterminate;测量语义独立于 Progress |
|
||||
| slider | 验证中(SLIDER-01) | 六部件、9/9 基线例;原生 range/局部指针适配,单值/范围、受控/reset/SSR/水合;差异见 SLIDER-01 |
|
||||
| table | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# COLLECTION-01:ListBox / Select 集合基建
|
||||
|
||||
2026-10-23。独立目录 `heroui-vue-core`,分支 `feat/listbox-select-foundation`,从已同步的 main `9f44ffb` 开始。另一 AI 在原目录做 AlertDialog / Drawer;本轮不修改其 checkout。
|
||||
|
||||
## 基线与当前边界
|
||||
|
||||
固定 HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`,审计实际安装的 Reka 2.11.0。无需新增依赖,不调用 Reka 未导出的内部接口。
|
||||
|
||||
- 上游源码:`packages/react/src/components/list-box/`、`list-box-item/`、`list-box-section/`、`select/`;对应 `packages/styles/components/` CSS 和 `packages/styles/src/components/` 变体。
|
||||
- ListBox 四部件:Root、Item、ItemIndicator、Section。Select 六部件:Root、Trigger、Value、Indicator、ClearButton、Popover。与 Label / Description / Header / Separator 的组合也属于验收范围。
|
||||
- 中文正文:`apps/docs/content/docs/cn/react/components/(collections)/list-box.mdx` 和 `(pickers)/select.mdx`。ListBox **9** 个正文预览:default、with-disabled-items、with-sections、multi-select、controlled、virtualization、custom-check-icon、render-function、custom-styles。
|
||||
- Select **19** 个正文预览:default、variants、full-width、with-description、required、disabled、with-disabled-options、multiple-select、with-sections、controlled、controlled-multiple、controlled-open-state、asynchronous-loading、custom-indicator、with-clear-button、custom-value、render-function、on-surface、custom-styles。
|
||||
- 目录中的 `release-scrollbar-modes` 不是 ListBox 正文预览,单独记录,不能拿它替换缺失的虚拟化预览。
|
||||
|
||||
本轮落地的是私有 key、接受值状态和已挂载成员注册层,以及安装版能力探针。**尚未导出公共 ListBox / Select,没有宣称公共组件、文档或视觉迁移完成。**
|
||||
|
||||
## 已实测的底座能力
|
||||
|
||||
夹具位于 `packages/vue/tests/fixtures/CollectionFoundation.vue`、`SelectFoundation.vue`。审计测试断言实际 DOM、焦点、事件载荷和 FormData;SSR 单独使用真正 node 环境。测试保留底座缺口,后续公共测试必须证明适配修复,不能直接把探针变绿视为公共验收。
|
||||
|
||||
| 场景 | Reka 2.11.0 实际结果 | 实施决定 |
|
||||
| ---------------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------- |
|
||||
| Listbox 数字 0 / 字符串 "0" | 选择状态区分两项,多选切换有效 | 公共 key 保留类型,不先 String(key) |
|
||||
| Listbox 受控拒绝连续两次选择 | 真实 aria-selected 保持父值,两次提案均发出 | 复用交互;本库状态同样只保存接受值 |
|
||||
| Listbox End / Ctrl+A | End 聚焦最后可用项;全选跳过禁用项 | 复用底座已具备能力,不能仅看局部源码猜缺陷 |
|
||||
| Listbox item select 取消 | DOM `listbox.select` preventDefault 后不改值 | 保留取消边界;公共事件与原始键盘/指针阶段还要专项验证 |
|
||||
| Listbox 多选表单 | name=choices 输出 choices[0]、choices[1];0 与 "0" 均序列化为 "0" | 本库独立原生提交层,同名多值;不把内部编码提交给用户 |
|
||||
| Listbox 原生 reset | 可见第二项和 FormData 均未恢复初值 | 复用现有 useChoiceForm 协调取消/受控/reset;底座不传 name,避免重复值 |
|
||||
| Select 多选初值 [0, "0"] | Trigger 显示两项,原生 options 存在;selectedOptions 为 0,FormData 为空 | 必须单独适配唯一表单层,不能以显示正确推断提交正确 |
|
||||
| Select 整体禁用 | Trigger 真正 disabled,FormData 不提交 | 合并 Fieldset 作用域并继续验证独立禁用项 |
|
||||
| Select 单选初值 0 | 挂载后 Trigger 显示 Numeric zero,FormData 为 choice=0 | 保留该基线;多选缺口不能笼统描述为 Select 全部不可用 |
|
||||
| Select 空字符串 item key | setup 抛错,空字符串被内部保留为清空值 | 私有 typed key 编码跨适配边界,公共空值用 null;不偷偷禁用合法 key |
|
||||
| Listbox node SSR | 三个 option、恰好一个选中项,无浏览器全局 | 后续实际水合另验,渲染成功不能代替水合 |
|
||||
| Select 关闭态 node SSR | 有 combobox,但没有 Numeric zero 或对应 option | 子项 onMounted 注册不能满足首屏展示;公共 Value/表单需先规划元数据,不能只等挂载 |
|
||||
|
||||
## 已实现的私有协议
|
||||
|
||||
`packages/vue/src/components/collection/` 不经公共入口导出。
|
||||
|
||||
1. `keys.ts`:只接受字符串和有限数字;数字 0 与字符串 "0" 不同,空字符串有效,NaN / Infinity / 对象不是 key。编码采用带类型的 JSON 元组,解码验证结构。编码仅供底座身份适配,不是 DOM id 或提交值。
|
||||
2. `selection.ts`:内部规范为 key 数组,集合相等不因顺序不同而重复发 change。数组复制、接受值快照冻结;显式 controlled getter 区分受控空值与非受控。父拒绝不会留下 lastEmitted 幽灵值,同一请求可重试。
|
||||
3. none / single / multiple、toggle / replace、readOnly、整体禁用、disabledKeys、disallowEmptySelection 的选择决策已覆盖。single 请求多个 key 报错;none 禁止改选,但不会擅自清理父级提供的 key。
|
||||
4. 禁用项不能被直接 toggle 或新增到选择。允许从禁用的初始单选项改选可用项;select-all 保留原本选中的禁用 key,同时只增加可用项。父级程序化替换不受用户编辑限制。
|
||||
5. reset 只恢复非受控初始副本、不发编辑事件。实际原生 reset 归属、取消和动态 form 关联继续由既有 `useChoiceForm` 驱动;本模块不建立第二套监听队列。
|
||||
6. `registry.ts`:实例内注册、作用域销毁清理、动态 key / disabled / text getter;交互时读取实际 DOM 顺序,支持节点重排。重复 key(含动态碰撞)明确报错,不静默覆盖。无节点与断开节点保留注册顺序,SSR 不访问 window/document。
|
||||
7. registry 提供可用项、相邻目标、first/last/loop 和范围 key;**不自动移动焦点或改选**。方向/RTL、typeahead、IME、焦点环优先适配 Reka,不能让每个组件再实现一套键盘状态。
|
||||
|
||||
注册表目前只代表挂载成员。虚拟化的完整数据、异步未挂载选项和 selectedItems 元数据必须由消费者的数据集合提供;不得拿挂载数量当全集或声称虚拟化已支持。selectAll 接收调用方提供的可用全集;范围工具只处理当前已知成员,未知锚点返回空范围,不能错误选择第一项。
|
||||
|
||||
## 公共迁移接续约定
|
||||
|
||||
- ListBox 沿用 selectionMode、disabledKeys、disallowEmptySelection 等概念;受控选择映射 Vue `v-model` key 数组(与已实现 ToggleButtonGroup 一致),事件 `selectionChange` / `action` 分开。RAC 的 Set / "all" 与 Vue 数组、虚拟集合全选的映射必须在公共实现时明示,不能无记录丢失。
|
||||
- Select 沿用基线单选 `Key | null` / 多选 `Key[]`,`v-model` / `update:modelValue`,展开 `v-model:open`。对象数据通过稳定 key 关联,不能把整个对象隐式 stringify 成提交值。
|
||||
- 集合共享选择身份和成员模型,不共享所有交互语义。ListBox action-only、菜单 action、Select 选中后关闭、多选保持打开、ComboBox 输入过滤分别适配,不能把菜单伪装成多选列表框。
|
||||
- 字段侧继续消费 FieldContext / Form / disabledContext,验证 Label、Description、FieldError 到实际 Trigger / listbox 节点的关联。Item 内 Label / Description 必须有自己的作用域,避免把每个选项名称注册到 Select 的外层字段;Section Header 对应 group 名称。
|
||||
- SSR 的子项元数据采用既有 VNode 规划思路并支持显式数据源;不运行用户任意组件 setup 来探测内容。任意自定义包装不能静态规划时,要求显式文本与 ARIA 数据并记录边界。
|
||||
- Select ClearButton 保持非 button 视觉入口及 aria-hidden,禁止嵌套 button;只有挂载 ClearButton 才启用关闭态 Backspace/Delete 清空。多个清除部件的注册、卸载和禁用状态需验,不用一个布尔变量代替注册计数。
|
||||
- Popover 继续接现有弹层层级/Presence/定位设施;样式完整移植源变量、data 属性、原点与进出动画,验证嵌套、焦点恢复和退出中重开。
|
||||
- 基线的 9 / 19 预览、部件 Props / 插槽 / 事件、tv / CSS / 导出、导航、矩阵、来源、验证报告一起完成;虚拟化与异步不能改成简短静态列表冒充原例。
|
||||
|
||||
## 后续必须验收的结果
|
||||
|
||||
公共实际 DOM 和 FormData、受控拒绝/重试、单多选空值、禁用/只读/Fieldset、required 和 Form 错误响应、取消 reset / form 归属、名称优先级、动态增删/重排/禁用项、键盘/IME/typeahead、范围/全选、Select 清空/关闭、异步值标签、虚拟滚动、嵌套弹层、node SSR 与实际水合、独立产物类型正反例。浏览器在 5174 只重点验几何、滚动、焦点和动效。
|
||||
|
||||
当前状态层及底座探针不覆盖上面这些公共组件验收,也没有逐像素、读屏、触屏或 Nuxt 结论。
|
||||
|
||||
## LISTBOX-01 公共实现接续
|
||||
|
||||
前文“尚未导出”是 COLLECTION-01 审计阶段的历史状态。ListBox 四部件和九个预览已接入,见 [LISTBOX-01 报告](../migrations/LISTBOX-01-list-box.md)。Select 公共组件与十九个预览仍未实现。
|
||||
|
||||
新增原始 Reka 探针确认:Content 的用户 keydown preventDefault 后,End 仍移动焦点。结合 none 语义、完整数据虚拟化与 textValue / 元数据需求,公共 ListBox 使用局部原生 role 节点与既有集合内核,VueUse 维护虚拟滚动测量;不修改依赖、不调用私有上下文,也不引入另一套组件底座。普通列表与虚拟列表共用唯一逻辑集合、选择和焦点状态。
|
||||
|
||||
泛型 SFC 不通过 Parameters 提取公共 Props:实测会让模型/模式反例失效。Root 和导出的 Props 复用 ListBoxOptions 明确 schema,保留消费端正反例;不能以 skipLibCheck 或删除反例规避。
|
||||
@@ -253,3 +253,11 @@ Modal / Popover / Tooltip 公共迁移与全部 26 个基线预览已接入,
|
||||
- 所有示例在同一父应用共存,查重复 ID 和实例串扰;node SSR、jsdom、水合与真实浏览器分别记录。
|
||||
- 已修复的回归保留,动态增删/拒绝重试/同类路径一并覆盖,报告准确写明已执行和未验证范围。
|
||||
- 当前 M30–M32 结论见最终验收;下一批 AlertDialog/Drawer 必须按提示词先拉最新 main,再新建 feat/m33-m34-alert-dialog-drawer,不在旧任务分支或 main 上继续开发。
|
||||
|
||||
## 集合基建实施中(COLLECTION-01)
|
||||
|
||||
集成人负责独立分支的 [ListBox/Select 集合基建](decisions/collection-foundation.md),其他 AI 继续 AlertDialog/Drawer。typed key、接受值选择状态和挂载成员注册为私有设施,暂不交给其他 AI 扩展或视为公共组件已完成。Reka 的多选显示与表单提交必须分别验;虚拟化全集与挂载 registry 必须区分。公共迁移、字段/标签作用域、SSR 元数据和 9/19 个基线预览按决策文档接续。
|
||||
|
||||
## LISTBOX-01 接续
|
||||
|
||||
ListBox 已完成公共首轮实现,见 [报告](migrations/LISTBOX-01-list-box.md)。后续 Select / ComboBox 等可沿用 typed key、接受值模型、项内文本作用域与完整数据集合;不能把独立 ListBox 的 action/选择直接当作 Select 的关闭与表单契约。Select 的十九个预览、唯一提交层、字段名称、SSR 展示元数据、清除和嵌套定位仍归集成人实施。
|
||||
|
||||
@@ -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 水合与真实浏览器的结论分别记录,不互相替代。
|
||||
@@ -160,3 +160,13 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生
|
||||
- 固定 ce90ea3 的 `packages/react/src/components/slider/slider.tsx`、`packages/styles/components/slider.css`、`packages/styles/src/components/slider/slider.styles.ts`;Apache-2.0 原声明见 third-party/HEROUI-LICENSE。
|
||||
- 英文正文 `apps/docs/content/docs/en/react/components/(controls)/slider.mdx` 与 `apps/docs/src/demos/cn/slider/` 九个正文示例。当前固定基线没有中文 Slider 正文。
|
||||
- CSS 保留视觉数值并改 hv- 命名空间;伪元素 reduced-motion 改等价原生媒体查询。局部原生 range / pointer capture 的原因与差异见 [SLIDER-01](migrations/SLIDER-01-slider.md)。
|
||||
|
||||
## COLLECTION-01 来源与能力审计(2026-10-23)
|
||||
|
||||
- 固定 ce90ea3 的 ListBox / ListBoxItem / ListBoxSection / Select 源码、CSS/tv、中文正文和 9/19 预览作为后续公共实现清单。本轮未复制这些组件 CSS 或演示。
|
||||
- 直接使用安装版 Reka 2.11.0(MIT)公开导出构造测试夹具;未修改 node_modules、未复制内部 Collection/Select 实现。私有 key、状态和成员层为 Vue 实现。
|
||||
- 依据、实际缺口及阶段边界见 [集合基建决策](decisions/collection-foundation.md)。
|
||||
|
||||
## LISTBOX-01(2026-10-23)
|
||||
|
||||
固定 ce90ea3 的 list-box / list-box-item / list-box-section 源码、CSS/tv,以及中文正文和九个预览。CSS/tv 按 hv- 移植,源勾选图形遵循原 Apache-2.0;文档图标用现有 Tabler Vue。原 alert 演示改为内联状态反馈,React render 改 as/插槽,Virtualizer/ListLayout 改 VueUse 固定行高虚拟化。依据、差异与限制见 [LISTBOX-01](migrations/LISTBOX-01-list-box.md)。
|
||||
|
||||
@@ -633,3 +633,17 @@ typecheck、build:docs、build:playground、format、diff-check 与 dist 正反
|
||||
## M30–M32 与 NumberField/Slider 最终整合
|
||||
|
||||
39 文件 / 593 项通过,类型检查、库与文档构建通过。独立 tarball 再次验证 M30–M32 ESM/SSR/名称/CSS 与两种解析模式下的严格类型,同时保留 NumberField/Slider 消费回归。兼容矩阵不再把已合入组件标为计划;共享入口、样式、导航和测试均增量保留。详见最终验收和返工经验清单。
|
||||
|
||||
## COLLECTION-01 私有集合基建(2026-10-23)
|
||||
|
||||
- 新增 19 项 key/接受值/成员协议回归、8 项安装版 Reka Listbox/Select jsdom 探针、4 项真正 node SSR 探针,共 31 项。完整 `pnpm test`:42 文件 / 624 项通过;`pnpm typecheck`、`pnpm build` 通过。
|
||||
- 断言包括 typed key、受控拒绝重试、禁用初值改选、不可变快照、DOM 重排、动态碰撞、清理/实例隔离、焦点、实际 FormData 和 SSR 缺口。底座缺陷的审计断言不代表公共组件已修复。
|
||||
- 本轮无公共导出或页面改动,未进行浏览器/文档视觉、实际水合、独立产物消费或完整 ListBox/Select 验收。详细边界和 9/19 基线清单见 [集合基建决策](decisions/collection-foundation.md)。
|
||||
|
||||
## LISTBOX-01 公共迁移(2026-10-23)
|
||||
|
||||
- 最终 `pnpm test`:44 文件 / 649 项通过;其中 ListBox 公共行为、九例同页挂载和实际 jsdom 水合 22 项,真正 node SSR 2 项。原始 Reka 取消探针单独保留,不作为公共验收替代。
|
||||
- `pnpm typecheck`、`pnpm build:docs`、Prettier 和 git diff --check 通过;库与生产文档包含完整新导出/CSS,只有既存 chunk 超过 500kB 提示。
|
||||
- 最终 tarball 在 `/private/tmp/heroui-slider-consumer` 重新安装,ListBox ESM/SSR/CSS、NodeNext / bundler 严格正反例通过;并保留 NumberField/Slider、M30–M32 消费回归。泛型 Props 的非法模型/模式反例没有被删除或放宽。
|
||||
- 5174 浏览器重点验证受控选择/Space、虚拟 End 到第 1000 项及 Home、连续 Liam 搜索、深浅色、鼠标后 Tab 返回原项与焦点环。1280×720 下九张表均为正文 736px,scrollWidth=clientWidth。
|
||||
- 普通列表 SSR 的选中/ID/名称/描述与水合已验;虚拟 SSR 是容器,挂载后测量显示固定高度行。可变行高/虚拟分组、自动逐像素、读屏/触屏、移动视口和 Nuxt 未验收。详见 [LISTBOX-01](migrations/LISTBOX-01-list-box.md)。Select 公共组件未完成。
|
||||
|
||||
+2
-2
@@ -15,8 +15,8 @@
|
||||
"build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts",
|
||||
"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",
|
||||
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts",
|
||||
"test:ssr": "vitest run tests/ssr.test.ts tests/input-otp-ssr.test.ts tests/slider-foundation-ssr.test.ts tests/slider-ssr.test.ts tests/collection-foundation-ssr.test.ts tests/list-box-ssr.test.ts",
|
||||
"format": "prettier --check .",
|
||||
"format:fix": "prettier --write .",
|
||||
"dev:playground": "pnpm build && pnpm --filter @heroui-vue/playground dev"
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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%];
|
||||
}
|
||||
}
|
||||
@@ -141,3 +141,7 @@
|
||||
@import "./components/number-field.css";
|
||||
|
||||
@import "./components/slider.css" layer(components);
|
||||
|
||||
@import "./components/list-box.css" layer(components);
|
||||
@import "./components/list-box-item.css" layer(components);
|
||||
@import "./components/list-box-section.css" layer(components);
|
||||
|
||||
@@ -1273,3 +1273,28 @@ export const sliderVariants = tv({
|
||||
},
|
||||
});
|
||||
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
|
||||
>;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/** Private collection identity. Keys remain typed; DOM/form strings are boundaries. */
|
||||
export type CollectionKey = string | number;
|
||||
|
||||
export function assertKey(key: CollectionKey): void {
|
||||
if (
|
||||
(typeof key !== "string" && typeof key !== "number") ||
|
||||
(typeof key === "number" && !Number.isFinite(key))
|
||||
) {
|
||||
throw new TypeError("Collection keys must be strings or finite numbers.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Reversible adapter value, including empty strings and string/number collisions. */
|
||||
export function encodeKey(key: CollectionKey): string {
|
||||
assertKey(key);
|
||||
return JSON.stringify([typeof key, key]);
|
||||
}
|
||||
|
||||
export function decodeKey(value: string): CollectionKey {
|
||||
const data: unknown = JSON.parse(value);
|
||||
if (!Array.isArray(data) || data.length !== 2 || data[0] !== typeof data[1]) {
|
||||
throw new TypeError("Invalid encoded collection key.");
|
||||
}
|
||||
assertKey(data[1]);
|
||||
return data[1];
|
||||
}
|
||||
|
||||
export function copyKeys(keys: readonly CollectionKey[]): CollectionKey[] {
|
||||
keys.forEach(assertKey);
|
||||
return [...new Set(keys)];
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { onScopeDispose, shallowRef } from "vue";
|
||||
import { assertKey, type CollectionKey } from "./keys";
|
||||
|
||||
export interface CollectionMember {
|
||||
key: () => CollectionKey;
|
||||
element: () => HTMLElement | undefined;
|
||||
textValue: () => string;
|
||||
disabled: () => boolean;
|
||||
}
|
||||
|
||||
/** One registry per collection provider. No document queries or global IDs.
|
||||
* Read order at interaction time: Vue can reorder nodes without changing refs. */
|
||||
export function useCollectionRegistry<
|
||||
T extends CollectionMember = CollectionMember,
|
||||
>() {
|
||||
const members = shallowRef<readonly T[]>([]);
|
||||
|
||||
function ordered(): T[] {
|
||||
const seen = new Set<CollectionKey>();
|
||||
for (const member of members.value) {
|
||||
const key = member.key();
|
||||
assertKey(key);
|
||||
if (seen.has(key)) throw new Error(`Duplicate collection key: ${key}`);
|
||||
seen.add(key);
|
||||
}
|
||||
return [...members.value].sort((a, b) => {
|
||||
const first = a.element();
|
||||
const second = b.element();
|
||||
if (!first || !second || first === second) return 0;
|
||||
const position = first.compareDocumentPosition(second);
|
||||
// DISCONNECTED: preserve registration order for SSR/closed popovers.
|
||||
if (position & 1) return 0;
|
||||
return position & 4 ? -1 : position & 2 ? 1 : 0;
|
||||
});
|
||||
}
|
||||
|
||||
function register(member: T): () => void {
|
||||
assertKey(member.key());
|
||||
if (ordered().some((item) => item.key() === member.key())) {
|
||||
throw new Error(`Duplicate collection key: ${member.key()}`);
|
||||
}
|
||||
members.value = [...members.value, member];
|
||||
const unregister = () => {
|
||||
members.value = members.value.filter((item) => item !== member);
|
||||
};
|
||||
onScopeDispose(unregister, true);
|
||||
return unregister;
|
||||
}
|
||||
|
||||
const available = () => ordered().filter((member) => !member.disabled());
|
||||
|
||||
/** Returns a navigation target without selecting or moving focus. */
|
||||
function adjacent(
|
||||
key: CollectionKey | undefined,
|
||||
intent: "first" | "last" | "next" | "previous",
|
||||
loop = false,
|
||||
): T | undefined {
|
||||
const items = available();
|
||||
if (intent === "first") return items[0];
|
||||
if (intent === "last") return items.at(-1);
|
||||
const index = items.findIndex((member) => member.key() === key);
|
||||
if (index === -1) return intent === "next" ? items[0] : items.at(-1);
|
||||
const target = index + (intent === "next" ? 1 : -1);
|
||||
return items[target] ?? (loop ? items.at(target < 0 ? -1 : 0) : undefined);
|
||||
}
|
||||
|
||||
function range(
|
||||
anchor: CollectionKey,
|
||||
target: CollectionKey,
|
||||
): CollectionKey[] {
|
||||
const items = available();
|
||||
const start = items.findIndex((member) => member.key() === anchor);
|
||||
const end = items.findIndex((member) => member.key() === target);
|
||||
if (start === -1 || end === -1) return [];
|
||||
return items
|
||||
.slice(Math.min(start, end), Math.max(start, end) + 1)
|
||||
.map((member) => member.key());
|
||||
}
|
||||
|
||||
return { ordered, available, register, adjacent, range };
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { computed, shallowRef } from "vue";
|
||||
import { assertKey, copyKeys, type CollectionKey } from "./keys";
|
||||
|
||||
export type CollectionSelectionMode = "none" | "single" | "multiple";
|
||||
|
||||
interface SelectionOptions {
|
||||
mode: () => CollectionSelectionMode;
|
||||
/** Presence is explicit: a controlled empty/undefined model is still controlled. */
|
||||
controlled: () => boolean;
|
||||
value: () => readonly CollectionKey[] | undefined;
|
||||
defaultValue?: readonly CollectionKey[];
|
||||
disabled?: () => boolean;
|
||||
readOnly?: () => boolean;
|
||||
disabledKeys?: () => readonly CollectionKey[];
|
||||
disallowEmptySelection?: () => boolean;
|
||||
onChange: (keys: CollectionKey[]) => void;
|
||||
}
|
||||
|
||||
/** Accepted selection only. Focus, actions, form serialization and range anchors
|
||||
* belong to the consuming composite, not a second optimistic selection store. */
|
||||
export function useCollectionSelection(options: SelectionOptions) {
|
||||
const initial = copyKeys(options.defaultValue ?? []);
|
||||
const internal = shallowRef([...initial]);
|
||||
const keys = computed(() =>
|
||||
Object.freeze(
|
||||
copyKeys(options.controlled() ? (options.value() ?? []) : internal.value),
|
||||
),
|
||||
);
|
||||
const selected = (key: CollectionKey) => keys.value.includes(key);
|
||||
const disabled = (key: CollectionKey) =>
|
||||
!!options.disabled?.() || !!options.disabledKeys?.().includes(key);
|
||||
const editable = () =>
|
||||
options.mode() !== "none" && !options.disabled?.() && !options.readOnly?.();
|
||||
|
||||
function request(next: readonly CollectionKey[]): boolean {
|
||||
if (!editable()) return false;
|
||||
const proposal = copyKeys(next);
|
||||
if (options.mode() === "single" && proposal.length > 1) {
|
||||
throw new TypeError("Single selection accepts at most one key.");
|
||||
}
|
||||
// A disabled key cannot be newly selected. Replacement may still leave an
|
||||
// initially selected disabled option, as with a native single select.
|
||||
if (proposal.some((key) => disabled(key) && !selected(key))) {
|
||||
return false;
|
||||
}
|
||||
if (!proposal.length && options.disallowEmptySelection?.()) return false;
|
||||
if (
|
||||
proposal.length === keys.value.length &&
|
||||
proposal.every((key) => selected(key))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!options.controlled()) internal.value = [...proposal];
|
||||
// An emitted array cannot mutate either props or accepted internal state.
|
||||
options.onChange([...proposal]);
|
||||
return true;
|
||||
}
|
||||
|
||||
function toggle(key: CollectionKey): boolean {
|
||||
assertKey(key);
|
||||
if (disabled(key)) return false;
|
||||
return request(
|
||||
selected(key)
|
||||
? keys.value.filter((item) => item !== key)
|
||||
: options.mode() === "multiple"
|
||||
? [...keys.value, key]
|
||||
: [key],
|
||||
);
|
||||
}
|
||||
|
||||
function replace(key: CollectionKey): boolean {
|
||||
assertKey(key);
|
||||
return !disabled(key) && request([key]);
|
||||
}
|
||||
|
||||
/** Eligible keys come from the consumer's data set, not necessarily mounted DOM.
|
||||
* Existing selected disabled keys survive select-all. */
|
||||
function selectAll(availableKeys: readonly CollectionKey[]): boolean {
|
||||
if (options.mode() !== "multiple") return false;
|
||||
return request([
|
||||
...keys.value.filter(disabled),
|
||||
...availableKeys.filter((key) => !disabled(key)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Called only after a non-cancelled native reset by the field adapter.
|
||||
* Reset is not an edit and never emits a change proposal. */
|
||||
function reset(): void {
|
||||
if (!options.controlled()) internal.value = [...initial];
|
||||
}
|
||||
|
||||
return {
|
||||
keys,
|
||||
selected,
|
||||
disabled,
|
||||
request,
|
||||
toggle,
|
||||
replace,
|
||||
selectAll,
|
||||
reset,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -630,3 +630,31 @@ export type {
|
||||
SliderOutputProps,
|
||||
SliderMarksProps,
|
||||
} from "./types";
|
||||
|
||||
export {
|
||||
default as ListBox,
|
||||
default as ListBoxRoot,
|
||||
} from "./components/list-box/ListBox.vue";
|
||||
export { default as ListBoxItem } from "./components/list-box/ListBoxItem.vue";
|
||||
export { default as ListBoxItemIndicator } from "./components/list-box/ListBoxItemIndicator.vue";
|
||||
export { default as ListBoxSection } from "./components/list-box/ListBoxSection.vue";
|
||||
export type {
|
||||
ListBoxKey,
|
||||
ListBoxDataItem,
|
||||
ListBoxItemState,
|
||||
} from "./components/list-box/context";
|
||||
export type {
|
||||
ListBoxProps,
|
||||
ListBoxRootProps,
|
||||
ListBoxItemProps,
|
||||
ListBoxItemIndicatorProps,
|
||||
ListBoxSectionProps,
|
||||
} from "./types";
|
||||
export {
|
||||
listboxVariants,
|
||||
listboxItemVariants,
|
||||
listboxSectionVariants,
|
||||
type ListBoxVariants,
|
||||
type ListBoxItemVariants,
|
||||
type ListBoxSectionVariants,
|
||||
} from "@heroui-vue/styles";
|
||||
|
||||
@@ -16,6 +16,35 @@ import type AvatarGroupCount from "./components/avatar/AvatarGroupCount.vue";
|
||||
import type Skeleton from "./components/skeleton/Skeleton.vue";
|
||||
|
||||
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 InputProps = InstanceType<typeof Input>["$props"];
|
||||
export type SwitchProps = InstanceType<typeof Switch>["$props"];
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<script setup lang="ts">
|
||||
import { ListboxRoot, ListboxContent, ListboxItem } from "reka-ui";
|
||||
|
||||
// Raw installed-library audit. This deliberately does not consume our adapter.
|
||||
defineOptions({ inheritAttrs: false });
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
modelValue?: string | number | (string | number)[];
|
||||
defaultValue?: string | number | (string | number)[];
|
||||
multiple?: boolean;
|
||||
disabled?: boolean;
|
||||
name?: string;
|
||||
cancelNavigation?: boolean;
|
||||
}>(),
|
||||
{ modelValue: undefined, defaultValue: undefined },
|
||||
);
|
||||
const emit = defineEmits<{ "update:modelValue": [value: unknown] }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ListboxRoot
|
||||
v-bind="$attrs"
|
||||
:model-value="modelValue"
|
||||
:default-value="defaultValue"
|
||||
:multiple="multiple"
|
||||
:disabled="disabled"
|
||||
:name="name"
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
>
|
||||
<ListboxContent
|
||||
aria-label="Audit choices"
|
||||
@keydown="
|
||||
(event: KeyboardEvent) => {
|
||||
if (cancelNavigation) event.preventDefault();
|
||||
}
|
||||
"
|
||||
>
|
||||
<ListboxItem :value="0">Numeric zero</ListboxItem>
|
||||
<ListboxItem value="0">String zero</ListboxItem>
|
||||
<ListboxItem value="disabled" disabled>Disabled</ListboxItem>
|
||||
</ListboxContent>
|
||||
</ListboxRoot>
|
||||
</template>
|
||||
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
SelectRoot,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectContent,
|
||||
SelectViewport,
|
||||
SelectItem,
|
||||
SelectItemText,
|
||||
} from "reka-ui";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
modelValue?: string | number | (string | number)[];
|
||||
defaultValue?: string | number | (string | number)[];
|
||||
multiple?: boolean;
|
||||
disabled?: boolean;
|
||||
name?: string;
|
||||
open?: boolean;
|
||||
includeEmpty?: boolean;
|
||||
}>(),
|
||||
{ modelValue: undefined, defaultValue: undefined, open: undefined },
|
||||
);
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: unknown];
|
||||
"update:open": [value: boolean];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SelectRoot
|
||||
v-bind="$attrs"
|
||||
:model-value="modelValue"
|
||||
:default-value="defaultValue"
|
||||
:multiple="multiple"
|
||||
:disabled="disabled"
|
||||
:name="name"
|
||||
:open="open"
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<SelectTrigger aria-label="Audit select">
|
||||
<SelectValue placeholder="Choose" />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper">
|
||||
<SelectViewport>
|
||||
<SelectItem v-if="includeEmpty" value="">
|
||||
<SelectItemText>Empty key</SelectItemText>
|
||||
</SelectItem>
|
||||
<SelectItem :value="0">
|
||||
<SelectItemText>Numeric zero</SelectItemText>
|
||||
</SelectItem>
|
||||
<SelectItem value="0">
|
||||
<SelectItemText>String zero</SelectItemText>
|
||||
</SelectItem>
|
||||
<SelectItem value="disabled" disabled>
|
||||
<SelectItemText>Disabled</SelectItemText>
|
||||
</SelectItem>
|
||||
</SelectViewport>
|
||||
</SelectContent>
|
||||
</SelectRoot>
|
||||
</template>
|
||||
@@ -0,0 +1,71 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createSSRApp, defineComponent, h } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import Foundation from "../packages/vue/tests/fixtures/CollectionFoundation.vue";
|
||||
import SelectFoundation from "../packages/vue/tests/fixtures/SelectFoundation.vue";
|
||||
import { useCollectionRegistry } from "../packages/vue/src/components/collection/registry";
|
||||
import { useCollectionSelection } from "../packages/vue/src/components/collection/selection";
|
||||
|
||||
describe("collection foundation in real node SSR", () => {
|
||||
it("renders typed selection without browser globals", async () => {
|
||||
expect(typeof window).toBe("undefined");
|
||||
const html = await renderToString(
|
||||
createSSRApp(Foundation, { multiple: true, modelValue: [0] }),
|
||||
);
|
||||
expect(html).toContain('role="listbox"');
|
||||
expect(html.match(/aria-selected="true"/g)).toHaveLength(1);
|
||||
expect(html.match(/role="option"/g)).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("keeps instance registries isolated with no DOM access", async () => {
|
||||
const Component = defineComponent({
|
||||
setup() {
|
||||
const registry = useCollectionRegistry();
|
||||
registry.register({
|
||||
key: () => 0,
|
||||
element: () => undefined,
|
||||
textValue: () => "Zero",
|
||||
disabled: () => false,
|
||||
});
|
||||
const state = useCollectionSelection({
|
||||
mode: () => "single",
|
||||
controlled: () => false,
|
||||
value: () => undefined,
|
||||
defaultValue: [0],
|
||||
onChange: () => {},
|
||||
});
|
||||
return () =>
|
||||
h("output", `${registry.ordered().length}:${state.keys.value[0]}`);
|
||||
},
|
||||
});
|
||||
const html = await renderToString(
|
||||
createSSRApp({ render: () => h("main", [h(Component), h(Component)]) }),
|
||||
);
|
||||
expect(html).toBe("<main><output>1:0</output><output>1:0</output></main>");
|
||||
});
|
||||
|
||||
it("records that raw closed Select cannot SSR its selected item label", async () => {
|
||||
const html = await renderToString(
|
||||
createSSRApp(SelectFoundation, { defaultValue: 0, name: "choice" }),
|
||||
);
|
||||
expect(html).toContain('role="combobox"');
|
||||
expect(html).not.toContain("Numeric zero");
|
||||
// ItemText registers options on mount; SSR cannot discover closed descendants.
|
||||
expect(html).not.toContain('<option value="0"');
|
||||
});
|
||||
|
||||
it("records the raw Select empty-string key restriction", async () => {
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
await expect(
|
||||
renderToString(
|
||||
createSSRApp(SelectFoundation, { includeEmpty: true, open: true }),
|
||||
),
|
||||
).rejects.toThrow("empty string");
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { defineComponent, h } from "vue";
|
||||
import Foundation from "../packages/vue/tests/fixtures/CollectionFoundation.vue";
|
||||
import SelectFoundation from "../packages/vue/tests/fixtures/SelectFoundation.vue";
|
||||
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
const originalScroll = Object.getOwnPropertyDescriptor(
|
||||
HTMLElement.prototype,
|
||||
"scrollIntoView",
|
||||
);
|
||||
beforeEach(() => {
|
||||
// Only focus/selection, no geometry claims.
|
||||
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
|
||||
configurable: true,
|
||||
value: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((wrapper) => wrapper.unmount());
|
||||
document.body.innerHTML = "";
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
if (originalScroll)
|
||||
Object.defineProperty(
|
||||
HTMLElement.prototype,
|
||||
"scrollIntoView",
|
||||
originalScroll,
|
||||
);
|
||||
else Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView");
|
||||
});
|
||||
|
||||
describe("installed Reka Select audit — not public component acceptance", () => {
|
||||
function form(props: Record<string, unknown>) {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
render: () => h("form", {}, [h(SelectFoundation, props)]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
it("records empty multiple FormData despite two selected trigger labels", async () => {
|
||||
const wrapper = form({
|
||||
multiple: true,
|
||||
defaultValue: [0, "0"],
|
||||
name: "choice",
|
||||
});
|
||||
await flushPromises();
|
||||
expect([...new FormData(wrapper.get("form").element)]).toEqual([]);
|
||||
const options = wrapper.get("select").findAll("option");
|
||||
expect(options).toHaveLength(3);
|
||||
expect(
|
||||
options.slice(0, 2).map((option) => option.attributes("value")),
|
||||
).toEqual(["0", "0"]);
|
||||
expect(wrapper.get("select").element.selectedOptions).toHaveLength(0);
|
||||
expect(wrapper.get('[role="combobox"]').text()).toBe(
|
||||
"Numeric zero, String zero",
|
||||
);
|
||||
expect(wrapper.get('[role="combobox"]').attributes("aria-expanded")).toBe(
|
||||
"false",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits disabled whole-field values from the native submission layer", async () => {
|
||||
const wrapper = form({ defaultValue: 0, disabled: true, name: "choice" });
|
||||
await flushPromises();
|
||||
expect([...new FormData(wrapper.get("form").element)]).toEqual([]);
|
||||
expect(
|
||||
wrapper.get('[role="combobox"]').attributes("disabled"),
|
||||
).toBeDefined();
|
||||
});
|
||||
|
||||
it("keeps selected content in the closed trigger after mounting", async () => {
|
||||
const wrapper = form({ defaultValue: 0, name: "choice" });
|
||||
await flushPromises();
|
||||
expect(wrapper.get('[role="combobox"]').text()).toBe("Numeric zero");
|
||||
expect(new FormData(wrapper.get("form").element).get("choice")).toBe("0");
|
||||
});
|
||||
});
|
||||
function fixture(props: Record<string, unknown> = {}) {
|
||||
const wrapper = mount(Foundation, { props, attachTo: document.body });
|
||||
wrappers.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
describe("installed Reka Listbox audit — not public component acceptance", () => {
|
||||
it("records that a cancelled Content keydown still performs navigation", async () => {
|
||||
const wrapper = fixture({ cancelNavigation: true });
|
||||
await flushPromises();
|
||||
await wrapper.get('[role="listbox"]').trigger("keydown", { key: "End" });
|
||||
expect(document.activeElement).toBe(
|
||||
wrapper.findAll('[role="option"]')[1].element,
|
||||
);
|
||||
});
|
||||
it("distinguishes numeric and string zero and toggles multiple values", async () => {
|
||||
const wrapper = fixture({ multiple: true, defaultValue: [0] });
|
||||
await flushPromises();
|
||||
await wrapper.findAll('[role="option"]')[1].trigger("click");
|
||||
expect(
|
||||
wrapper
|
||||
.findAll('[role="option"]')
|
||||
.map((item) => item.attributes("aria-selected")),
|
||||
).toEqual(["true", "true", "false"]);
|
||||
expect(wrapper.emitted("update:modelValue")).toEqual([[[0, "0"]]]);
|
||||
});
|
||||
|
||||
it("keeps controlled rejection visible and emits repeated proposals", async () => {
|
||||
const wrapper = fixture({ multiple: true, modelValue: [0] });
|
||||
await flushPromises();
|
||||
const item = wrapper.findAll('[role="option"]')[1];
|
||||
await item.trigger("click");
|
||||
await item.trigger("click");
|
||||
expect(item.attributes("aria-selected")).toBe("false");
|
||||
expect(wrapper.emitted("update:modelValue")).toEqual([
|
||||
[[0, "0"]],
|
||||
[[0, "0"]],
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips disabled items for navigation and select-all", async () => {
|
||||
const wrapper = fixture({ multiple: true });
|
||||
await flushPromises();
|
||||
const listbox = wrapper.get('[role="listbox"]');
|
||||
await listbox.trigger("keydown", { key: "End" });
|
||||
expect(document.activeElement).toBe(
|
||||
wrapper.findAll('[role="option"]')[1].element,
|
||||
);
|
||||
await listbox.trigger("keydown", { key: "a", ctrlKey: true });
|
||||
expect(wrapper.emitted("update:modelValue")).toEqual([[[0, "0"]]]);
|
||||
expect(
|
||||
wrapper.findAll('[role="option"]')[2].attributes("aria-selected"),
|
||||
).toBe("false");
|
||||
});
|
||||
|
||||
it("serializes indexed names and does not restore selection on native reset", async () => {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h("form", {}, [
|
||||
h(Foundation, {
|
||||
multiple: true,
|
||||
defaultValue: [0],
|
||||
name: "choices",
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await flushPromises();
|
||||
await wrapper.findAll('[role="option"]')[1].trigger("click");
|
||||
const form = wrapper.get("form").element;
|
||||
expect([...new FormData(form)]).toEqual([
|
||||
["choices[0]", "0"],
|
||||
["choices[1]", "0"],
|
||||
]);
|
||||
form.reset();
|
||||
await flushPromises();
|
||||
expect(
|
||||
wrapper.findAll('[role="option"]')[1].attributes("aria-selected"),
|
||||
).toBe("true");
|
||||
expect([...new FormData(form)]).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("allows cancelling item select before a value change", async () => {
|
||||
// Raw item event is tested in the fixture through the actual DOM CustomEvent.
|
||||
const wrapper = fixture({ multiple: true });
|
||||
await flushPromises();
|
||||
const option = wrapper.findAll('[role="option"]')[0];
|
||||
option.element.addEventListener("listbox.select", (event) =>
|
||||
event.preventDefault(),
|
||||
);
|
||||
await option.trigger("click");
|
||||
expect(option.attributes("aria-selected")).toBe("false");
|
||||
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { effectScope, reactive, ref } from "vue";
|
||||
import {
|
||||
copyKeys,
|
||||
decodeKey,
|
||||
encodeKey,
|
||||
type CollectionKey,
|
||||
} from "../packages/vue/src/components/collection/keys";
|
||||
import { useCollectionSelection } from "../packages/vue/src/components/collection/selection";
|
||||
import { useCollectionRegistry } from "../packages/vue/src/components/collection/registry";
|
||||
|
||||
function selection(overrides = {}) {
|
||||
const props = reactive({
|
||||
mode: "multiple" as "none" | "single" | "multiple",
|
||||
controlled: false,
|
||||
value: undefined as CollectionKey[] | undefined,
|
||||
disabled: false,
|
||||
readOnly: false,
|
||||
disabledKeys: [] as CollectionKey[],
|
||||
disallowEmptySelection: false,
|
||||
...overrides,
|
||||
});
|
||||
const onChange = vi.fn();
|
||||
const state = useCollectionSelection({
|
||||
mode: () => props.mode,
|
||||
controlled: () => props.controlled,
|
||||
value: () => props.value,
|
||||
disabled: () => props.disabled,
|
||||
readOnly: () => props.readOnly,
|
||||
disabledKeys: () => props.disabledKeys,
|
||||
disallowEmptySelection: () => props.disallowEmptySelection,
|
||||
defaultValue: ["initial"],
|
||||
onChange,
|
||||
});
|
||||
return { state, props, onChange };
|
||||
}
|
||||
|
||||
describe("private collection identity and accepted selection", () => {
|
||||
it("round trips typed keys including empty, zero and adapter-like strings", () => {
|
||||
const keys = ["", 0, "0", 1, "1", '["number",1]', "__proto__", "中文"];
|
||||
expect(new Set(keys.map(encodeKey)).size).toBe(keys.length);
|
||||
expect(keys.map(encodeKey).map(decodeKey)).toEqual(keys);
|
||||
expect(copyKeys([0, "0", 0, "0"])).toEqual([0, "0"]);
|
||||
});
|
||||
|
||||
it("rejects unsupported identities and malformed adapter values", () => {
|
||||
for (const key of [NaN, Infinity, null, undefined, {}, []]) {
|
||||
expect(() => encodeKey(key as CollectionKey)).toThrow(TypeError);
|
||||
}
|
||||
for (const encoded of ['["number","1"]', "{}", "null", '["object",{}]']) {
|
||||
expect(() => decodeKey(encoded)).toThrow(TypeError);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps caller arrays and emitted snapshots independent", () => {
|
||||
const initial: CollectionKey[] = [1];
|
||||
const onChange = vi.fn((value: CollectionKey[]) => value.push("injected"));
|
||||
const state = useCollectionSelection({
|
||||
mode: () => "multiple",
|
||||
controlled: () => false,
|
||||
value: () => undefined,
|
||||
defaultValue: initial,
|
||||
onChange,
|
||||
});
|
||||
initial.push(2);
|
||||
state.toggle("1");
|
||||
expect(state.keys.value).toEqual([1, "1"]);
|
||||
state.reset();
|
||||
expect(state.keys.value).toEqual([1]);
|
||||
});
|
||||
|
||||
it("retries equal rejected proposals from the last accepted value", () => {
|
||||
const { state, props, onChange } = selection({
|
||||
controlled: true,
|
||||
value: [1],
|
||||
});
|
||||
state.toggle("1");
|
||||
state.toggle("1");
|
||||
expect(onChange.mock.calls).toEqual([[[1, "1"]], [[1, "1"]]]);
|
||||
expect(state.keys.value).toEqual([1]);
|
||||
props.value = [1, "1"];
|
||||
state.toggle("1");
|
||||
expect(onChange).toHaveBeenLastCalledWith([1]);
|
||||
expect(state.keys.value).toEqual([1, "1"]);
|
||||
});
|
||||
|
||||
it("treats an explicitly controlled undefined as empty", () => {
|
||||
const { state, onChange } = selection({ controlled: true });
|
||||
expect(state.keys.value).toEqual([]);
|
||||
state.toggle(0);
|
||||
state.reset();
|
||||
expect(state.keys.value).toEqual([]);
|
||||
expect(onChange).toHaveBeenCalledExactlyOnceWith([0]);
|
||||
});
|
||||
|
||||
it("exposes immutable accepted snapshots and treats reordering as the same selection", () => {
|
||||
const { state, onChange } = selection({
|
||||
controlled: true,
|
||||
value: [0, "0"],
|
||||
});
|
||||
expect(Object.isFrozen(state.keys.value)).toBe(true);
|
||||
expect(state.request(["0", 0])).toBe(false);
|
||||
expect(state.keys.value).toEqual([0, "0"]);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("supports single replace, toggle and disallow-empty without duplicate changes", () => {
|
||||
const { state, props, onChange } = selection({ mode: "single" });
|
||||
expect(state.replace(0)).toBe(true);
|
||||
expect(state.replace(0)).toBe(false);
|
||||
props.disallowEmptySelection = true;
|
||||
expect(state.toggle(0)).toBe(false);
|
||||
expect(state.request([])).toBe(false);
|
||||
props.disallowEmptySelection = false;
|
||||
expect(state.toggle(0)).toBe(true);
|
||||
expect(state.keys.value).toEqual([]);
|
||||
expect(onChange.mock.calls).toEqual([[[0]], [[]]]);
|
||||
expect(() => state.request([1, 2])).toThrow(TypeError);
|
||||
});
|
||||
|
||||
it.each(["none", "disabled", "readOnly"])(
|
||||
"blocks selection for %s",
|
||||
(kind) => {
|
||||
const { state, onChange } = selection(
|
||||
kind === "none" ? { mode: "none" } : { [kind]: true },
|
||||
);
|
||||
expect(state.toggle("x")).toBe(false);
|
||||
expect(state.replace("x")).toBe(false);
|
||||
expect(state.selectAll(["x"])).toBe(false);
|
||||
expect(state.request([])).toBe(false);
|
||||
expect(state.keys.value).toEqual(["initial"]);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves disabled selections and excludes disabled additions in bulk paths", () => {
|
||||
const { state, props, onChange } = selection({
|
||||
disabledKeys: ["initial", 0],
|
||||
});
|
||||
expect(state.toggle("initial")).toBe(false);
|
||||
expect(state.request(["initial", 0])).toBe(false);
|
||||
state.selectAll([0, "0", "other"]);
|
||||
expect(state.keys.value).toEqual(["initial", "0", "other"]);
|
||||
props.disabledKeys = [];
|
||||
state.toggle("initial");
|
||||
expect(state.keys.value).toEqual(["0", "other"]);
|
||||
expect(onChange).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("can replace a disabled initial selection with an available single option", () => {
|
||||
const { state, onChange } = selection({
|
||||
mode: "single",
|
||||
disabledKeys: ["initial"],
|
||||
});
|
||||
expect(state.toggle("initial")).toBe(false);
|
||||
expect(state.replace(0)).toBe(true);
|
||||
expect(state.keys.value).toEqual([0]);
|
||||
expect(onChange).toHaveBeenCalledExactlyOnceWith([0]);
|
||||
});
|
||||
|
||||
it("leaves accepted missing keys intact until caller explicitly edits them", () => {
|
||||
const { state, props, onChange } = selection({
|
||||
controlled: true,
|
||||
value: ["missing"],
|
||||
});
|
||||
expect(state.keys.value).toEqual(["missing"]);
|
||||
props.value = ["replacement"];
|
||||
expect(state.keys.value).toEqual(["replacement"]);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reset restores the initial snapshot silently, including while disabled", () => {
|
||||
const { state, props, onChange } = selection();
|
||||
state.toggle("added");
|
||||
props.disabled = true;
|
||||
state.reset();
|
||||
expect(state.keys.value).toEqual(["initial"]);
|
||||
expect(onChange).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("collection membership, DOM order and navigation targets", () => {
|
||||
function member(key: CollectionKey, disabled = false) {
|
||||
const data = reactive({ key, disabled, text: `Item ${key}` });
|
||||
const element = document.createElement("div");
|
||||
return {
|
||||
data,
|
||||
node: element,
|
||||
member: {
|
||||
key: () => data.key,
|
||||
element: () => element,
|
||||
textValue: () => data.text,
|
||||
disabled: () => data.disabled,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("tracks live DOM reordering, disabled updates and native member removal", () => {
|
||||
const registry = useCollectionRegistry();
|
||||
const a = member("a"),
|
||||
b = member("b"),
|
||||
c = member("c", true);
|
||||
const parent = document.createElement("div");
|
||||
parent.append(a.node, b.node, c.node);
|
||||
registry.register(c.member);
|
||||
registry.register(a.member);
|
||||
const removeB = registry.register(b.member);
|
||||
expect(registry.ordered().map((item) => item.key())).toEqual([
|
||||
"a",
|
||||
"b",
|
||||
"c",
|
||||
]);
|
||||
parent.prepend(c.node);
|
||||
expect(registry.available().map((item) => item.key())).toEqual(["a", "b"]);
|
||||
c.data.disabled = false;
|
||||
expect(registry.adjacent("b", "next", true)?.key()).toBe("c");
|
||||
expect(registry.adjacent("b", "next")).toBeUndefined();
|
||||
expect(registry.adjacent(undefined, "previous")?.key()).toBe("b");
|
||||
expect(registry.adjacent("a", "previous")?.key()).toBe("c");
|
||||
removeB();
|
||||
removeB();
|
||||
expect(registry.ordered().map((item) => item.key())).toEqual(["c", "a"]);
|
||||
});
|
||||
|
||||
it("distinguishes typed keys and rejects initial and dynamic duplicates", () => {
|
||||
const registry = useCollectionRegistry();
|
||||
const a = member(1),
|
||||
b = member("1");
|
||||
registry.register(a.member);
|
||||
registry.register(b.member);
|
||||
expect(() => registry.register(member(1).member)).toThrow("Duplicate");
|
||||
b.data.key = 1;
|
||||
expect(() => registry.ordered()).toThrow("Duplicate");
|
||||
b.data.key = "fixed";
|
||||
expect(registry.ordered()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses available DOM order for ranges and handles stale anchors", () => {
|
||||
const registry = useCollectionRegistry();
|
||||
const items = [member(0), member(1, true), member("1"), member(2)];
|
||||
const parent = document.createElement("div");
|
||||
items.forEach((item) => {
|
||||
parent.append(item.node);
|
||||
registry.register(item.member);
|
||||
});
|
||||
expect(registry.range(2, 0)).toEqual([0, "1", 2]);
|
||||
expect(registry.range(1, 2)).toEqual([]);
|
||||
expect(registry.range("missing", 2)).toEqual([]);
|
||||
expect(registry.adjacent(0, "first")?.key()).toBe(0);
|
||||
expect(registry.adjacent(0, "last")?.key()).toBe(2);
|
||||
expect(registry.adjacent(0, "previous", true)?.key()).toBe(2);
|
||||
});
|
||||
|
||||
it("isolates instances and disposes scope-owned registrations", () => {
|
||||
const outer = useCollectionRegistry(),
|
||||
inner = useCollectionRegistry();
|
||||
const scope = effectScope();
|
||||
scope.run(() => outer.register(member("same").member));
|
||||
inner.register(member("same").member);
|
||||
expect(outer.ordered()).toHaveLength(1);
|
||||
scope.stop();
|
||||
expect(outer.ordered()).toEqual([]);
|
||||
expect(inner.ordered()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("works without elements and retains registration order", () => {
|
||||
const registry = useCollectionRegistry();
|
||||
const element = ref<HTMLElement>();
|
||||
registry.register({
|
||||
key: () => 0,
|
||||
element: () => element.value,
|
||||
textValue: () => "Zero",
|
||||
disabled: () => false,
|
||||
});
|
||||
expect(registry.adjacent(undefined, "next")?.key()).toBe(0);
|
||||
expect(registry.range(0, 0)).toEqual([0]);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -15,3 +15,5 @@ pnpm exec tsc --noEmit --strict --skipLibCheck --module esnext --moduleResolutio
|
||||
SLIDER-01 已在 `/private/tmp/heroui-slider-consumer` 完成上述检查,临时契约文件名为 `contract.ts`。默认工作区 typecheck 仍使用源码 alias,所以不能代替此独立产物检查。
|
||||
|
||||
M30–M32 增加 consume-m30-m32.mjs 和 m30-m32-contract.ts。将它们复制到同一个独立消费工程,执行运行脚本,并将契约文件加入上述两种 tsc 命令。合并后的产物还应同时通过原 NumberField/Slider 消费检查,避免只验证新加组件。
|
||||
|
||||
LISTBOX-01 增加 `consume-list-box.mjs` / `list-box-contract.ts`。同样复制到独立消费者,用两份新 tarball 安装后运行脚本,并在 NodeNext / bundler 两种模式执行契约文件。Root 的泛型 Props 曾在 Parameters 提取后退化,非法模型/模式反例与事件参数推断必须保留。
|
||||
|
||||
@@ -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.",
|
||||
);
|
||||
@@ -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,
|
||||
];
|
||||
Reference in New Issue
Block a user