/* c8 ignore start */ import { onMounted, onUnmounted } from 'vue' import { useUserStore } from '#lib/stores' import { useResetStore } from '#lib/composables' import { AppStoreEnum, AppStorageEnum } from '#lib/enums' import { navigateTo, useNuxtApp } from 'nuxt/app' import type { AppCookies } from '#lib/types' /** * Synchronizes authentication data between browser tabs by listening to storage events. * * This composable handles authentication changes and manages page reloads or navigations based on token updates. * @namespace */ export function useSyncAuthenticateDataTab() { const resetStore = useResetStore() const store = useUserStore() const $appCookies = useNuxtApp().$appCookies as AppCookies const RELOAD_TIMEOUT = 500 /** * Extracts the token from a stringified JSON data. * * @param {string} data - The stringified JSON data containing the token. * @returns {string | undefined} The extracted token, or undefined if not found. */ const parseToken = (data: string = '') => { return JSON.parse(data)?.data?.token } /** * Reloads the current page after a specified timeout. * * The timeout is used to ensure the reload occurs after a delay. * * @returns {void} */ const reloadPage = (): void => { setTimeout(() => { window.location.reload() }, RELOAD_TIMEOUT) } /** * Resets cookies and application state, then navigates to the home page. * * This function is called when a user logs out from another tab or if the token is removed. * * @returns {void} */ const resetAndNavigate = (): void => { $appCookies.token.value = null $appCookies.gpToken.value = null resetStore.resetAll() store.resetUser() navigateTo('/') } onMounted(() => { window.addEventListener(AppStorageEnum.Storage, (event) => { if (event.key === AppStoreEnum.User) { const oldToken = parseToken(event.oldValue!) const newToken = parseToken(event.newValue!) if (!oldToken && newToken) { reloadPage() return } if (oldToken && !newToken) { resetAndNavigate() } } }) }) onUnmounted(() => { window.removeEventListener(AppStorageEnum.Storage, () => {}) }) } /* c8 ignore end */