feat: migrate Toolbar with teleport-safe focus ownership

This commit is contained in:
maoyingjie
2026-10-23 10:50:42 +08:00
parent 9c93647ad2
commit b2525bb04d
33 changed files with 2168 additions and 30 deletions
+34
View File
@@ -0,0 +1,34 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
/* ==========================================================================
Toolbar - Container for interactive controls with arrow key navigation
========================================================================== */
/* Base styles */
.hv-toolbar {
@apply grid w-fit grid-flow-col items-center gap-2;
.hv-separator--vertical {
@apply h-1/2 self-center;
}
.hv-separator--horizontal {
@apply w-1/2 justify-center justify-self-center;
}
}
/* Orientation variants */
.hv-toolbar--horizontal {
}
.hv-toolbar--vertical {
@apply grid-flow-row items-start justify-start;
.hv-button-group {
@apply justify-start;
}
}
/* Attached variant */
.hv-toolbar--attached {
@apply rounded-3xl bg-surface p-1 shadow-overlay;
}
+1
View File
@@ -133,3 +133,4 @@
@import "./components/button-group.css" layer(components);
@import "./components/toggle-button.css" layer(components);
@import "./components/toggle-button-group.css" layer(components);
@import "./components/toolbar.css" layer(components);
+19
View File
@@ -1148,3 +1148,22 @@ export const toggleButtonGroupVariants = tv({
export type ToggleButtonGroupVariants = VariantProps<
typeof toggleButtonGroupVariants
>;
export const toolbarVariants = tv({
base: "hv-toolbar",
defaultVariants: {
isAttached: false,
orientation: "horizontal",
},
variants: {
isAttached: {
true: "hv-toolbar--attached",
},
orientation: {
horizontal: "hv-toolbar--horizontal",
vertical: "hv-toolbar--vertical",
},
},
});
export type ToolbarVariants = VariantProps<typeof toolbarVariants>;
+59 -3
View File
@@ -1,12 +1,14 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import { computed, inject, ref, watch } from "vue";
import { computed, inject, onBeforeUnmount, ref, useAttrs, watch } from "vue";
import { Primitive } from "reka-ui";
import type { ButtonHTMLAttributes } from "vue";
import { buttonVariants, type ButtonVariants } from "@heroui-vue/styles";
import Spinner from "../spinner/Spinner.vue";
import { buttonGroupContextKey } from "../button-group/context";
import { toolbarKey } from "../toolbar/context";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const props = withDefaults(
defineProps<{
variant?: ButtonVariants["variant"];
@@ -32,6 +34,7 @@ const props = withDefaults(
},
);
const buttonGroupContext = inject(buttonGroupContextKey, undefined);
const toolbar = inject(toolbarKey, undefined);
const isButtonGroupChild = computed(() => props.__button_group_child === true);
const finalSize = computed(
() =>
@@ -69,6 +72,55 @@ const localDisabled = computed(() =>
);
const pending = computed(() => props.isPending || props.loading);
const disabled = useInheritedDisabled(() => localDisabled.value);
const root = ref<HTMLElement | undefined>();
let toolbarUnregister: (() => void) | undefined;
function setRoot(el: unknown) {
const node = el as { $el?: HTMLElement } | HTMLElement | null;
const next = !node
? undefined
: node instanceof HTMLElement
? node
: ((node.$el as HTMLElement) ?? undefined);
if (root.value === next) return;
root.value = next;
}
/** Toolbar owns focus only for DOM-contained buttons (not Teleport). */
const inToolbarDom = computed(() =>
Boolean(toolbar && root.value && toolbar.owns(root.value)),
);
watch(
() => [Boolean(toolbar), root.value, inToolbarDom.value] as const,
() => {
toolbarUnregister?.();
toolbarUnregister = undefined;
if (toolbar && inToolbarDom.value) {
toolbarUnregister = toolbar.register(() => root.value, disabled);
}
},
{ immediate: true, flush: "post" },
);
onBeforeUnmount(() => toolbarUnregister?.());
const toolbarTabIndex = computed(() =>
inToolbarDom.value ? toolbar!.tabIndex(root.value) : undefined,
);
/** Merge focus-owner attributes during rendering; preserve asChild attributes otherwise. */
function rootBind() {
const bound: Record<string, unknown> = { ...attrs };
const tab = toolbarTabIndex.value;
if (tab !== undefined) bound.tabindex = tab;
return bound;
}
function noteToolbarFocus(e: FocusEvent) {
void e;
if (inToolbarDom.value) toolbar!.noteFocus(root.value);
}
const hovered = ref(false),
pressed = ref(false),
focused = ref(false),
@@ -96,10 +148,11 @@ function focus(e: FocusEvent) {
</script>
<template>
<Primitive
:ref="setRoot"
@click.capture="guard"
as="button"
:as-child="asChild"
v-bind="$attrs"
v-bind="rootBind()"
:type="type"
:class="
buttonVariants({
@@ -128,7 +181,10 @@ function focus(e: FocusEvent) {
@keydown.space="pressed = !pending && !disabled"
@keydown.enter="pressed = !pending && !disabled"
@keyup="pressed = false"
@focus="focus"
@focus="
focus($event);
noteToolbarFocus($event);
"
@blur="
focused = false;
focusVisible = false;
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed, useAttrs } from "vue";
import { computed, inject, useAttrs } from "vue";
import { toolbarKey } from "../toolbar/context";
import { Separator as SeparatorPrimitive } from "reka-ui";
import { separatorVariants, type SeparatorVariants } from "@heroui-vue/styles";
@@ -17,7 +18,7 @@ const props = withDefaults(
asChild?: boolean;
}>(),
{
orientation: "horizontal",
orientation: undefined,
variant: "default",
decorative: false,
as: "hr",
@@ -26,10 +27,15 @@ const props = withDefaults(
);
const attrs = useAttrs();
const toolbar = inject(toolbarKey, undefined);
const orientation = computed(
() =>
props.orientation ?? toolbar?.separatorOrientation.value ?? "horizontal",
);
const baseClass = computed(() =>
separatorVariants({
orientation: props.orientation,
orientation: orientation.value,
variant: props.variant,
}),
);
@@ -6,7 +6,9 @@ import {
computed,
defineComponent,
h,
inject,
isVNode,
ref,
provide,
useAttrs,
type PropType,
@@ -17,6 +19,7 @@ import {
type ToggleButtonVariants,
} from "@heroui-vue/styles";
import { buttonGroupOrientationKey } from "../button-group/context";
import { toolbarKey } from "../toolbar/context";
import { useConfig } from "../../providers/context";
import {
toggleButtonGroupKey,
@@ -98,7 +101,7 @@ export default defineComponent({
disallowEmptySelection: { type: Boolean, default: false },
orientation: {
type: String as PropType<"horizontal" | "vertical">,
default: "horizontal",
default: undefined,
},
dir: {
type: String as PropType<"ltr" | "rtl">,
@@ -125,10 +128,27 @@ export default defineComponent({
setup(props, { attrs, slots, emit }) {
const isSingle = computed(() => props.selectionMode !== "multiple");
const isDisabled = computed(() => props.isDisabled || props.disabled);
const orientation = computed(() => props.orientation);
const toolbar = inject(toolbarKey, undefined);
const rootEl = ref<HTMLElement | undefined>();
function setRoot(el: unknown) {
const node = el as { $el?: HTMLElement } | HTMLElement | null;
const next = !node
? undefined
: node instanceof HTMLElement
? node
: ((node.$el as HTMLElement) ?? undefined);
if (rootEl.value === next) return;
rootEl.value = next;
}
const inToolbarDom = computed(() =>
Boolean(toolbar && rootEl.value && toolbar.owns(rootEl.value)),
);
const orientation = computed(
() => props.orientation ?? toolbar?.orientation.value ?? "horizontal",
);
const config = useConfig();
const dir = computed<"ltr" | "rtl">(
() => props.dir ?? config?.dir.value ?? "ltr",
() => props.dir ?? toolbar?.dir.value ?? config?.dir.value ?? "ltr",
);
const selection = useToggleButtonSelection({
@@ -166,10 +186,18 @@ export default defineComponent({
change: selection.request,
orientation,
dir,
tabIndex: roving.tabIndex,
register: (key, el, disabled) => roving.register({ key, el, disabled }),
keydown: roving.keydown,
noteFocus: roving.noteFocus,
// Focus ownership: defer only when this group is DOM-owned by a Toolbar.
tabIndex: (key) => (inToolbarDom.value ? -1 : roving.tabIndex(key)),
register: (key, el, disabled) =>
inToolbarDom.value ? () => {} : roving.register({ key, el, disabled }),
keydown: (event, key) => {
if (inToolbarDom.value) return;
roving.keydown(event, key);
},
noteFocus: (key) => {
if (inToolbarDom.value) return;
roving.noteFocus(key);
},
};
provide(toggleButtonGroupKey, groupContext);
@@ -179,6 +207,7 @@ export default defineComponent({
return h(
props.as,
{
ref: setRoot,
...attrs,
role: isSingle.value ? "radiogroup" : "toolbar",
class: [slotsMap.value.base(), attrs.class],
@@ -9,6 +9,7 @@ import {
toggleButtonGroupKey,
type ToggleButtonGroupKey,
} from "../toggle-button-group/context";
import { toolbarKey } from "../toolbar/context";
defineOptions({ inheritAttrs: false });
@@ -48,6 +49,7 @@ const emit = defineEmits<{
const attrs = useAttrs();
const group = inject(toggleButtonGroupKey, undefined);
const toolbar = inject(toolbarKey, undefined);
const groupKey = computed<ToggleButtonGroupKey | null>(() => {
const key = props.value ?? props.id;
return key === undefined || key === null ? null : key;
@@ -101,14 +103,13 @@ let unregister: (() => void) | undefined;
function setRoot(el: unknown) {
const node = el as { $el?: HTMLElement } | HTMLElement | null;
if (!node) {
root.value = undefined;
return;
}
root.value =
node instanceof HTMLElement
const next = !node
? undefined
: node instanceof HTMLElement
? node
: ((node.$el as HTMLElement) ?? undefined);
if (root.value === next) return;
root.value = next;
}
watch(
@@ -122,19 +123,28 @@ watch(
{ flush: "sync" },
);
const inToolbarDom = computed(() =>
Boolean(toolbar && root.value && toolbar.owns(root.value)),
);
function bindRegistration() {
unregister?.();
unregister = undefined;
if (toolbar && inToolbarDom.value) {
unregister = toolbar.register(() => root.value, disabled);
return;
}
if (!inGroup.value || !group || groupKey.value === null) return;
unregister = group.register(groupKey.value, () => root.value, disabled);
}
watch(
() => [inGroup.value, groupKey.value] as const,
() =>
[inGroup.value, groupKey.value, root.value, inToolbarDom.value] as const,
() => {
bindRegistration();
},
{ immediate: true },
{ immediate: true, flush: "post" },
);
onBeforeUnmount(() => unregister?.());
@@ -147,12 +157,18 @@ function guard(e: MouseEvent) {
function focus(e: FocusEvent) {
focused.value = true;
focusVisible.value = (e.target as HTMLElement).matches(":focus-visible");
if (inToolbarDom.value) {
toolbar!.noteFocus(root.value);
return;
}
if (inGroup.value && group && groupKey.value !== null) {
group.noteFocus(groupKey.value);
}
}
function onKeydown(e: KeyboardEvent) {
if (e.defaultPrevented) return;
// Toolbar root handles bubbled arrows for owned nodes only.
if (inToolbarDom.value) return;
if (!inGroup.value || !group || groupKey.value === null) return;
group.keydown(e, groupKey.value);
}
@@ -164,18 +180,27 @@ const finalVariant = computed(() => props.variant ?? "default");
const domId = computed(() =>
inGroup.value ? (attrs.id as string | undefined) : props.id,
);
const tabIndex = computed(() =>
inGroup.value && group && groupKey.value !== null
const tabIndex = computed(() => {
if (inToolbarDom.value) return toolbar!.tabIndex(root.value);
return inGroup.value && group && groupKey.value !== null
? group.tabIndex(groupKey.value)
: undefined,
);
: undefined;
});
/** Merge focus-owner attributes during rendering; preserve asChild attributes otherwise. */
function rootBind() {
const bound: Record<string, unknown> = { ...attrs };
const tab = tabIndex.value;
if (tab !== undefined) bound.tabindex = tab;
return bound;
}
</script>
<template>
<Primitive
:ref="setRoot"
as="button"
:as-child="asChild"
v-bind="$attrs"
v-bind="rootBind()"
:id="domId"
type="button"
:class="
@@ -190,7 +215,6 @@ const tabIndex = computed(() =>
:aria-checked="isSingleInGroup ? String(selected) : undefined"
:aria-pressed="isSingleInGroup ? undefined : String(selected)"
:aria-disabled="disabled || undefined"
:tabindex="tabIndex"
:data-selected="selected || undefined"
:data-hovered="(!disabled && hovered) || undefined"
:data-pressed="(!disabled && pressed) || undefined"
@@ -0,0 +1,136 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
onBeforeUnmount,
onUpdated,
provide,
ref,
useAttrs,
type PropType,
} from "vue";
import { toolbarVariants } from "@heroui-vue/styles";
import { buttonGroupOrientationKey } from "../button-group/context";
import { useConfig } from "../../providers/context";
import {
toolbarKey,
type ToolbarContextValue,
type ToolbarDir,
type ToolbarOrientation,
} from "./context";
import { useToolbarFocus } from "./useToolbarFocus";
type Handler = (event: Event) => void;
function mergeHandlers(
...parts: Array<Handler | Handler[] | undefined>
): Handler[] {
const list: Handler[] = [];
for (const part of parts) {
if (!part) continue;
if (Array.isArray(part)) list.push(...part.filter(Boolean));
else list.push(part);
}
return list;
}
export default defineComponent({
name: "Toolbar",
inheritAttrs: false,
props: {
isAttached: { type: Boolean, default: false },
orientation: {
type: String as PropType<ToolbarOrientation>,
default: "horizontal",
},
dir: {
type: String as PropType<ToolbarDir>,
default: undefined,
},
as: { type: String, default: "div" },
},
setup(props, { attrs, slots }) {
const config = useConfig();
const orientation = computed(() => props.orientation);
const dir = computed<ToolbarDir>(
() => props.dir ?? config?.dir.value ?? "ltr",
);
const separatorOrientation = computed<ToolbarOrientation>(() =>
orientation.value === "horizontal" ? "vertical" : "horizontal",
);
const focus = useToolbarFocus({
orientation: () => orientation.value,
dir: () => dir.value,
});
const rootEl = ref<HTMLElement | undefined>();
function setRoot(el: unknown) {
const node = el as { $el?: HTMLElement } | HTMLElement | null;
if (!node) {
rootEl.value = undefined;
focus.setRoot(undefined);
return;
}
rootEl.value =
node instanceof HTMLElement
? node
: ((node.$el as HTMLElement) ?? undefined);
focus.setRoot(rootEl.value);
}
const slotsMap = computed(() =>
toolbarVariants({
isAttached: props.isAttached,
orientation: orientation.value,
}),
);
const toolbarContext: ToolbarContextValue = {
slots: slotsMap,
orientation,
dir,
separatorOrientation,
register: (el, disabled) => focus.register({ el, disabled }),
tabIndex: focus.tabIndex,
noteFocus: focus.noteFocus,
keydown: focus.keydown,
owns: focus.owns,
};
provide(toolbarKey, toolbarContext);
provide(buttonGroupOrientationKey, orientation);
onBeforeUnmount(() => focus.dispose());
// Teleport moves the same nodes; refresh ownership when this subtree updates.
onUpdated(() => focus.refresh());
function render() {
const userKeydown = (attrs as Record<string, unknown>).onKeydown as
Handler | Handler[] | undefined;
const rest: Record<string, unknown> = { ...attrs };
delete rest.onKeydown;
// Caller handlers run first so preventDefault can cancel navigation.
const keydownHandlers = mergeHandlers(userKeydown, (event: Event) => {
toolbarContext.keydown(event as KeyboardEvent);
});
return h(
props.as,
{
...rest,
role: "toolbar",
"aria-orientation": orientation.value,
class: [slotsMap.value, attrs.class],
"data-slot": "toolbar",
dir: dir.value,
ref: setRoot,
onKeydown: keydownHandlers,
},
slots.default?.({ orientation: orientation.value }),
);
}
return render;
},
});
</script>
@@ -0,0 +1,29 @@
import type { ComputedRef, InjectionKey } from "vue";
export type ToolbarOrientation = "horizontal" | "vertical";
export type ToolbarDir = "ltr" | "rtl";
export interface ToolbarContextValue {
/** Class string from toolbarVariants. */
slots: ComputedRef<string>;
orientation: ComputedRef<ToolbarOrientation>;
dir: ComputedRef<ToolbarDir>;
/** Separator default direction is perpendicular to the toolbar. */
separatorOrientation: ComputedRef<ToolbarOrientation>;
/** Register a focusable member; returns unregister. */
register: (
el: () => HTMLElement | undefined,
disabled: ComputedRef<boolean>,
) => () => void;
/** Single Tab entry; undefined when the element is outside the toolbar DOM. */
tabIndex: (el: HTMLElement | undefined) => number | undefined;
/** Sync Tab entry after a real focus. */
noteFocus: (el: HTMLElement | undefined) => void;
/** Arrow/Home/End navigation across the whole toolbar. */
keydown: (event: KeyboardEvent) => void;
/** Whether an element is rendered inside this toolbar (excludes Teleport). */
owns: (el: HTMLElement | undefined | null) => boolean;
}
export const toolbarKey: InjectionKey<ToolbarContextValue> =
Symbol("HeroUIVue.Toolbar");
@@ -0,0 +1,220 @@
import { ref, watch, type ComputedRef } from "vue";
import type { ToolbarDir, ToolbarOrientation } from "./context";
export interface ToolbarMember {
el: () => HTMLElement | undefined;
disabled: ComputedRef<boolean>;
}
function domOrder(members: ToolbarMember[]): ToolbarMember[] {
const placed = members.map((m) => ({ m, el: m.el() }));
const withEl = placed.filter(
(p): p is { m: ToolbarMember; el: HTMLElement } => !!p.el,
);
const without = placed.filter((p) => !p.el).map((p) => p.m);
withEl.sort((a, b) => {
const pos = a.el.compareDocumentPosition(b.el);
if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;
if (pos & Node.DOCUMENT_POSITION_PRECEDING) return 1;
return 0;
});
return [...withEl.map((p) => p.m), ...without];
}
/**
* Element-based roving tabindex for a toolbar.
* Owns arrow navigation across DOM-contained members only (Teleport-safe).
*/
export function useToolbarFocus(options: {
orientation: () => ToolbarOrientation;
dir: () => ToolbarDir;
}) {
const members = new Set<ToolbarMember>();
const version = ref(0);
const activeEl = ref<HTMLElement | null>(null);
const rootEl = ref<HTMLElement | null>(null);
let observer: MutationObserver | undefined;
function bump() {
version.value++;
}
function disconnectObserver() {
observer?.disconnect();
observer = undefined;
}
function watchSubtree(el: HTMLElement) {
disconnectObserver();
if (typeof MutationObserver === "undefined") return;
// childList only: DOM moves (Teleport) change membership without attribute loops
observer = new MutationObserver(() => {
bump();
});
observer.observe(el, { childList: true, subtree: true });
}
function setRoot(el: HTMLElement | null | undefined) {
const next = el ?? null;
if (rootEl.value === next) return;
rootEl.value = next;
if (next) watchSubtree(next);
else disconnectObserver();
bump();
}
function dispose() {
disconnectObserver();
members.clear();
}
/** Re-evaluate DOM membership after moves (Teleport, reparent). */
function refresh() {
bump();
syncActive();
}
/** True when the element is rendered inside this toolbar's DOM subtree. */
function owns(el: HTMLElement | undefined | null): boolean {
// Track subtree moves so computed owners refresh after Teleport.
void version.value;
if (!el || !rootEl.value) return false;
return rootEl.value === el || rootEl.value.contains(el);
}
function ordered(): ToolbarMember[] {
void version.value;
return domOrder(
[...members].filter((m) => {
const el = m.el();
return !m.disabled.value && el && owns(el);
}),
);
}
function syncActive() {
const list = ordered();
const activeOk =
activeEl.value &&
list.some((m) => m.el() === activeEl.value) &&
!activeEl.value.hasAttribute("disabled");
if (!activeOk) {
activeEl.value = list[0]?.el() ?? null;
}
}
function register(member: ToolbarMember) {
members.add(member);
bump();
syncActive();
const stop = watch(
member.disabled,
() => {
syncActive();
bump();
},
{ flush: "sync" },
);
return () => {
stop();
members.delete(member);
syncActive();
bump();
};
}
function tabIndex(el: HTMLElement | undefined): number | undefined {
// Non-members (e.g. teleported) keep caller tabindex.
if (!el || !owns(el)) return undefined;
const list = ordered();
if (!list.length) return -1;
syncActive();
return el === activeEl.value ? 0 : -1;
}
function noteFocus(el: HTMLElement | undefined) {
if (!el || !owns(el)) return;
const member = [...members].find((m) => m.el() === el);
if (member?.disabled.value) return;
if (activeEl.value === el) return;
activeEl.value = el;
bump();
}
function focusMember(member: ToolbarMember) {
const el = member.el();
if (!el || !owns(el)) return;
activeEl.value = el;
bump();
el.focus();
}
function keydown(event: KeyboardEvent) {
if (event.defaultPrevented) return;
const list = ordered();
if (!list.length) return;
const current = (event.target as HTMLElement | null) ?? activeEl.value;
const index = list.findIndex((m) => m.el() === current);
if (index < 0) return;
const horizontal = options.orientation() === "horizontal";
const rtl = options.dir() === "rtl";
let nextIndex = index;
if (horizontal) {
switch (event.key) {
case "ArrowRight":
nextIndex = rtl
? (index - 1 + list.length) % list.length
: (index + 1) % list.length;
break;
case "ArrowLeft":
nextIndex = rtl
? (index + 1) % list.length
: (index - 1 + list.length) % list.length;
break;
case "Home":
nextIndex = 0;
break;
case "End":
nextIndex = list.length - 1;
break;
default:
return;
}
} else {
switch (event.key) {
case "ArrowDown":
nextIndex = (index + 1) % list.length;
break;
case "ArrowUp":
nextIndex = (index - 1 + list.length) % list.length;
break;
case "Home":
nextIndex = 0;
break;
case "End":
nextIndex = list.length - 1;
break;
default:
return;
}
}
event.preventDefault();
event.stopPropagation();
focusMember(list[nextIndex]!);
}
return {
register,
tabIndex,
noteFocus,
keydown,
setRoot,
owns,
dispose,
refresh,
version,
};
}
+9
View File
@@ -527,3 +527,12 @@ export type {
ToggleButtonGroupProps,
ToggleButtonGroupSeparatorProps,
} from "./types";
export { default as Toolbar } from "./components/toolbar/Toolbar.vue";
export type {
ToolbarOrientation,
ToolbarDir,
ToolbarContextValue,
} from "./components/toolbar/context";
export { toolbarVariants, type ToolbarVariants } from "@heroui-vue/styles";
export type { ToolbarProps } from "./types";
+3
View File
@@ -392,3 +392,6 @@ export type ToggleButtonGroupProps = InstanceType<
export type ToggleButtonGroupSeparatorProps = InstanceType<
typeof ToggleButtonGroupSeparator
>["$props"];
import type Toolbar from "./components/toolbar/Toolbar.vue";
export type ToolbarProps = InstanceType<typeof Toolbar>["$props"];