Compare commits
3 Commits
0cfe7b6195
...
3c878d2582
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c878d2582 | |||
| 50f561a758 | |||
| 2b569451b6 |
@@ -431,3 +431,18 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V
|
||||
- 必须阅读[M33–M34迁移经验](docs/migrations/M33-M34-lessons.md):真实动画所有者、Presence与transition差异、完成/取消手势、捕获与旧节点清理、退出中重开、reduced-motion级联、同页演示、完整文档与独立产物类型。
|
||||
- M33/M34最终范围见[验收记录](docs/migrations/M33-M34-acceptance.md),不能用历史返修报告或绿色测试数量推断全视觉/读屏已验收。
|
||||
- 其他AI下一批为[M35 Toast → M36 Table](docs/migrations/M35-M36-toast-table-prompt.md),先同步最新main再开feat/m35-m36-toast-table。集成人继续ListBox/Select、日期与颜色基建;不要改写共享collection/field/overlay内核。
|
||||
|
||||
## SELECT-01 迁移经验(2026-10-23)
|
||||
|
||||
- Select 六部件与十九例已实现,自动化验证和浏览器待验范围见 [SELECT-01](docs/migrations/SELECT-01-select.md)。不能把此前“Select 未实现”的历史描述当作当前状态,也不能把代码已落地等同完整验收。
|
||||
- 复用 Popover 时核对真正节点的 role、data-slot、aria-haspopup 与 controls:通用 dialog 默认值会覆盖字段 listbox 语义。显式部件透传放到实际 asChild 原生节点,通用默认行为保留回归。
|
||||
- 非模态不代表 Tab 不循环;Reka Popover FocusScope 默认 loop。字段复合组件要明确原生 Tab 起点与 Portal 顺序,复用现有栈,不能新增全局导航监听队列。
|
||||
- 表单可见值、原生提交、自动填充和 reset 同时验;受控值未变化时 Vue 不一定重写被浏览器 reset 的 option。原生层显式恢复接受值,数字/字符串 key 通过 option 索引恢复,内部编码不得进入提交。
|
||||
- SSR 的关闭态元数据必须先于 Value/原生选项渲染;未知包装要求显式完整 items。动态移除不得保留成功提交,布尔属性的空字符串按 true 处理,不执行用户任意 setup/render 来取文字。
|
||||
- 清空控件使用非 button、计数注册、实际 Trigger 禁用及原生取消协议;十九例同页检查 ID,异步例不能以静态假数据替代,分页失败重试和卸载 AbortSignal 都要测。
|
||||
- 本轮浏览器工具 URL 安全策略阻断,不绕过、不写成已验证;代码/SSR/水合/独立产物与真实几何/动效的结论分开,补验前留在任务分支。
|
||||
|
||||
## SELECT-01 浏览器补验接续(2026-10-23)
|
||||
|
||||
- 正常 HTTP 页面恢复访问后,Select 已完成重点浏览器补验,可以按本轮验证结果集成 main;上一节“留在任务分支”的要求是此前阻断阶段,不再适用。
|
||||
- 不能只断言焦点正确:Floating 首次定位前 scrollIntoView 可能无效。定位后的动画开始及无动画路径重新检查当前焦点可见性;尊重取消、不抢焦点、忽略子动画、清理帧回调。长列表同时核对 activeElement、滚动区边界和 scrollTop。
|
||||
|
||||
@@ -103,6 +103,7 @@ const groups = [
|
||||
{ title: "NumberField 数字输入框", url: "/components/number-field" },
|
||||
{ title: "Slider 滑块", url: "/components/slider" },
|
||||
{ title: "ListBox 列表框", url: "/components/list-box" },
|
||||
{ title: "Select 选择器", url: "/components/select" },
|
||||
{ title: "Tooltip 工具提示", url: "/components/tooltip" },
|
||||
{
|
||||
title: "ToggleButton 切换按钮",
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
---
|
||||
title: Select 选择器
|
||||
description: Select 展示可折叠的选项列表,并允许用户从中选择一项。
|
||||
component: select
|
||||
group: 组件
|
||||
---
|
||||
|
||||
## 用法
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
```
|
||||
|
||||
<ComponentPreview name="select-default" />
|
||||
|
||||
## 组件结构
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectClearButton,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
Label,
|
||||
Description,
|
||||
Header,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
ListBoxSection,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<Select>
|
||||
<Label>选项</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectClearButton />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<Description>请选择一项</Description>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<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>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
```
|
||||
|
||||
## 示例
|
||||
|
||||
### 变体
|
||||
|
||||
Select 组件支持两种视觉变体:
|
||||
|
||||
- **`primary`**(默认)— 带阴影的标准样式,适用于大多数场景
|
||||
- **`secondary`** — 低强调、无阴影,适合在 Surface 等表面背景上使用
|
||||
|
||||
<ComponentPreview name="select-variants" />
|
||||
|
||||
### 宽度充满
|
||||
|
||||
<ComponentPreview name="select-full-width" />
|
||||
|
||||
### 带描述
|
||||
|
||||
<ComponentPreview name="select-with-description" />
|
||||
|
||||
### 必填
|
||||
|
||||
<ComponentPreview name="select-required" />
|
||||
|
||||
### 禁用
|
||||
|
||||
<ComponentPreview name="select-disabled" />
|
||||
|
||||
### 含禁用选项
|
||||
|
||||
<ComponentPreview name="select-with-disabled-options" />
|
||||
|
||||
### 多选
|
||||
|
||||
<ComponentPreview name="select-multiple-select" />
|
||||
|
||||
### 分组选项
|
||||
|
||||
<ComponentPreview name="select-with-sections" />
|
||||
|
||||
### 受控组件
|
||||
|
||||
<ComponentPreview name="select-controlled" />
|
||||
|
||||
### 受控多选
|
||||
|
||||
<ComponentPreview name="select-controlled-multiple" />
|
||||
|
||||
### 受控展开状态
|
||||
|
||||
<ComponentPreview name="select-controlled-open-state" />
|
||||
|
||||
### 异步加载
|
||||
|
||||
Vue 使用响应式数组、Fetch 与 VueUse 可见性观察加载 PokeAPI 分页;保留取消、加载中、错误重试和手动加载入口,不导出 React Collection / ListBoxLoadMoreItem。
|
||||
|
||||
<ComponentPreview name="select-asynchronous-loading" />
|
||||
|
||||
### 自定义指示器
|
||||
|
||||
<ComponentPreview name="select-custom-indicator" />
|
||||
|
||||
### 带清除按钮
|
||||
|
||||
`SelectTrigger` 本身是 button,因此不能再嵌套 `<button>` 来实现清除。请在触发器内组合 `SelectClearButton` — 它渲染为非 button 控件,且不会打开菜单。
|
||||
|
||||
<ComponentPreview name="select-with-clear-button" />
|
||||
|
||||
由于 ARIA 将 button 的子节点视为纯展示内容,清除控件无法获得焦点,因此它带有 `aria-hidden`,仅作为指针操作的可视入口。当组合了 `SelectClearButton` 时,触发器同时支持按 `Backspace` 或 `Delete` 清除,这是键盘与屏幕阅读器用户的清除方式。两种方式都会调用 `clear`。
|
||||
|
||||
### 自定义展示值
|
||||
|
||||
<ComponentPreview name="select-custom-value" />
|
||||
|
||||
### 渲染函数
|
||||
|
||||
通过 `as`、原生 attrs 和作用域插槽表达 Vue 渲染能力。
|
||||
|
||||
<ComponentPreview
|
||||
name="select-render-function"
|
||||
/>
|
||||
|
||||
### 表面样式
|
||||
|
||||
在 [Surface](/components/surface) 内使用时,请使用 `variant="secondary"`,以应用适合表面背景的低强调变体。
|
||||
|
||||
<ComponentPreview name="select-on-surface" />
|
||||
|
||||
## 自定义样式
|
||||
|
||||
### Tailwind CSS
|
||||
|
||||
<ComponentPreview name="select-custom-styles" />
|
||||
|
||||
### 全局 CSS
|
||||
|
||||
若要自定义组件类,可使用 `@layer components` 指令。[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
|
||||
|
||||
```css
|
||||
@layer components {
|
||||
.hv-select {
|
||||
@apply flex flex-col gap-1;
|
||||
}
|
||||
|
||||
.hv-select__trigger {
|
||||
@apply rounded-lg border border-border bg-surface p-2;
|
||||
}
|
||||
|
||||
.hv-select__value {
|
||||
@apply text-current;
|
||||
}
|
||||
|
||||
.hv-select__indicator {
|
||||
@apply text-muted;
|
||||
}
|
||||
|
||||
.hv-select__popover {
|
||||
@apply rounded-lg border border-border bg-surface p-2;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 样式参考
|
||||
|
||||
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
|
||||
|
||||
### CSS 类
|
||||
|
||||
Select 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/select.css)):
|
||||
|
||||
#### 基础类
|
||||
|
||||
- `.hv-select` - Select 根容器
|
||||
- `.hv-select__trigger` - 打开下拉的触发按钮
|
||||
- `.hv-select__value` - 当前显示的值或占位符
|
||||
- `.hv-select__clear-button` - 触发器内的可选清除控件
|
||||
- `.hv-select__indicator` - 下拉指示图标
|
||||
- `.hv-select__popover` - 弹出层容器
|
||||
|
||||
#### 变体类
|
||||
|
||||
- `.hv-select--primary` - Primary 变体,带阴影(默认)
|
||||
- `.hv-select--secondary` - Secondary 变体,无阴影,适合在 Surface 上使用
|
||||
|
||||
#### 状态类
|
||||
|
||||
- `.hv-select[data-invalid="true"]` - 无效状态
|
||||
- `.hv-select__trigger[data-focus-visible="true"]` - 触发器聚焦状态
|
||||
- `.hv-select__trigger[data-disabled="true"]` - 触发器禁用状态
|
||||
- `.hv-select__value[data-placeholder="true"]` - 占位符状态
|
||||
- `.hv-select__clear-button[data-empty="true"]` - 无选中项时隐藏清除控件
|
||||
- `.hv-select__indicator[data-open="true"]` - 展开时的指示器状态
|
||||
|
||||
### 交互状态
|
||||
|
||||
该组件同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制:
|
||||
|
||||
- **悬停**:触发器上的 `:hover` 或 `[data-hovered="true"]`
|
||||
- **聚焦**:触发器上的 `:focus-visible` 或 `[data-focus-visible="true"]`
|
||||
- **禁用**:Select 上的 `:disabled` 或 `[data-disabled="true"]`
|
||||
- **展开**:指示器上的 `[data-open="true"]`
|
||||
|
||||
## API 参考
|
||||
|
||||
### Select
|
||||
|
||||
`SelectRoot` 是 `Select` 的别名。Key 为字符串或有限数值,数字 `0` 和字符串 `"0"` 不相同,空字符串有效。单选清空为 `null`,多选为 `[]`。显式 `modelValue` 优先于 `value`,显式 `open` 优先于 `isOpen`,包括显式传入 `undefined`。
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| ------------------------------ | --------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `placeholder` | `string` | `"Select an item"` | 空选择的占位符。 |
|
||||
| `selectionMode` | `"single" \| "multiple"` | `"single"` | 单选或多选。ListBox 的选择模式由 Select 统一管理。 |
|
||||
| `modelValue` / `value` | `Key \| Key[] \| null` | — | 受控值,推荐 `v-model`。多选必须是数组。 |
|
||||
| `defaultValue` | `Key \| Key[] \| null` | `null` / `[]` | 非受控初值,也是 reset 的目标值。 |
|
||||
| `open` / `isOpen` | `boolean` | — | 受控展开状态,推荐 `v-model:open`。 |
|
||||
| `defaultOpen` | `boolean` | `false` | 非受控展开初值。 |
|
||||
| `disabledKeys` | `readonly Key[]` | — | 禁用选项 key;Vue 使用数组替代 Iterable。 |
|
||||
| `items` | `readonly SelectItem[]` | — | `{ id, textValue, isDisabled? }` 完整元数据。用于不透明包装和异步数据,保证关闭态/SSR 的文字与提交正确;不负责渲染选项。 |
|
||||
| `isDisabled` / `disabled` | `boolean` | `false` | 禁用交互与原生提交;继承 Fieldset 禁用。 |
|
||||
| `isReadOnly` | `boolean` | `false` | 保留提交值,阻止用户改选与展开。 |
|
||||
| `isRequired` | `boolean` | `false` | 必填,校验有效且未禁用的已选项。 |
|
||||
| `isInvalid` | `boolean` | `false` | 外部无效状态。 |
|
||||
| `validationBehavior` | `"native" \| "aria"` | 继承 Form,默认 `"native"` | 原生约束或仅 ARIA 校验。 |
|
||||
| `validate` | `(value: SelectModelValue) => ValidateResult` | — | 本地自定义校验;同时消费 Form 服务端错误。 |
|
||||
| `name` / `form` | `string` | — | 原生表单名称和外部 form ID。多选同名重复提交;空/不存在/禁用选项不提交。 |
|
||||
| `autoComplete` | `string` | — | 传给唯一的原生 select 自动填充层;空选择时用稳定 ID 标识,首次自动填充是否出现由浏览器决定。 |
|
||||
| `fullWidth` | `boolean` | `false` | 占满容器宽度。 |
|
||||
| `variant` | `"primary" \| "secondary"` | `"primary"` | 主要/次要变体。 |
|
||||
| `id` | `string` | 自动生成 | 触发器 DOM ID,关联 Label、选项列表与校验。 |
|
||||
| `as` | `string` | `"div"` | 根 HTML 标签。 |
|
||||
| `class` / `style` / 原生 attrs | 原生属性 | — | 传给根容器。根 `aria-label` 同时用于触发器;触发器可单独覆盖。 |
|
||||
|
||||
### 事件
|
||||
|
||||
| 事件 | 参数 | 描述 |
|
||||
| ------------------------------ | ------------------ | -------------------------------------------------------------------------- |
|
||||
| `update:modelValue` / `change` | `SelectModelValue` | 用户选择提案;父组件未接受时可见状态和 FormData 保持父值,相同提案可重试。 |
|
||||
| `update:open` / `openChange` | `boolean` | 展开状态提案;父更新和 reset 不伪造值变化事件。 |
|
||||
| `clear` | 无 | 指针或关闭态 Backspace/Delete 请求清空;同时触发值事件。 |
|
||||
|
||||
### SelectTrigger
|
||||
|
||||
| Prop / 事件 | 类型 | 默认值 | 描述 |
|
||||
| ------------------------ | --------- | ---------- | ---------------------------------------------------------- |
|
||||
| `as` | `string` | `"button"` | 触发器标签;保留正确键盘激活行为。 |
|
||||
| `isDisabled` | `boolean` | `false` | 单独禁用触发器及其内部清空控件。 |
|
||||
| `class` / `style` / ARIA | 原生属性 | — | 传到真正的交互节点;显式名称优先。 |
|
||||
| 原生键盘/指针事件 | DOM Event | — | 用户处理器先运行,可通过 `preventDefault()` 取消内部行为。 |
|
||||
|
||||
### SelectValue
|
||||
|
||||
| Prop / 插槽 | 类型 | 默认值 | 描述 |
|
||||
| ----------------- | ---------- | -------- | ------------------------ |
|
||||
| `as` | `string` | `"span"` | 展示值标签。 |
|
||||
| `class` / `style` | 原生属性 | — | 值区域样式。 |
|
||||
| `default` | 作用域插槽 | 已选文字 | 自定义展示值,参数如下。 |
|
||||
|
||||
### SelectIndicator
|
||||
|
||||
| Prop / 插槽 | 类型 | 描述 |
|
||||
| ----------------- | ------------- | -------------------------------------------------------------- |
|
||||
| `class` / `style` | 原生属性 | 指示器样式。 |
|
||||
| `default` | 单一 Vue 节点 | 自定义图标;状态与样式合并到该节点。默认使用移植自基线的图标。 |
|
||||
|
||||
### SelectClearButton
|
||||
|
||||
| Prop / 事件 / 插槽 | 类型 | 默认值 | 描述 |
|
||||
| ------------------ | ------------ | ------------ | -------------------------------------- |
|
||||
| `as` | `string` | `"span"` | 保持非 button 标签,避免嵌套交互按钮。 |
|
||||
| `class` / `style` | 原生属性 | — | 清除控件样式。 |
|
||||
| `click` | `MouseEvent` | — | 可取消清除;不会打开弹层。 |
|
||||
| `default` | Vue 插槽 | 基线关闭图标 | 自定义内容。 |
|
||||
|
||||
### SelectPopover
|
||||
|
||||
| Prop / 事件 | 类型 | 默认值 | 描述 |
|
||||
| ----------------------------------- | ----------------------- | ---------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `placement` | `OverlayPlacement` | `"bottom"` | bottom/top/left/right/start/end 及对应 left/right/top/bottom/start/end 对齐组合,沿用 Popover 定位协议。 |
|
||||
| `offset` | `number` | `8` | 与触发器的距离。 |
|
||||
| `shouldFlip` | `boolean` | `true` | 空间不足时翻转。 |
|
||||
| `containerPadding` | `number` | `12` | 视口碰撞边距。 |
|
||||
| `to` | `string \| HTMLElement` | `body` | Teleport 目标;SSR 默认关闭态不会渲染弹层。 |
|
||||
| `class` / `style` / attrs | 原生属性 | — | 弹层节点属性;选择器只承载一个 ListBox。 |
|
||||
| `openAutoFocus` / `closeAutoFocus` | `Event` | — | 可取消默认焦点。默认进入已选/首项,关闭恢复触发器;外部交互保留外部焦点。 |
|
||||
| `escapeKeyDown` / `interactOutside` | DOM / CustomEvent | — | 复用 Popover 的事件与取消协议。 |
|
||||
|
||||
### 作用域插槽状态
|
||||
|
||||
| 插槽 | 参数 | 描述 |
|
||||
| --------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------- |
|
||||
| Select `default` | `{ value, isOpen, selectedItems }` | 当前接受状态;初次 SSR 需要直接使用 selectedItems 时请提供 items 元数据。 |
|
||||
| SelectValue `default` | `{ defaultChildren, isPlaceholder, selectedItems, state }` | 默认文字、占位状态与选中项。 |
|
||||
| `selectedItems` | `{ key: Key; textValue: string }[]` | 已选元数据;自定义头像等通过业务数据查找。 |
|
||||
| `state` | `{ selectedItems, isOpen }` | Vue 响应式状态快照,不暴露 React SelectState。 |
|
||||
|
||||
非受控 `selectionMode` 切换会适配标量/数组外观,切回单选取首项,不发编辑事件;受控切换应由父组件同时提供匹配模式的值。
|
||||
|
||||
通过组件 ref 调用 `focus()`、`open()`、`close()`,`element` 指向触发器。
|
||||
|
||||
## 无障碍与兼容差异
|
||||
|
||||
- 原生按钮承担触发、取消与禁用。触发器使用选择型 `combobox`,关联实际 `listbox`,选项名称与字段标签隔离。
|
||||
- 方向键进入已选项(空选择时 ArrowDown 首项、ArrowUp 末项),列表复用 ListBox 导航、首字母搜索和禁用跳过。单选激活关闭,多选保持展开;Escape 关闭,Tab 离开弹层。
|
||||
- 复用现有 Popover 非模态焦点与定位体系;与上游 RAC 的移动端原生选择菜单、模态隐藏外部内容不同。当前不提供移动端原生菜单切换。
|
||||
- 关闭态从已知 ListBox/Section/Item 插槽预规划元数据;不执行任意包装组件的 setup/render。不透明包装请提供 Select 的 `items`,否则首次打开前未知选项只能显示 key,且无法提交未知选项。
|
||||
- 唯一原生 select 提交层保留字符串边界,多选使用重复 name;类型区分只用于组件值与事件。浏览器自动填充通过选中 option 的索引恢复原始 key,不把内部编码放进 FormData。
|
||||
- 支持原生必填、重置、Fieldset 与 Form 错误关联;跨浏览器自动填充与实际屏幕阅读器播报仍需专项验收,不声明等同 React Aria 全部能力。
|
||||
- 样式及 19 个中文示例来自固定 HeroUI 基线;React 渲染函数改为 Vue 插槽,文档的表单成功反馈使用内联状态,图标扩展示例使用 Tabler。
|
||||
|
||||
## 相关组件
|
||||
|
||||
[ListBox](/components/list-box)、[Popover](/components/popover)、[Fieldset](/components/fieldset)、[Label](/components/label)、[FieldError](/components/field-error)
|
||||
@@ -0,0 +1,91 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useIntersectionObserver } from "@vueuse/core";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
Spinner,
|
||||
Button,
|
||||
} from "@heroui-vue/components";
|
||||
const items = ref<{ id: string; textValue: string }[]>([]);
|
||||
const cursor = ref<string | null>("https://pokeapi.co/api/v2/pokemon");
|
||||
const loading = ref(false),
|
||||
error = ref(false),
|
||||
sentinel = ref<HTMLElement>();
|
||||
let controller: AbortController | undefined;
|
||||
async function loadMore() {
|
||||
if (loading.value || !cursor.value) return;
|
||||
controller = new AbortController();
|
||||
loading.value = true;
|
||||
error.value = false;
|
||||
try {
|
||||
const response = await fetch(cursor.value, { signal: controller.signal });
|
||||
if (!response.ok) throw new Error("Unable to load Pokémon");
|
||||
const page = (await response.json()) as {
|
||||
next: string | null;
|
||||
results: { name: string }[];
|
||||
};
|
||||
const seen = new Set(items.value.map((item) => item.id));
|
||||
items.value.push(
|
||||
...page.results
|
||||
.filter((item) => !seen.has(item.name))
|
||||
.map((item) => ({ id: item.name, textValue: item.name })),
|
||||
);
|
||||
cursor.value = page.next;
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) error.value = true;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
useIntersectionObserver(sentinel, ([entry]) => {
|
||||
if (entry?.isIntersecting && !error.value) void loadMore();
|
||||
});
|
||||
onMounted(loadMore);
|
||||
onBeforeUnmount(() => controller?.abort());
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" placeholder="请选择宝可梦" :items="items">
|
||||
<Label>选择宝可梦</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover class="max-h-80">
|
||||
<ListBox :items="items" :aria-busy="loading || undefined">
|
||||
<template #default="{ item }">
|
||||
<ListBoxItem :id="item.id" :text-value="item.textValue">
|
||||
{{ item.textValue }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</template>
|
||||
<template #empty>
|
||||
<p class="px-4 py-2 text-sm text-muted">
|
||||
{{ error ? "加载失败,请重试" : "正在加载…" }}
|
||||
</p>
|
||||
</template>
|
||||
</ListBox>
|
||||
<div
|
||||
v-if="cursor"
|
||||
ref="sentinel"
|
||||
class="flex items-center justify-center gap-2 py-2"
|
||||
role="status"
|
||||
>
|
||||
<template v-if="loading">
|
||||
<Spinner size="sm" />
|
||||
<span class="text-sm text-muted">加载更多…</span>
|
||||
</template>
|
||||
<Button v-else variant="ghost" size="sm" @click="loadMore">
|
||||
{{ error ? "重试" : "加载更多…" }}
|
||||
</Button>
|
||||
</div>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
import { ref, computed } from "vue";
|
||||
import type { SelectModelValue } from "@heroui-vue/components";
|
||||
const states = [
|
||||
{ id: "california", name: "加利福尼亚" },
|
||||
{ id: "texas", name: "德克萨斯" },
|
||||
{ id: "florida", name: "佛罗里达" },
|
||||
{ id: "new-york", name: "纽约" },
|
||||
{ id: "illinois", name: "伊利诺伊" },
|
||||
{ id: "pennsylvania", name: "宾夕法尼亚" },
|
||||
];
|
||||
const state = ref<SelectModelValue>(["california", "texas"]);
|
||||
const selected = computed(
|
||||
() =>
|
||||
states
|
||||
.filter((s) =>
|
||||
Array.isArray(state.value)
|
||||
? state.value.includes(s.id)
|
||||
: state.value === s.id,
|
||||
)
|
||||
.map((s) => s.name)
|
||||
.join(", ") || "无",
|
||||
);
|
||||
</script>
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<Select
|
||||
class="w-[256px]"
|
||||
placeholder="请选择州"
|
||||
v-model="state"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>州(受控多选)</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="illinois" text-value="伊利诺伊">
|
||||
伊利诺伊
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="pennsylvania" text-value="宾夕法尼亚">
|
||||
宾夕法尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
<p class="text-sm text-muted">已选:{{ selected }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,57 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
Button,
|
||||
} from "@heroui-vue/components";
|
||||
import { ref } from "vue";
|
||||
const open = ref(false);
|
||||
</script>
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<Select v-model:open="open" class="w-[256px]" placeholder="请选择">
|
||||
<Label>州</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="特拉华">
|
||||
特拉华
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="华盛顿">
|
||||
华盛顿
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
<Button @click="open = !open">{{ open ? "关闭" : "打开" }}选择框</Button>
|
||||
<p class="text-sm text-muted">选择框{{ open ? "已打开" : "已关闭" }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,75 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
import { ref, computed } from "vue";
|
||||
import type { SelectModelValue } from "@heroui-vue/components";
|
||||
const states = [
|
||||
{ id: "california", name: "加利福尼亚" },
|
||||
{ id: "texas", name: "德克萨斯" },
|
||||
{ id: "florida", name: "佛罗里达" },
|
||||
{ id: "new-york", name: "纽约" },
|
||||
{ id: "illinois", name: "伊利诺伊" },
|
||||
{ id: "pennsylvania", name: "宾夕法尼亚" },
|
||||
];
|
||||
const state = ref<SelectModelValue>("california");
|
||||
const selected = computed(
|
||||
() =>
|
||||
states
|
||||
.filter((s) =>
|
||||
Array.isArray(state.value)
|
||||
? state.value.includes(s.id)
|
||||
: state.value === s.id,
|
||||
)
|
||||
.map((s) => s.name)
|
||||
.join(", ") || "无",
|
||||
);
|
||||
</script>
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<Select class="w-[256px]" placeholder="请选择州" v-model="state">
|
||||
<Label>州(受控)</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="illinois" text-value="伊利诺伊">
|
||||
伊利诺伊
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="pennsylvania" text-value="宾夕法尼亚">
|
||||
宾夕法尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
<p class="text-sm text-muted">已选:{{ selected }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,53 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
import { IconSelector } from "@tabler/icons-vue";
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" placeholder="请选择">
|
||||
<Label>州</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator class="size-3">
|
||||
<IconSelector />
|
||||
</SelectIndicator>
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="特拉华">
|
||||
特拉华
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="华盛顿">
|
||||
华盛顿
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,38 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
const itemClass =
|
||||
"rounded-lg data-[focused=true]:bg-accent/10 data-[selected=true]:text-foreground";
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-56" placeholder="选择套餐" variant="secondary">
|
||||
<Label class="font-medium text-foreground">套餐</Label>
|
||||
<SelectTrigger class="rounded-xl bg-default">
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover
|
||||
class="rounded-xl border border-border bg-surface p-1 shadow-lg"
|
||||
>
|
||||
<ListBox>
|
||||
<ListBoxItem :class="itemClass" id="free" text-value="免费">
|
||||
免费
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem :class="itemClass" id="pro" text-value="专业版">
|
||||
专业版
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,107 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
Description,
|
||||
} from "@heroui-vue/components";
|
||||
import { Avatar, AvatarImage, AvatarFallback } from "@heroui-vue/components";
|
||||
const users = [
|
||||
{
|
||||
id: "1",
|
||||
name: "Bob",
|
||||
email: "bob@heroui.com",
|
||||
fallback: "B",
|
||||
avatarUrl:
|
||||
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
name: "Fred",
|
||||
email: "fred@heroui.com",
|
||||
fallback: "F",
|
||||
avatarUrl:
|
||||
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
name: "Martha",
|
||||
email: "martha@heroui.com",
|
||||
fallback: "M",
|
||||
avatarUrl:
|
||||
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
name: "John",
|
||||
email: "john@heroui.com",
|
||||
fallback: "J",
|
||||
avatarUrl:
|
||||
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/red.jpg",
|
||||
},
|
||||
{
|
||||
id: "5",
|
||||
name: "Jane",
|
||||
email: "jane@heroui.com",
|
||||
fallback: "J",
|
||||
avatarUrl:
|
||||
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/orange.jpg",
|
||||
},
|
||||
];
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" placeholder="请选择用户">
|
||||
<Label>用户</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue v-slot="{ defaultChildren, isPlaceholder, selectedItems }">
|
||||
<template v-if="isPlaceholder || !selectedItems.length">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<template v-else-if="selectedItems.length > 1">
|
||||
{{ selectedItems.length }} 位用户已选
|
||||
</template>
|
||||
<div v-else class="flex items-center gap-2">
|
||||
<Avatar class="size-4" size="sm">
|
||||
<AvatarImage
|
||||
:src="
|
||||
users.find((u) => u.id === selectedItems[0]?.key)?.avatarUrl ??
|
||||
''
|
||||
"
|
||||
/>
|
||||
<AvatarFallback>
|
||||
{{ users.find((u) => u.id === selectedItems[0]?.key)?.fallback }}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{{ defaultChildren }}</span>
|
||||
</div>
|
||||
</SelectValue>
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="user in users"
|
||||
:key="user.id"
|
||||
:id="user.id"
|
||||
:text-value="user.name"
|
||||
>
|
||||
<Avatar size="sm">
|
||||
<AvatarImage :src="user.avatarUrl" />
|
||||
<AvatarFallback>{{ user.fallback }}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="flex flex-col">
|
||||
<Label>{{ user.name }}</Label>
|
||||
<Description>{{ user.email }}</Description>
|
||||
</div>
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" placeholder="请选择">
|
||||
<Label>州</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="特拉华">
|
||||
特拉华
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="华盛顿">
|
||||
华盛顿
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Select
|
||||
is-disabled
|
||||
class="w-[256px]"
|
||||
default-value="california"
|
||||
placeholder="请选择"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="特拉华">
|
||||
特拉华
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="华盛顿">
|
||||
华盛顿
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
<Select
|
||||
is-disabled
|
||||
class="w-[256px]"
|
||||
:default-value="['argentina', 'japan', 'france']"
|
||||
placeholder="请选择国家"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>拟访问国家</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="argentina" text-value="阿根廷">
|
||||
阿根廷
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="venezuela" text-value="委内瑞拉">
|
||||
委内瑞拉
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="japan" text-value="日本">
|
||||
日本
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="france" text-value="法国">
|
||||
法国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="italy" text-value="意大利">
|
||||
意大利
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="spain" text-value="西班牙">
|
||||
西班牙
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,40 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<div class="w-[400px] space-y-4">
|
||||
<Select full-width placeholder="请选择">
|
||||
<Label>喜爱的动物</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="cat" text-value="猫">
|
||||
猫
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="dog" text-value="狗">
|
||||
狗
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="bird" text-value="鸟">
|
||||
鸟
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" placeholder="请选择国家" selection-mode="multiple">
|
||||
<Label>拟访问国家</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox selection-mode="multiple">
|
||||
<ListBoxItem id="argentina" text-value="阿根廷">
|
||||
阿根廷
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="venezuela" text-value="委内瑞拉">
|
||||
委内瑞拉
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="japan" text-value="日本">
|
||||
日本
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="france" text-value="法国">
|
||||
法国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="italy" text-value="意大利">
|
||||
意大利
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="spain" text-value="西班牙">
|
||||
西班牙
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="thailand" text-value="泰国">
|
||||
泰国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-zealand" text-value="新西兰">
|
||||
新西兰
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="iceland" text-value="冰岛">
|
||||
冰岛
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,113 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
Form,
|
||||
FieldError,
|
||||
Button,
|
||||
Surface,
|
||||
} from "@heroui-vue/components";
|
||||
import { ref } from "vue";
|
||||
const submitted = ref(false);
|
||||
</script>
|
||||
<template>
|
||||
<Surface class="w-[320px] rounded-3xl p-6">
|
||||
<Form class="flex w-full flex-col gap-4" @submit.prevent="submitted = true">
|
||||
<Select
|
||||
is-required
|
||||
class="w-full"
|
||||
name="state"
|
||||
placeholder="请选择"
|
||||
variant="secondary"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="特拉华">
|
||||
特拉华
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="华盛顿">
|
||||
华盛顿
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
<FieldError />
|
||||
</Select>
|
||||
<Select
|
||||
is-required
|
||||
class="w-full"
|
||||
name="country"
|
||||
placeholder="请选择国家"
|
||||
variant="secondary"
|
||||
>
|
||||
<Label>国家</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="usa" text-value="美国">
|
||||
美国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="canada" text-value="加拿大">
|
||||
加拿大
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="mexico" text-value="墨西哥">
|
||||
墨西哥
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="uk" text-value="英国">
|
||||
英国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="france" text-value="法国">
|
||||
法国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="germany" text-value="德国">
|
||||
德国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
<FieldError />
|
||||
</Select>
|
||||
<Button type="submit">提交</Button>
|
||||
<p v-if="submitted" role="status" class="text-sm text-success">
|
||||
表单提交成功!
|
||||
</p>
|
||||
</Form>
|
||||
</Surface>
|
||||
</template>
|
||||
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" placeholder="请选择" as="div" data-custom="foo">
|
||||
<Label>州</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="特拉华">
|
||||
特拉华
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="华盛顿">
|
||||
华盛顿
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,101 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
Form,
|
||||
FieldError,
|
||||
Button,
|
||||
} from "@heroui-vue/components";
|
||||
import { ref } from "vue";
|
||||
const submitted = ref(false);
|
||||
</script>
|
||||
<template>
|
||||
<Form
|
||||
class="flex w-[256px] flex-col gap-4"
|
||||
@submit.prevent="submitted = true"
|
||||
>
|
||||
<Select is-required class="w-full" name="state" placeholder="请选择">
|
||||
<Label>州</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="特拉华">
|
||||
特拉华
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="华盛顿">
|
||||
华盛顿
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
<FieldError />
|
||||
</Select>
|
||||
<Select is-required class="w-full" name="country" placeholder="请选择国家">
|
||||
<Label>国家</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="usa" text-value="美国">
|
||||
美国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="canada" text-value="加拿大">
|
||||
加拿大
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="mexico" text-value="墨西哥">
|
||||
墨西哥
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="uk" text-value="英国">
|
||||
英国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="france" text-value="法国">
|
||||
法国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="germany" text-value="德国">
|
||||
德国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
<FieldError />
|
||||
</Select>
|
||||
<Button type="submit">提交</Button>
|
||||
<p v-if="submitted" role="status" class="text-sm text-success">
|
||||
表单提交成功!
|
||||
</p>
|
||||
</Form>
|
||||
</template>
|
||||
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Select class="w-[256px]" placeholder="请选择" variant="primary">
|
||||
<Label>主要变体</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="option1" text-value="选项 1">
|
||||
Option 1
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="option2" text-value="选项 2">
|
||||
Option 2
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
<Select class="w-[256px]" placeholder="请选择" variant="secondary">
|
||||
<Label>次要变体</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="option1" text-value="选项 1">
|
||||
Option 1
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="option2" text-value="选项 2">
|
||||
Option 2
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,52 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectClearButton,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" default-value="california" placeholder="Select one">
|
||||
<Label>State</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectClearButton />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="Florida">
|
||||
Florida
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="Delaware">
|
||||
Delaware
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="California">
|
||||
California
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="Texas">
|
||||
Texas
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="New York">
|
||||
New York
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="Washington">
|
||||
Washington
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,52 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
Description,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" placeholder="请选择">
|
||||
<Label>州</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="florida" text-value="佛罗里达">
|
||||
佛罗里达
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="delaware" text-value="特拉华">
|
||||
特拉华
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="california" text-value="加利福尼亚">
|
||||
加利福尼亚
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="德克萨斯">
|
||||
德克萨斯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="new-york" text-value="纽约">
|
||||
纽约
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="washington" text-value="华盛顿">
|
||||
华盛顿
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
<Description>请选择居住州</Description>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<Select
|
||||
class="w-[256px]"
|
||||
:disabled-keys="['cat', 'kangaroo']"
|
||||
placeholder="请选择动物"
|
||||
>
|
||||
<Label>动物</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxItem id="dog" text-value="狗">
|
||||
狗
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="cat" text-value="猫">
|
||||
猫
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="bird" text-value="鸟">
|
||||
鸟
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="kangaroo" text-value="袋鼠">
|
||||
袋鼠
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="elephant" text-value="大象">
|
||||
大象
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="tiger" text-value="老虎">
|
||||
老虎
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -0,0 +1,88 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
ListBoxSection,
|
||||
Label,
|
||||
Header,
|
||||
Separator,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
<template>
|
||||
<Select class="w-[256px]" placeholder="请选择国家">
|
||||
<Label>国家</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox>
|
||||
<ListBoxSection>
|
||||
<Header>北美洲</Header>
|
||||
<ListBoxItem id="usa" text-value="美国">
|
||||
美国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="canada" text-value="加拿大">
|
||||
加拿大
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="mexico" text-value="墨西哥">
|
||||
墨西哥
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBoxSection>
|
||||
<Separator />
|
||||
<ListBoxSection>
|
||||
<Header>欧洲</Header>
|
||||
<ListBoxItem id="uk" text-value="英国">
|
||||
英国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="france" text-value="法国">
|
||||
法国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="germany" text-value="德国">
|
||||
德国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="spain" text-value="西班牙">
|
||||
西班牙
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="italy" text-value="意大利">
|
||||
意大利
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBoxSection>
|
||||
<Separator />
|
||||
<ListBoxSection>
|
||||
<Header>亚洲</Header>
|
||||
<ListBoxItem id="japan" text-value="日本">
|
||||
日本
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="china" text-value="中国">
|
||||
中国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="india" text-value="印度">
|
||||
印度
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="south-korea" text-value="韩国">
|
||||
韩国
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBoxSection>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</template>
|
||||
@@ -15,6 +15,7 @@
|
||||
"@heroui-vue/components": "workspace:*",
|
||||
"@heroui-vue/styles": "workspace:*",
|
||||
"@tabler/icons-vue": "^3.49.0",
|
||||
"@vueuse/core": "14.4.0",
|
||||
"reka-ui": "^2.11.0",
|
||||
"vue": "^3.5.44"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import SelectLifecycle from "../../../packages/vue/tests/fixtures/SelectLifecycle.vue";
|
||||
const selectLifecycle =
|
||||
typeof window !== "undefined" &&
|
||||
new URLSearchParams(window.location.search).has("select-lifecycle");
|
||||
import ScrollTabsLab from "./ScrollTabsLab.vue";
|
||||
const scrollTabsLab =
|
||||
typeof window !== "undefined" &&
|
||||
@@ -27,7 +31,8 @@ function save() {
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<ScrollTabsLab v-if="scrollTabsLab" />
|
||||
<SelectLifecycle v-if="selectLifecycle" />
|
||||
<ScrollTabsLab v-else-if="scrollTabsLab" />
|
||||
<OverlayAnimationLab v-else-if="animationLab" />
|
||||
<OverlayComponentsLab v-else-if="componentsLab" />
|
||||
<OverlayLab v-else-if="overlayLab" />
|
||||
|
||||
@@ -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 | 基建中(未公开) | 集合状态与公开 ListBox 已落地;Select 六部件、字段/弹层/SSR 接入及 19 个基线预览仍待迁移,见 COLLECTION-01 |
|
||||
| select | 验证中(SELECT-01) | 六部件、19/19 例、单/多选、清空、字段/原生提交/SSR/异步;复用 ListBox + Popover,重点浏览器已验,限制见 SELECT-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 | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
|
||||
@@ -71,3 +71,9 @@
|
||||
新增原始 Reka 探针确认:Content 的用户 keydown preventDefault 后,End 仍移动焦点。结合 none 语义、完整数据虚拟化与 textValue / 元数据需求,公共 ListBox 使用局部原生 role 节点与既有集合内核,VueUse 维护虚拟滚动测量;不修改依赖、不调用私有上下文,也不引入另一套组件底座。普通列表与虚拟列表共用唯一逻辑集合、选择和焦点状态。
|
||||
|
||||
泛型 SFC 不通过 Parameters 提取公共 Props:实测会让模型/模式反例失效。Root 和导出的 Props 复用 ListBoxOptions 明确 schema,保留消费端正反例;不能以 skipLibCheck 或删除反例规避。
|
||||
|
||||
## SELECT-01 公共实现接续
|
||||
|
||||
前文 Select 未实现是此前阶段状态。六部件、十九例、唯一原生 select 提交/自动填充边界、字段/reset 与 SSR 元数据已落地,见 [SELECT-01](../migrations/SELECT-01-select.md)。私有 CollectionOwner 将接受值、模式、禁用、Tab 离开与激活关闭连接到现有 ListBox,不另建全局集合或焦点内核。真实浏览器验收受工具 URL 策略阻断,待补后再决定合入 main。
|
||||
|
||||
Select 后续重点浏览器补验已完成并修复定位后已选项不在可视区的问题;此前 URL 阻断解除,当前可以集成 main,见 SELECT-01 补验节。
|
||||
|
||||
@@ -278,3 +278,7 @@ ListBox 已完成公共首轮实现,见 [报告](migrations/LISTBOX-01-list-bo
|
||||
## M33–M34 最终收口与下一批
|
||||
|
||||
原7项失败已修复,集成人补旧节点清理/退出中重开回归、真实outside、23例同页与独立tarball消费;实际边界见[验收记录](migrations/M33-M34-acceptance.md)。后续必须先读[本轮经验](migrations/M33-M34-lessons.md)。下一批安排为[M35 Toast → M36 Table](migrations/M35-M36-toast-table-prompt.md),从最新main新开分支;历史返修说明不再要求继续旧任务。
|
||||
|
||||
## SELECT-01 接续与复核要点
|
||||
|
||||
Select 已接入六部件和十九例,见 [报告](migrations/SELECT-01-select.md)。后续集合/日期选择字段复用 CollectionOwner / ListBox、choice/Form 与 overlay,不复制状态或焦点栈。通用弹层 role/ARIA 默认覆盖、非模态 Tab 仍循环、受控 reset 后原生 DOM 不回写、SSR 关闭态缺少元数据、空字符串布尔属性及动态删除留下幽灵提交是本轮重点回归。其他 AI 不自行修改这些共享协议。真实浏览器受 URL 策略阻断,仍待补验,不能把已通过的自动化检查当作最终视觉或交互验收。
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# SELECT-01:Select 公共迁移
|
||||
|
||||
2026-10-23,独立目录 `heroui-vue-core`,分支 `feat/select`,起点 main `65db60a`。固定 HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`。其他 AI 的 checkout 未修改。
|
||||
|
||||
## 交付与结构
|
||||
|
||||
- 六部件 Select / SelectRoot、SelectTrigger、SelectValue、SelectIndicator、SelectClearButton、SelectPopover;公开 Props、SelectModelValue / SelectItem / SelectSelectedItem、tv 与主题 CSS。
|
||||
- 完整移植 select.css / select.styles.ts:primary / secondary、fullWidth、字段尺寸/阴影/圆角、clear target、指示器旋转、150ms fade/zoom95 进入、100ms 退出、方向位移、字段状态与 reduced-motion。使用 hv- 命名空间;placement 改为 Reka 实际 data-side,宽度/原点/可用空间映射到测量变量。默认 SVG 来自基线 icons.tsx,原 Apache-2.0 见 third-party/HEROUI-LICENSE;自定义图标使用 Tabler Vue。
|
||||
- 中文十九个正文预览全部迁移并保持顺序: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。
|
||||
- 原文标题/介绍、示例布局、选项数据、头像、清空说明、Tailwind 自定义示例和 API 部件已接入;预览、代码高亮与复制仍共用同一 SFC。React render 改 Vue as/插槽,表单 alert 改内联成功反馈。
|
||||
|
||||
复用现有 ListBox、choice/field/Form、Popover 与 Reka 弹层设施。私有 CollectionOwner 把字段接受值、模式/禁用、激活关闭与焦点目标连接给 ListBox;ListBox 仍使用同一个集合状态内核,没有新增全局选择状态、焦点栈、outside/Escape 监听或滚动锁。
|
||||
|
||||
直接包装 Reka Select 的 SSR 展示、多选表单和空字符串缺口已在 COLLECTION-01 探针确认,因此选择已有 ListBox + Popover 组合,而非复制 Reka 内部实现或引入第二套组件库。PopoverContent 仅补充原生 role 与 data-slot 的显式透传,默认 dialog 行为保留。
|
||||
|
||||
## 值、字段与表单
|
||||
|
||||
- 单选 Key/null、多选 Key[],推荐 v-model;value / isOpen 兼容别名保留,推荐 v-model:open。显式 modelValue/open 优先,包括显式 undefined。父拒绝后真实选择/展示/提交仍为父值,相同提案可重试。
|
||||
- 数字 0、字符串 "0"、空字符串分别保留身份。唯一原生 select 负责提交及 autocomplete,option 索引还原原始 key;提交值是 String(key),内部身份编码不进入 FormData。空值、未知或禁用项不提交,多选同名重复提交。
|
||||
- 空选择时原生 select 不设置 name,以免产生虚假的空提交;浏览器可通过稳定 ID 与 autocomplete 识别。不同浏览器首次自动填充表现尚未实测,不声明与 RAC 原生隐藏选择层完全一致。
|
||||
- nameless checkbox 仅负责约束和 form/reset 归属,不重复提交。native/aria、required、validate、Form 服务端错误消退/刷新、只读/Fieldset 禁用消费现有字段协议。原生 reset 后显式恢复原生选项,避免受控值未变化时 DOM 留在浏览器默认选项。
|
||||
- 非受控切换 selectionMode 时适配公开值形状,单选取首项,不发编辑事件;受控父级须同步提供匹配形状。reset 仍使用捕获的初值。
|
||||
- Item 的 Label/Description 保持自身作用域;外层标签/描述/错误只关联字段触发器。根 aria-label 传给触发器及 listbox,显式触发器名称可独立覆盖;字段 Label 点击仅聚焦触发器。
|
||||
|
||||
## SSR、异步与键盘
|
||||
|
||||
- 关闭态预规划已知 Popover/ListBox/Section/Item、Fragment 与原生结构,SSR 首屏即可显示已选文字和原生 option。布尔 props 的空字符串按 Vue 布尔属性规则解释。
|
||||
- 不执行任意用户组件的 setup/render 来探测内容;显式 items 是完整元数据,适合不透明包装与异步标签。未提供元数据的未知项在首次打开前只显示 key,无法提交。挂载 registry 不冒充逻辑全集;动态移除不能留下已删除项的成功提交。
|
||||
- Enter/Space 使用既有原生触发器与 ListBox 协议;方向键进入已选/首末项,单选激活关闭,多选保持展开,关闭态首字母搜索跳过禁用项并尊重 IME/取消。清空控件为 aria-hidden span,计数注册决定是否启用关闭态 Delete/Backspace,独立 Trigger 禁用同样阻止清空。
|
||||
- Select 使用 Popover 非模态组合。Tab 从 ListBox 退出时先把原生遍历起点返回 Trigger,再允许浏览器默认 Tab,避免底座 FocusScope 循环及 Teleport 文档顺序;不新建全局 Tab 队列。Escape 和外部交互仍由弹层底座处理。
|
||||
- 异步例使用真实 PokeAPI、AbortSignal、VueUse IntersectionObserver、分页、加载提示、失败重试与手动加载。React Collection / ListBoxLoadMoreItem 不作为 Vue 公共导出。
|
||||
|
||||
## 验证与尚未验收
|
||||
|
||||
最终命令与数量见 [verification.md](../verification.md)。Select 新增 34 项 jsdom 行为/水合/十九例共存/异步分页失败重试与取消,以及 3 项真正 node SSR;既有 ListBox/Popover/Modal、字段与其他组件完整回归保留。测试核对实际焦点、ARIA、FormData 和事件载荷;嵌套 Modal 中的 Escape 单独覆盖。
|
||||
|
||||
两个新 tarball 安装到 `/private/tmp/heroui-slider-consumer`,执行 ESM/SSR/CSS 及 NodeNext、bundler 严格正反例;旧 ListBox、NumberField/Slider、M30–M32 消费用例同时保留。
|
||||
|
||||
**本轮真实浏览器未验收。** 5174 文档服务已启动,但浏览器工具在获取既有标签页时被 URL 协议安全策略拦截,未绕过。没有把 jsdom 的 Tab/焦点或已移植动画 CSS 描述为真实浏览器结果。实际焦点遍历、碰撞/滚动、进出动效、重开、深浅色/移动布局及表格宽度仍需重点浏览器核验;暂不据此合入 main。
|
||||
|
||||
也未完成逐像素视觉、实际读屏/触屏、跨浏览器自动填充、移动端原生选择菜单切换和 Nuxt 验收。当前为“公共实现与自动化验证已落地,浏览器验收待补”,不声明完整兼容 HeroUI。
|
||||
|
||||
## 浏览器补验接续(2026-10-23)
|
||||
|
||||
本轮正常 HTTP 页面已恢复访问,替代上节“浏览器待验、暂不合 main”的阶段结论。已核验默认/受控多选/清空/深浅色、真实 Tab、嵌套 Modal Escape、表格宽度,以及真实 150ms / scale .95 进入和 100ms 退出事件。长列表定位前聚焦未滚入可视区的问题已修复,保留 SelectLifecycle 夹具与回归;详情见 verification.md。当前可集成 main,完整视觉/移动/读屏等限制继续保留。
|
||||
@@ -176,3 +176,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生
|
||||
- 固定ce90ea3的react/components/{alert-dialog,drawer}、styles对应CSS/tv、中文components/(overlays)正文与demos/cn:AlertDialog14例,Drawer9例。
|
||||
- hv-命名空间保留源视觉数值,AlertDialog默认图标路径来自固定icons.tsx(Apache-2.0,原声明见third-party/HEROUI-LICENSE);演示自定义图标为Tabler Vue。
|
||||
- Vue复用既有Reka Dialog/Presence/FocusScope/Portal,Drawer源transition改为同方向/时长/缓动的局部keyframes以适配Presence;拖动逻辑由源阈值适配Vue生命周期与受控状态。未修改上游或安装依赖实现。
|
||||
|
||||
## SELECT-01(2026-10-23)
|
||||
|
||||
固定 ce90ea3 的 `packages/react/src/components/select/select.tsx`、`packages/styles/components/select.css`、`packages/styles/src/components/select/select.styles.ts`、`icons.tsx` 的 ChevronDown/Close,以及中文 `(pickers)/select.mdx` 和十九个 `demos/cn/select` 预览。CSS/tv/默认图形沿用 Apache-2.0 声明并加 hv- 前缀,方向/宽度/原点适配 Reka 实际状态。Vue 使用现有 ListBox + Popover + 字段协议;异步 React Stately/Collection 改 Fetch + VueUse(文档包显式声明既有 14.4.0),保留数据接口、分页与错误/取消体验。差异与待验收范围见 [SELECT-01](migrations/SELECT-01-select.md)。
|
||||
|
||||
@@ -718,3 +718,24 @@ typecheck、build:docs、build:playground、format、diff-check 与 dist 正反
|
||||
- 重点浏览器验证Drawer进入关键帧、阶段结束、关闭卸载/焦点/锁释放;AlertDialog标题、默认Escape策略、关闭焦点恢复,两页API表无内部横向溢出。
|
||||
- 独立tarball在/private/tmp/heroui-m33-consumer通过ESM/node SSR/CSS与NodeNext、bundler正反类型;来源与未验收范围见[M33–M34最终记录](migrations/M33-M34-acceptance.md)。
|
||||
- 最新main的ListBox与M33/M34共同保留;下一批Toast→Table,须先同步main并新开任务分支。
|
||||
|
||||
## SELECT-01 公共实现自动化验证(2026-10-23)
|
||||
|
||||
- `pnpm test`:46 文件 / 686 项通过;Select 新增 34 项 jsdom 行为、实际水合、十九例同页挂载及异步分页/重试/取消,另 3 项真正 node SSR。预期的重复 key 拒绝用例会输出 Vue render 警告;普通示例合并挂载无 Vue 警告或重复 ID。
|
||||
- `pnpm typecheck`、`pnpm build:docs` 通过;构建只保留既存文档 chunk 超过 500kB 提示。Select CSS 为基线 150ms zoom95 进入 / 100ms 退出,data-side、宽度/原点与可用空间已适配;这些是代码/构建核对,不是实测动效结论。
|
||||
- 新 tarball 安装到 `/private/tmp/heroui-slider-consumer`:Select ESM/SSR/CSS、NodeNext / bundler 严格正反例通过;ListBox、NumberField/Slider、M30–M32 消费回归同时通过。模型、变体、模式、metadata、事件、部件位置及作用域插槽 key 类型反例保留;没有源码 alias。
|
||||
- 已验证接受值/拒绝重试、单多选空值及 0/"0"/空字符串、单项/Fieldset 禁用/只读、唯一原生提交、autocomplete 提案与回退、native/aria required/Form 错误、原生 reset/取消/受控/动态外部 form、动态移除/异步标签、清空注册/独立 Trigger 禁用、名称/描述/错误隔离、取消与处理器数组停止传播、焦点进入/Tab 起点、嵌套 Modal 的 Escape。jsdom 不模拟真正的浏览器 Tab 默认遍历,也不证明读屏或自动填充弹窗体验。
|
||||
- **真实浏览器验收未完成**:5174 文档服务已启动;浏览器工具在读取既有标签页时被 URL 协议安全策略阻止,未绕过或切换其他控制方式。因此碰撞/滚动、Tab 真实落点、进出动效/重开、深浅色/移动布局与表格几何仍待重点补验。本批留在 feat/select,不据此合入 main。
|
||||
- 公开差异与当前边界见 [SELECT-01](migrations/SELECT-01-select.md)。未做逐像素、完整读屏/触屏、跨浏览器自动填充、移动原生菜单及 Nuxt 验收;此前 Select“未实现”描述为历史阶段状态。
|
||||
|
||||
## SELECT-01 浏览器补验与定位后焦点修复(2026-10-23)
|
||||
|
||||
- 本次正常 HTTP 验收页可访问,前节的 URL 策略阻断属于此前阶段。重点验证 5174,不逐一点击全部示例。
|
||||
- 单选选择关闭/恢复焦点、重新打开聚焦已选项、真实 Tab 到代码展开按钮、受控多选保持展开、Escape、清空与深浅色已验。八张 API 表在 1280×720 下均为 736px,scrollWidth=clientWidth。
|
||||
- 40 项夹具发现定位前 scrollIntoView 无效:第 12 项得到焦点但在 387px 滚动区外。SelectPopover 在进入动画开始和下一帧复核当前焦点的可见性(取消自动焦点时不运行、忽略子动画、卸载清理),修复后 scrollTop=99.5,第 12 项范围 668–704px 位于弹层 321.5–708px 内;End 聚焦第 40 项,scrollTop=1219.5。
|
||||
- 原生 animationstart/end 记录进入 enter / elapsed=0.15s / scale=.95,退出 exit / elapsed=0.1s;退出后节点卸载并恢复 Trigger。Modal 内 Select 的 Escape 只关闭当前选择层,父 dialog 保留。未将截图当作动画时长证据。
|
||||
- 保留 `SelectLifecycle.vue` 夹具,可在 playground `?select-lifecycle` 运行;临时文档验收路由已移除。截图 `/private/tmp/heroui-select-review.png`。修复后完整检查结果见本轮提交;不宣称逐像素、读屏/触屏、移动端或跨浏览器自动填充验收完成。
|
||||
|
||||
本次定位后焦点修复最终 `pnpm test`:46 文件 / 687 项通过,typecheck 和 build:docs 通过;Prettier/diff 与独立消费回归继续验证。
|
||||
|
||||
与远程 main 的 M33–M34 集成后,完整测试 51 文件 / 720 项通过,typecheck、build:docs 通过。导出/样式/脚本/报告均保留双方增量;Select 文档移除 MDX 专用 [!toc] 标记。
|
||||
|
||||
+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 tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts",
|
||||
"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",
|
||||
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts",
|
||||
"test:ssr": "vitest run tests/ssr.test.ts tests/input-otp-ssr.test.ts tests/slider-foundation-ssr.test.ts tests/slider-ssr.test.ts tests/collection-foundation-ssr.test.ts tests/list-box-ssr.test.ts tests/select-ssr.test.ts",
|
||||
"format": "prettier --check .",
|
||||
"format:fix": "prettier --write .",
|
||||
"dev:playground": "pnpm build && pnpm --filter @heroui-vue/playground dev"
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
/* Adapted from HeroUI ce90ea3, Apache-2.0. See third-party/HEROUI-LICENSE.
|
||||
* Modified: hv- namespace, Reka placement state. */
|
||||
/* Select styles */
|
||||
.hv-select {
|
||||
@apply flex flex-col gap-1;
|
||||
|
||||
&[data-invalid="true"],
|
||||
&[aria-invalid="true"] {
|
||||
[data-slot="description"] {
|
||||
@apply hidden;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="label"] {
|
||||
@apply w-fit;
|
||||
}
|
||||
}
|
||||
|
||||
.hv-select__trigger {
|
||||
@apply relative isolate inline-flex min-h-9 rounded-field border bg-field px-3 py-2 text-sm text-field-foreground shadow-field outline-none select-none no-highlight;
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
background-color 150ms var(--ease-smooth),
|
||||
border-color 150ms var(--ease-smooth),
|
||||
box-shadow 150ms var(--ease-out);
|
||||
@apply motion-reduce:transition-none;
|
||||
|
||||
/* Cursor */
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
border-width: var(--border-width-field);
|
||||
border-color: var(--field-border);
|
||||
|
||||
/* Add inline-end padding when indicator is present */
|
||||
&:has(.hv-select__indicator) {
|
||||
@apply pe-7;
|
||||
}
|
||||
|
||||
/* Hover state - exclude when clear button is hovered to prevent double hover effect */
|
||||
@media (hover: hover) {
|
||||
&:hover:not(:has(.hv-select__clear-button:hover)),
|
||||
&[data-hovered="true"]:not(:has(.hv-select__clear-button:hover)) {
|
||||
@apply bg-field-hover;
|
||||
border-color: var(--field-border-hover);
|
||||
}
|
||||
}
|
||||
|
||||
/* Focus visible state */
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
@apply status-focused;
|
||||
border-color: var(--field-border-focus);
|
||||
background-color: var(--field-focus);
|
||||
}
|
||||
|
||||
/* Focus state */
|
||||
&:focus,
|
||||
&[data-focus="true"] {
|
||||
}
|
||||
|
||||
/* Invalid state */
|
||||
.hv-select[data-invalid="true"] &,
|
||||
.hv-select[aria-invalid="true"] & {
|
||||
@apply status-invalid-field;
|
||||
background-color: var(--field-focus);
|
||||
}
|
||||
|
||||
/* Disabled state */
|
||||
&:disabled,
|
||||
&[data-disabled="true"],
|
||||
&[aria-disabled="true"] {
|
||||
@apply status-disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/* Variant property definitions */
|
||||
.hv-select--primary {
|
||||
/* Default styles */
|
||||
}
|
||||
|
||||
.hv-select--secondary .hv-select__trigger {
|
||||
@apply shadow-none;
|
||||
background-color: var(--select-trigger-bg);
|
||||
|
||||
--select-trigger-bg: var(--default);
|
||||
--select-trigger-bg-hover: var(--default-hover);
|
||||
--select-trigger-bg-focus: var(--default);
|
||||
|
||||
/* Exclude when clear button is hovered to prevent double hover effect */
|
||||
@media (hover: hover) {
|
||||
&:hover:not(:has(.hv-select__clear-button:hover)),
|
||||
&[data-hovered="true"]:not(:has(.hv-select__clear-button:hover)) {
|
||||
background-color: var(--select-trigger-bg-hover);
|
||||
}
|
||||
}
|
||||
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
background-color: var(--select-trigger-bg-focus);
|
||||
}
|
||||
|
||||
&:focus,
|
||||
&[data-focus="true"] {
|
||||
}
|
||||
|
||||
.hv-select[data-invalid="true"] &,
|
||||
.hv-select[aria-invalid="true"] & {
|
||||
background-color: var(--select-trigger-bg-focus);
|
||||
}
|
||||
}
|
||||
|
||||
.hv-select__value {
|
||||
@apply flex-1 text-start text-base wrap-break-word text-current sm:text-sm;
|
||||
|
||||
&[data-placeholder="true"] {
|
||||
@apply text-field-placeholder;
|
||||
}
|
||||
|
||||
/* Removes the list-box-item indicator element from the select value*/
|
||||
[data-slot="list-box-item-indicator"] {
|
||||
@apply hidden;
|
||||
}
|
||||
}
|
||||
|
||||
/* Clear Button styles */
|
||||
.hv-select__clear-button {
|
||||
@apply relative isolate inline-flex size-5 shrink-0 origin-center transform-gpu items-center justify-center self-center rounded-xl bg-transparent p-1 text-muted select-none no-highlight;
|
||||
|
||||
/* Cursor */
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
/**
|
||||
* The visible box stays at 20px so it fits inside the trigger's 36px min-height
|
||||
* without growing it. Expand the pointer target to the 24px floor in WCAG 2.5.8.
|
||||
*/
|
||||
&::after {
|
||||
@apply absolute -inset-0.5;
|
||||
content: "";
|
||||
}
|
||||
|
||||
/* Transition only when visible - disappears immediately when cleared */
|
||||
&:not([data-empty="true"]) {
|
||||
transition: opacity 150ms var(--ease-smooth);
|
||||
@apply motion-reduce:transition-none;
|
||||
}
|
||||
|
||||
&[data-empty="true"] {
|
||||
@apply pointer-events-none opacity-0;
|
||||
}
|
||||
|
||||
[data-slot="select-clear-button-icon"] {
|
||||
@apply size-3.5;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
&:hover,
|
||||
&[data-hovered="true"] {
|
||||
@apply bg-default-hover;
|
||||
}
|
||||
}
|
||||
|
||||
&:active,
|
||||
&[data-pressed="true"] {
|
||||
transform: scale(0.93);
|
||||
}
|
||||
}
|
||||
|
||||
.hv-select__indicator {
|
||||
@apply absolute inset-y-0 end-2 my-auto flex shrink-0 items-center justify-center text-field-placeholder transition duration-150;
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
&[data-open="true"] {
|
||||
@apply rotate-180;
|
||||
}
|
||||
|
||||
&[data-slot="select-default-indicator"] {
|
||||
@apply size-4;
|
||||
}
|
||||
}
|
||||
|
||||
/* Similar to popover content styles */
|
||||
.hv-select__popover {
|
||||
/* RAC constrains overlays to available space; use Reka measurement variables. */
|
||||
max-height: var(--reka-popover-content-available-height);
|
||||
max-width: var(--reka-popover-content-available-width);
|
||||
@apply min-w-(--trigger-width) origin-(--trigger-anchor-point) scroll-py-1 scrollbar overflow-y-auto overscroll-contain bg-overlay p-0 text-sm;
|
||||
border-radius: min(32px, var(--radius-3xl));
|
||||
box-shadow: var(--overlay-shadow);
|
||||
|
||||
/* Focus state */
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
@apply outline-none;
|
||||
}
|
||||
|
||||
/* Entering animations */
|
||||
&[data-entering="true"] {
|
||||
@apply animate-in duration-150 ease-smooth fade-in-0 zoom-in-95;
|
||||
|
||||
/* Placement-specific translations */
|
||||
&[data-side="top"] {
|
||||
@apply slide-in-from-bottom-1;
|
||||
}
|
||||
|
||||
&[data-side="bottom"] {
|
||||
@apply slide-in-from-top-1;
|
||||
}
|
||||
|
||||
&[data-side="left"] {
|
||||
@apply slide-in-from-right-1;
|
||||
}
|
||||
|
||||
&[data-side="right"] {
|
||||
@apply slide-in-from-left-1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Exiting animations */
|
||||
&[data-exiting="true"] {
|
||||
@apply animate-out duration-100 ease-smooth zoom-out-95 fade-out;
|
||||
/* Stays non-interactive while closing, even if the exit animation is interrupted. */
|
||||
@apply pointer-events-none;
|
||||
}
|
||||
|
||||
&[data-exiting="true"],
|
||||
&[data-entering="true"] {
|
||||
@apply transition-[opacity,transform] will-change-[opacity,transform];
|
||||
}
|
||||
|
||||
/* Arrow styling */
|
||||
& [data-slot="popover-overlay-arrow"] {
|
||||
fill: var(--overlay);
|
||||
}
|
||||
|
||||
/* Arrow rotation based on placement */
|
||||
&[data-side="bottom"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: 180deg;
|
||||
}
|
||||
|
||||
&[data-side="left"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: -90deg;
|
||||
}
|
||||
|
||||
&[data-side="right"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: 90deg;
|
||||
}
|
||||
|
||||
/* Listbox styles */
|
||||
[data-slot="list-box"] {
|
||||
@apply p-1.5 outline-none;
|
||||
}
|
||||
|
||||
[data-slot="list-box-item"] {
|
||||
@apply px-2.5;
|
||||
}
|
||||
|
||||
/* As the popover closes fast in single-select mode, the default item indicator transition is not even visible - so we disable it only for single-select */
|
||||
[data-slot="list-box"]:not([aria-multiselectable="true"])
|
||||
[data-slot="list-box-item-indicator"],
|
||||
[data-slot="list-box"]:not([aria-multiselectable="true"])
|
||||
[data-slot="list-box-item-indicator"]
|
||||
[data-slot="list-box-item-indicator--checkmark"] {
|
||||
@apply transition-none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Full width modifier */
|
||||
.hv-select--full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.hv-select__trigger--full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
@@ -147,3 +147,5 @@
|
||||
@import "./components/list-box.css" layer(components);
|
||||
@import "./components/list-box-item.css" layer(components);
|
||||
@import "./components/list-box-section.css" layer(components);
|
||||
|
||||
@import "./components/select.css" layer(components);
|
||||
|
||||
@@ -1419,3 +1419,37 @@ export const drawerVariants = tv({
|
||||
});
|
||||
|
||||
export type DrawerVariants = VariantProps<typeof drawerVariants>;
|
||||
|
||||
export const selectVariants = tv({
|
||||
defaultVariants: {
|
||||
fullWidth: false,
|
||||
variant: "primary",
|
||||
},
|
||||
slots: {
|
||||
base: "hv-select",
|
||||
clearButton: "hv-select__clear-button",
|
||||
indicator: "hv-select__indicator",
|
||||
popover: "hv-select__popover",
|
||||
trigger: "hv-select__trigger",
|
||||
value: "hv-select__value",
|
||||
},
|
||||
variants: {
|
||||
fullWidth: {
|
||||
false: {},
|
||||
true: {
|
||||
base: "hv-select--full-width",
|
||||
trigger: "hv-select__trigger--full-width",
|
||||
},
|
||||
},
|
||||
variant: {
|
||||
primary: {
|
||||
base: "hv-select--primary",
|
||||
},
|
||||
secondary: {
|
||||
base: "hv-select--secondary",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export type SelectVariants = VariantProps<typeof selectVariants>;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { ComputedRef, InjectionKey } from "vue";
|
||||
import type { CollectionKey } from "./keys";
|
||||
export interface CollectionRecord {
|
||||
key: CollectionKey;
|
||||
text: string;
|
||||
disabled: boolean;
|
||||
}
|
||||
export interface OwnedCollection {
|
||||
items: () => CollectionRecord[];
|
||||
focus: (edge: "first" | "last" | "selected") => Promise<void>;
|
||||
}
|
||||
/** A field composite may own a ListBox, without adding another value store. */
|
||||
export interface CollectionOwner {
|
||||
keys: ComputedRef<readonly CollectionKey[]>;
|
||||
mode: ComputedRef<"single" | "multiple">;
|
||||
disabled: ComputedRef<boolean>;
|
||||
readOnly: ComputedRef<boolean>;
|
||||
disabledKeys: ComputedRef<readonly CollectionKey[]>;
|
||||
id: string;
|
||||
labelledBy: () => string | undefined;
|
||||
ariaLabel: () => string | undefined;
|
||||
request: (keys: CollectionKey[]) => void;
|
||||
action: (key: CollectionKey) => void;
|
||||
leave: () => void;
|
||||
connect: (collection: OwnedCollection) => () => void;
|
||||
}
|
||||
export const collectionOwnerKey: InjectionKey<CollectionOwner | undefined> =
|
||||
Symbol("hv-collection-owner");
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts" generic="T extends ListBoxDataItem = ListBoxDataItem">
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
getCurrentInstance,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
@@ -17,6 +18,7 @@ import { useConfig } from "../../providers/context";
|
||||
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
|
||||
import { useCollectionSelection } from "../collection/selection";
|
||||
import { useCollectionRegistry } from "../collection/registry";
|
||||
import { collectionOwnerKey } from "../collection/owner";
|
||||
import { assertKey } from "../collection/keys";
|
||||
import {
|
||||
listBoxKey,
|
||||
@@ -36,6 +38,21 @@ const props = withDefaults(defineProps<ListBoxOptions<T>>(), {
|
||||
rowHeight: 50,
|
||||
overscan: 5,
|
||||
});
|
||||
const owner = inject(collectionOwnerKey, undefined);
|
||||
provide(collectionOwnerKey, undefined);
|
||||
const mode = computed(() => owner?.mode.value ?? props.selectionMode);
|
||||
const behavior = computed(() =>
|
||||
owner
|
||||
? mode.value === "single"
|
||||
? "replace"
|
||||
: "toggle"
|
||||
: props.selectionBehavior,
|
||||
);
|
||||
const readOnly = computed(() => props.isReadOnly || !!owner?.readOnly.value);
|
||||
const disabledKeys = computed(() => [
|
||||
...(props.disabledKeys ?? []),
|
||||
...(owner?.disabledKeys.value ?? []),
|
||||
]);
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [keys: ListBoxKey[]];
|
||||
selectionChange: [keys: ListBoxKey[]];
|
||||
@@ -62,13 +79,32 @@ onBeforeUpdate(() => {
|
||||
controlled.value = hasModel.value || selectedPresence();
|
||||
});
|
||||
const config = useConfig();
|
||||
const disabled = useInheritedDisabled(() => props.isDisabled);
|
||||
const disabled = useInheritedDisabled(
|
||||
() => props.isDisabled || owner?.disabled.value,
|
||||
);
|
||||
provide(disabledContextKey, disabled);
|
||||
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
|
||||
const registry = useCollectionRegistry<ListBoxMember>();
|
||||
const mounted = ref(false);
|
||||
let disconnectOwner: (() => void) | undefined;
|
||||
onMounted(() => {
|
||||
mounted.value = true;
|
||||
if (owner)
|
||||
disconnectOwner = owner.connect({
|
||||
items: known,
|
||||
focus: async (edge) => {
|
||||
const available = eligible();
|
||||
const key =
|
||||
edge === "last"
|
||||
? available.at(-1)?.key
|
||||
: edge === "first"
|
||||
? available[0]?.key
|
||||
: (available.find((item) => selection.selected(item.key))?.key ??
|
||||
available[0]?.key);
|
||||
if (key !== undefined) await focus(key);
|
||||
else root.value?.focus();
|
||||
},
|
||||
});
|
||||
});
|
||||
const data = computed(() => {
|
||||
const seen = new Set<ListBoxKey>();
|
||||
@@ -79,14 +115,14 @@ const data = computed(() => {
|
||||
seen.add(item.id);
|
||||
return {
|
||||
key: item.id,
|
||||
disabled: !!item.isDisabled || !!props.disabledKeys?.includes(item.id),
|
||||
disabled: !!item.isDisabled || !!disabledKeys.value.includes(item.id),
|
||||
text: item.textValue ?? "",
|
||||
};
|
||||
});
|
||||
});
|
||||
const keyDisabled = (key: ListBoxKey) =>
|
||||
disabled.value ||
|
||||
!!props.disabledKeys?.includes(key) ||
|
||||
!!disabledKeys.value.includes(key) ||
|
||||
!!data.value?.find((item) => item.key === key)?.disabled;
|
||||
const known = () => {
|
||||
const members = registry.ordered();
|
||||
@@ -115,15 +151,18 @@ const blockedKeys = computed(() =>
|
||||
.map((item) => item.key),
|
||||
);
|
||||
const selection = useCollectionSelection({
|
||||
mode: () => props.selectionMode,
|
||||
controlled: () => controlled.value,
|
||||
value: () => (hasModel.value ? props.modelValue : props.selectedKeys),
|
||||
mode: () => mode.value,
|
||||
controlled: () => !!owner || controlled.value,
|
||||
value: () =>
|
||||
owner?.keys.value ??
|
||||
(hasModel.value ? props.modelValue : props.selectedKeys),
|
||||
defaultValue: props.defaultValue ?? props.defaultSelectedKeys,
|
||||
disabled: () => disabled.value,
|
||||
readOnly: () => props.isReadOnly,
|
||||
readOnly: () => readOnly.value,
|
||||
disabledKeys: () => blockedKeys.value,
|
||||
disallowEmptySelection: () => props.disallowEmptySelection,
|
||||
onChange: (keys) => {
|
||||
owner?.request(keys);
|
||||
emit("update:modelValue", [...keys]);
|
||||
emit("selectionChange", [...keys]);
|
||||
},
|
||||
@@ -137,9 +176,8 @@ const active = computed(() => {
|
||||
const items = eligible();
|
||||
return (
|
||||
items.find((item) => item.key === lastFocused.value)?.key ??
|
||||
items.find(
|
||||
(item) => props.selectionMode !== "none" && selection.selected(item.key),
|
||||
)?.key ??
|
||||
items.find((item) => mode.value !== "none" && selection.selected(item.key))
|
||||
?.key ??
|
||||
items[0]?.key
|
||||
);
|
||||
});
|
||||
@@ -165,6 +203,7 @@ function restoreFocus() {
|
||||
let focusRequest = 0;
|
||||
let disposing = false;
|
||||
onBeforeUnmount(() => {
|
||||
disconnectOwner?.();
|
||||
disposing = true;
|
||||
focusRequest++;
|
||||
});
|
||||
@@ -203,22 +242,19 @@ function activate(key: ListBoxKey, event: MouseEvent | KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
disabled.value ||
|
||||
props.isReadOnly ||
|
||||
readOnly.value ||
|
||||
!item ||
|
||||
item.disabled
|
||||
)
|
||||
return;
|
||||
if (props.selectionMode === "multiple" && event.shiftKey) {
|
||||
if (mode.value === "multiple" && event.shiftKey) {
|
||||
anchor ??= selection.keys.value[0] ?? active.value ?? key;
|
||||
selectRange(anchor, key);
|
||||
} else if (
|
||||
props.selectionBehavior === "replace" &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey
|
||||
)
|
||||
} else if (behavior.value === "replace" && !event.ctrlKey && !event.metaKey)
|
||||
selection.replace(key);
|
||||
else selection.toggle(key);
|
||||
if (!event.shiftKey) anchor = key;
|
||||
owner?.action(key);
|
||||
emit("action", key);
|
||||
}
|
||||
function selectRange(startKey: ListBoxKey, endKey: ListBoxKey) {
|
||||
@@ -245,13 +281,23 @@ function keydown(event: KeyboardEvent) {
|
||||
(event.target as Element).closest("[data-hv-listbox]") !== root.value
|
||||
)
|
||||
return;
|
||||
if (
|
||||
owner &&
|
||||
event.key === "Tab" &&
|
||||
!event.altKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey
|
||||
) {
|
||||
owner.leave();
|
||||
return;
|
||||
}
|
||||
keyboard.value = true;
|
||||
const items = eligible();
|
||||
if (!items.length) return;
|
||||
if (
|
||||
(event.ctrlKey || event.metaKey) &&
|
||||
event.key.toLowerCase() === "a" &&
|
||||
props.selectionMode === "multiple"
|
||||
mode.value === "multiple"
|
||||
) {
|
||||
event.preventDefault();
|
||||
selection.selectAll(items.map((item) => item.key));
|
||||
@@ -296,11 +342,11 @@ function keydown(event: KeyboardEvent) {
|
||||
? (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") {
|
||||
if (event.shiftKey && mode.value === "multiple") {
|
||||
anchor ??= active.value;
|
||||
if (anchor !== undefined) selectRange(anchor, key);
|
||||
} else if (
|
||||
props.selectionBehavior === "replace" &&
|
||||
behavior.value === "replace" &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey
|
||||
) {
|
||||
@@ -318,7 +364,7 @@ function keydown(event: KeyboardEvent) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (props.isReadOnly) {
|
||||
if (readOnly.value) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
@@ -380,8 +426,8 @@ 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),
|
||||
mode: computed(() => mode.value),
|
||||
readOnly: computed(() => readOnly.value),
|
||||
keyboard,
|
||||
focused,
|
||||
noteFocus: (key) => {
|
||||
@@ -390,7 +436,7 @@ provide(listBoxKey, {
|
||||
},
|
||||
pressed,
|
||||
active,
|
||||
selected: (key) => props.selectionMode !== "none" && selection.selected(key),
|
||||
selected: (key) => mode.value !== "none" && selection.selected(key),
|
||||
disabled: keyDisabled,
|
||||
register: registry.register,
|
||||
activate,
|
||||
@@ -406,7 +452,7 @@ provide(listBoxKey, {
|
||||
: undefined,
|
||||
});
|
||||
function rootAttrs() {
|
||||
if (props.selectionMode === "single" && selection.keys.value.length > 1)
|
||||
if (mode.value === "single" && selection.keys.value.length > 1)
|
||||
throw new TypeError("Single ListBox accepts at most one selected key.");
|
||||
if (
|
||||
props.virtualized &&
|
||||
@@ -418,6 +464,13 @@ function rootAttrs() {
|
||||
// Force duplicate validation even when a scoped item renderer is absent.
|
||||
void data.value;
|
||||
return mergeProps(attrs, {
|
||||
id: owner?.id ?? attrs.id,
|
||||
"aria-label": attrs["aria-label"] ?? owner?.ariaLabel(),
|
||||
"aria-labelledby":
|
||||
attrs["aria-labelledby"] ??
|
||||
((attrs["aria-label"] ?? owner?.ariaLabel())
|
||||
? undefined
|
||||
: owner?.labelledBy()),
|
||||
class: listboxVariants({ variant: props.variant }),
|
||||
role: "listbox",
|
||||
dir: dir.value,
|
||||
@@ -425,12 +478,10 @@ function rootAttrs() {
|
||||
"data-hv-listbox": "",
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"aria-disabled": disabled.value || undefined,
|
||||
"aria-readonly": props.isReadOnly || undefined,
|
||||
"aria-readonly": readOnly.value || undefined,
|
||||
"aria-orientation": props.orientation,
|
||||
"aria-multiselectable":
|
||||
props.selectionMode === "none"
|
||||
? undefined
|
||||
: props.selectionMode === "multiple",
|
||||
mode.value === "none" ? undefined : mode.value === "multiple",
|
||||
tabindex:
|
||||
disabled.value ||
|
||||
(mounted.value &&
|
||||
|
||||
@@ -108,7 +108,7 @@ function escape(event: KeyboardEvent) {
|
||||
:side-flip="shouldFlip"
|
||||
:collision-padding="containerPadding"
|
||||
class="hv-popover"
|
||||
data-slot="popover-content"
|
||||
:data-slot="$attrs['data-slot'] ?? 'popover-content'"
|
||||
:data-entering="entering || undefined"
|
||||
:data-exiting="exiting || undefined"
|
||||
:lang="($attrs.lang as string | undefined) ?? config?.locale.value"
|
||||
@@ -123,6 +123,7 @@ function escape(event: KeyboardEvent) {
|
||||
<component
|
||||
:is="as"
|
||||
ref="contentElement"
|
||||
:role="($attrs.role as string | undefined) ?? 'dialog'"
|
||||
:aria-label="
|
||||
($attrs['aria-label'] as string | undefined) ??
|
||||
(ctx.dialogAttrs.value['aria-label'] as string | undefined)
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
getCurrentInstance,
|
||||
h,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type SlotsType,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { selectVariants } from "@heroui-vue/styles";
|
||||
import Popover from "../popover/Popover";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import {
|
||||
useChoiceField,
|
||||
useChoiceForm,
|
||||
useChoiceValue,
|
||||
validationInput,
|
||||
} from "../choice/shared";
|
||||
import { disabledContextKey } from "../field/disabled";
|
||||
import type { ValidationBehavior, ValidateResult } from "../field/context";
|
||||
import {
|
||||
assertKey,
|
||||
copyKeys,
|
||||
encodeKey,
|
||||
type CollectionKey,
|
||||
} from "../collection/keys";
|
||||
import {
|
||||
collectionOwnerKey,
|
||||
type CollectionRecord,
|
||||
type OwnedCollection,
|
||||
} from "../collection/owner";
|
||||
import { planSelectItems } from "./metadata";
|
||||
import { selectKey, type SelectValue, type SelectItem } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "Select",
|
||||
inheritAttrs: false,
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: {
|
||||
value: SelectValue;
|
||||
isOpen: boolean;
|
||||
selectedItems: { key: CollectionKey; textValue: string }[];
|
||||
}) => VNodeChild;
|
||||
}>,
|
||||
props: {
|
||||
modelValue: {
|
||||
type: [String, Number, Array, null] as PropType<SelectValue>,
|
||||
default: undefined,
|
||||
},
|
||||
value: {
|
||||
type: [String, Number, Array, null] as PropType<SelectValue>,
|
||||
default: undefined,
|
||||
},
|
||||
defaultValue: [String, Number, Array, null] as PropType<SelectValue>,
|
||||
selectionMode: {
|
||||
type: String as PropType<"single" | "multiple">,
|
||||
default: "single",
|
||||
},
|
||||
disabledKeys: Array as PropType<readonly CollectionKey[]>,
|
||||
items: Array as PropType<readonly SelectItem[]>,
|
||||
open: { type: Boolean, default: undefined },
|
||||
isOpen: { type: Boolean, default: undefined },
|
||||
defaultOpen: Boolean,
|
||||
placeholder: { type: String, default: "Select an item" },
|
||||
autoComplete: String,
|
||||
fullWidth: Boolean,
|
||||
variant: {
|
||||
type: String as PropType<"primary" | "secondary">,
|
||||
default: "primary",
|
||||
},
|
||||
as: { type: String, default: "div" },
|
||||
id: String,
|
||||
name: String,
|
||||
form: String,
|
||||
isDisabled: Boolean,
|
||||
disabled: Boolean,
|
||||
isReadOnly: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
validate: Function as PropType<(value: SelectValue) => ValidateResult>,
|
||||
},
|
||||
emits: {
|
||||
"update:modelValue": (_value: SelectValue) => true,
|
||||
change: (_value: SelectValue) => true,
|
||||
"update:open": (_value: boolean) => true,
|
||||
openChange: (_value: boolean) => true,
|
||||
clear: () => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const instance = getCurrentInstance()!;
|
||||
const config = useConfig();
|
||||
const hasModel = () =>
|
||||
["modelValue", "model-value"].some((key) =>
|
||||
Object.hasOwn(instance.vnode.props ?? {}, key),
|
||||
);
|
||||
const model = useChoiceValue<SelectValue | undefined>(
|
||||
() => (hasModel() ? props.modelValue : props.value),
|
||||
() =>
|
||||
props.defaultValue ?? (props.selectionMode === "multiple" ? [] : null),
|
||||
["modelValue", "model-value", "value"],
|
||||
(value) => {
|
||||
const next = value ?? (props.selectionMode === "multiple" ? [] : null);
|
||||
emit("update:modelValue", next);
|
||||
emit("change", next);
|
||||
},
|
||||
);
|
||||
const value = computed<SelectValue>(() => {
|
||||
const raw = model.value.value;
|
||||
const controlled = ["modelValue", "model-value", "value"].some((key) =>
|
||||
Object.hasOwn(instance.vnode.props ?? {}, key),
|
||||
);
|
||||
if (controlled)
|
||||
return raw ?? (props.selectionMode === "multiple" ? [] : null);
|
||||
// Uncontrolled mode changes adapt the accepted value's public shape,
|
||||
// without emitting an edit or mutating the captured reset baseline.
|
||||
if (props.selectionMode === "multiple")
|
||||
return raw == null ? [] : Array.isArray(raw) ? raw : [raw];
|
||||
return Array.isArray(raw) ? (raw[0] ?? null) : (raw ?? null);
|
||||
});
|
||||
const keys = computed(() => {
|
||||
const raw = value.value;
|
||||
if (
|
||||
props.selectionMode === "multiple" &&
|
||||
raw !== null &&
|
||||
!Array.isArray(raw)
|
||||
)
|
||||
throw new TypeError("Multiple Select expects a key array.");
|
||||
const keys = copyKeys(
|
||||
raw === null ? [] : Array.isArray(raw) ? raw : [raw],
|
||||
);
|
||||
if (props.selectionMode === "single" && keys.length > 1)
|
||||
throw new TypeError("Single Select expects one key or null.");
|
||||
return Object.freeze(keys);
|
||||
});
|
||||
const planned = shallowRef<CollectionRecord[]>([]),
|
||||
discovered = shallowRef<CollectionRecord[]>([]);
|
||||
const collection = shallowRef<OwnedCollection>();
|
||||
const plannedComplete = ref(false);
|
||||
const records = computed(() => {
|
||||
const explicit = new Set<CollectionKey>();
|
||||
const result = new Map(
|
||||
(props.items || plannedComplete.value ? [] : discovered.value).map(
|
||||
(record) => [record.key, record],
|
||||
),
|
||||
);
|
||||
if (!props.items)
|
||||
planned.value.forEach((record) => result.set(record.key, record));
|
||||
props.items?.forEach((item) => {
|
||||
assertKey(item.id);
|
||||
if (explicit.has(item.id))
|
||||
throw new Error(`Duplicate collection key: ${item.id}`);
|
||||
explicit.add(item.id);
|
||||
result.set(item.id, {
|
||||
key: item.id,
|
||||
text: item.textValue,
|
||||
disabled:
|
||||
!!item.isDisabled ||
|
||||
!!planned.value.find((record) => record.key === item.id)?.disabled,
|
||||
});
|
||||
});
|
||||
return [...result.values()].map((record) => ({
|
||||
...record,
|
||||
disabled: record.disabled || !!props.disabledKeys?.includes(record.key),
|
||||
}));
|
||||
});
|
||||
watchEffect(() => {
|
||||
if (!collection.value) return;
|
||||
const next = collection.value.items();
|
||||
if (JSON.stringify(next) !== JSON.stringify(discovered.value))
|
||||
discovered.value = next;
|
||||
});
|
||||
const successful = computed(() =>
|
||||
keys.value.filter((key) =>
|
||||
records.value.some((record) => record.key === key && !record.disabled),
|
||||
),
|
||||
);
|
||||
const field = useChoiceField(props, attrs, {
|
||||
kind: "group",
|
||||
value,
|
||||
validate: (value) => props.validate?.(value),
|
||||
satisfied: () => successful.value.length > 0,
|
||||
requiredMessage: "请选择一个选项。",
|
||||
});
|
||||
provide(disabledContextKey, field.field.disabled);
|
||||
const nativeSelect = ref<HTMLSelectElement>();
|
||||
function restoreNative() {
|
||||
if (!nativeSelect.value) return;
|
||||
[...nativeSelect.value.options].forEach((option) => {
|
||||
const key = records.value[Number(option.dataset.index)]?.key;
|
||||
option.selected =
|
||||
option.dataset.index === undefined
|
||||
? !successful.value.length
|
||||
: key !== undefined && successful.value.includes(key);
|
||||
});
|
||||
}
|
||||
const trigger = ref<HTMLElement>(),
|
||||
proxy = ref<HTMLInputElement>();
|
||||
const openModel = useChoiceValue<boolean | undefined>(
|
||||
() =>
|
||||
Object.hasOwn(instance.vnode.props ?? {}, "open")
|
||||
? props.open
|
||||
: props.isOpen,
|
||||
() => props.defaultOpen,
|
||||
["open", "isOpen", "is-open"],
|
||||
(open) => {
|
||||
emit("update:open", !!open);
|
||||
emit("openChange", !!open);
|
||||
},
|
||||
);
|
||||
const open = computed(() => !!openModel.value.value);
|
||||
const slotsMap = computed(() =>
|
||||
selectVariants({ variant: props.variant, fullWidth: props.fullWidth }),
|
||||
);
|
||||
const listId = `${field.field.controlId.value}-listbox`,
|
||||
valueId = `${field.field.controlId.value}-value`;
|
||||
const clearCount = ref(0),
|
||||
intent = ref<"first" | "last" | "selected">("selected");
|
||||
function setOpen(next: boolean) {
|
||||
if (next && (field.field.disabled.value || field.field.readOnly.value))
|
||||
return;
|
||||
if (next !== open.value) openModel.request(next);
|
||||
}
|
||||
function request(next: CollectionKey[]) {
|
||||
if (field.field.disabled.value || field.field.readOnly.value) return;
|
||||
if (
|
||||
next.some(
|
||||
(key) =>
|
||||
records.value.find((record) => record.key === key)?.disabled &&
|
||||
!keys.value.includes(key),
|
||||
)
|
||||
)
|
||||
return;
|
||||
if (
|
||||
next.length === keys.value.length &&
|
||||
next.every((key) => keys.value.includes(key))
|
||||
)
|
||||
return;
|
||||
field.edit();
|
||||
model.request(
|
||||
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
|
||||
);
|
||||
}
|
||||
let query = "",
|
||||
lastSearch = 0;
|
||||
function search(character: string) {
|
||||
const now = Date.now();
|
||||
query = now - lastSearch > 1000 ? character : query + character;
|
||||
lastSearch = now;
|
||||
const needle = [...query].every((c) => c === query[0]) ? query[0] : query;
|
||||
const available = records.value.filter((record) => !record.disabled);
|
||||
const index = available.findIndex((record) =>
|
||||
keys.value.includes(record.key),
|
||||
);
|
||||
const ordered =
|
||||
needle.length > 1 && index >= 0
|
||||
? [...available.slice(index), ...available.slice(0, index)]
|
||||
: [...available.slice(index + 1), ...available.slice(0, index + 1)];
|
||||
const collator = new Intl.Collator(config?.locale.value, {
|
||||
usage: "search",
|
||||
sensitivity: "base",
|
||||
});
|
||||
const match = ordered.find(
|
||||
(record) =>
|
||||
collator.compare(record.text.slice(0, needle.length), needle) === 0,
|
||||
);
|
||||
if (match)
|
||||
request(
|
||||
props.selectionMode === "multiple"
|
||||
? [...new Set([...keys.value, match.key])]
|
||||
: [match.key],
|
||||
);
|
||||
}
|
||||
async function focusCollection() {
|
||||
await nextTick();
|
||||
if (open.value) await collection.value?.focus(intent.value);
|
||||
}
|
||||
provide(collectionOwnerKey, {
|
||||
keys,
|
||||
mode: computed(() => props.selectionMode),
|
||||
disabled: field.field.disabled,
|
||||
readOnly: field.field.readOnly,
|
||||
disabledKeys: computed(() => [
|
||||
...(props.disabledKeys ?? []),
|
||||
...(props.items
|
||||
?.filter((item) => item.isDisabled)
|
||||
.map((item) => item.id) ?? []),
|
||||
]),
|
||||
id: listId,
|
||||
ariaLabel: () => attrs["aria-label"] as string | undefined,
|
||||
labelledBy: () =>
|
||||
field.labelledBy() ??
|
||||
(attrs["aria-label"] ? undefined : trigger.value?.id),
|
||||
request,
|
||||
leave: () => {
|
||||
// Move the native Tab starting point back to the trigger before default
|
||||
// traversal, avoiding Popover FocusScope's loop and Teleport DOM order.
|
||||
trigger.value?.focus({ preventScroll: true });
|
||||
setOpen(false);
|
||||
},
|
||||
action: () => {
|
||||
if (props.selectionMode === "single") setOpen(false);
|
||||
},
|
||||
connect: (next) => {
|
||||
if (collection.value && collection.value !== next)
|
||||
throw new Error("Select supports one ListBox.");
|
||||
collection.value = next;
|
||||
return () => {
|
||||
if (collection.value === next) collection.value = undefined;
|
||||
};
|
||||
},
|
||||
});
|
||||
provide(selectKey, {
|
||||
field,
|
||||
slots: slotsMap,
|
||||
keys,
|
||||
records,
|
||||
open,
|
||||
setOpen,
|
||||
trigger,
|
||||
valueId,
|
||||
listId,
|
||||
collection,
|
||||
intent,
|
||||
focusCollection,
|
||||
placeholder: () => props.placeholder,
|
||||
ariaLabel: () => attrs["aria-label"] as string | undefined,
|
||||
selectedItems: computed(() =>
|
||||
keys.value.map((key) => ({
|
||||
key,
|
||||
textValue:
|
||||
records.value.find((record) => record.key === key)?.text ??
|
||||
String(key),
|
||||
})),
|
||||
),
|
||||
clearCount,
|
||||
search,
|
||||
registerClear: () => {
|
||||
clearCount.value++;
|
||||
let active = true;
|
||||
return () => {
|
||||
if (active) {
|
||||
active = false;
|
||||
clearCount.value--;
|
||||
}
|
||||
};
|
||||
},
|
||||
clear: () => {
|
||||
if (
|
||||
keys.value.length &&
|
||||
!field.field.disabled.value &&
|
||||
!field.field.readOnly.value
|
||||
) {
|
||||
request([]);
|
||||
emit("clear");
|
||||
}
|
||||
},
|
||||
});
|
||||
useChoiceForm(
|
||||
proxy,
|
||||
() => {
|
||||
model.reset();
|
||||
field.reset();
|
||||
setOpen(false);
|
||||
},
|
||||
() => {
|
||||
field.validity(proxy.value);
|
||||
void nextTick(restoreNative);
|
||||
},
|
||||
);
|
||||
watchEffect(() => {
|
||||
field.validity(proxy.value);
|
||||
});
|
||||
expose({
|
||||
element: trigger,
|
||||
focus: () => trigger.value?.focus(),
|
||||
open: () => setOpen(true),
|
||||
close: () => setOpen(false),
|
||||
});
|
||||
return () => {
|
||||
const rendered = slots.default?.({
|
||||
isOpen: open.value,
|
||||
value: value.value,
|
||||
selectedItems: keys.value.map((key) => ({
|
||||
key,
|
||||
textValue:
|
||||
records.value.find((item) => item.key === key)?.text ?? String(key),
|
||||
})),
|
||||
});
|
||||
const children = Array.isArray(rendered)
|
||||
? rendered
|
||||
: rendered == null
|
||||
? []
|
||||
: [rendered];
|
||||
const plan = planSelectItems(children);
|
||||
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
|
||||
planned.value = plan.records;
|
||||
plannedComplete.value = plan.complete;
|
||||
// Touch keys now: reject malformed models during SSR as well as on edit.
|
||||
void keys.value;
|
||||
const nodes = field.prepare(children, true);
|
||||
return h(
|
||||
Popover,
|
||||
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
props.as,
|
||||
mergeProps(attrs, {
|
||||
class: slotsMap.value.base(),
|
||||
"data-slot": "select",
|
||||
"data-invalid": field.field.invalid.value || undefined,
|
||||
"data-disabled": field.field.disabled.value || undefined,
|
||||
onClick: (event: MouseEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const label = (event.target as Element).closest?.(
|
||||
'[data-slot="label"]',
|
||||
);
|
||||
if (
|
||||
label?.id &&
|
||||
field.labelledBy()?.split(" ").includes(label.id)
|
||||
)
|
||||
trigger.value?.focus();
|
||||
},
|
||||
}),
|
||||
[
|
||||
...nodes,
|
||||
validationInput(
|
||||
proxy,
|
||||
props,
|
||||
field.field.disabled.value || field.field.readOnly.value,
|
||||
field.behavior.value,
|
||||
(event) =>
|
||||
field.invalidEvent(event, () => trigger.value?.focus()),
|
||||
props.isRequired && field.behavior.value === "native",
|
||||
successful.value.length > 0,
|
||||
),
|
||||
h(
|
||||
"select",
|
||||
{
|
||||
ref: nativeSelect,
|
||||
id: `${field.field.controlId.value}-native`,
|
||||
class: "hv-choice-input",
|
||||
"aria-hidden": "true",
|
||||
tabindex: -1,
|
||||
name: successful.value.length ? props.name : undefined,
|
||||
form: props.form,
|
||||
multiple: props.selectionMode === "multiple",
|
||||
autocomplete: props.autoComplete,
|
||||
disabled: field.field.disabled.value,
|
||||
onChange: (event: Event) => {
|
||||
const element = event.currentTarget as HTMLSelectElement;
|
||||
const next = [...element.selectedOptions]
|
||||
.filter((option) => !option.disabled)
|
||||
.map(
|
||||
(option) =>
|
||||
records.value[Number(option.dataset.index)]?.key,
|
||||
)
|
||||
.filter(
|
||||
(key): key is CollectionKey => key !== undefined,
|
||||
);
|
||||
request(next);
|
||||
// Autofill is a proposal too: restore the parent's accepted value.
|
||||
void nextTick(restoreNative);
|
||||
},
|
||||
},
|
||||
[
|
||||
...(props.selectionMode === "single"
|
||||
? [
|
||||
h(
|
||||
"option",
|
||||
{
|
||||
value: "",
|
||||
disabled: true,
|
||||
selected: !successful.value.length,
|
||||
},
|
||||
props.placeholder,
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...records.value.map((record, index) =>
|
||||
h(
|
||||
"option",
|
||||
{
|
||||
key: encodeKey(record.key),
|
||||
value: String(record.key),
|
||||
"data-index": index,
|
||||
disabled: record.disabled,
|
||||
selected: successful.value.includes(record.key),
|
||||
},
|
||||
record.text,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,51 @@
|
||||
<script setup lang="ts">
|
||||
import { inject, mergeProps, onScopeDispose, useAttrs } from "vue";
|
||||
import { selectTriggerDisabledKey, useSelect } from "./context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
withDefaults(defineProps<{ as?: string }>(), { as: "span" });
|
||||
const ctx = useSelect(),
|
||||
attrs = useAttrs();
|
||||
const disabled = inject(selectTriggerDisabledKey, ctx.field.field.disabled);
|
||||
onScopeDispose(ctx.registerClear());
|
||||
function click(event: MouseEvent) {
|
||||
// Always isolate this pointer-only affordance from its enclosing trigger.
|
||||
event.stopPropagation();
|
||||
if (!event.defaultPrevented && event.button === 0 && !disabled.value)
|
||||
ctx.clear();
|
||||
event.preventDefault();
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<component
|
||||
:is="as"
|
||||
v-bind="
|
||||
mergeProps(attrs, {
|
||||
onClick: click,
|
||||
onPointerdown: (event: PointerEvent) => event.stopPropagation(),
|
||||
})
|
||||
"
|
||||
:class="[ctx.slots.value.clearButton(), attrs.class]"
|
||||
aria-hidden="true"
|
||||
data-slot="select-clear-button"
|
||||
:data-empty="!ctx.keys.value.length || undefined"
|
||||
>
|
||||
<slot>
|
||||
<svg
|
||||
fill="none"
|
||||
width="16"
|
||||
height="16"
|
||||
role="presentation"
|
||||
viewBox="0 0 16 16"
|
||||
aria-hidden="true"
|
||||
data-slot="select-clear-button-icon"
|
||||
>
|
||||
<path
|
||||
d="M3.47 3.47a.75.75 0 0 1 1.06 0L8 6.94l3.47-3.47a.75.75 0 1 1 1.06 1.06L9.06 8l3.47 3.47a.75.75 0 1 1-1.06 1.06L8 9.06l-3.47 3.47a.75.75 0 0 1-1.06-1.06L6.94 8 3.47 4.53a.75.75 0 0 1 0-1.06Z"
|
||||
fill="currentColor"
|
||||
fill-rule="evenodd"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</slot>
|
||||
</component>
|
||||
</template>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script lang="ts">
|
||||
import { cloneVNode, defineComponent, h, mergeProps } from "vue";
|
||||
import { useSelect } from "./context";
|
||||
import { overlayNodes } from "../overlay/OverlayAction";
|
||||
// Default icon adapted from HeroUI ce90ea3 icons.tsx (Apache-2.0).
|
||||
export default defineComponent({
|
||||
name: "SelectIndicator",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useSelect();
|
||||
return () => {
|
||||
const children = overlayNodes(slots.default?.());
|
||||
const props = mergeProps(attrs, {
|
||||
class: ctx.slots.value.indicator(),
|
||||
"data-open": ctx.open.value || undefined,
|
||||
"aria-hidden": "true",
|
||||
});
|
||||
if (children.length === 1)
|
||||
return cloneVNode(children[0], {
|
||||
...props,
|
||||
"data-slot": "select-indicator",
|
||||
});
|
||||
return h(
|
||||
"svg",
|
||||
{
|
||||
...props,
|
||||
"data-slot": "select-default-indicator",
|
||||
fill: "none",
|
||||
height: 16,
|
||||
width: 16,
|
||||
role: "presentation",
|
||||
viewBox: "0 0 16 16",
|
||||
},
|
||||
[
|
||||
h("path", {
|
||||
d: "M2.97 5.47a.75.75 0 0 1 1.06 0L8 9.44l3.97-3.97a.75.75 0 1 1 1.06 1.06l-4.5 4.5a.75.75 0 0 1-1.06 0l-4.5-4.5a.75.75 0 0 1 0-1.06",
|
||||
fill: "currentColor",
|
||||
"fill-rule": "evenodd",
|
||||
"clip-rule": "evenodd",
|
||||
}),
|
||||
],
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,91 @@
|
||||
<script setup lang="ts">
|
||||
import { mergeProps, nextTick, onBeforeUnmount, useAttrs } from "vue";
|
||||
import PopoverContent from "../popover/PopoverContent.vue";
|
||||
import { useSelect } from "./context";
|
||||
import type { OverlayPlacement } from "../overlay/placement";
|
||||
defineOptions({ name: "SelectPopover", inheritAttrs: false });
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
placement?: OverlayPlacement;
|
||||
offset?: number;
|
||||
to?: string | HTMLElement;
|
||||
shouldFlip?: boolean;
|
||||
containerPadding?: number;
|
||||
}>(),
|
||||
{ placement: "bottom", offset: 8, shouldFlip: true, containerPadding: 12 },
|
||||
);
|
||||
const ctx = useSelect(),
|
||||
attrs = useAttrs();
|
||||
let frame: number | undefined;
|
||||
let allowScroll = false;
|
||||
let disposed = false;
|
||||
function revealFocused(event?: AnimationEvent) {
|
||||
if (event && event.target !== event.currentTarget) return;
|
||||
const element = event?.currentTarget as HTMLElement | undefined;
|
||||
const active = ctx.trigger.value?.ownerDocument
|
||||
.activeElement as HTMLElement | null;
|
||||
if (
|
||||
allowScroll &&
|
||||
ctx.open.value &&
|
||||
active?.dataset.slot === "list-box-item" &&
|
||||
active.closest('[role="listbox"]')?.id === ctx.listId &&
|
||||
(!element || element.contains(active))
|
||||
)
|
||||
active.scrollIntoView?.({ block: "nearest", inline: "nearest" });
|
||||
}
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true;
|
||||
if (frame !== undefined) cancelAnimationFrame(frame);
|
||||
});
|
||||
function openFocus(event: Event) {
|
||||
if (frame !== undefined) {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = undefined;
|
||||
}
|
||||
allowScroll = false;
|
||||
if (!event.defaultPrevented) {
|
||||
event.preventDefault();
|
||||
allowScroll = true;
|
||||
void ctx.focusCollection();
|
||||
// Floating positioning finishes after mount autofocus. Reveal the accepted
|
||||
// focus after layout too, including the reduced-motion path with no event.
|
||||
void nextTick(() => {
|
||||
if (!disposed && typeof requestAnimationFrame !== "undefined")
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined;
|
||||
revealFocused();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<PopoverContent
|
||||
:placement="placement"
|
||||
:offset="offset"
|
||||
:to="to"
|
||||
:should-flip="shouldFlip"
|
||||
:container-padding="containerPadding"
|
||||
v-bind="
|
||||
mergeProps(attrs, {
|
||||
onOpenAutoFocus: openFocus,
|
||||
onAnimationstart: revealFocused,
|
||||
})
|
||||
"
|
||||
:id="`${ctx.listId}-popover`"
|
||||
role="presentation"
|
||||
:class="[ctx.slots.value.popover(), attrs.class]"
|
||||
data-slot="select-popover"
|
||||
:aria-labelledby="
|
||||
ctx.field.labelledBy() ??
|
||||
ctx.trigger.value?.id ??
|
||||
ctx.field.field.controlId.value
|
||||
"
|
||||
:style="{
|
||||
'--trigger-width': 'var(--reka-popover-trigger-width)',
|
||||
'--trigger-anchor-point': 'var(--reka-popper-transform-origin)',
|
||||
}"
|
||||
>
|
||||
<slot />
|
||||
</PopoverContent>
|
||||
</template>
|
||||
@@ -0,0 +1,158 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
h,
|
||||
mergeProps,
|
||||
provide,
|
||||
ref,
|
||||
watch,
|
||||
} from "vue";
|
||||
import { PopoverAnchor, injectPopoverRootContext } from "reka-ui";
|
||||
import OverlayAction from "../overlay/OverlayAction";
|
||||
import { usePopover } from "../popover/context";
|
||||
import { mergeIds } from "../field/context";
|
||||
import { selectTriggerDisabledKey, useSelect } from "./context";
|
||||
export default defineComponent({
|
||||
name: "SelectTrigger",
|
||||
inheritAttrs: false,
|
||||
props: { as: { type: String, default: "button" }, isDisabled: Boolean },
|
||||
setup(props, { attrs, slots, expose }) {
|
||||
const ctx = useSelect();
|
||||
const popup = usePopover(),
|
||||
root = injectPopoverRootContext();
|
||||
watch(
|
||||
ctx.trigger,
|
||||
(element) => {
|
||||
root.triggerElement.value = element;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
root.triggerId = ctx.field.field.controlId.value;
|
||||
const disabled = computed(
|
||||
() =>
|
||||
props.isDisabled ||
|
||||
ctx.field.field.disabled.value ||
|
||||
attrs.disabled === true ||
|
||||
attrs.disabled === "",
|
||||
);
|
||||
provide(selectTriggerDisabledKey, disabled);
|
||||
const focused = ref(false),
|
||||
keyboard = ref(true);
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
event.keyCode === 229 ||
|
||||
disabled.value
|
||||
)
|
||||
return;
|
||||
keyboard.value = true;
|
||||
if (
|
||||
!ctx.open.value &&
|
||||
["Backspace", "Delete"].includes(event.key) &&
|
||||
ctx.clearCount.value &&
|
||||
ctx.keys.value.length
|
||||
) {
|
||||
event.preventDefault();
|
||||
ctx.clear();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!ctx.open.value &&
|
||||
event.key.length === 1 &&
|
||||
event.key !== " " &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.altKey
|
||||
) {
|
||||
event.preventDefault();
|
||||
ctx.search(event.key);
|
||||
return;
|
||||
}
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
ctx.intent.value = ctx.keys.value.length
|
||||
? "selected"
|
||||
: event.key === "ArrowUp"
|
||||
? "last"
|
||||
: "first";
|
||||
if (ctx.open.value) void ctx.focusCollection();
|
||||
else ctx.setOpen(true);
|
||||
}
|
||||
}
|
||||
expose({ focus: () => ctx.trigger.value?.focus(), element: ctx.trigger });
|
||||
return () =>
|
||||
h(
|
||||
PopoverAnchor,
|
||||
{ asChild: true },
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
OverlayAction,
|
||||
{
|
||||
asChild: true,
|
||||
isDisabled: disabled.value,
|
||||
activate: popup.state.toggle,
|
||||
},
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
props.as,
|
||||
mergeProps(attrs, {
|
||||
ref: ctx.trigger,
|
||||
id: attrs.id ?? ctx.field.field.controlId.value,
|
||||
type:
|
||||
props.as === "button"
|
||||
? (attrs.type ?? "button")
|
||||
: undefined,
|
||||
role: "combobox",
|
||||
"aria-haspopup": "listbox",
|
||||
"aria-expanded": ctx.open.value,
|
||||
"aria-controls": ctx.open.value ? ctx.listId : undefined,
|
||||
"aria-required":
|
||||
ctx.field.field.required.value || undefined,
|
||||
"aria-invalid":
|
||||
ctx.field.field.invalid.value || undefined,
|
||||
"aria-disabled": disabled.value || undefined,
|
||||
"aria-label": attrs["aria-label"] ?? ctx.ariaLabel(),
|
||||
"aria-labelledby":
|
||||
attrs["aria-labelledby"] ??
|
||||
((attrs["aria-label"] ?? ctx.ariaLabel())
|
||||
? undefined
|
||||
: mergeIds(ctx.field.labelledBy(), ctx.valueId)),
|
||||
"aria-describedby": mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
ctx.field.describedBy(),
|
||||
),
|
||||
disabled: disabled.value || undefined,
|
||||
class: ctx.slots.value.trigger(),
|
||||
"data-slot": "select-trigger",
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"data-focused": focused.value || undefined,
|
||||
"data-focus-visible":
|
||||
(focused.value &&
|
||||
(keyboard.value ||
|
||||
ctx.trigger.value?.matches(":focus-visible"))) ||
|
||||
undefined,
|
||||
onKeydown: keydown,
|
||||
onPointerdown: () => {
|
||||
keyboard.value = false;
|
||||
ctx.intent.value = "selected";
|
||||
},
|
||||
onFocus: () => {
|
||||
focused.value = true;
|
||||
},
|
||||
onBlur: () => {
|
||||
focused.value = false;
|
||||
},
|
||||
}),
|
||||
slots.default?.(),
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,40 @@
|
||||
<script setup lang="ts">
|
||||
import { useSelect, type SelectSelectedItem } from "./context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
withDefaults(defineProps<{ as?: string }>(), { as: "span" });
|
||||
defineSlots<{
|
||||
default?: (state: {
|
||||
defaultChildren: string;
|
||||
isPlaceholder: boolean;
|
||||
selectedItems: SelectSelectedItem[];
|
||||
state: { selectedItems: SelectSelectedItem[]; isOpen: boolean };
|
||||
}) => unknown;
|
||||
}>();
|
||||
const ctx = useSelect();
|
||||
const valueText = () =>
|
||||
ctx.keys.value.length
|
||||
? ctx.selectedItems.value.map((item) => item.textValue).join(", ")
|
||||
: ctx.placeholder();
|
||||
</script>
|
||||
<template>
|
||||
<component
|
||||
:is="as"
|
||||
v-bind="$attrs"
|
||||
:id="ctx.valueId"
|
||||
:class="[ctx.slots.value.value(), $attrs.class]"
|
||||
data-slot="select-value"
|
||||
:data-placeholder="!ctx.keys.value.length || undefined"
|
||||
>
|
||||
<slot
|
||||
:default-children="valueText()"
|
||||
:is-placeholder="!ctx.keys.value.length"
|
||||
:selected-items="ctx.selectedItems.value"
|
||||
:state="{
|
||||
selectedItems: ctx.selectedItems.value,
|
||||
isOpen: ctx.open.value,
|
||||
}"
|
||||
>
|
||||
{{ valueText() }}
|
||||
</slot>
|
||||
</component>
|
||||
</template>
|
||||
@@ -0,0 +1,44 @@
|
||||
import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
|
||||
import type { CollectionKey } from "../collection/keys";
|
||||
import type { CollectionRecord, OwnedCollection } from "../collection/owner";
|
||||
import type { useChoiceField } from "../choice/shared";
|
||||
import type { selectVariants } from "@heroui-vue/styles";
|
||||
export type SelectValue = CollectionKey | CollectionKey[] | null;
|
||||
export interface SelectItem {
|
||||
id: CollectionKey;
|
||||
textValue: string;
|
||||
isDisabled?: boolean;
|
||||
}
|
||||
export interface SelectSelectedItem {
|
||||
key: CollectionKey;
|
||||
textValue: string;
|
||||
}
|
||||
export interface SelectContext {
|
||||
field: ReturnType<typeof useChoiceField<SelectValue>>;
|
||||
slots: ComputedRef<ReturnType<typeof selectVariants>>;
|
||||
keys: ComputedRef<readonly CollectionKey[]>;
|
||||
selectedItems: ComputedRef<SelectSelectedItem[]>;
|
||||
records: ComputedRef<CollectionRecord[]>;
|
||||
open: ComputedRef<boolean>;
|
||||
setOpen: (open: boolean) => void;
|
||||
trigger: Ref<HTMLElement | undefined>;
|
||||
valueId: string;
|
||||
listId: string;
|
||||
placeholder: () => string;
|
||||
ariaLabel: () => string | undefined;
|
||||
clearCount: Ref<number>;
|
||||
registerClear: () => () => void;
|
||||
clear: () => void;
|
||||
search: (key: string) => void;
|
||||
collection: Ref<OwnedCollection | undefined>;
|
||||
intent: Ref<"first" | "last" | "selected">;
|
||||
focusCollection: () => Promise<void>;
|
||||
}
|
||||
export const selectKey: InjectionKey<SelectContext> = Symbol("hv-select");
|
||||
export const selectTriggerDisabledKey: InjectionKey<ComputedRef<boolean>> =
|
||||
Symbol("hv-select-trigger-disabled");
|
||||
export function useSelect() {
|
||||
const context = inject(selectKey);
|
||||
if (!context) throw new Error("Select parts require Select.");
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Fragment, Text, isVNode, type VNode, type VNodeChild } from "vue";
|
||||
import { assertKey, type CollectionKey } from "../collection/keys";
|
||||
import type { CollectionRecord } from "../collection/owner";
|
||||
function name(node: VNode) {
|
||||
const type = node.type as { name?: string; __name?: string };
|
||||
return type.name ?? type.__name;
|
||||
}
|
||||
function children(node: VNode): VNodeChild[] {
|
||||
if (Array.isArray(node.children)) return node.children as VNodeChild[];
|
||||
if (node.children && typeof node.children === "object") {
|
||||
const result = (
|
||||
node.children as { default?: () => VNodeChild }
|
||||
).default?.();
|
||||
return Array.isArray(result) ? result : result == null ? [] : [result];
|
||||
}
|
||||
return typeof node.children === "string" ? [node.children] : [];
|
||||
}
|
||||
function text(nodes: VNodeChild[]): string {
|
||||
return nodes
|
||||
.map((node) => {
|
||||
if (typeof node === "string" || typeof node === "number")
|
||||
return String(node);
|
||||
if (Array.isArray(node)) return text(node);
|
||||
if (!isVNode(node)) return "";
|
||||
if (node.type === Text) return String(node.children);
|
||||
// Descriptions/icons and arbitrary components are not option name sources.
|
||||
if (
|
||||
node.type === Fragment ||
|
||||
typeof node.type === "string" ||
|
||||
name(node) === "Label"
|
||||
)
|
||||
return text(children(node));
|
||||
return "";
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
/** Inspect known collection slots only; never execute arbitrary setup/render. */
|
||||
export function planSelectItems(nodes: VNodeChild[]) {
|
||||
const records: CollectionRecord[] = [];
|
||||
let found = false,
|
||||
opaque = false;
|
||||
function add(record: CollectionRecord) {
|
||||
assertKey(record.key);
|
||||
if (records.some((item) => item.key === record.key))
|
||||
throw new Error(`Duplicate collection key: ${record.key}`);
|
||||
records.push(record);
|
||||
}
|
||||
function walk(
|
||||
nodes: VNodeChild[],
|
||||
inside = false,
|
||||
blocked: readonly CollectionKey[] = [],
|
||||
) {
|
||||
for (const node of nodes) {
|
||||
if (Array.isArray(node)) {
|
||||
walk(node, inside, blocked);
|
||||
continue;
|
||||
}
|
||||
if (!isVNode(node)) continue;
|
||||
const component = name(node);
|
||||
if (component === "ListBoxItem") {
|
||||
const key = node.props?.id;
|
||||
const disabled = node.props?.isDisabled ?? node.props?.["is-disabled"];
|
||||
add({
|
||||
key,
|
||||
text:
|
||||
node.props?.textValue ??
|
||||
node.props?.["text-value"] ??
|
||||
text(children(node)),
|
||||
disabled:
|
||||
disabled === true || disabled === "" || blocked.includes(key),
|
||||
});
|
||||
} else if (component === "ListBox") {
|
||||
found = true;
|
||||
const disabledKeys =
|
||||
node.props?.disabledKeys ?? node.props?.["disabled-keys"] ?? [];
|
||||
const keys = [...blocked, ...disabledKeys] as CollectionKey[];
|
||||
if (node.props?.items) {
|
||||
const slot = (
|
||||
node.children as { default?: (state: unknown) => VNodeChild[] }
|
||||
)?.default;
|
||||
const items = node.props.items as {
|
||||
id: CollectionKey;
|
||||
textValue?: string;
|
||||
isDisabled?: boolean;
|
||||
}[];
|
||||
items.forEach((item, index) => {
|
||||
const before = records.length;
|
||||
if (slot) {
|
||||
const rendered = slot({ item, index });
|
||||
walk(Array.isArray(rendered) ? rendered : [rendered], true, keys);
|
||||
}
|
||||
if (records.length === before)
|
||||
add({
|
||||
key: item.id,
|
||||
text: item.textValue ?? String(item.id),
|
||||
disabled: !!item.isDisabled || keys.includes(item.id),
|
||||
});
|
||||
else if (item.isDisabled)
|
||||
records.slice(before).forEach((record) => {
|
||||
record.disabled = true;
|
||||
});
|
||||
});
|
||||
} else walk(children(node), true, keys);
|
||||
} else if (
|
||||
node.type === Fragment ||
|
||||
typeof node.type === "string" ||
|
||||
["SelectPopover", "ListBoxSection"].includes(component ?? "")
|
||||
)
|
||||
walk(children(node), inside, blocked);
|
||||
else if (
|
||||
inside &&
|
||||
component &&
|
||||
!["Header", "Separator"].includes(component)
|
||||
)
|
||||
opaque = true;
|
||||
}
|
||||
}
|
||||
walk(nodes);
|
||||
return { records, complete: found && !opaque };
|
||||
}
|
||||
@@ -724,3 +724,28 @@ export type {
|
||||
DrawerCloseTriggerProps,
|
||||
DrawerCloseProps,
|
||||
} from "./types";
|
||||
|
||||
export {
|
||||
default as Select,
|
||||
default as SelectRoot,
|
||||
} from "./components/select/Select.vue";
|
||||
export { default as SelectTrigger } from "./components/select/SelectTrigger.vue";
|
||||
export { default as SelectValue } from "./components/select/SelectValue.vue";
|
||||
export { default as SelectIndicator } from "./components/select/SelectIndicator.vue";
|
||||
export { default as SelectClearButton } from "./components/select/SelectClearButton.vue";
|
||||
export { default as SelectPopover } from "./components/select/SelectPopover.vue";
|
||||
export type {
|
||||
SelectValue as SelectModelValue,
|
||||
SelectItem,
|
||||
SelectSelectedItem,
|
||||
} from "./components/select/context";
|
||||
export { selectVariants, type SelectVariants } from "@heroui-vue/styles";
|
||||
export type {
|
||||
SelectProps,
|
||||
SelectRootProps,
|
||||
SelectTriggerProps,
|
||||
SelectValueProps,
|
||||
SelectIndicatorProps,
|
||||
SelectClearButtonProps,
|
||||
SelectPopoverProps,
|
||||
} from "./types";
|
||||
|
||||
@@ -591,3 +591,28 @@ export type DrawerCloseTriggerProps = InstanceType<
|
||||
typeof DrawerCloseTrigger
|
||||
>["$props"];
|
||||
export type DrawerCloseProps = InstanceType<typeof DrawerClose>["$props"];
|
||||
|
||||
export type SelectProps = InstanceType<
|
||||
(typeof import("./components/select/Select.vue"))["default"]
|
||||
>["$props"];
|
||||
|
||||
export type SelectTriggerProps = InstanceType<
|
||||
(typeof import("./components/select/SelectTrigger.vue"))["default"]
|
||||
>["$props"];
|
||||
|
||||
export type SelectValueProps = InstanceType<
|
||||
(typeof import("./components/select/SelectValue.vue"))["default"]
|
||||
>["$props"];
|
||||
|
||||
export type SelectIndicatorProps = InstanceType<
|
||||
(typeof import("./components/select/SelectIndicator.vue"))["default"]
|
||||
>["$props"];
|
||||
|
||||
export type SelectClearButtonProps = InstanceType<
|
||||
(typeof import("./components/select/SelectClearButton.vue"))["default"]
|
||||
>["$props"];
|
||||
|
||||
export type SelectPopoverProps = InstanceType<
|
||||
(typeof import("./components/select/SelectPopover.vue"))["default"]
|
||||
>["$props"];
|
||||
export type SelectRootProps = SelectProps;
|
||||
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
Button,
|
||||
Modal,
|
||||
ModalTrigger,
|
||||
ModalBackdrop,
|
||||
ModalContainer,
|
||||
ModalDialog,
|
||||
ModalHeading,
|
||||
} from "@heroui-vue/components";
|
||||
const log = ref<string[]>([]);
|
||||
function record(event: AnimationEvent) {
|
||||
const element = event.target as HTMLElement;
|
||||
if (element.dataset.slot !== "select-popover") return;
|
||||
const style = getComputedStyle(element);
|
||||
log.value.push(
|
||||
JSON.stringify({
|
||||
event: event.type,
|
||||
name: event.animationName,
|
||||
elapsed: event.elapsedTime,
|
||||
entering: element.dataset.entering,
|
||||
exiting: element.dataset.exiting,
|
||||
duration: style.animationDuration,
|
||||
scale: style.getPropertyValue("--tw-enter-scale"),
|
||||
side: element.dataset.side,
|
||||
}),
|
||||
);
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-4 p-8">
|
||||
<Button>Before select</Button>
|
||||
<Select class="w-64" placeholder="Choose" default-value="12">
|
||||
<Label>Lifecycle select</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover @animationstart="record" @animationend="record">
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="index in 40"
|
||||
:id="String(index)"
|
||||
:key="index"
|
||||
:text-value="`Option ${index}`"
|
||||
>
|
||||
Option {{ index }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
<Button>After select</Button>
|
||||
<Modal>
|
||||
<ModalTrigger>Open parent</ModalTrigger>
|
||||
<ModalBackdrop>
|
||||
<ModalContainer>
|
||||
<ModalDialog>
|
||||
<ModalHeading>Parent</ModalHeading>
|
||||
<Select class="w-64">
|
||||
<Label>Nested select</Label>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
<SelectIndicator />
|
||||
</SelectTrigger>
|
||||
<SelectPopover>
|
||||
<ListBox><ListBoxItem id="one">One</ListBoxItem></ListBox>
|
||||
</SelectPopover>
|
||||
</Select>
|
||||
</ModalDialog>
|
||||
</ModalContainer>
|
||||
</ModalBackdrop>
|
||||
</Modal>
|
||||
<pre aria-label="Animation log">{{ log.join("\n") }}</pre>
|
||||
</div>
|
||||
</template>
|
||||
Generated
+3
@@ -56,6 +56,9 @@ importers:
|
||||
'@tabler/icons-vue':
|
||||
specifier: ^3.49.0
|
||||
version: 3.49.0(vue@3.5.44(typescript@5.9.3))
|
||||
'@vueuse/core':
|
||||
specifier: 14.4.0
|
||||
version: 14.4.0(vue@3.5.44(typescript@5.9.3))
|
||||
reka-ui:
|
||||
specifier: ^2.11.0
|
||||
version: 2.11.0(vue@3.5.44(typescript@5.9.3))
|
||||
|
||||
@@ -19,3 +19,5 @@ M30–M32 增加 consume-m30-m32.mjs 和 m30-m32-contract.ts。将它们复制
|
||||
LISTBOX-01 增加 `consume-list-box.mjs` / `list-box-contract.ts`。同样复制到独立消费者,用两份新 tarball 安装后运行脚本,并在 NodeNext / bundler 两种模式执行契约文件。Root 的泛型 Props 曾在 Parameters 提取后退化,非法模型/模式反例与事件参数推断必须保留。
|
||||
|
||||
M33–M34 使用 consume-m33-m34.mjs / m33-m34-contract.ts;同样复制到独立 tarball 消费工程,分别运行 node 与两种解析模式的 tsc。包括所有公开部件、真正 node SSR、CSS 关键帧与策略/尺寸/方向的正反类型检查。集成验证目录为 /private/tmp/heroui-m33-consumer,不复用其他并行任务的临时产物。
|
||||
|
||||
SELECT-01 增加 `consume-select.mjs` / `select-contract.ts`。新 tarball 安装后运行 ESM/SSR/CSS 脚本,两种模块解析模式都纳入类型正反例;数字/字符串/空 key、六部件、validate 与事件载荷推断不应退化。保留旧组件消费回归。
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createSSRApp, h } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectClearButton,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
Label,
|
||||
selectVariants,
|
||||
} from "@heroui-vue/components";
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h(
|
||||
Select,
|
||||
{
|
||||
defaultValue: [0, "0", ""],
|
||||
selectionMode: "multiple",
|
||||
name: "choices",
|
||||
},
|
||||
() => [
|
||||
h(Label, {}, () => "Choice"),
|
||||
h(SelectTrigger, {}, () => [
|
||||
h(SelectValue),
|
||||
h(SelectClearButton),
|
||||
h(SelectIndicator),
|
||||
]),
|
||||
h(SelectPopover, {}, () =>
|
||||
h(ListBox, {}, () => [
|
||||
h(ListBoxItem, { id: 0, textValue: "Numeric" }, () => "Numeric"),
|
||||
h(ListBoxItem, { id: "0", textValue: "String" }, () => "String"),
|
||||
h(ListBoxItem, { id: "", textValue: "Empty" }, () => "Empty"),
|
||||
]),
|
||||
),
|
||||
],
|
||||
),
|
||||
}),
|
||||
);
|
||||
assert(html.includes("Numeric, String, Empty"));
|
||||
assert(html.includes('name="choices"'));
|
||||
assert.equal((html.match(/data-index="\d" selected/g) ?? []).length, 3);
|
||||
assert(!html.includes('role="listbox"'));
|
||||
assert(html.includes('aria-haspopup="listbox"'));
|
||||
assert(
|
||||
selectVariants({ variant: "secondary" })
|
||||
.base()
|
||||
.includes("hv-select--secondary"),
|
||||
);
|
||||
const css = readFileSync(
|
||||
new URL(import.meta.resolve("@heroui-vue/styles/css")),
|
||||
"utf8",
|
||||
);
|
||||
for (const part of [
|
||||
".hv-select",
|
||||
".hv-select__trigger",
|
||||
".hv-select__value",
|
||||
".hv-select__clear-button",
|
||||
".hv-select__indicator",
|
||||
".hv-select__popover",
|
||||
])
|
||||
assert(css.includes(part));
|
||||
console.log(
|
||||
"Select independent tarball: ESM, SSR labels, raw native values, variants and CSS passed.",
|
||||
);
|
||||
@@ -0,0 +1,77 @@
|
||||
import {
|
||||
Select,
|
||||
SelectRoot,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectClearButton,
|
||||
SelectPopover,
|
||||
selectVariants,
|
||||
type SelectProps,
|
||||
type SelectValueProps,
|
||||
type SelectPopoverProps,
|
||||
type SelectModelValue,
|
||||
} from "@heroui-vue/components";
|
||||
const value: SelectModelValue = [0, "0", ""];
|
||||
const props: SelectProps = {
|
||||
modelValue: value,
|
||||
selectionMode: "multiple",
|
||||
variant: "secondary",
|
||||
autoComplete: "country",
|
||||
items: [{ id: 0, textValue: "Zero" }],
|
||||
onChange: (next) => {
|
||||
if (Array.isArray(next)) next.forEach((key) => String(key));
|
||||
},
|
||||
validate: (next) => (next === null ? "Required" : undefined),
|
||||
onOpenChange: (open) => Boolean(open),
|
||||
};
|
||||
const part: SelectValueProps = { as: "span" };
|
||||
const popup: SelectPopoverProps = { placement: "bottom start", offset: 8 };
|
||||
// @ts-expect-error Keys are strings or numbers, never objects
|
||||
const badValue: SelectProps = { modelValue: { id: 0 } };
|
||||
// @ts-expect-error Selection mode is constrained
|
||||
const badMode: SelectProps = { selectionMode: "checkbox" };
|
||||
// @ts-expect-error Variants are constrained
|
||||
const badVariant: SelectProps = { variant: "solid" };
|
||||
// @ts-expect-error Metadata text is required
|
||||
const badItems: SelectProps = { items: [{ id: 0 }] };
|
||||
// @ts-expect-error Model listener receives SelectModelValue, not boolean
|
||||
const badEvent: SelectProps = { onChange: (value: boolean) => value };
|
||||
// @ts-expect-error Popover placement is constrained
|
||||
const badPlacement: SelectPopoverProps = { placement: "diagonal" };
|
||||
const badComponent: InstanceType<typeof Select>["$props"] = {
|
||||
// @ts-expect-error Generated component props are also constrained
|
||||
modelValue: [false],
|
||||
};
|
||||
void [
|
||||
Select,
|
||||
SelectRoot,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectIndicator,
|
||||
SelectClearButton,
|
||||
SelectPopover,
|
||||
selectVariants,
|
||||
props,
|
||||
part,
|
||||
popup,
|
||||
badValue,
|
||||
badMode,
|
||||
badVariant,
|
||||
badItems,
|
||||
badEvent,
|
||||
badPlacement,
|
||||
badComponent,
|
||||
];
|
||||
type RootSlot = Parameters<
|
||||
NonNullable<InstanceType<typeof Select>["$slots"]["default"]>
|
||||
>[0];
|
||||
const slotState: RootSlot = {
|
||||
value: 0,
|
||||
isOpen: false,
|
||||
selectedItems: [{ key: 0, textValue: "Zero" }],
|
||||
};
|
||||
const selectedKey: string | number = slotState.selectedItems[0].key;
|
||||
// @ts-expect-error Root scoped slot keys must retain their actual type
|
||||
const booleanKey: boolean = slotState.selectedItems[0].key;
|
||||
void [selectedKey, booleanKey];
|
||||
@@ -0,0 +1,86 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createSSRApp, h } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
Label,
|
||||
Description,
|
||||
} from "../packages/vue/src";
|
||||
function select() {
|
||||
return h(
|
||||
Select,
|
||||
{ defaultValue: [0, "0", ""], selectionMode: "multiple", name: "choices" },
|
||||
() => [
|
||||
h(Label, {}, () => "选择"),
|
||||
h(SelectTrigger, {}, () => h(SelectValue)),
|
||||
h(Description, {}, () => "帮助"),
|
||||
h(SelectPopover, {}, () =>
|
||||
h(ListBox, {}, () => [
|
||||
h(ListBoxItem, { id: 0 }, () => [
|
||||
h(Label, {}, () => "Number"),
|
||||
h(Description, {}, () => "Excluded"),
|
||||
h(ListBoxItemIndicator),
|
||||
]),
|
||||
h(ListBoxItem, { id: "0" }, () => "String"),
|
||||
h(ListBoxItem, { id: "" }, () => "Empty"),
|
||||
]),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
describe("Select server rendering", () => {
|
||||
it("renders closed metadata and repeated native selected values without browser globals", async () => {
|
||||
expect(typeof window).toBe("undefined");
|
||||
const html = await renderToString(
|
||||
createSSRApp({ render: () => h("form", [select(), select()]) }),
|
||||
);
|
||||
expect(html.match(/Number, String, Empty/g)).toHaveLength(2);
|
||||
expect(html.match(/data-index="\d" selected/g)).toHaveLength(6);
|
||||
expect(html).not.toContain('role="listbox"');
|
||||
expect(html).not.toContain("Excluded");
|
||||
const ids = [...html.matchAll(/ id="([^"]+)"/g)].map((m) => m[1]);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
for (const match of html.matchAll(
|
||||
/aria-(?:labelledby|describedby)="([^"]+)"/g,
|
||||
))
|
||||
for (const id of match[1].split(" ")) expect(ids).toContain(id);
|
||||
});
|
||||
it("uses explicit metadata for opaque options and isolates SSR request IDs", async () => {
|
||||
const app = () =>
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h(
|
||||
Select,
|
||||
{ defaultValue: 0, items: [{ id: 0, textValue: "Known" }] },
|
||||
() => h(SelectTrigger, {}, () => h(SelectValue)),
|
||||
),
|
||||
});
|
||||
const first = await renderToString(app());
|
||||
expect(first).toContain("Known");
|
||||
expect(first).toBe(await renderToString(app()));
|
||||
});
|
||||
it("rejects duplicate or malformed keys before mounting", async () => {
|
||||
const app = (items: { id: string | number; textValue: string }[]) =>
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h(Select, { items }, () =>
|
||||
h(SelectTrigger, {}, () => h(SelectValue)),
|
||||
),
|
||||
});
|
||||
await expect(
|
||||
renderToString(
|
||||
app([
|
||||
{ id: "a", textValue: "A" },
|
||||
{ id: "a", textValue: "B" },
|
||||
]),
|
||||
),
|
||||
).rejects.toThrow("Duplicate collection key");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,715 @@
|
||||
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 {
|
||||
Modal,
|
||||
ModalBackdrop,
|
||||
ModalContainer,
|
||||
ModalDialog,
|
||||
ModalHeading,
|
||||
ModalBody,
|
||||
ModalTrigger,
|
||||
Button,
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectClearButton,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
ListBoxSection,
|
||||
Label,
|
||||
Description,
|
||||
Header,
|
||||
FieldError,
|
||||
Fieldset,
|
||||
Form,
|
||||
} from "../packages/vue/src";
|
||||
const components = {
|
||||
Modal,
|
||||
ModalBackdrop,
|
||||
ModalContainer,
|
||||
ModalDialog,
|
||||
ModalHeading,
|
||||
ModalBody,
|
||||
ModalTrigger,
|
||||
Button,
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectClearButton,
|
||||
SelectIndicator,
|
||||
SelectPopover,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
ListBoxSection,
|
||||
Label,
|
||||
Description,
|
||||
Header,
|
||||
FieldError,
|
||||
Fieldset,
|
||||
Form,
|
||||
};
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
const options =
|
||||
'<ListBoxItem :id="0"><Label>Zero number</Label><Description>Details</Description><ListBoxItemIndicator/></ListBoxItem><ListBoxItem id="0"><Label>Zero string</Label><ListBoxItemIndicator/></ListBoxItem><ListBoxItem id="disabled" is-disabled>Disabled</ListBoxItem><ListBoxItem id="last">Last</ListBoxItem>';
|
||||
const content = `<Label>Choice</Label><SelectTrigger><SelectValue/><SelectClearButton/><SelectIndicator/></SelectTrigger><Description>Help</Description><FieldError/><SelectPopover><ListBox>${options}</ListBox></SelectPopover>`;
|
||||
function fixture(template: string, setup = () => ({})) {
|
||||
const wrapper = mount(defineComponent({ components, setup, template }), {
|
||||
attachTo: document.body,
|
||||
});
|
||||
wrappers.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
const trigger = (w: ReturnType<typeof mount>) =>
|
||||
w.get('[data-slot="select-trigger"]');
|
||||
const option = (index: number) =>
|
||||
document.querySelectorAll<HTMLElement>('[role="option"]')[index];
|
||||
async function clickOption(index: number) {
|
||||
option(index).click();
|
||||
await flushPromises();
|
||||
}
|
||||
const data = () => [...new FormData(document.querySelector("form")!).entries()];
|
||||
describe("Select public contracts", () => {
|
||||
it("plans closed labels and submits raw numeric/string keys once", async () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" :default-value="0">${content}</Select></form>`,
|
||||
);
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number");
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
expect(document.querySelector('[role="listbox"]')).toBeNull();
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[role="listbox"]')).not.toBeNull();
|
||||
expect(option(0).getAttribute("aria-selected")).toBe("true");
|
||||
await clickOption(1);
|
||||
expect(
|
||||
w.getComponent(components.Select).emitted("update:modelValue"),
|
||||
).toEqual([["0"]]);
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Zero string");
|
||||
});
|
||||
it("uses parent accepted multiple values, retries rejected proposals, and keeps the popup open", async () => {
|
||||
const value = ref<(string | number)[]>([0]);
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" selection-mode="multiple" :model-value="value">${content}</Select></form>`,
|
||||
() => ({ value }),
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(1);
|
||||
await clickOption(1);
|
||||
expect(
|
||||
w.getComponent(components.Select).emitted("update:modelValue"),
|
||||
).toEqual([[[0, "0"]], [[0, "0"]]]);
|
||||
expect(option(1).getAttribute("aria-selected")).toBe("false");
|
||||
value.value = [0, "0"];
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([
|
||||
["choice", "0"],
|
||||
["choice", "0"],
|
||||
]);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("true");
|
||||
});
|
||||
it("clears without toggling, supports closed Delete only with a clear affordance", async () => {
|
||||
const w = fixture(`<Select default-value="last">${content}</Select>`);
|
||||
await w
|
||||
.get('[data-slot="select-clear-button"]')
|
||||
.trigger("click", { button: 0 });
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
expect(w.getComponent(components.Select).emitted("clear")).toHaveLength(1);
|
||||
expect(
|
||||
w.getComponent(components.Select).emitted("update:modelValue"),
|
||||
).toEqual([[null]]);
|
||||
const plain = fixture(
|
||||
`<Select default-value="last">${content.replace("<SelectClearButton/>", "")}</Select>`,
|
||||
);
|
||||
await trigger(plain).trigger("keydown", { key: "Delete" });
|
||||
expect(
|
||||
plain.getComponent(components.Select).emitted("change"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
it("honors disabled/readonly state and native reset", async () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" default-value="last">${content}</Select></form>`,
|
||||
);
|
||||
await trigger(w).trigger("keydown", { key: "Delete" });
|
||||
expect(data()).toEqual([]);
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
w.unmount();
|
||||
wrappers.pop();
|
||||
document.body.innerHTML = "";
|
||||
const readonly = fixture(
|
||||
`<form><Select is-read-only name="choice" default-value="last">${content}</Select></form>`,
|
||||
);
|
||||
await trigger(readonly).trigger("click");
|
||||
expect(trigger(readonly).attributes("aria-expanded")).toBe("false");
|
||||
await trigger(readonly).trigger("keydown", { key: "Delete" });
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
});
|
||||
it("links field labels, descriptions and errors without option leakage", async () => {
|
||||
const w = fixture(`<Select is-required>${content}</Select>`);
|
||||
const t = trigger(w);
|
||||
const ids = t.attributes("aria-labelledby")!.split(" ");
|
||||
expect(
|
||||
ids.map((id) => document.getElementById(id)?.textContent).join(" "),
|
||||
).toContain("Choice");
|
||||
expect(t.attributes("aria-describedby")).toBeTruthy();
|
||||
expect(
|
||||
w.get<HTMLInputElement>('input[type="checkbox"]').element.checkValidity(),
|
||||
).toBe(false);
|
||||
await flushPromises();
|
||||
expect(t.attributes("aria-invalid")).toBe("true");
|
||||
await t.trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(0);
|
||||
expect(
|
||||
w.get<HTMLInputElement>('input[type="checkbox"]').element.checkValidity(),
|
||||
).toBe(true);
|
||||
expect(t.attributes("aria-labelledby")).toBe(ids.join(" "));
|
||||
});
|
||||
it("allows trigger event cancellation and honors explicit root accessible names", async () => {
|
||||
const w = fixture(
|
||||
`<Select aria-label="Named">${content.replace("<SelectTrigger>", "<SelectTrigger @click.prevent>")}</Select>`,
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
expect(trigger(w).attributes("aria-label")).toBe("Named");
|
||||
});
|
||||
it("renders selected labels and native submission on SSR without mounting popup", async () => {
|
||||
const app = createSSRApp(
|
||||
defineComponent({
|
||||
components,
|
||||
template: `<Select name="choice" :default-value="0">${content}</Select>`,
|
||||
}),
|
||||
);
|
||||
const html = await renderToString(app);
|
||||
expect(html).toContain("Zero number");
|
||||
expect(html).not.toContain('role="listbox"');
|
||||
expect(html).toContain('name="choice"');
|
||||
expect(html).toContain('value="0" data-index="0" selected');
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select form and collection changes", () => {
|
||||
it("uses native autocomplete proposals and restores rejected parent values", async () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" auto-complete="country" :model-value="0">${content}</Select></form>`,
|
||||
);
|
||||
const native = w.get<HTMLSelectElement>("select");
|
||||
expect(native.attributes("autocomplete")).toBe("country");
|
||||
native.element.selectedIndex = 2;
|
||||
await native.trigger("change");
|
||||
await flushPromises();
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([["0"]]);
|
||||
expect(native.element.selectedIndex).toBe(1);
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
});
|
||||
it("omits removed or disabled selected options from FormData and constraints", async () => {
|
||||
const show = ref(true),
|
||||
disabled = ref(false);
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" default-value="a" is-required><Label>Dynamic</Label><SelectTrigger><SelectValue/></SelectTrigger><SelectPopover><ListBox><ListBoxItem v-if="show" id="a" :is-disabled="disabled">Alpha</ListBoxItem></ListBox></SelectPopover></Select></form>`,
|
||||
() => ({ show, disabled }),
|
||||
);
|
||||
expect(data()).toEqual([["choice", "a"]]);
|
||||
disabled.value = true;
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([]);
|
||||
disabled.value = false;
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "a"]]);
|
||||
show.value = false;
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([]);
|
||||
});
|
||||
it("omits Fieldset-disabled values and preserves readonly values", async () => {
|
||||
const w = fixture(
|
||||
`<form><Fieldset disabled><Select name="choice" default-value="last">${content}</Select></Fieldset></form>`,
|
||||
);
|
||||
expect(trigger(w).attributes("disabled")).toBeDefined();
|
||||
expect(data()).toEqual([]);
|
||||
});
|
||||
it("keeps controlled reset and cancelled reset without synthetic changes", async () => {
|
||||
const w = fixture(
|
||||
`<form @reset.prevent><Select name="choice" default-value="last">${content}</Select></form>`,
|
||||
);
|
||||
await trigger(w).trigger("keydown", { key: "Backspace" });
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([]);
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([[null]]);
|
||||
});
|
||||
it("counts conditional clear affordances and honors actual trigger disabled state", async () => {
|
||||
const clear = ref(true),
|
||||
disabled = ref(true);
|
||||
const w = fixture(
|
||||
`<Select default-value="last">${content.replace("<SelectTrigger>", '<SelectTrigger :is-disabled="disabled">').replace("<SelectClearButton/>", '<SelectClearButton v-if="clear"/>')}</Select>`,
|
||||
() => ({ clear, disabled }),
|
||||
);
|
||||
await w
|
||||
.get('[data-slot="select-clear-button"]')
|
||||
.trigger("click", { button: 0 });
|
||||
expect(w.getComponent(Select).emitted("change")).toBeUndefined();
|
||||
disabled.value = false;
|
||||
clear.value = false;
|
||||
await flushPromises();
|
||||
await trigger(w).trigger("keydown", { key: "Delete" });
|
||||
expect(w.getComponent(Select).emitted("change")).toBeUndefined();
|
||||
clear.value = true;
|
||||
await flushPromises();
|
||||
await trigger(w).trigger("keydown", { key: "Delete" });
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([[null]]);
|
||||
});
|
||||
it("keeps open controlled, retries rejected openings and respects explicit undefined precedence", async () => {
|
||||
const w = fixture(
|
||||
`<Select :open="undefined" :is-open="true">${content}</Select>`,
|
||||
);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
await trigger(w).trigger("click");
|
||||
await trigger(w).trigger("click");
|
||||
expect(w.getComponent(Select).emitted("update:open")).toEqual([
|
||||
[true],
|
||||
[true],
|
||||
]);
|
||||
});
|
||||
it("focuses the selected option on open and skips disabled items", async () => {
|
||||
const w = fixture(`<Select default-value="last">${content}</Select>`);
|
||||
await trigger(w).trigger("keydown", { key: "ArrowDown" });
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(option(3));
|
||||
option(3).dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "Home", bubbles: true }),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(option(0));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select popup boundary", () => {
|
||||
it("uses a presentation popup and a named listbox with correct ARIA ownership", async () => {
|
||||
const w = fixture(`<Select>${content}</Select>`);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
const popup = document.querySelector('[data-slot="select-popover"]')!;
|
||||
expect(popup).not.toBeNull();
|
||||
expect(popup.getAttribute("role")).toBe("presentation");
|
||||
const list = document.querySelector('[role="listbox"]')!;
|
||||
expect(trigger(w).attributes("aria-controls")).toBe(list.id);
|
||||
expect(trigger(w).attributes("aria-haspopup")).toBe("listbox");
|
||||
expect(list.getAttribute("aria-labelledby")).toBe(
|
||||
w.get('[data-slot="label"]').attributes("id"),
|
||||
);
|
||||
});
|
||||
it("leaves Tab default traversal at the trigger without looping in the portal", async () => {
|
||||
const w = fixture(
|
||||
`<div><Select>${content}</Select><button>After</button></div>`,
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
const event = new KeyboardEvent("keydown", {
|
||||
key: "Tab",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
option(0).dispatchEvent(event);
|
||||
await flushPromises();
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
expect(document.activeElement).toBe(trigger(w).element);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
});
|
||||
it("keeps controlled native selected options on reset even when Vue props did not change", async () => {
|
||||
const value = ref<string | number | (string | number)[] | null>("last");
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" :model-value="value">${content}</Select></form>`,
|
||||
() => ({ value }),
|
||||
);
|
||||
value.value = 0;
|
||||
await flushPromises();
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number");
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select hydration and baseline demos", () => {
|
||||
it("hydrates default closed metadata, IDs and native selection without mismatches", async () => {
|
||||
const Component = defineComponent({
|
||||
components,
|
||||
template: `<Select name="choice" :default-value="0">${content}</Select>`,
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
host.innerHTML = await renderToString(createSSRApp(Component));
|
||||
document.body.append(host);
|
||||
const before = host.querySelector('[data-slot="select-trigger"]');
|
||||
const warnings: string[] = [];
|
||||
const app = createSSRApp(Component);
|
||||
app.config.warnHandler = (message) => warnings.push(message);
|
||||
app.mount(host);
|
||||
await flushPromises();
|
||||
try {
|
||||
expect(warnings).toEqual([]);
|
||||
expect(host.querySelector('[data-slot="select-trigger"]')).toBe(before);
|
||||
expect(
|
||||
host.querySelector("select")?.selectedOptions[0].dataset.index,
|
||||
).toBe("0");
|
||||
} finally {
|
||||
app.unmount();
|
||||
}
|
||||
});
|
||||
it("mounts all nineteen source demos with unique IDs and real async data", async () => {
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = async () =>
|
||||
new Response(
|
||||
JSON.stringify({ next: null, results: [{ name: "bulbasaur" }] }),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
try {
|
||||
const demos = import.meta.glob("../apps/docs/demos/select-*.vue", {
|
||||
eager: true,
|
||||
import: "default",
|
||||
});
|
||||
expect(Object.keys(demos)).toHaveLength(19);
|
||||
const warnings: string[] = [];
|
||||
const w = 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(w);
|
||||
await flushPromises();
|
||||
expect(warnings).toEqual([]);
|
||||
const ids = w.findAll("[id]").map((node) => node.attributes("id"));
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
expect(w.findAll('[data-slot="select-trigger"]')).toHaveLength(23);
|
||||
const asyncDemo = w
|
||||
.findAllComponents(Select)
|
||||
.find(
|
||||
(component) => component.props("placeholder") === "请选择宝可梦",
|
||||
)!;
|
||||
expect(asyncDemo.get("select").text()).toContain("bulbasaur");
|
||||
} finally {
|
||||
globalThis.fetch = original;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select names, cancellation and closed keyboard", () => {
|
||||
it("moves focus on field Label click without opening the menu", async () => {
|
||||
const w = fixture(`<Select>${content}</Select>`);
|
||||
await w.get('[data-slot="label"]').trigger("click");
|
||||
expect(document.activeElement).toBe(trigger(w).element);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
});
|
||||
it("supports closed typeahead and skips disabled options without editing during IME", async () => {
|
||||
const w = fixture(
|
||||
`<Select><Label>People</Label><SelectTrigger><SelectValue/></SelectTrigger><SelectPopover><ListBox><ListBoxItem id="a" text-value="Liam Smith">Liam Smith</ListBoxItem><ListBoxItem id="b" text-value="Liam Jones">Liam Jones</ListBoxItem><ListBoxItem id="c" is-disabled text-value="Martha">Martha</ListBoxItem></ListBox></SelectPopover></Select>`,
|
||||
);
|
||||
for (const key of ["l", "i", "a", "m"])
|
||||
await trigger(w).trigger("keydown", { key });
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Liam Smith");
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([["a"]]);
|
||||
await trigger(w).trigger("keydown", { key: "m", isComposing: true });
|
||||
expect(w.getComponent(Select).emitted("change")).toHaveLength(1);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
});
|
||||
it("respects ListBox activation cancellation before selection or closing", async () => {
|
||||
const w = fixture(
|
||||
`<Select>${content.replace("<ListBox>", "<ListBox @keydown.prevent>")}</Select>`,
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
option(0).dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Enter",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(w.getComponent(Select).emitted("change")).toBeUndefined();
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("true");
|
||||
});
|
||||
it("keeps aria validation nonblocking and refreshes Form server errors", async () => {
|
||||
const errors = ref<Record<string, string>>({ choice: "Server error" });
|
||||
const w = fixture(
|
||||
`<Form :validation-errors="errors" validation-behavior="aria"><Select name="choice" is-required>${content}</Select></Form>`,
|
||||
() => ({ errors }),
|
||||
);
|
||||
expect(trigger(w).attributes("aria-invalid")).toBe("true");
|
||||
expect(w.text()).toContain("Server error");
|
||||
expect(
|
||||
w.get<HTMLInputElement>('input[type="checkbox"]').element.checkValidity(),
|
||||
).toBe(true);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(0);
|
||||
expect(w.text()).not.toContain("Server error");
|
||||
errors.value = { choice: "Refreshed" };
|
||||
await flushPromises();
|
||||
expect(w.text()).toContain("Refreshed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select metadata and identity", () => {
|
||||
it("retains empty-string identities through native form submission", async () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" default-value=""><Label>Empty</Label><SelectTrigger><SelectValue/></SelectTrigger><SelectPopover><ListBox><ListBoxItem id="">Empty key</ListBoxItem><ListBoxItem id="a">Alpha</ListBoxItem></ListBox></SelectPopover></Select></form>`,
|
||||
);
|
||||
expect(data()).toEqual([["choice", ""]]);
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Empty key");
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(option(0).getAttribute("aria-selected")).toBe("true");
|
||||
});
|
||||
it("associates an external form dynamically and restores reset values", async () => {
|
||||
const owner = ref("one");
|
||||
const w = fixture(
|
||||
`<div><form id="one"></form><form id="two"></form><Select :form="owner" name="choice" default-value="last">${content}</Select></div>`,
|
||||
() => ({ owner }),
|
||||
);
|
||||
owner.value = "two";
|
||||
await flushPromises();
|
||||
await trigger(w).trigger("keydown", { key: "Delete" });
|
||||
(w.get("#one").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(
|
||||
w.get('[data-slot="select-value"]').attributes("data-placeholder"),
|
||||
).toBe("true");
|
||||
(w.get("#two").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(
|
||||
new FormData(w.get("#two").element as HTMLFormElement).get("choice"),
|
||||
).toBe("last");
|
||||
});
|
||||
it("refreshes explicit asynchronous selected metadata before opening", async () => {
|
||||
const items = ref<{ id: number; textValue: string }[]>([]);
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" :model-value="0" :items="items"><Label>Async</Label><SelectTrigger><SelectValue/></SelectTrigger></Select></form>`,
|
||||
() => ({ items }),
|
||||
);
|
||||
expect(data()).toEqual([]);
|
||||
items.value = [{ id: 0, textValue: "Loaded label" }];
|
||||
await flushPromises();
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Loaded label");
|
||||
expect(data()).toEqual([["choice", "0"]]);
|
||||
items.value = [];
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([]);
|
||||
});
|
||||
it("gives root accessible names to the popup list and keeps cancellation intact", async () => {
|
||||
const w = fixture(`<Select aria-label="Root name">${content}</Select>`);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(
|
||||
document.querySelector('[role="listbox"]')?.getAttribute("aria-label"),
|
||||
).toBe("Root name");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select integration boundaries", () => {
|
||||
it("keeps a nested Modal open when its Select handles Escape", async () => {
|
||||
const w = fixture(
|
||||
`<Modal><ModalTrigger>Open modal</ModalTrigger><ModalBackdrop><ModalContainer><ModalDialog><ModalHeading>Parent dialog</ModalHeading><ModalBody><Select>${content}</Select></ModalBody></ModalDialog></ModalContainer></ModalBackdrop></Modal>`,
|
||||
);
|
||||
await w.get('[data-slot="modal-trigger"]').trigger("click");
|
||||
await flushPromises();
|
||||
const selectTrigger = document.querySelector<HTMLElement>(
|
||||
'[data-slot="select-trigger"]',
|
||||
)!;
|
||||
selectTrigger.click();
|
||||
await flushPromises();
|
||||
expect(option(0)).toBeTruthy();
|
||||
option(0).dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Escape",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
|
||||
expect(selectTrigger.getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
it("honors open autofocus cancellation and native handler array stop semantics", async () => {
|
||||
const calls: string[] = [];
|
||||
const stop = (event: Event) => {
|
||||
calls.push("first");
|
||||
event.stopImmediatePropagation();
|
||||
};
|
||||
const second = () => calls.push("second");
|
||||
const w = fixture(
|
||||
`<Select>${content.replace("<SelectTrigger>", '<SelectTrigger :onKeydown="[stop,second]">').replace("<SelectPopover>", "<SelectPopover @open-auto-focus.prevent>")}</Select>`,
|
||||
() => ({ stop, second }),
|
||||
);
|
||||
await trigger(w).trigger("keydown", { key: "ArrowDown" });
|
||||
expect(calls).toEqual(["first"]);
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("false");
|
||||
(trigger(w).element as HTMLElement).focus();
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(trigger(w).element);
|
||||
});
|
||||
it("honors per-item cancellation before changing or closing", async () => {
|
||||
const w = fixture(
|
||||
`<Select>${content.replace('<ListBoxItem :id="0">', '<ListBoxItem :id="0" @select.prevent>')}</Select>`,
|
||||
);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(0);
|
||||
expect(w.getComponent(Select).emitted("change")).toBeUndefined();
|
||||
expect(trigger(w).attributes("aria-expanded")).toBe("true");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select async demo lifecycle", () => {
|
||||
it("loads a second page, retains existing options on failure, and retries", async () => {
|
||||
const original = globalThis.fetch;
|
||||
const cursors: string[] = [];
|
||||
let call = 0;
|
||||
globalThis.fetch = async (input) => {
|
||||
cursors.push(String(input));
|
||||
call++;
|
||||
if (call === 2) return new Response("", { status: 503 });
|
||||
return new Response(
|
||||
JSON.stringify(
|
||||
call === 1
|
||||
? {
|
||||
next: "https://pokeapi.co/api/v2/pokemon?offset=20",
|
||||
results: [{ name: "bulbasaur" }],
|
||||
}
|
||||
: { next: null, results: [{ name: "ivysaur" }] },
|
||||
),
|
||||
{ status: 200 },
|
||||
);
|
||||
};
|
||||
try {
|
||||
const { default: Demo } =
|
||||
await import("../apps/docs/demos/select-asynchronous-loading.vue");
|
||||
const w = mount(Demo, { attachTo: document.body });
|
||||
wrappers.push(w);
|
||||
await flushPromises();
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
const more = [
|
||||
...document.querySelectorAll<HTMLButtonElement>(
|
||||
'[data-slot="select-popover"] button',
|
||||
),
|
||||
].find((button) => button.textContent?.includes("加载更多"))!;
|
||||
more.click();
|
||||
await flushPromises();
|
||||
expect(w.get("select").text()).toContain("bulbasaur");
|
||||
const retry = [
|
||||
...document.querySelectorAll<HTMLButtonElement>(
|
||||
'[data-slot="select-popover"] button',
|
||||
),
|
||||
].find((button) => button.textContent?.includes("重试"))!;
|
||||
expect(retry).toBeTruthy();
|
||||
retry.click();
|
||||
await flushPromises();
|
||||
await vi.waitFor(() =>
|
||||
expect(w.get("select").text()).toContain("ivysaur"),
|
||||
);
|
||||
expect(cursors).toEqual([
|
||||
"https://pokeapi.co/api/v2/pokemon",
|
||||
"https://pokeapi.co/api/v2/pokemon?offset=20",
|
||||
"https://pokeapi.co/api/v2/pokemon?offset=20",
|
||||
]);
|
||||
} finally {
|
||||
globalThis.fetch = original;
|
||||
}
|
||||
});
|
||||
it("aborts the pending request on unmount", async () => {
|
||||
const original = globalThis.fetch;
|
||||
let signal: AbortSignal | undefined;
|
||||
globalThis.fetch = async (_input, init) => {
|
||||
signal = init?.signal ?? undefined;
|
||||
return new Promise<Response>(() => {});
|
||||
};
|
||||
try {
|
||||
const { default: Demo } =
|
||||
await import("../apps/docs/demos/select-asynchronous-loading.vue");
|
||||
const w = mount(Demo, { attachTo: document.body });
|
||||
expect(signal?.aborted).toBe(false);
|
||||
w.unmount();
|
||||
expect(signal?.aborted).toBe(true);
|
||||
} finally {
|
||||
globalThis.fetch = original;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Select dynamic mode", () => {
|
||||
it("adapts uncontrolled single/multiple shapes and reset without synthetic edits", async () => {
|
||||
const mode = ref<"single" | "multiple">("single");
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" :selection-mode="mode" default-value="last">${content}</Select></form>`,
|
||||
() => ({ mode }),
|
||||
);
|
||||
mode.value = "multiple";
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
await clickOption(0);
|
||||
expect(w.getComponent(Select).emitted("change")).toEqual([[["last", 0]]]);
|
||||
mode.value = "single";
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
(w.get("form").element as HTMLFormElement).reset();
|
||||
await flushPromises();
|
||||
expect(data()).toEqual([["choice", "last"]]);
|
||||
expect(w.getComponent(Select).emitted("change")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps locally disabled options out of the native submission even with explicit text metadata", () => {
|
||||
const w = fixture(
|
||||
`<form><Select name="choice" default-value="a" :items="[{ id:'a', textValue:'Alpha' }]"><Label>Metadata</Label><SelectTrigger><SelectValue/></SelectTrigger><SelectPopover><ListBox><ListBoxItem id="a" is-disabled>Alpha</ListBoxItem></ListBox></SelectPopover></Select></form>`,
|
||||
);
|
||||
expect(data()).toEqual([]);
|
||||
expect(w.get('[data-slot="select-value"]').text()).toBe("Alpha");
|
||||
});
|
||||
|
||||
it("reveals only the currently focused owned option after popup positioning starts", async () => {
|
||||
const w = fixture(`<Select default-value="last">${content}</Select>`);
|
||||
await trigger(w).trigger("click");
|
||||
await flushPromises();
|
||||
const active = option(3);
|
||||
const reveal = vi.fn();
|
||||
active.scrollIntoView = reveal;
|
||||
const popup = document.querySelector<HTMLElement>(
|
||||
'[data-slot="select-popover"]',
|
||||
)!;
|
||||
popup.dispatchEvent(new Event("animationstart", { bubbles: true }));
|
||||
expect(reveal).toHaveBeenCalledOnce();
|
||||
active.dispatchEvent(new Event("animationstart", { bubbles: true }));
|
||||
expect(reveal).toHaveBeenCalledOnce();
|
||||
(trigger(w).element as HTMLElement).focus();
|
||||
popup.dispatchEvent(new Event("animationstart", { bubbles: true }));
|
||||
expect(reveal).toHaveBeenCalledOnce();
|
||||
});
|
||||
Reference in New Issue
Block a user