/** * Stash/adopt across re-key / re-parent (API §10). A live window handed off across * an unmount so a remount can ADOPT it instead of closing + reloading it. Mirrors * ShellProvider's deferred-teardown pattern: the unmounting host stashes the * record, and either the remount takes it (one macrotask) or it disposes. */ import type { Window } from '@astrale-os/shell' import type { WindowState } from './lifecycle/states.js' import type { StageSlot } from './placement.js' export interface AdoptRecord { readonly windowId: string readonly window: Window readonly slot: StageSlot readonly state: WindowState /** Close the window, release its slot, drop it from the registry (fired if unadopted). */ dispose(): void } export interface AdoptStash { /** Stash an unmounting host's live window; disposes after one macrotask if unadopted. */ stash(key: string, record: AdoptRecord): void /** Reclaim a stashed window for a remount of the same source, cancelling its dispose. */ take(key: string): AdoptRecord | null } /** The pending-adoption registry — one per stage hub. */ export function createAdoptStash(): AdoptStash { const pendingAdopt = new Map< string, { record: AdoptRecord; timer: ReturnType } >() return { stash(key, record) { // Rapid same-key churn: an unclaimed prior stash disposes now. const prior = pendingAdopt.get(key) if (prior !== undefined) { clearTimeout(prior.timer) prior.record.dispose() } const timer = setTimeout(() => { pendingAdopt.delete(key) record.dispose() }, 0) pendingAdopt.set(key, { record, timer }) }, take(key) { const entry = pendingAdopt.get(key) if (entry === undefined) return null clearTimeout(entry.timer) pendingAdopt.delete(key) return entry.record }, } }