fix: complete TagGroup semantics event ownership and removal focus

This commit is contained in:
maoyingjie
2026-10-25 14:34:07 +08:00
parent af6bfda3ee
commit 20d34d7169
12 changed files with 528 additions and 53 deletions
+2 -2
View File
@@ -89,11 +89,11 @@ HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态
ErrorMessage 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/error-message.css)): ErrorMessage 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/error-message.css)):
#### 基础类 [!toc] #### 基础类
- `.hv-error-message` - 基础错误消息样式,danger 色与文本换行 - `.hv-error-message` - 基础错误消息样式,danger 色与文本换行
#### 插槽类 [!toc] #### 插槽类
- `[slot="errorMessage"]` - 与固定基线一致的 DOM 标记,可用作 CSS 选择器 - `[slot="errorMessage"]` - 与固定基线一致的 DOM 标记,可用作 CSS 选择器
- `[data-slot="error-message"]` - 组件标记 - `[data-slot="error-message"]` - 组件标记
+17 -17
View File
@@ -100,7 +100,7 @@ import {
<ComponentPreview name="tag-group-render-function" /> <ComponentPreview name="tag-group-render-function" />
上游用 React `render` 函数替换根 DOM 元素;Vue 中对应 `as`(自定义根元素标签)与 `as-child`(使用自定义组件作为唯一根)。本库示例用 `as="section"` 演示同一能力。 上游用 React `render` 函数替换根 DOM 元素;Vue 中对应 `as`(自定义根元素标签)与 `as-child`(使用自定义组件作为唯一根)。本库示例用 `as="div"` 演示同一能力。
## 自定义样式 ## 自定义样式
@@ -140,30 +140,30 @@ HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态
TagGroup 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/tag-group.css) 与 [tag.css](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/tag.css)): TagGroup 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/tag-group.css) 与 [tag.css](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/tag.css)):
#### 基础类 [!toc] #### 基础类
- `.hv-tag-group` - TagGroup 根容器 - `.hv-tag-group` - TagGroup 根容器
- `.hv-tag-group__list` - 标签列表容器 - `.hv-tag-group__list` - 标签列表容器
- `.hv-tag` - 标签基础样式 - `.hv-tag` - 标签基础样式
- `.hv-tag__remove-button` - 移除按钮触发器 - `.hv-tag__remove-button` - 移除按钮触发器
#### 插槽类 [!toc] #### 插槽类
- `.hv-tag-group [data-slot="description"]` - Description 插槽样式 - `.hv-tag-group [data-slot="description"]` - Description 插槽样式
- `.hv-tag-group [data-slot="error-message"]` - ErrorMessage 插槽样式 - `.hv-tag-group [data-slot="error-message"]` - ErrorMessage 插槽样式
#### 尺寸类 [!toc] #### 尺寸类
- `.hv-tag--sm` - 小尺寸标签 - `.hv-tag--sm` - 小尺寸标签
- `.hv-tag--md` - 中尺寸标签(默认) - `.hv-tag--md` - 中尺寸标签(默认)
- `.hv-tag--lg` - 大尺寸标签 - `.hv-tag--lg` - 大尺寸标签
#### 变体类 [!toc] #### 变体类
- `.hv-tag--default` - 默认变体 - `.hv-tag--default` - 默认变体
- `.hv-tag--surface` - 带 Surface 背景的变体 - `.hv-tag--surface` - 带 Surface 背景的变体
#### 状态类 [!toc] #### 状态类
- `.hv-tag[data-selected="true"]` - 选中状态 - `.hv-tag[data-selected="true"]` - 选中状态
- `.hv-tag[data-disabled="true"]` - 禁用状态 - `.hv-tag[data-disabled="true"]` - 禁用状态
@@ -226,15 +226,15 @@ TagGroup 组件使用以下 CSS 类([查看源码样式](https://github.com/he
### Tag ### Tag
| Prop | 类型 | 默认值 | 描述 | | Prop | 类型 | 默认值 | 描述 |
| ------------- | --------------------------- | ------- | -------------------------------------------------- | | ------------- | --------------------------- | ------- | ------------------------------------------------------------ |
| `id` | `string \| number` | - | 标签唯一标识(必填,集合 key) | | `id` | `string \| number` | - | 标签唯一标识(必填,集合 key) |
| `text-value` | `string` | - | 标签内容的字符串表示,用于无障碍名称与移除按钮名称 | | `text-value` | `string` | - | 标签内容的字符串表示,用于无障碍名称与移除按钮名称 |
| `is-disabled` | `boolean` | `false` | 是否禁用该标签 | | `is-disabled` | `boolean` | `false` | 是否禁用该标签 |
| `as` | `string` | `'div'` | 自定义行元素标签 | | `as` | `string` | `'div'` | 自定义行元素标签 |
| `as-child` | `boolean` | `false` | 使用唯一子元素作为行节点并合并属性 | | `as-child` | `boolean` | `false` | 使用唯一子元素作为行节点并合并属性;组件需透传属性与默认插槽 |
| 默认插槽 | `{ ...TagRenderState }` | - | 标签内容;作用域提供渲染状态 | | 默认插槽 | `{ ...TagRenderState }` | - | 标签内容;作用域提供渲染状态 |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | | `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
**提示:** `size`、`variant` 由父级 `TagGroup` 继承,不能在单个 `Tag` 上直接设置。 **提示:** `size`、`variant` 由父级 `TagGroup` 继承,不能在单个 `Tag` 上直接设置。
@@ -273,12 +273,12 @@ TagGroup 组件使用以下 CSS 类([查看源码样式](https://github.com/he
## 无障碍 ## 无障碍
- 列表节点为 `role="grid"`,每个标签为 `role="row"`,行的可访问名称来自其文本内容。 - 列表节点为 `role="grid"`,每个标签为 `role="row"`,行包含 `gridcell`,可访问名称来自其文本内容。
- 方向键在标签之间移动焦点(RTL 下左右互换),`Home` / `End` 跳到第一个 / 最后一个标签;禁用标签会被跳过。 - 方向键在标签之间移动焦点(RTL 下左右互换),`Home` / `End` 跳到第一个 / 最后一个标签;禁用标签会被跳过。
- `Enter` 与 `Space` 切换选中(`Space` 在 `keyup` 时激活,调用方可通过 `preventDefault` 取消)。 - `Enter` 与 `Space` 切换选中(`Space` 在 `keyup` 时激活,调用方可通过 `preventDefault` 取消)。
- `Backspace` / `Delete` 在允许移除时请求移除当前聚焦标签。 - `Backspace` / `Delete` 在允许移除时请求移除当前聚焦标签。
- 移除确认后焦点移到原位置的下一个标签,删除最后一项时回到列表本身;父级拒绝删除时标签与焦点都保留。 - 移除确认后焦点移到原位置的下一个标签,删除最后一项时回到列表本身;父级拒绝删除时标签与焦点都保留。
- 列表节点声明 `aria-atomic="false"` 与 `aria-relevant="additions text"`,集合内容的增删会被读屏软件播报。 - 列表保留 `aria-atomic="false"` 与 `aria-relevant="additions text"` 标记;独立的 polite 状态区域在确认移除后更新公告,父级拒绝移除时不公告。实际读屏效果尚未验证。
## 相关组件 ## 相关组件
@@ -12,7 +12,7 @@ import { Tag, TagGroup, TagGroupList } from "@heroui-vue/components";
<!-- Upstream 的 render 函数在此对应 as(自定义根元素标签)。 --> <!-- Upstream 的 render 函数在此对应 as(自定义根元素标签)。 -->
<TagGroup <TagGroup
aria-label="标签" aria-label="标签"
as="section" as="div"
data-custom="foo" data-custom="foo"
selection-mode="single" selection-mode="single"
> >
+29
View File
@@ -0,0 +1,29 @@
# B03 复核与接手修复(2026-10-25)
起点:`af6bfda`,任务分支 `feat/b03-tag-error-message`。本记录补充并优先于初始迁移报告的验收结论;未合 main、未推送。固定 HeroUI 3.2.6 / `ce90ea3`。未改共享 field/collection/overlay 内核。
## 已修复
1. **属性归属**:TagGroup 根 style、TagGroupList style 被过滤后遗漏;列表自身的 ARIA 名称/描述也被忽略。现在保留样式,列表显式名称优先,描述与组上下文合并。
2. **键盘所有权**:嵌入 input、原生移除按钮及嵌套 grid 的事件不能触发外层标签选择、删除或导航。Enter/Space 保留原生按钮激活,Space 在焦点改变后不会激活旧行。
3. **禁用链路**:移除按钮继承单个 Tag 的禁用状态;组与条目禁用计算不再相互递归。动态禁用清理按下/悬停状态。
4. **指针状态**:在行外释放/取消指针时同步清理本地与组级 pressed,右键与取消事件不建立按下状态。
5. **真实语义**:每个 row 增加 gridcell,使用 display:contents 保留源 flex 布局;空状态也有合法的 row/cell 容器。
6. **焦点恢复**:外部已有焦点时,删除曾聚焦的行不能抢回焦点。用户移除时单独保存焦点归属,避免浏览器先派发失焦、后注销成员导致焦点落到 body。禁用行不再干扰“下一个邻项”的索引;移除位置使用当前 DOM 顺序。
7. **asChild**:保留调用方真实根节点、属性/事件/ref,并在其内部建立 gridcell;组件根需透传默认插槽和属性。
8. **Tab 入口**:默认移除按钮 tabindex=-1,整个集合保持一个默认 Tab 入口;行的 Delete/Backspace 仍可请求移除。
9. **公告**:仅 aria-atomic/relevant 不构成 live region。增加独立 polite status,在父级实际移除条目后更新;拒绝删除不公告。不宣称读屏软件已经实测。
10. **一致性**:none 模式作用域状态不暴露遗留的 isSelected;render 示例恢复源 div 根,不另换 section;去除 VitePress 无法解析而直接显示的源文档 `[!toc]` 标记。
## 验证
- 本批原有 35 项测试加 12 项回归,共 **47 项**;覆盖属性归属、子控件键盘、单项禁用、行外释放、gridcell、外部焦点、原生失焦顺序、禁用邻项、删除拒绝、原生/组件 asChild、单 Tab 入口。
- 全套 **74 文件 / 985 项**;typecheck、文档生产构建、格式与 diff 检查通过。构建仍有既有的文档 chunk 体积提示。
- 独立新 tarball 消费(`/private/tmp/heroui-b03-review-consumer`,使用已有 pnpm 缓存安装):ESM/HTML/CSS 脚本,以及 bundler/NodeNext 类型正反例通过;不使用源码 alias。
- 真实浏览器 5183:点击默认“旅行”移除、再次移除“游戏”后焦点为“购物”;自定义 React 移除按钮按 Enter 后焦点为 Vue,未发生选择;全部 Tag 行存在 gridcell。公告仅在确认删除后更新。截图保存在 `/private/tmp/b03-tag-removal-review.png`。
首个浏览器点击暴露了原生失焦顺序问题,修复后复验邻项焦点;未把单测模拟的失焦顺序代替真实浏览器结论。
## 保留边界
未做读屏软件、物理触屏与逐像素视觉验收。原报告的主要 Vue 框架差异继续有效;ErrorMessage 为展示部件,不新增校验状态。用户不要求新增 SSR/水合/Nuxt 专项;保留已有全套测试。
+4
View File
@@ -174,3 +174,7 @@ export {
- 检查 sm/md/lg 间距、surface 背景、禁用透明度 0.5、键盘焦点环。 - 检查 sm/md/lg 间距、surface 背景、禁用透明度 0.5、键盘焦点环。
3. 打开 `/components/error-message`:确认两个示例渲染 `<p class="hv-error-message" slot="errorMessage">`,并检查 API 表满宽无溢出。 3. 打开 `/components/error-message`:确认两个示例渲染 `<p class="hv-error-message" slot="errorMessage">`,并检查 API 表满宽无溢出。
4. 独立消费:把 `tests/package/{consume-b03-tag-error-message.mjs,b03-tag-error-message-contract.ts}` 复制到工作区外的新工程,装两份 `pnpm pack` 产物后执行脚本 + 两种 `tsc` 模式。 4. 独立消费:把 `tests/package/{consume-b03-tag-error-message.mjs,b03-tag-error-message-contract.ts}` 复制到工作区外的新工程,装两份 `pnpm pack` 产物后执行脚本 + 两种 `tsc` 模式。
## 2026-10-25 集成人复核补充
本报告为初次交付记录;后续发现并修复的属性、语义、焦点及键盘问题与最新验证结论见 [B03 复核与接手修复](B03-review-acceptance.md)。其中“as=section”已恢复为基线 div;旧 aria-atomic/relevant 标记不能证明已提供公告,现已补独立状态区域。旧 35 项/973 项为当时结果,最新为 47 项/985 项。
+4
View File
@@ -1009,3 +1009,7 @@ Button/PopoverTrigger/Link/ToggleButtonGroup 源码及几何复核后,移除
- 文档:API 表格全部 728px = 正文宽度、`display: table`、`table-layout: fixed`、`scrollWidth === clientWidth`(长 16 行与短 4 行表均无横向溢出);侧栏顺序为 EmptyState → ErrorMessage → FieldError,TagGroup 位于 Tabs 与 TextArea 之间;ErrorMessage 页面渲染 `<p class="hv-error-message" slot="errorMessage">`。 - 文档:API 表格全部 728px = 正文宽度、`display: table`、`table-layout: fixed`、`scrollWidth === clientWidth`(长 16 行与短 4 行表均无横向溢出);侧栏顺序为 EmptyState → ErrorMessage → FieldError,TagGroup 位于 Tabs 与 TextArea 之间;ErrorMessage 页面渲染 `<p class="hv-error-message" slot="errorMessage">`。
未验证:逐像素对比、读屏软件、物理触屏、窄屏断点截图。截图在本轮首次采集后 IAB 合成器不再返回帧(`capture timed out`),因此尺寸/配色改为计算样式断言,未以旧截图充当本轮证据。 未验证:逐像素对比、读屏软件、物理触屏、窄屏断点截图。截图在本轮首次采集后 IAB 合成器不再返回帧(`capture timed out`),因此尺寸/配色改为计算样式断言,未以旧截图充当本轮证据。
## B03 复核与接手修复(2026-10-25)
Tag/TagGroup/ErrorMessage 的最新验收见 [B03 复核记录](migrations/B03-review-acceptance.md)。修复属性透传、子控件键盘所有权、禁用/按下状态、gridcell、单 Tab 入口、asChild 和真实浏览器移除焦点时序;新增确认移除公告。47 项本批测试、全套 985 项、类型/文档构建与独立 tarball 消费通过。浏览器仅重点检查移除与键盘,不宣称全量视觉或读屏验收。
+63 -9
View File
@@ -11,8 +11,12 @@ import {
provide, provide,
ref, ref,
watchEffect, watchEffect,
watch,
type PropType, type PropType,
type Component,
type Slots,
type SlotsType, type SlotsType,
type VNodeArrayChildren,
type VNode, type VNode,
type VNodeChild, type VNodeChild,
} from "vue"; } from "vue";
@@ -104,7 +108,7 @@ export default defineComponent({
); );
const textValue = () => props.textValue ?? latestText; const textValue = () => props.textValue ?? latestText;
const state = (): TagRenderState => ({ const state = (): TagRenderState => ({
isSelected: group.selected(props.id), isSelected: group.mode.value !== "none" && group.selected(props.id),
isDisabled: disabled.value, isDisabled: disabled.value,
isHovered: hovered.value && !disabled.value, isHovered: hovered.value && !disabled.value,
isPressed: isPressed:
@@ -119,6 +123,7 @@ export default defineComponent({
provide(tagKey, { provide(tagKey, {
tagSlots: group.tagSlots, tagSlots: group.tagSlots,
textValue, textValue,
disabled,
}); });
const unregister = group.register({ const unregister = group.register({
@@ -139,6 +144,7 @@ export default defineComponent({
const owner = node.ownerDocument; const owner = node.ownerDocument;
const release = () => { const release = () => {
pressed.value = false; pressed.value = false;
if (group.pressed.value === props.id) group.pressed.value = undefined;
}; };
owner.addEventListener("pointerup", release, true); owner.addEventListener("pointerup", release, true);
owner.addEventListener("pointercancel", release, true); owner.addEventListener("pointercancel", release, true);
@@ -148,6 +154,15 @@ export default defineComponent({
}); });
}); });
watch(disabled, (value) => {
if (value) {
pressed.value = false;
hovered.value = false;
if (group.pressed.value === props.id) group.pressed.value = undefined;
}
});
expose({ element, focus: () => group.focus(props.id) });
function click(event: MouseEvent) { function click(event: MouseEvent) {
if (event.defaultPrevented || disabled.value) return; if (event.defaultPrevented || disabled.value) return;
const target = event.target as Element | null; const target = event.target as Element | null;
@@ -191,6 +206,44 @@ export default defineComponent({
if (key === "class" || key === "style") continue; if (key === "class" || key === "style") continue;
restAttrs[key] = value; restAttrs[key] = value;
} }
const cell = (children: VNodeChild[]) =>
h(
"span",
{ role: "gridcell", style: { display: "contents" } },
children,
);
let rowChildren: VNodeChild[] = [cell(removable)];
if (props.asChild) {
// Keep the caller's actual row root, then insert its semantic cell.
const child =
content.length === 1 && isVNode(content[0]) ? content[0] : undefined;
if (!child)
throw new Error("Tag asChild requires one element or component.");
const buttons = current.allowsRemoving
? removable.slice(content.length)
: [];
if (typeof child.type === "string") {
const children = Array.isArray(child.children)
? (child.children as VNodeChild[])
: [child.children as VNodeChild];
rowChildren = [
h(child.type, child.props, [cell([...children, ...buttons])]),
];
} else {
const childSlots = child.children as Slots | null;
rowChildren = [
h(child.type as Component, child.props, {
...childSlots,
default: (...args: unknown[]) => [
cell([...(childSlots?.default?.(...args) ?? []), ...buttons]),
],
}),
];
}
// Preserve the caller's normalized ref owner when rebuilding children.
const row = rowChildren[0];
if (isVNode(row)) row.ref = child.ref;
}
return h( return h(
Primitive, Primitive,
mergeProps({ as: props.as, asChild: props.asChild }, restAttrs, { mergeProps({ as: props.as, asChild: props.asChild }, restAttrs, {
@@ -217,12 +270,15 @@ export default defineComponent({
focusVisible.value = !!element()?.matches(":focus-visible"); focusVisible.value = !!element()?.matches(":focus-visible");
if (!disabled.value) group.noteFocus(props.id); if (!disabled.value) group.noteFocus(props.id);
}, },
onBlur: () => { onBlur: (event: FocusEvent) => {
if (element()?.contains(event.relatedTarget as Node | null)) return;
focused.value = false; focused.value = false;
focusVisible.value = false; focusVisible.value = false;
pressed.value = false; pressed.value = false;
if (group.focused.value === props.id) if (group.focused.value === props.id)
group.focused.value = undefined; group.focused.value = undefined;
if (group.pressed.value === props.id)
group.pressed.value = undefined;
}, },
onPointerenter: () => { onPointerenter: () => {
hovered.value = true; hovered.value = true;
@@ -232,12 +288,10 @@ export default defineComponent({
pressed.value = false; pressed.value = false;
}, },
onPointerdown: (event: PointerEvent) => { onPointerdown: (event: PointerEvent) => {
if ( if (event.defaultPrevented || disabled.value || event.button !== 0)
!event.defaultPrevented && return;
!disabled.value && group.keyboard.value = false;
event.button === 0 pressed.value = true;
)
pressed.value = true;
group.pressed.value = props.id; group.pressed.value = props.id;
}, },
onPointerup: () => { onPointerup: () => {
@@ -246,7 +300,7 @@ export default defineComponent({
group.pressed.value = undefined; group.pressed.value = undefined;
}, },
}), }),
{ default: () => removable }, { default: () => rowChildren as VNodeArrayChildren },
); );
}; };
}, },
+77 -12
View File
@@ -123,12 +123,7 @@ export default defineComponent({
.map((member) => member.key()), .map((member) => member.key()),
); );
const isDisabledKey = (key: TagKey) => const isDisabledKey = (key: TagKey) =>
disabled.value || disabled.value || props.disabledKeys.includes(key);
props.disabledKeys.includes(key) ||
!!registry
.ordered()
.find((member) => member.key() === key)
?.disabled();
const selection = useCollectionSelection({ const selection = useCollectionSelection({
mode: () => props.selectionMode, mode: () => props.selectionMode,
@@ -291,14 +286,38 @@ export default defineComponent({
const allowsRemoving = () => removing.value && !disabled.value; const allowsRemoving = () => removing.value && !disabled.value;
function requestRemoval(key: TagKey) { function requestRemoval(key: TagKey) {
if (disabled.value || !removing.value || isDisabledKey(key)) return; if (
disabled.value ||
!removing.value ||
isDisabledKey(key) ||
registry
.ordered()
.find((member) => member.key() === key)
?.disabled()
)
return;
// Remember where the removal started: pressing the remove button moves // Remember where the removal started: pressing the remove button moves
// DOM focus to that button, so the row itself was never focused. // DOM focus to that button, so the row itself was never focused.
lastFocused.value = key; lastFocused.value = key;
lastIndex = order.value.indexOf(key); const list = listElement.value?.();
const current = list?.ownerDocument.activeElement ?? null;
if (
list &&
(list.contains(current) || current === list.ownerDocument.body)
) {
focused.value = key;
removalFocus = key;
}
lastIndex = registry
.ordered()
.findIndex((member) => member.key() === key);
pendingRemovals.set(key, textValue(key));
emit("remove", [key]); emit("remove", [key]);
} }
let removalFocus: TagKey | undefined;
const announcement = ref("");
const pendingRemovals = new Map<TagKey, string>();
// Focus follows the removal only after the item is actually gone: a parent // Focus follows the removal only after the item is actually gone: a parent
// that rejects the proposal keeps both the item and the focus. // that rejects the proposal keeps both the item and the focus.
const order = computed(() => const order = computed(() =>
@@ -306,22 +325,59 @@ export default defineComponent({
); );
let lastIndex = -1; let lastIndex = -1;
watch(order, (next) => { watch(order, (next) => {
for (const [removedKey, label] of pendingRemovals) {
if (next.includes(removedKey)) continue;
pendingRemovals.delete(removedKey);
announcement.value = config?.locale.value.startsWith("zh")
? `已移除 ${label}`
: `Removed ${label}`;
}
const key = lastFocused.value; const key = lastFocused.value;
if (key === undefined || !mounted || disposing) return; if (key === undefined || !mounted || disposing) return;
if (next.includes(key)) return; if (next.includes(key)) return;
// Remembering the Tab entry does not grant ownership of external focus.
const list = listElement.value?.();
const current = list?.ownerDocument.activeElement ?? null;
const restoringRemoval =
removalFocus === key &&
list &&
(current === list.ownerDocument.body || list.contains(current));
removalFocus = undefined;
if (focused.value !== key && !restoringRemoval) {
lastFocused.value = undefined;
return;
}
const remaining = eligible(); const remaining = eligible();
if (!remaining.length) { if (!remaining.length) {
restoreFocus(); restoreFocus();
return; return;
} }
const index = Math.min(Math.max(lastIndex, 0), remaining.length - 1); const enabledKeys = new Set(remaining.map((member) => member.key()));
void focus(remaining[index].key()); const index = Math.max(lastIndex, 0);
const neighbour =
next.slice(index).find((key) => enabledKeys.has(key)) ??
next
.slice(0, index)
.reverse()
.find((key) => enabledKeys.has(key));
if (neighbour !== undefined) void focus(neighbour);
}); });
let pendingSpace: TagKey | undefined; let pendingSpace: TagKey | undefined;
function ownsKey(event: KeyboardEvent) {
const target = event.target as Element | null;
const list = listElement.value?.();
if (!target || !list || target.closest('[role="grid"]') !== list)
return false;
const interactive = target.closest(
'button, a, input, select, textarea, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="textbox"], [role="checkbox"], [role="switch"]',
);
return !interactive || interactive === list;
}
function onKeydown(event: KeyboardEvent) { function onKeydown(event: KeyboardEvent) {
if ( if (
event.defaultPrevented || event.defaultPrevented ||
!ownsKey(event) ||
event.isComposing || event.isComposing ||
event.keyCode === 229 || event.keyCode === 229 ||
disabled.value disabled.value
@@ -375,7 +431,12 @@ export default defineComponent({
const key = pendingSpace; const key = pendingSpace;
pendingSpace = undefined; pendingSpace = undefined;
pressed.value = undefined; pressed.value = undefined;
if (key !== undefined && !event.defaultPrevented) { if (
key !== undefined &&
!event.defaultPrevented &&
ownsKey(event) &&
focused.value === key
) {
activate(key, event); activate(key, event);
event.preventDefault(); event.preventDefault();
} }
@@ -399,6 +460,7 @@ export default defineComponent({
provide(tagGroupKey, { provide(tagGroupKey, {
slots: groupSlots, slots: groupSlots,
announcement,
tagSlots, tagSlots,
mode: computed(() => props.selectionMode), mode: computed(() => props.selectionMode),
disabled, disabled,
@@ -420,7 +482,9 @@ export default defineComponent({
noteFocus: (key) => { noteFocus: (key) => {
lastFocused.value = key; lastFocused.value = key;
focused.value = key; focused.value = key;
lastIndex = order.value.indexOf(key); lastIndex = registry
.ordered()
.findIndex((member) => member.key() === key);
}, },
textValue, textValue,
ariaLabel, ariaLabel,
@@ -457,6 +521,7 @@ export default defineComponent({
Primitive, Primitive,
mergeProps({ as: props.as, asChild: props.asChild }, rest, { mergeProps({ as: props.as, asChild: props.asChild }, rest, {
class: [tagGroupVariants().base(), attrs.class], class: [tagGroupVariants().base(), attrs.class],
style: attrs.style,
dir: dir.value, dir: dir.value,
"data-slot": "tag-group", "data-slot": "tag-group",
"data-disabled": disabled.value || undefined, "data-disabled": disabled.value || undefined,
@@ -1,5 +1,5 @@
<script setup lang="ts" generic="T extends TagGroupDataItem = TagGroupDataItem"> <script setup lang="ts" generic="T extends TagGroupDataItem = TagGroupDataItem">
import { computed, mergeProps, ref, useAttrs } from "vue"; import { mergeProps, ref, useAttrs } from "vue";
import { Primitive } from "reka-ui"; import { Primitive } from "reka-ui";
import { elementFromRef } from "./dom"; import { elementFromRef } from "./dom";
import { import {
@@ -24,11 +24,6 @@ const root = ref<unknown>();
const element = () => elementFromRef(root.value); const element = () => elementFromRef(root.value);
group.registerList(element); group.registerList(element);
const describedBy = computed(() => group.describedBy());
const labelledBy = computed(() =>
group.ariaLabel() ? undefined : group.labelledBy(),
);
function rootAttrs() { function rootAttrs() {
const rest: Record<string, unknown> = {}; const rest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(attrs)) { for (const [key, value] of Object.entries(attrs)) {
@@ -46,14 +41,22 @@ function rootAttrs() {
ref: root, ref: root,
role: "grid", role: "grid",
class: [group.slots.value.list(), attrs.class], class: [group.slots.value.list(), attrs.class],
style: attrs.style,
"data-slot": "tag-group-list", "data-slot": "tag-group-list",
"data-disabled": group.disabled.value || undefined, "data-disabled": group.disabled.value || undefined,
"aria-label": group.ariaLabel(), "aria-label": attrs["aria-label"] ?? group.ariaLabel(),
"aria-labelledby": labelledBy.value, "aria-labelledby":
"aria-describedby": describedBy.value, attrs["aria-labelledby"] ??
(attrs["aria-label"] || group.ariaLabel()
? undefined
: group.labelledBy()),
"aria-describedby":
[attrs["aria-describedby"], group.describedBy()]
.filter(Boolean)
.join(" ") || undefined,
"aria-disabled": group.disabled.value || undefined, "aria-disabled": group.disabled.value || undefined,
"aria-multiselectable": group.mode.value === "multiple" ? true : undefined, "aria-multiselectable": group.mode.value === "multiple" ? true : undefined,
// Baseline announces collection additions/removals on the list itself. // Preserve baseline metadata; confirmed removals use the status below.
"aria-atomic": "false", "aria-atomic": "false",
"aria-relevant": "additions text", "aria-relevant": "additions text",
tabindex: group.hasEnabled() ? -1 : 0, tabindex: group.hasEnabled() ? -1 : 0,
@@ -76,8 +79,28 @@ function rootAttrs() {
<slot :item="item" :index="index" /> <slot :item="item" :index="index" />
</template> </template>
</template> </template>
<slot v-else name="empty" /> <div v-else role="row">
<span role="gridcell"><slot name="empty" /></span>
</div>
</template> </template>
<slot v-else :item="undefined!" :index="-1" /> <slot v-else :item="undefined!" :index="-1" />
</Primitive> </Primitive>
<span
role="status"
aria-live="polite"
aria-atomic="true"
style="
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
"
>
{{ group.announcement.value }}
</span>
</template> </template>
@@ -30,7 +30,8 @@ const label = computed(() => {
v-bind="attrs" v-bind="attrs"
:aria-label="(attrs['aria-label'] as string | undefined) ?? label" :aria-label="(attrs['aria-label'] as string | undefined) ?? label"
:class="[tag?.tagSlots.value.removeButton(), attrs.class]" :class="[tag?.tagSlots.value.removeButton(), attrs.class]"
:is-disabled="props.isDisabled || !tag" :is-disabled="props.isDisabled || !tag || tag.disabled.value"
:tabindex="(attrs.tabindex as number | string | undefined) ?? -1"
data-slot="tag-remove-button" data-slot="tag-remove-button"
> >
<slot /> <slot />
@@ -22,6 +22,7 @@ export interface TagGroupOptions {
disallowEmptySelection?: boolean; disallowEmptySelection?: boolean;
size?: "sm" | "md" | "lg"; size?: "sm" | "md" | "lg";
variant?: "default" | "surface"; variant?: "default" | "surface";
dir?: "ltr" | "rtl";
as?: string; as?: string;
asChild?: boolean; asChild?: boolean;
} }
@@ -45,6 +46,7 @@ export interface TagGroupListProps<
asChild?: boolean; asChild?: boolean;
} }
export interface TagGroupContext { export interface TagGroupContext {
announcement: Ref<string>;
slots: ComputedRef<ReturnType<typeof tagGroupVariants>>; slots: ComputedRef<ReturnType<typeof tagGroupVariants>>;
tagSlots: ComputedRef<ReturnType<typeof tagVariants>>; tagSlots: ComputedRef<ReturnType<typeof tagVariants>>;
mode: ComputedRef<CollectionSelectionMode>; mode: ComputedRef<CollectionSelectionMode>;
@@ -71,6 +73,7 @@ export interface TagGroupContext {
onKeyup: (event: KeyboardEvent) => void; onKeyup: (event: KeyboardEvent) => void;
} }
export interface TagContext { export interface TagContext {
disabled: ComputedRef<boolean>;
tagSlots: ComputedRef<ReturnType<typeof tagVariants>>; tagSlots: ComputedRef<ReturnType<typeof tagVariants>>;
textValue: () => string; textValue: () => string;
} }
+292
View File
@@ -987,6 +987,7 @@ describe("Tag demos and documentation", () => {
...document.matchAll(/<ComponentPreview name="tag-group-([^"]+)"/g), ...document.matchAll(/<ComponentPreview name="tag-group-([^"]+)"/g),
].map((match) => match[1]); ].map((match) => match[1]);
expect(document).not.toContain("[!toc]");
expect(names).toEqual(previews); expect(names).toEqual(previews);
for (const name of previews) { for (const name of previews) {
const source = readFileSync( const source = readFileSync(
@@ -1008,6 +1009,7 @@ describe("Tag demos and documentation", () => {
), ),
].map((match) => match[1]); ].map((match) => match[1]);
expect(errorDocument).not.toContain("[!toc]");
expect(errorNames).toEqual(["basic", "custom-styles"]); expect(errorNames).toEqual(["basic", "custom-styles"]);
for (const name of errorNames) { for (const name of errorNames) {
const source = readFileSync( const source = readFileSync(
@@ -1084,3 +1086,293 @@ describe("Tag demos and documentation", () => {
} }
}); });
}); });
describe("B03 review regressions", () => {
it("preserves root/list styles and list-local accessible names", async () => {
await mountGroup({
props: { style: { marginTop: "7px" } },
groupProps: {
style: { paddingTop: "9px" },
"aria-label": "Local tags",
"aria-describedby": "external-help",
},
});
expect(queryOne('[data-slot="tag-group"]')!.style.marginTop).toBe("7px");
const list = queryOne('[role="grid"]')!;
expect(list.style.paddingTop).toBe("9px");
expect(list.getAttribute("aria-label")).toBe("Local tags");
expect(list.getAttribute("aria-describedby")).toContain("external-help");
});
it("does not select or navigate from an embedded input or remove button", async () => {
const update = vi.fn();
const remove = vi.fn();
await mountGroup({
props: { "onUpdate:modelValue": update, onRemove: remove },
content: (item) => [item.label, h("input", { "aria-label": "Edit" })],
});
const input = queryOne("input")!;
input.focus();
for (const key of ["ArrowRight", "Home", "Delete", "Enter", " "]) {
input.dispatchEvent(
new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }),
);
input.dispatchEvent(
new KeyboardEvent("keyup", { key, bubbles: true, cancelable: true }),
);
}
await nextTick();
expect(document.activeElement).toBe(input);
expect(update).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
const button = queryOne('[data-slot="tag-remove-button"]')!;
button.focus();
button.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Enter",
bubbles: true,
cancelable: true,
}),
);
await nextTick();
expect(update).not.toHaveBeenCalled();
});
it("disables the remove button of an individually disabled tag", async () => {
await mountGroup({
props: { onRemove: vi.fn() },
tags: [{ id: "a", label: "A", disabled: true }],
});
expect(queryOne<HTMLButtonElement>("button")!.disabled).toBe(true);
});
it("clears a pointer press released outside the row", async () => {
await mountGroup();
const tag = row("资讯")!;
tag.dispatchEvent(
new MouseEvent("pointerdown", { button: 0, bubbles: true }),
);
await nextTick();
expect(tag.hasAttribute("data-pressed")).toBe(true);
document.dispatchEvent(new Event("pointerup", { bubbles: true }));
await nextTick();
expect(tag.hasAttribute("data-pressed")).toBe(false);
});
it("provides gridcell children for every grid row", async () => {
await mountGroup();
for (const tag of queryAll('[role="row"]'))
expect(tag.querySelector('[role="gridcell"]')).not.toBeNull();
});
it("does not steal external focus when a previously focused item is removed", async () => {
const tags = ref([
{ id: "a", label: "A" },
{ id: "b", label: "B" },
]);
const wrapper = mount(
defineComponent({
setup: () => () =>
h("div", [
h("input", { "aria-label": "Outside" }),
h(
TagGroup,
{ "aria-label": "Tags" },
{
default: () =>
h(TagGroupList, null, {
default: () =>
tags.value.map((item) =>
h(Tag, { id: item.id, key: item.id }, () => item.label),
),
}),
},
),
]),
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
queryOne('[role="row"]')!.focus();
await nextTick();
const outside = queryOne("input")!;
outside.focus();
await nextTick();
tags.value = tags.value.slice(1);
await nextTick();
await nextTick();
await nextTick();
expect(document.activeElement).toBe(outside);
});
});
describe("B03 composition and removal", () => {
it.each([false, true])(
"keeps the custom row root and grid cell with asChild (component=%s)",
async (component) => {
const Custom = defineComponent({
setup:
(_, { slots }) =>
() =>
h("article", { "data-custom": "row" }, slots.default?.()),
});
const wrapper = mount(TagGroup, {
props: { onRemove: vi.fn(), "aria-label": "Custom" },
slots: {
default: () =>
h(TagGroupList, null, {
default: () =>
h(Tag, { id: "custom", asChild: true }, () =>
component
? h(
Custom,
{ "data-custom": "row" },
{ default: () => "Custom" },
)
: h("article", { "data-custom": "row" }, "Custom"),
),
}),
},
attachTo: document.body,
});
wrappers.push(wrapper);
await nextTick();
await settle();
const tag = queryOne('[data-slot="tag"]')!;
expect(tag.tagName).toBe("ARTICLE");
expect(tag.getAttribute("data-custom")).toBe("row");
expect(tag.getAttribute("role")).toBe("row");
expect(tag.querySelector('[role="gridcell"]')!.textContent).toContain(
"Custom",
);
expect(tag.querySelectorAll("button")).toHaveLength(1);
},
);
it("uses actual neighbour order when disabled rows precede a removed row", async () => {
const items = ref([
{ id: "d", label: "Disabled", disabled: true },
{ id: "a", label: "A" },
{ id: "b", label: "B" },
{ id: "c", label: "C" },
]);
const wrapper = mount(
defineComponent({
setup: () => () =>
h(
TagGroup,
{
"aria-label": "Tags",
onRemove: (keys: (string | number)[]) => {
items.value = items.value.filter(
(item) => !keys.includes(item.id),
);
},
},
{
default: () =>
h(TagGroupList, null, {
default: () =>
items.value.map((item) =>
h(
Tag,
{
id: item.id,
key: item.id,
isDisabled: item.disabled,
},
() => item.label,
),
),
}),
},
),
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
const tag = row("A")!;
tag.focus();
await nextTick();
tag.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Delete",
bubbles: true,
cancelable: true,
}),
);
await nextTick();
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("B"));
expect(queryOne('[role="status"]')!.textContent).toContain("A");
});
it("does not announce removal rejected by the parent", async () => {
await mountGroup({ props: { onRemove: vi.fn() } });
row("资讯")!.focus();
await nextTick();
row("资讯")!.dispatchEvent(
new KeyboardEvent("keydown", { key: "Delete", bubbles: true }),
);
await nextTick();
expect(queryOne('[role="status"]')!.textContent).toBe("");
expect(document.activeElement).toBe(row("资讯"));
});
});
describe("B03 native focus regressions", () => {
it("restores after native removal clears focus before the registry updates", async () => {
const items = ref(["A", "B"]);
const wrapper = mount(
defineComponent({
setup: () => () =>
h(
TagGroup,
{
"aria-label": "Native",
onRemove: (keys: (string | number)[]) => {
(document.activeElement as HTMLElement).blur();
items.value = items.value.filter((key) => !keys.includes(key));
},
},
{
default: () =>
h(TagGroupList, null, {
default: () =>
items.value.map((key) =>
h(Tag, { id: key, key }, () => key),
),
}),
},
),
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
const button = row("A")!.querySelector("button")!;
button.focus();
await nextTick();
button.click();
await nextTick();
await nextTick();
await nextTick();
expect(document.activeElement).toBe(row("B"));
});
it("keeps one default Tab stop in a removable collection", async () => {
await mountGroup({ props: { onRemove: vi.fn() } });
expect(
queryAll('[role="row"]').filter((el) => el.tabIndex === 0),
).toHaveLength(1);
expect(
queryAll<HTMLButtonElement>("button").every((el) => el.tabIndex === -1),
).toBe(true);
});
});