/** Carry one selected gallery reference into the same-origin NGSpice controls. */ export function createSimulator(report, onSelection = () => {}) { const frame = document.querySelector("#simulator"); const status = document.querySelector("#simulator-status"); let ready = false, starting = null, pending = null, sentKey = null, awaitingKey = null; const key = (value) => JSON.stringify([value.topology, value.ratio, value.vout, value.iout]); function deliver() { if (!ready || !pending || key(pending) === sentKey) return; sentKey = key(pending); awaitingKey = sentKey; frame.contentWindow.postMessage( { type: "pe:select-topology", ...pending }, location.origin, ); } window.addEventListener("message", (event) => { if ( event.origin !== location.origin || event.source !== frame.contentWindow ) return; const data = event.data; if (data?.type === "pe:simulator-ready") { ready = true; status.textContent = ""; deliver(); } if (data?.type === "pe:simulator-busy") status.textContent = "Finishing the current run; your selected topology is next."; if (data?.type === "pe:reference-applied" && key(data) === awaitingKey) { awaitingKey = null; status.textContent = ""; } if (data?.type === "pe:simulation-point") { if (awaitingKey !== null) return; const reference = { topology: data.topology, ratio: data.topology === "sp2" ? 2 : 4, vout: data.vout, iout: data.iout, }; pending = reference; sentKey = key(reference); onSelection(data.topology, reference); } }); async function show(reference = null) { if (reference) pending = reference; if (ready) { deliver(); return; } if (starting) return starting; status.textContent = "Connecting to NGSpice…"; starting = (async () => { try { const response = await fetch("./healthz", { cache: "no-store", signal: AbortSignal.timeout(10000), }); if (!response.ok || !(await response.json()).simulator) throw Error("The simulator service is unavailable. Retry shortly."); if (!frame.getAttribute("src")) frame.src = "./simulator/"; } catch (error) { status.textContent = error.message; report(error.message); } finally { starting = null; } })(); return starting; } return { show }; }