From d8eec1ed5e75222f54d7ecc47af31a42651b7339 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20S=C3=A1nchez?= Date: Fri, 6 Jan 2023 00:39:10 +0100 Subject: [PATCH] fix: sync current account across tabs (#815) --- composables/users.ts | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/composables/users.ts b/composables/users.ts index f43bd79d..103847f5 100644 --- a/composables/users.ts +++ b/composables/users.ts @@ -60,6 +60,41 @@ export const currentInstance = computed(() => currentUser.value export const publicServer = ref(DEFAULT_SERVER) export const currentServer = computed(() => currentUser.value?.server || publicServer.value) +// when multiple tabs: we need to reload window when sign in, switch account or sign out +if (process.client) { + const windowReload = () => { + document.visibilityState === 'visible' && window.location.reload() + } + watch(currentUserId, async (id, oldId) => { + // when sign in or switch account + if (id) { + // initial load + if (!oldId) + return + + if (id === currentUser.value?.account?.id) { + // when sign in, the other tab will not have the user, idb is not reactive + const newUser = users.value.find(user => user.account?.id === id) + // if the user is there, then we are switching account + if (newUser) { + // check if the change is on current tab: if so, don't reload + if (document.hasFocus() || document.visibilityState === 'visible') + return + } + } + + window.addEventListener('visibilitychange', windowReload, { capture: true }) + } + // when sign out + else if (oldId) { + const oldUser = users.value.find(user => user.account?.id === oldId) + // when sign out, the other tab will not have the user, idb is not reactive + if (oldUser) + window.addEventListener('visibilitychange', windowReload, { capture: true }) + } + }, { immediate: true, flush: 'post' }) +} + export const currentUserHandle = computed(() => currentUser.value?.account.id ? `${currentUser.value.account.acct}@${currentInstance.value?.uri || currentServer.value}` : '[anonymous]',