| 5 | type OnSyncCallbackFunction = (allWindows: StateWithId[]) => void; |
| 6 | |
| 7 | export class WindowWorkerHandler { |
| 8 | windows: StateWithId[] = []; |
| 9 | currentWindow: WindowState = getCurrentWindowState(); |
| 10 | id: number; |
| 11 | onSyncCallbacks: OnSyncCallbackFunction[] = []; |
| 12 | worker: SharedWorker; |
| 13 | |
| 14 | constructor() { |
| 15 | this.worker = new SharedWorker(new URL("worker.ts", import.meta.url)); |
| 16 | const connectedMessage: WorkerMessage = { |
| 17 | action: "connected", |
| 18 | payload: { state: this.currentWindow }, |
| 19 | }; |
| 20 | this.onSyncCallback = this.onSyncCallback.bind(this); |
| 21 | this.worker.port.postMessage(connectedMessage); |
| 22 | this.worker.port.onmessage = (ev: MessageEvent<WorkerMessage>) => { |
| 23 | const msg = ev.data; |
| 24 | switch (msg.action) { |
| 25 | case "attributedId": { |
| 26 | this.id = msg.payload.id; |
| 27 | break; |
| 28 | } |
| 29 | case "sync": { |
| 30 | this.onSyncCallback(msg.payload.allWindows); |
| 31 | break; |
| 32 | } |
| 33 | } |
| 34 | }; |
| 35 | window.addEventListener("beforeunload", () => { |
| 36 | this.worker.port.postMessage({ |
| 37 | action: "windowUnloaded", |
| 38 | payload: { id: this.id }, |
| 39 | } satisfies WorkerMessage); |
| 40 | }); |
| 41 | } |
| 42 | |
| 43 | private onSyncCallback(allWindows: StateWithId[]) { |
| 44 | this.currentWindow = getCurrentWindowState(); |
| 45 | this.windows = allWindows; |
| 46 | this.onSyncCallbacks.forEach((cb) => cb(allWindows)); |
| 47 | } |
| 48 | |
| 49 | onSync(cb: OnSyncCallbackFunction) { |
| 50 | // TODO : send back the unregister |
| 51 | this.onSyncCallbacks.push(cb); |
| 52 | } |
| 53 | |
| 54 | windowHasChanged() { |
| 55 | const newWindow = getCurrentWindowState(); |
| 56 | const oldWindow = this.currentWindow; |
| 57 | if ( |
| 58 | didWindowChange({ |
| 59 | newWindow, |
| 60 | oldWindow, |
| 61 | }) |
| 62 | ) { |
| 63 | this.currentWindow = newWindow; |
| 64 | this.worker.port.postMessage({ |
nothing calls this directly
no test coverage detected