fix: sync current account across tabs (#815)

zio/stable
Joaquín Sánchez 2023-01-06 00:39:10 +01:00 committed by GitHub
parent b1fbac6ba3
commit d8eec1ed5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 35 additions and 0 deletions

View File

@ -60,6 +60,41 @@ export const currentInstance = computed<null | Instance>(() => currentUser.value
export const publicServer = ref(DEFAULT_SERVER)
export const currentServer = computed<string>(() => 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]',