@lincyaw/host 0.0.0-stage → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/windows.ts ADDED
@@ -0,0 +1,28 @@
1
+ type Message = { join: true } | { value: unknown }
2
+
3
+ export interface WindowChannel {
4
+ send(value: unknown): void
5
+ close(): void
6
+ }
7
+
8
+ export function deckChannel(name: string): string {
9
+ return `${name} @ ${import.meta.env?.BASE_URL ?? '/'}`
10
+ }
11
+
12
+ export function joinWindows(name: string, receive: (value: unknown) => void, known: () => unknown): WindowChannel | undefined {
13
+ if (typeof window === 'undefined' || typeof BroadcastChannel === 'undefined') return undefined
14
+ const channel = new BroadcastChannel(deckChannel(name))
15
+ channel.onmessage = ({ data }: MessageEvent<Message>) => {
16
+ if ('value' in data) {
17
+ receive(data.value)
18
+ return
19
+ }
20
+ const value = known()
21
+ if (value !== undefined) channel.postMessage({ value } satisfies Message)
22
+ }
23
+ channel.postMessage({ join: true } satisfies Message)
24
+ return {
25
+ send: value => channel.postMessage({ value } satisfies Message),
26
+ close: () => channel.close(),
27
+ }
28
+ }