// src/elements/keep.ts // // Defining an element empties its declarative root. Specs can name the control // to refocus and any scrollers to restore after the first build, in the same // task. The focus handoff reads identity and focus visibility, never form data. import { shadowHost } from "../core/dom/shadow-host"; type FocusKey = (node: Element) => string | null; /** What an element's spec lets it keep across an upgrade over server markup. */ export interface KeepSpec { /** A stable, unique key for a control owned by this element. */ focus?: FocusKey; /** The element's own scrollers, each under a stable name. */ scroll?: (root: ShadowRoot) => Record; } interface FocusSnapshot { key: string; tag: string; role: string | null; visible?: boolean; roots: ShadowRoot[]; document: Document; moved(): boolean; release(): void; } interface Kept { focus: FocusSnapshot | null; scroll: Map; } const withKey = (root: ShadowRoot, keyOf: FocusKey, key: string): Element[] => Array.from(root.querySelectorAll("*")).filter(node => keyOf(node) === key); // A move between controls in one outer shadow root can be retargeted away // before it reaches the window. Include both containing and assigned roots. const containingRoots = (root: ShadowRoot): ShadowRoot[] => { const roots = [root]; for (const scope of roots) { const host = shadowHost(scope); for (const candidate of [host?.getRootNode(), host?.assignedSlot?.getRootNode()]) { if (shadowHost(candidate) && !roots.includes(candidate as ShadowRoot)) roots.push(candidate as ShadowRoot); } } return roots; }; const captureFocus = (root: ShadowRoot, keyOf: FocusKey, form = false): FocusSnapshot | null => { const node = root.activeElement; const key = node && keyOf(node); if (!node || key === null || withKey(root, keyOf, key).length !== 1) return null; let moved = false; const seen = (event: Event): void => { if (event.isTrusted) moved = true; }; const roots = form ? containingRoots(root) : []; const type = form ? "focus" : "focusin"; const view = root.ownerDocument.defaultView; for (const scope of roots) scope.addEventListener(type, seen, true); view?.addEventListener(type, seen, true); return { key, tag: node.localName, role: node.getAttribute("role"), visible: form ? node.matches(":focus-visible") : undefined, roots, document: root.ownerDocument, moved: () => moved, release: () => { for (const scope of roots) scope.removeEventListener(type, seen, true); view?.removeEventListener(type, seen, true); }, }; }; const restoreFocus = (root: ShadowRoot, keyOf: FocusKey, wanted: FocusSnapshot): void => { wanted.release(); if (wanted.moved()) return; const document = root.ownerDocument; const current = document.activeElement; const host = shadowHost(root); if (wanted.roots.length) { if (!host?.isConnected || document !== wanted.document || !document.hasFocus()) return; const scopes = containingRoots(root); if (scopes.length !== wanted.roots.length || scopes.some((scope, i) => scope !== wanted.roots[i])) return; const hosts = scopes.map(shadowHost); if (current && current !== document.body && !hosts.includes(current)) return; if (scopes.some(scope => scope.activeElement && !hosts.includes(scope.activeElement))) return; } else if (root.activeElement || (current && current !== document.body && current !== host)) { return; } const [target, extra] = withKey(root, keyOf, wanted.key); if (!target || extra || target.localName !== wanted.tag || target.getAttribute("role") !== wanted.role || target.getAttribute("aria-disabled") === "true") return; const options = { preventScroll: true, focusVisible: wanted.visible }; (target as HTMLElement).focus(options); }; const capture = (root: ShadowRoot, keep: KeepSpec, expire: () => void): Kept | null => { const focus = keep.focus ? captureFocus(root, keep.focus) : null; const scroll = new Map(); for (const [name, node] of Object.entries(keep.scroll?.(root) ?? {})) { if (node && (node.scrollTop || node.scrollLeft)) scroll.set(name, [node.scrollTop, node.scrollLeft]); } if (!focus && !scroll.size) return null; const kept = { focus, scroll }; queueMicrotask(() => { kept.focus?.release(); kept.focus = null; kept.scroll.clear(); expire(); }); return kept; }; /** The element layer carries the spec's callbacks with no runtime import. */ export interface Keeping { capture: (root: ShadowRoot, expire: () => void) => Upgrade | null; } /** Returns true when the handoff already synced form data. */ export type Upgrade = ((root: ShadowRoot) => boolean | void) & { /** Called after the first build and its form sync. */ focus?: (root: ShadowRoot) => void; }; export const keeping = (keep: KeepSpec): Keeping => ({ capture(root, expire) { const kept = capture(root, keep, expire); if (!kept) return null; return target => { kept.focus?.release(); const scrollers = kept.scroll.size ? (keep.scroll?.(target) ?? {}) : {}; for (const [name, [top, left]] of kept.scroll) { const node = scrollers[name]; if (!node || node.scrollHeight - node.clientHeight < top || node.scrollWidth - node.clientWidth < left) continue; node.scrollTop = top; node.scrollLeft = left; } if (kept.focus && keep.focus) restoreFocus(target, keep.focus, kept.focus); }; }, }); /** Add focus to an existing state handoff, including when there is no edit. */ export const keepingFocus = (state: Keeping, keyOf: FocusKey): Keeping => ({ capture(root, expire) { const focus = captureFocus(root, keyOf, true); const stateHandoff = state.capture(root, expire); if (!focus) return stateHandoff; const apply: Upgrade = stateHandoff ?? (() => {}); apply.focus = target => restoreFocus(target, keyOf, focus); queueMicrotask(() => { focus.release(); apply.focus = undefined; expire(); }); return apply; }, });