import { useEffect } from "react"; import { useStore } from "react-redux"; import { RootState } from "../../types/state"; import { createOutputChannel, createSnapshotCollector, } from "../../features/outputChannel/outputChannel"; /** * Controller-side publisher. Mounted once in the app shell, it mirrors the * broadcast slices of the store to the relay (see server/relayServer.js) so any * number of output pages stay in sync. Add "?bridge=0" to a URL to opt out. * * Two rules keep it from disturbing the UI it is mirroring: * - nothing is read or sent while no relay is attached; * - every state transition is flushed on a microtask so the output sees the * same sequence of states the controller rendered. A time-based throttle * would merge them (e.g. the chyron's "closed" and "open" states) and the * output would mount already-open, skipping the enter animation entirely. */ export function BroadcastBridge() { const store = useStore(); useEffect(() => { const params = new URLSearchParams(window.location.search); if (params.get("bridge") === "0") return undefined; const collector = createSnapshotCollector(); let scheduled = false; const flush = () => { scheduled = false; if (channel.getStatus() !== "open") return; const patch = collector.collect(store.getState()); if (patch != null) channel.sendState(patch); }; const schedule = () => { if (scheduled) return; scheduled = true; queueMicrotask(flush); }; const channel = createOutputChannel({ role: "controller", onStatus: (status) => { // A fresh (or reconnected) output needs the whole picture. if (status !== "open") return; collector.reset(); schedule(); }, }); const unsubscribe = store.subscribe(schedule); schedule(); return () => { unsubscribe(); channel.close(); }; }, [store]); return null; }