import { injectDialogRootContext } from 'reka-ui'; import { watch } from 'vue'; /** Reka restores registered triggers; also support dialogs opened programmatically. */ export function useDialogFocus() { const context = injectDialogRootContext(); let previousFocus: HTMLElement | null = null; watch( context.open, (open) => { if (open && typeof document !== 'undefined') { previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; } }, { flush: 'sync', immediate: true }, ); function restoreFocus(event: Event): void { if ( !event.defaultPrevented && !context.triggerElement.value && previousFocus?.isConnected ) { event.preventDefault(); previousFocus.focus({ preventScroll: true }); } } return { restoreFocus }; }