import { mount, unmount } from 'svelte'; // Every window is mounted once, into a host element this registry owns, and // moved into whichever slot shows it: a tile, a tab, a window on a canvas. // Where the browser has moveBefore the move keeps everything (an artifact's // page, scroll, focus); elsewhere it is a plain move, which reloads an iframe // but remounts nothing. // // A slot that goes away parks its window out of sight, and windows still // parked on the next frame are unmounted unless held or kept for an open board. // A window moved from one slot to another in the same frame stays alive; one // removed from its board is gone a frame later. Svelte takes a slot out of the // document before it lets its window // go, so a layout change shelters every window first (`shelter`): otherwise // whatever the slot is rebuilt around would lose its page and scroll. type Mounted = ReturnType; type Entry = { board: string; window: string; host: HTMLElement; instance: Mounted | null; slot: HTMLElement | null; }; const DEFAULT_KEPT_BOARDS = 3; /** The key a window of `board` is hosted under, stamped on its host as `data-window`. */ function hostKey(board: string, window: string) { return `${board}:${window}`; } /** The window of `board` whose host holds `element`, if any. */ export function windowOfHost( board: string, element: Element | null | undefined, ): string | null { const key = element?.closest('.window-host')?.dataset.window; return key?.startsWith(`${board}:`) ? key.slice(board.length + 1) : null; } const movable = typeof Element !== 'undefined' && 'moveBefore' in Element.prototype; function moveInto(parent: HTMLElement, node: HTMLElement) { if (movable && node.isConnected && parent.isConnected) { try { ( parent as HTMLElement & { moveBefore(node: Node, child: Node | null): void; } ).moveBefore(node, null); return; } catch {} } parent.appendChild(node); } class Hosts { #entries = new Map(); #parking: HTMLElement | null = null; #sweep = 0; #held = new Map>(); #maxKeptBoards = DEFAULT_KEPT_BOARDS; #keptBoards = new Map boolean>(); /** The slot showing each window, by window id: only one board is on screen at a time. */ #slots = new Map(); /** Each host's last laid-out size, for parking one whose slot is already gone. */ #sizes = new WeakMap(); #sizer: ResizeObserver | null = null; /** Shows `window` of `board` in `slot`, mounting it with `make` the first time. */ claim( board: string, window: string, slot: HTMLElement, make: (target: HTMLElement) => Mounted, ) { const kept = this.#keptBoards.get(board); if (kept) { this.#keptBoards.delete(board); this.#keptBoards.set(board, kept); } const key = hostKey(board, window); let entry = this.#entries.get(key); if (!entry) { const host = document.createElement('div'); host.className = 'window-host'; host.dataset.window = key; host.style.cssText = 'width: 100%; height: 100%'; const fresh: Entry = (entry = { board, window, host, instance: null, slot: null, }); this.#entries.set(key, fresh); this.#sizer ??= new ResizeObserver((resized) => { for (const { target, contentRect } of resized) if (contentRect.width && contentRect.height) this.#sizes.set(target, [contentRect.width, contentRect.height]); }); this.#sizer.observe(host); // Mounted outside the claiming slot's effect: svelte would make the // window's root a child of it, tying the window to the first slot that // showed it (and leaving it inert if that slot was). queueMicrotask(() => { if (this.#entries.get(key) === fresh) fresh.instance = make(host); }); } entry.slot = slot; this.#slots.set(window, slot); // A slot svelte is still building joins the page within the task; moved in // before that, the window would leave the page and lose its scroll. if (slot.isConnected || !entry.host.isConnected) return this.#show(entry.host, slot); const waiting = entry; queueMicrotask(() => { if (waiting.slot === slot && slot.isConnected) this.#show(waiting.host, slot); }); } /** * Parks the windows of `board` before a layout change rebuilds their slots, * and puts each one whose slot stayed back once it is done. Only where moves * keep a window's state; elsewhere a park would cost what it saves. * * `back` false leaves them all parked: the board itself is leaving the page, * and a window taken out of it with its slot loses its scroll — Chrome * clamps a scroller that is no longer rendered — before `release` could park * it. Only a park while the window is still in the page saves where it was. */ shelter(board: string, back = true) { if (!movable) return; const parked = [...this.#entries] .filter( ([key, entry]) => key.startsWith(`${board}:`) && entry.slot && entry.host.isConnected, ) .map(([, entry]) => entry); // Every size is read before anything moves: a read after a move would lay the board out again. const sizes = parked.map((entry) => [ entry.host.offsetWidth, entry.host.offsetHeight, ]); parked.forEach((entry, at) => { entry.host.style.width = `${sizes[at][0]}px`; entry.host.style.height = `${sizes[at][1]}px`; this.#hide(entry.host); }); this.#settle(); if (!back) return; queueMicrotask(() => { for (const entry of parked) { if (!entry.slot?.isConnected || entry.host.parentElement === entry.slot) continue; this.#show(entry.host, entry.slot); } }); } /** The slot is going; its window is parked, and unmounted next frame unless another slot claims it first. */ release(board: string, window: string, slot: HTMLElement) { if (this.#slots.get(window) === slot) this.#slots.delete(window); const entry = this.#entries.get(hostKey(board, window)); if (!entry || entry.slot !== slot) return; // The parked window keeps the size it had, so nothing inside it reflows on the way to its next slot. // A slot Svelte has already taken out (a board switch) measures nothing: the window was sized as it // left (`shelter`), or keeps the size it last had. const { width, height } = slot.getBoundingClientRect(); const [lastWidth, lastHeight] = this.#sizes.get(entry.host) ?? [0, 0]; if ((width && height) || (lastWidth && lastHeight)) { entry.host.style.width = `${width || lastWidth}px`; entry.host.style.height = `${height || lastHeight}px`; } entry.slot = null; this.#hide(entry.host); this.#settle(); this.#sweep ||= requestAnimationFrame(() => this.#collect()); } /** The element `window` is shown in, while it is on screen. */ slot(window: string): HTMLElement | null { const slot = this.#slots.get(window); return slot?.isConnected ? slot : null; } /** Keeps a parked window mounted. Independent reasons (a carry, a live settings draft) release only their own hold. */ hold(board: string, window: string, reason = 'carry') { const key = hostKey(board, window); let reasons = this.#held.get(key); if (!reasons) this.#held.set(key, (reasons = new Set())); reasons.add(reason); } /** Lets a held window go: unmounted next frame unless a slot has claimed it. */ free(board: string, window: string, reason = 'carry') { const key = hostKey(board, window); const reasons = this.#held.get(key); reasons?.delete(reason); if (!reasons?.size) this.#held.delete(key); this.#sweep ||= requestAnimationFrame(() => this.#collect()); } /** Sets how many open boards stay parked (including the active board) and drops any excess. */ setMaxKeptBoards(limit: number) { const next = Math.max(1, Math.round(limit)); if (next === this.#maxKeptBoards) return; this.#maxKeptBoards = next; this.#trimKeptBoards(); } /** Keeps `board`'s mounted windows parked across board switches while `hasWindow` still holds them. */ keepBoard(board: string, hasWindow: (window: string) => boolean) { this.#keptBoards.delete(board); this.#keptBoards.set(board, hasWindow); this.#trimKeptBoards(); } #trimKeptBoards() { while (this.#keptBoards.size > this.#maxKeptBoards) { const oldest = this.#keptBoards.keys().next().value; if (oldest === undefined) break; this.#keptBoards.delete(oldest); this.#sweep ||= requestAnimationFrame(() => this.#collect()); } } /** Stops keeping `board`'s parked windows and sweeps them next frame. */ dropBoard(board: string) { if (!this.#keptBoards.delete(board)) return; this.#sweep ||= requestAnimationFrame(() => this.#collect()); } #show(host: HTMLElement, slot: HTMLElement) { host.style.width = host.style.height = '100%'; moveInto(slot, host); host.style.visibility = ''; } /** * Parks `host`, hidden by its own style as well as by the parking's. Chrome * can keep the `visibility: hidden` a laid-out host inherited in the parking * after moveBefore takes it back to a slot, even when its style changed * just before the move, leaving the window invisible there. Clearing the * host's own visibility after the move makes it inherit from the slot again. */ #hide(host: HTMLElement) { host.style.visibility = 'hidden'; moveInto(this.#park(), host); } /** * Lays out what was just parked. Chrome keeps a moved scroller's offset * through one move before layout, not two: a window parked and claimed * again in the same task would come back scrolled to its top. */ #settle() { void this.#parking?.offsetWidth; } #park() { if (!this.#parking?.isConnected) { this.#parking = document.createElement('div'); this.#parking.className = 'window-parking'; this.#parking.setAttribute('aria-hidden', 'true'); this.#parking.inert = true; Object.assign(this.#parking.style, { position: 'fixed', left: '-100000px', top: '0', visibility: 'hidden', // Not content-visibility: hidden, under which Chrome drops a parked scroller's scroll offset. contain: 'strict', width: '0', height: '0', overflow: 'hidden', }); document.body.appendChild(this.#parking); } return this.#parking; } #collect() { this.#sweep = 0; for (const [key, entry] of this.#entries) { const kept = this.#keptBoards.get(entry.board); if (entry.slot || this.#held.has(key) || kept?.(entry.window)) continue; this.#entries.delete(key); if (entry.instance) void unmount(entry.instance); this.#sizer?.unobserve(entry.host); entry.host.remove(); } } } export const hosts = new Hosts(); /** * An attachment for a slot element: `
`. * Keyed by window, so a window moved between slots keeps its one mount. */ export function hosted( board: string, window: string, make: (target: HTMLElement) => Mounted, ) { return (slot: HTMLElement) => { hosts.claim(board, window, slot, make); return () => hosts.release(board, window, slot); }; }