|
| 1 | +import { nanoid } from "nanoid"; |
| 2 | + |
| 3 | +type TabSyncConfig = { tabIds: string[] }; |
| 4 | + |
| 5 | +/** |
| 6 | + * Service for syncing data across tabs using `BroadcastChannel` |
| 7 | + */ |
| 8 | +export default class TabSyncService { |
| 9 | + static storageKey = "btrix.tabSync"; |
| 10 | + |
| 11 | + public tabId = nanoid(); |
| 12 | + public channel: BroadcastChannel; |
| 13 | + public get tabCount() { |
| 14 | + return this.getStoredSyncConfig()?.tabIds.length; |
| 15 | + } |
| 16 | + |
| 17 | + constructor(channelName: string) { |
| 18 | + // Open channel |
| 19 | + this.channel = new BroadcastChannel(channelName); |
| 20 | + |
| 21 | + // Update number of open tabs |
| 22 | + const syncConfig = this.getStoredSyncConfig() || { tabIds: [] }; |
| 23 | + |
| 24 | + syncConfig.tabIds.push(this.tabId); |
| 25 | + |
| 26 | + window.localStorage.setItem( |
| 27 | + TabSyncService.storageKey, |
| 28 | + JSON.stringify({ |
| 29 | + ...syncConfig, |
| 30 | + // Somewhat arbitrary, but only store latest 20 tabs to keep list managable |
| 31 | + tabIds: syncConfig.tabIds.slice(-20), |
| 32 | + }), |
| 33 | + ); |
| 34 | + |
| 35 | + // Remove tab ID on page unload |
| 36 | + window.addEventListener("unload", () => { |
| 37 | + const syncConfig = this.getStoredSyncConfig(); |
| 38 | + |
| 39 | + if (syncConfig) { |
| 40 | + const tabIds = syncConfig.tabIds.filter((id) => id === this.tabId); |
| 41 | + |
| 42 | + window.localStorage.setItem( |
| 43 | + TabSyncService.storageKey, |
| 44 | + JSON.stringify({ |
| 45 | + ...syncConfig, |
| 46 | + tabIds, |
| 47 | + }), |
| 48 | + ); |
| 49 | + } |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + private getStoredSyncConfig(): TabSyncConfig | null { |
| 54 | + const storedSyncConfig = window.localStorage.getItem( |
| 55 | + TabSyncService.storageKey, |
| 56 | + ); |
| 57 | + |
| 58 | + if (storedSyncConfig) { |
| 59 | + return JSON.parse(storedSyncConfig) as TabSyncConfig; |
| 60 | + } |
| 61 | + |
| 62 | + return null; |
| 63 | + } |
| 64 | +} |
0 commit comments