2026-07-30 09:21:55 +08:00
|
|
|
import { createSignal, onCleanup, onMount } from "solid-js";
|
|
|
|
|
import type { View } from "../lib/model";
|
|
|
|
|
import { isHostMessage, type HostSharedState, type PageCommand } from "../sdk/protocol";
|
|
|
|
|
import { notifyReady, sendCommand } from "../sdk/page";
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Connects one iframe document to the persistent Host Shell.
|
|
|
|
|
*
|
2026-07-30 09:43:08 +08:00
|
|
|
* A keep-alive document remains mounted while inactive and exposes that state
|
|
|
|
|
* through `active`. Removing the iframe still runs `onCleanup`, so an evicted
|
|
|
|
|
* document cannot continue to receive Host snapshots.
|
2026-07-30 09:21:55 +08:00
|
|
|
*/
|
|
|
|
|
export function createFrameBridge(view: View) {
|
|
|
|
|
const [state, setState] = createSignal<HostSharedState | null>(null);
|
2026-07-30 09:43:08 +08:00
|
|
|
const [active, setActive] = createSignal(false);
|
2026-07-30 09:21:55 +08:00
|
|
|
|
|
|
|
|
const receive = (event: MessageEvent<unknown>) => {
|
|
|
|
|
if (event.origin !== window.location.origin || event.source !== window.parent) return;
|
|
|
|
|
if (!isHostMessage(event.data)) return;
|
|
|
|
|
if (event.data.type === "state" && event.data.state.view === view) {
|
|
|
|
|
setState(event.data.state);
|
|
|
|
|
}
|
2026-07-30 09:43:08 +08:00
|
|
|
if (event.data.type === "lifecycle") {
|
|
|
|
|
const phase = event.data.phase;
|
|
|
|
|
setActive(phase === "activate");
|
|
|
|
|
window.dispatchEvent(
|
|
|
|
|
new CustomEvent("wasmeld:lifecycle", {
|
|
|
|
|
detail: { phase },
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
window.dispatchEvent(new Event(`wasmeld:${phase}`));
|
2026-07-30 09:21:55 +08:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
onMount(() => {
|
|
|
|
|
window.addEventListener("message", receive);
|
|
|
|
|
notifyReady(view);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
onCleanup(() => window.removeEventListener("message", receive));
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
state,
|
2026-07-30 09:43:08 +08:00
|
|
|
active,
|
2026-07-30 09:21:55 +08:00
|
|
|
command(command: PageCommand) {
|
|
|
|
|
sendCommand(view, command);
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|