import type { Shell } from '@astrale-os/shell' /** * useCloseGuard (API §10) — child-side willClose negotiation. The parent sends a * `willClose` intent before closing; the guard answers `closeAck` (allow) or * `closeRefuse` (veto, with reason). Guards stack per shell and the last-mounted * one wins; a single shared subscription owns the reply so a `willClose` is * answered exactly once regardless of how many guards are mounted. */ import { useEffect, useRef } from 'react' import { useShell } from '../../session/shell.hook.js' export type CloseVerdict = 'ack' | 'refuse' | { readonly refuse: string } export type CloseGuard = () => CloseVerdict | Promise interface CloseGuardHub { push(guard: CloseGuard): () => void } function sendAck(parent: NonNullable): void { parent.send({ type: 'intent', version: 1, envelope: { name: 'closeAck', payload: {}, sender: { windowId: 'self' } }, }) } function sendRefuse(parent: NonNullable, reason: string): void { parent.send({ type: 'intent', version: 1, envelope: { name: 'closeRefuse', payload: { reason }, sender: { windowId: 'self' } }, }) } const HUBS = new WeakMap() function getCloseGuardHub(shell: Shell): CloseGuardHub { const existing = HUBS.get(shell) if (existing !== undefined) return existing const stack: CloseGuard[] = [] let off: (() => void) | null = null function ensureSubscribed(): void { if (off !== null) return const parent = shell.parent if (parent === null) return off = parent.on('intent', (message) => { if (message.envelope.name !== 'willClose') return const guard = stack[stack.length - 1] if (guard === undefined) return void answer(parent, guard) }) } async function answer(parent: NonNullable, guard: CloseGuard): Promise { let verdict: CloseVerdict try { verdict = await guard() } catch { // A throwing guard must not trap the user in the window — allow the close. verdict = 'ack' } if (verdict === 'ack') sendAck(parent) else if (verdict === 'refuse') sendRefuse(parent, '') else sendRefuse(parent, verdict.refuse) } const hub: CloseGuardHub = { push(guard) { stack.push(guard) ensureSubscribed() return () => { const i = stack.lastIndexOf(guard) if (i >= 0) stack.splice(i, 1) if (stack.length === 0 && off !== null) { off() off = null } } }, } HUBS.set(shell, hub) return hub } export function useCloseGuard(guard: CloseGuard): void { const shell = useShell() const guardRef = useRef(guard) guardRef.current = guard useEffect(() => { const hub = getCloseGuardHub(shell) // Push a stable wrapper so a changed guard closure never re-registers // (latest-handler semantics; unmount pops this exact entry). return hub.push(() => guardRef.current()) }, [shell]) }