// A claim made on one Referrals page tells this browser's other open pages, so a queue left open in another tab // looks for the claimed referral instead of showing the old list until a reload. The hint names the practice and // the referral id only: nothing about the patient or the reason, and it grants nothing. A page that hears it // reads its own queue with its own authority, and only for the practice it is showing. const CHANNEL = "akashic-referral-claims"; export type ReferralClaimHint = { kind: "claimed" | "matched"; practice: string; referralId: string }; const asHint = (data: unknown): ReferralClaimHint | undefined => { const hint = data as Partial | null; if (!hint || (hint.kind !== "claimed" && hint.kind !== "matched")) return undefined; if (typeof hint.practice !== "string" || !hint.practice) return undefined; if (typeof hint.referralId !== "string" || !hint.referralId) return undefined; return { kind: hint.kind, practice: hint.practice, referralId: hint.referralId }; }; /** Listens for other pages' claims and posts this page's; a page never hears its own. Close it with the page. */ export const openReferralClaimHints = (onHint: (hint: ReferralClaimHint) => void) => { if (typeof BroadcastChannel === "undefined") return { post: () => undefined, close: () => undefined }; const channel = new BroadcastChannel(CHANNEL); channel.onmessage = (event: MessageEvent) => { const hint = asHint(event.data); if (hint) onHint(hint); }; return { post: (hint: ReferralClaimHint) => channel.postMessage(asHint(hint)), close: () => channel.close(), }; };