import type { CloseResult, HostCapabilities, MountCredential, MountParams, ResolvedView, SandboxProfile, Window, } from '@astrale-os/shell' import type { CSSProperties, ReactElement, ReactNode } from 'react' /** * ViewHost (API §10) — hosts one view. It renders a normal-flow anchor and * projects that box onto a stage slot (ResizeObserver); the iframe lives in the * stage, so reorder/re-key never reloads a healthy frame. It drives the * `WindowState` machine, owns teardown (unmount closes its window), survives * StrictMode double-mount. The complete target-bound View is the sole source * of mount identity, route, target, and handshake behavior. */ import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, } from 'react' import type { AdoptRecord } from './adopt.js' import type { WindowState } from './lifecycle/states.js' import type { SlotRect, StageController, StageSlot } from './placement.js' import { useShell } from '../session/shell.hook.js' import { getStageHub } from './hub.js' import { viewMountKey } from './lifecycle/mount.js' import { rectOf, sameRect } from './placement.js' /** Imperative handle on a mounted `ViewHost` (API §10). */ export interface ViewHostHandle { readonly windowId: string | null close(opts?: { force?: boolean; timeoutMs?: number }): Promise /** The one explicit remount. */ refresh(): void } /** Static iframe sandbox flags, an explicit opt-out, or a policy over the resolved mount. */ export type SandboxPolicy = SandboxProfile | null | ((view: ResolvedView) => SandboxProfile | null) export interface ViewHostProps { /** One canonical target paired with one untouched View route. */ view: ResolvedView capabilities?: HostCapabilities sandbox?: SandboxPolicy credential?: MountCredential handshakeTimeoutMs?: number delegationTtlSeconds?: number /** Rendered inside the anchor while the frame is not `ready`. */ fallback?: (state: WindowState) => ReactNode onStateChange?: (state: WindowState) => void className?: string style?: CSSProperties } const MOUNTING: WindowState = { phase: 'mounting' } /** The live window a host owns — enough to hand off (adopt) across a remount. */ interface LiveWindow { readonly windowId: string readonly window: Window readonly state: WindowState } export const ViewHost = forwardRef( function ViewHost(props, ref): ReactElement { const shell = useShell() const hub = useMemo(() => getStageHub(shell), [shell]) const anchorRef = useRef(null) const slotRef = useRef(null) const windowIdRef = useRef(null) const aliveRef = useRef(true) // The live window (set at ready / on adopt, cleared on close) — the unit an // unmount stashes for a re-key/re-parent remount to adopt (§10). const liveRef = useRef(null) // Set by `refresh()`: the next unmount CLOSES (real remount) instead of stashing. const refreshingRef = useRef(false) // Last placed slot rect — reset when the slot changes; guards redundant places. const lastRectRef = useRef(null) const propsRef = useRef(props) propsRef.current = props const [state, setState] = useState(MOUNTING) const [refreshNonce, setRefreshNonce] = useState(0) const mountKey = viewMountKey(props.view) const setStateSafe = (next: WindowState) => { if (!aliveRef.current) return setState(next) propsRef.current.onStateChange?.(next) } useEffect(() => { aliveRef.current = true return () => { aliveRef.current = false } }, []) useImperativeHandle( ref, (): ViewHostHandle => ({ get windowId() { return windowIdRef.current }, async close(opts): Promise { const id = windowIdRef.current if (id === null) return { kind: 'noop' } const result = await shell.close(id, opts) if (result.kind === 'closed') { windowIdRef.current = null liveRef.current = null hub.registry.remove(id) setStateSafe({ phase: 'closed', windowId: id }) } return result }, refresh() { // A real remount: the next unmount closes (not stashes) so the frame reloads. refreshingRef.current = true setRefreshNonce((n) => n + 1) }, }), [shell, hub], ) // ── Placement: project the anchor box onto the current stage slot. Guarded by // rect-equality, so it is cheap to call on every commit (a sibling reorder // moves the anchor with no resize/scroll event — API §10). const measure = useCallback((): void => { const slot = slotRef.current const anchor = anchorRef.current if (slot === null || anchor === null) return const rect = rectOf(anchor) const last = lastRectRef.current if (last !== null && sameRect(last, rect)) return lastRectRef.current = rect slot.place(rect) }, []) // ── Mount lifecycle. Keyed on complete target + route provenance and // refresh nonce. A same-selection re-key/re-parent can adopt the live // window; any target or provenance change necessarily remounts. useEffect(() => { let cancelled = false let controllerWaiter: (() => void) | null = null // Consume the refresh flag: this setup is the (real) remount a refresh asked // for, so it must NOT adopt the window its own cleanup just closed. const wasRefresh = refreshingRef.current refreshingRef.current = false /** Close the window, release its slot, drop it from the registry (unadopted). */ function closeAndRelease(id: string, slot: StageSlot): void { void shell .close(id, { force: false }) .then((r) => (r.kind === 'closed' ? undefined : shell.close(id, { force: true }))) .catch(() => {}) .finally(() => hub.registry.remove(id)) slot.release() } /** Stash the live window for adoption, or (on refresh) close it outright. */ function cleanup(): void { cancelled = true controllerWaiter?.() const live = liveRef.current const slot = slotRef.current slotRef.current = null windowIdRef.current = null liveRef.current = null lastRectRef.current = null if (live === null || slot === null) { // Mount never resolved: release the slot; an in-flight mount self-closes. slot?.release() return } const record: AdoptRecord = { windowId: live.windowId, window: live.window, slot, state: live.state, dispose: () => closeAndRelease(live.windowId, slot), } if (refreshingRef.current) record.dispose() else hub.stashForAdopt(mountKey, record) } /** A pre-ready failure must not leave an empty stage slot over the fallback UI. */ function crashAndRelease(error: unknown): void { const slot = slotRef.current slotRef.current = null lastRectRef.current = null slot?.release() setStateSafe({ phase: 'crashed', windowId: windowIdRef.current ?? undefined, error }) } // Adopt a live window a just-unmounted same-source host left behind. if (!wasRefresh) { const adopted = hub.takeAdopt(mountKey) if (adopted !== null) { slotRef.current = adopted.slot windowIdRef.current = adopted.windowId liveRef.current = { windowId: adopted.windowId, window: adopted.window, state: adopted.state, } hub.registry.upsert(adopted.windowId, adopted.window, adopted.state) lastRectRef.current = null measure() // reposition the surviving slot onto this host's anchor setStateSafe(adopted.state) return cleanup } } async function mountView(): Promise { const p = propsRef.current let sandbox: SandboxProfile | null | undefined try { sandbox = typeof p.sandbox === 'function' ? p.sandbox(p.view) : p.sandbox } catch (err) { if (!cancelled) crashAndRelease(err) return } const params: MountParams = { host: slotRef.current!.element, view: p.view, capabilities: p.capabilities ?? { version: 1, navigation: {}, actions: {}, browser: {}, access: {}, }, sandbox, credential: p.credential, ...(p.handshakeTimeoutMs === undefined ? {} : { handshakeTimeoutMs: p.handshakeTimeoutMs }), ...(p.delegationTtlSeconds === undefined ? {} : { delegationTtlSeconds: p.delegationTtlSeconds }), } try { const win = await shell.openView(params) // A StrictMode cleanup (or refresh) fired before mount resolved: adopt // then immediately close so no orphan window survives. if (cancelled) { void win.close({ force: true }).catch(() => {}) return } windowIdRef.current = win.windowId const ready: WindowState = { phase: 'ready', windowId: win.windowId } liveRef.current = { windowId: win.windowId, window: win.window, state: ready, } hub.registry.upsert(win.windowId, win.window, ready) setStateSafe(ready) } catch (err) { if (cancelled) return crashAndRelease(err) } } function begin(controller: StageController): void { if (cancelled || slotRef.current !== null) return const slot = controller.acquire() slotRef.current = slot lastRectRef.current = null measure() setStateSafe(MOUNTING) void mountView() } const existing = hub.getController() if (existing !== null) begin(existing) else { controllerWaiter = hub.onController((c) => { if (c !== null) begin(c) }) } return cleanup // eslint-disable-next-line react-hooks/exhaustive-deps }, [hub, shell, mountKey, refreshNonce]) // ── Placement observers: reposition on resize/scroll/anchor-resize. useLayoutEffect(() => { measure() const anchor = anchorRef.current const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null if (anchor !== null) ro?.observe(anchor) window.addEventListener('resize', measure) window.addEventListener('scroll', measure, true) return () => { ro?.disconnect() window.removeEventListener('resize', measure) window.removeEventListener('scroll', measure, true) } }, [measure]) // Re-measure on EVERY commit (rect-equality-guarded): a sibling reorder moves // the anchor with no resize/scroll event, so the slot must chase it here (§10). useLayoutEffect(() => { measure() }) return (
{state.phase !== 'ready' ? props.fallback?.(state) : null}
) }, )