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
@@ -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,
};
}