/** * Focus restoration for transient popovers and menus. * * `restoreFocus` is a Svelte action for a surface that is rendered only * while open (an `{#if open}` popover/menu/drawer). On mount it records * the element that had focus — the trigger that opened it — and on * destroy it returns focus there, so dismissing the surface (Escape, * outside click, or selecting an item) never drops keyboard focus to the * document body. * * Unlike `trapFocus`, it neither traps focus nor moves it into the * surface: menus are non-modal, so the user tabs in only if they want. * Focus is restored only when it would otherwise be lost (it is inside * the closing surface or already on ``); if the user has * deliberately moved focus to another control, that choice is left * alone. */ export function restoreFocus(node: HTMLElement): { destroy(): void } { const trigger = document.activeElement instanceof HTMLElement ? document.activeElement : null; return { destroy(): void { const active = document.activeElement; const lost = active === null || active === document.body || node.contains(active); if (lost) trigger?.focus(); }, }; }