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
+63 -9
View File
@@ -11,8 +11,12 @@ import {
provide,
ref,
watchEffect,
watch,
type PropType,
type Component,
type Slots,
type SlotsType,
type VNodeArrayChildren,
type VNode,
type VNodeChild,
} from "vue";
@@ -104,7 +108,7 @@ export default defineComponent({
);
const textValue = () => props.textValue ?? latestText;
const state = (): TagRenderState => ({
isSelected: group.selected(props.id),
isSelected: group.mode.value !== "none" && group.selected(props.id),
isDisabled: disabled.value,
isHovered: hovered.value && !disabled.value,
isPressed:
@@ -119,6 +123,7 @@ export default defineComponent({
provide(tagKey, {
tagSlots: group.tagSlots,
textValue,
disabled,
});
const unregister = group.register({
@@ -139,6 +144,7 @@ export default defineComponent({
const owner = node.ownerDocument;
const release = () => {
pressed.value = false;
if (group.pressed.value === props.id) group.pressed.value = undefined;
};
owner.addEventListener("pointerup", 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) {
if (event.defaultPrevented || disabled.value) return;
const target = event.target as Element | null;
@@ -191,6 +206,44 @@ export default defineComponent({
if (key === "class" || key === "style") continue;
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(
Primitive,
mergeProps({ as: props.as, asChild: props.asChild }, restAttrs, {
@@ -217,12 +270,15 @@ export default defineComponent({
focusVisible.value = !!element()?.matches(":focus-visible");
if (!disabled.value) group.noteFocus(props.id);
},
onBlur: () => {
onBlur: (event: FocusEvent) => {
if (element()?.contains(event.relatedTarget as Node | null)) return;
focused.value = false;
focusVisible.value = false;
pressed.value = false;
if (group.focused.value === props.id)
group.focused.value = undefined;
if (group.pressed.value === props.id)
group.pressed.value = undefined;
},
onPointerenter: () => {
hovered.value = true;
@@ -232,12 +288,10 @@ export default defineComponent({
pressed.value = false;
},
onPointerdown: (event: PointerEvent) => {
if (
!event.defaultPrevented &&
!disabled.value &&
event.button === 0
)
pressed.value = true;
if (event.defaultPrevented || disabled.value || event.button !== 0)
return;
group.keyboard.value = false;
pressed.value = true;
group.pressed.value = props.id;
},
onPointerup: () => {
@@ -246,7 +300,7 @@ export default defineComponent({
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()),
);
const isDisabledKey = (key: TagKey) =>
disabled.value ||
props.disabledKeys.includes(key) ||
!!registry
.ordered()
.find((member) => member.key() === key)
?.disabled();
disabled.value || props.disabledKeys.includes(key);
const selection = useCollectionSelection({
mode: () => props.selectionMode,
@@ -291,14 +286,38 @@ export default defineComponent({
const allowsRemoving = () => removing.value && !disabled.value;
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
// DOM focus to that button, so the row itself was never focused.
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]);
}
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
// that rejects the proposal keeps both the item and the focus.
const order = computed(() =>
@@ -306,22 +325,59 @@ export default defineComponent({
);
let lastIndex = -1;
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;
if (key === undefined || !mounted || disposing) 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();
if (!remaining.length) {
restoreFocus();
return;
}
const index = Math.min(Math.max(lastIndex, 0), remaining.length - 1);
void focus(remaining[index].key());
const enabledKeys = new Set(remaining.map((member) => member.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;
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) {
if (
event.defaultPrevented ||
!ownsKey(event) ||
event.isComposing ||
event.keyCode === 229 ||
disabled.value
@@ -375,7 +431,12 @@ export default defineComponent({
const key = pendingSpace;
pendingSpace = undefined;
pressed.value = undefined;
if (key !== undefined && !event.defaultPrevented) {
if (
key !== undefined &&
!event.defaultPrevented &&
ownsKey(event) &&
focused.value === key
) {
activate(key, event);
event.preventDefault();
}
@@ -399,6 +460,7 @@ export default defineComponent({
provide(tagGroupKey, {
slots: groupSlots,
announcement,
tagSlots,
mode: computed(() => props.selectionMode),
disabled,
@@ -420,7 +482,9 @@ export default defineComponent({
noteFocus: (key) => {
lastFocused.value = key;
focused.value = key;
lastIndex = order.value.indexOf(key);
lastIndex = registry
.ordered()
.findIndex((member) => member.key() === key);
},
textValue,
ariaLabel,
@@ -457,6 +521,7 @@ export default defineComponent({
Primitive,
mergeProps({ as: props.as, asChild: props.asChild }, rest, {
class: [tagGroupVariants().base(), attrs.class],
style: attrs.style,
dir: dir.value,
"data-slot": "tag-group",
"data-disabled": disabled.value || undefined,
@@ -1,5 +1,5 @@
<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 { elementFromRef } from "./dom";
import {
@@ -24,11 +24,6 @@ const root = ref<unknown>();
const element = () => elementFromRef(root.value);
group.registerList(element);
const describedBy = computed(() => group.describedBy());
const labelledBy = computed(() =>
group.ariaLabel() ? undefined : group.labelledBy(),
);
function rootAttrs() {
const rest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(attrs)) {
@@ -46,14 +41,22 @@ function rootAttrs() {
ref: root,
role: "grid",
class: [group.slots.value.list(), attrs.class],
style: attrs.style,
"data-slot": "tag-group-list",
"data-disabled": group.disabled.value || undefined,
"aria-label": group.ariaLabel(),
"aria-labelledby": labelledBy.value,
"aria-describedby": describedBy.value,
"aria-label": attrs["aria-label"] ?? group.ariaLabel(),
"aria-labelledby":
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-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-relevant": "additions text",
tabindex: group.hasEnabled() ? -1 : 0,
@@ -76,8 +79,28 @@ function rootAttrs() {
<slot :item="item" :index="index" />
</template>
</template>
<slot v-else name="empty" />
<div v-else role="row">
<span role="gridcell"><slot name="empty" /></span>
</div>
</template>
<slot v-else :item="undefined!" :index="-1" />
</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>
@@ -30,7 +30,8 @@ const label = computed(() => {
v-bind="attrs"
:aria-label="(attrs['aria-label'] as string | undefined) ?? label"
: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"
>
<slot />
@@ -22,6 +22,7 @@ export interface TagGroupOptions {
disallowEmptySelection?: boolean;
size?: "sm" | "md" | "lg";
variant?: "default" | "surface";
dir?: "ltr" | "rtl";
as?: string;
asChild?: boolean;
}
@@ -45,6 +46,7 @@ export interface TagGroupListProps<
asChild?: boolean;
}
export interface TagGroupContext {
announcement: Ref<string>;
slots: ComputedRef<ReturnType<typeof tagGroupVariants>>;
tagSlots: ComputedRef<ReturnType<typeof tagVariants>>;
mode: ComputedRef<CollectionSelectionMode>;
@@ -71,6 +73,7 @@ export interface TagGroupContext {
onKeyup: (event: KeyboardEvent) => void;
}
export interface TagContext {
disabled: ComputedRef<boolean>;
tagSlots: ComputedRef<ReturnType<typeof tagVariants>>;
textValue: () => string;
}