From 5b9675b0747497bbf648e34e672ac51944f66851 Mon Sep 17 00:00:00 2001 From: Alexander Zinchuk Date: Sun, 8 Sep 2024 19:58:32 +0200 Subject: [PATCH] Multitab: Fix global diff sync --- src/util/multitab.ts | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/util/multitab.ts b/src/util/multitab.ts index b4cb4d648..1c88b0ff2 100644 --- a/src/util/multitab.ts +++ b/src/util/multitab.ts @@ -113,24 +113,26 @@ type BroadcastChannelMessage = ( let resolveGlobalPromise: VoidFunction | undefined; let isFirstGlobalResolved = false; -let prevGlobal: GlobalState | undefined; +let currentGlobal: GlobalState | undefined; let isDisabled = false; const channel = IS_MULTITAB_SUPPORTED ? new BroadcastChannel(DATA_BROADCAST_CHANNEL_NAME) as TypedBroadcastChannel : undefined; -let globalToDiffWith: GlobalState | undefined; +let isBroadcastDiffScheduled = false; +let lastBroadcastDiffGlobal: GlobalState | undefined; -function broadcastDiffOnIdle(_globalToDiffWith: GlobalState) { - globalToDiffWith = _globalToDiffWith; +function broadcastDiffOnIdle() { + if (isBroadcastDiffScheduled) return; + + isBroadcastDiffScheduled = true; + lastBroadcastDiffGlobal = currentGlobal; onFullyIdle(() => { - if (!channel || !globalToDiffWith) return; + if (!channel) return; - const diff = deepDiff(globalToDiffWith, prevGlobal); - - globalToDiffWith = undefined; + const diff = deepDiff(lastBroadcastDiffGlobal, currentGlobal); if (typeof diff !== 'symbol') { channel.postMessage({ @@ -138,6 +140,8 @@ function broadcastDiffOnIdle(_globalToDiffWith: GlobalState) { diff, }); } + + isBroadcastDiffScheduled = false; }); } @@ -181,16 +185,16 @@ export function subscribeToMultitabBroadcastChannel() { addCallback((global: GlobalState) => { if (!isFirstGlobalResolved || isDisabled) { - prevGlobal = global; + currentGlobal = global; return; } - if (prevGlobal === global) { + if (currentGlobal === global) { return; } - if (!prevGlobal) { - prevGlobal = global; + if (!currentGlobal) { + currentGlobal = global; channel.postMessage({ type: 'globalUpdate', global, @@ -198,9 +202,9 @@ export function subscribeToMultitabBroadcastChannel() { return; } - broadcastDiffOnIdle(prevGlobal); + broadcastDiffOnIdle(); - prevGlobal = global; + currentGlobal = global; }); channel.addEventListener('message', handleMessage); @@ -228,7 +232,7 @@ export function handleMessage({ data }: { data: BroadcastChannelMessage }) { // @ts-ignore global.DEBUG_capturedId = oldGlobal.DEBUG_capturedId; - prevGlobal = global; + currentGlobal = global; setGlobal(global); break; } @@ -238,7 +242,7 @@ export function handleMessage({ data }: { data: BroadcastChannelMessage }) { const oldGlobal = getGlobal(); // @ts-ignore data.global.DEBUG_capturedId = oldGlobal.DEBUG_capturedId; - prevGlobal = data.global; + currentGlobal = data.global; setGlobal(data.global); if (resolveGlobalPromise) { resolveGlobalPromise();