1 import { useEffect, useRef } from 'react';
3 import { useGetUser } from '@proton/account/user/hooks';
4 import { stripLocalBasenameFromPathname } from '@proton/shared/lib/authentication/pathnameHelper';
5 import { getLocalStorageUserDrawerKey } from '@proton/shared/lib/drawer/helpers';
6 import type { DrawerApp, DrawerLocalStorageValue, IframeSrcMap } from '@proton/shared/lib/drawer/interfaces';
7 import { removeItem, setItem } from '@proton/shared/lib/helpers/storage';
9 const useDrawerLocalStorage = (iframeSrcMap: IframeSrcMap, drawerIsReady: boolean, appInView?: DrawerApp) => {
10 const getUser = useGetUser();
13 * Use a ref to allow deletion of the localStorage value only if we opened an app during the session.
14 * Otherwise, when loading the app, no app is opened in the drawer, and we would delete the value stored.
15 * By deleting this value directly, we would not be able to open the previously opened app
17 const hasSetAppInView = useRef(false);
19 const setDrawerLocalStorageKey = (item: DrawerLocalStorageValue, userID: string) => {
20 setItem(getLocalStorageUserDrawerKey(userID), JSON.stringify(item));
23 const handleSetLocalStorage = async () => {
24 // Only perform these actions when drawer can be shown
25 // Otherwise it can trigger /users request when not authenticated
27 const { ID } = await getUser();
30 const url = iframeSrcMap[appInView];
31 const pathname = url ? new URL(url).pathname : '';
32 const path = stripLocalBasenameFromPathname(pathname);
33 hasSetAppInView.current = true;
34 const item: DrawerLocalStorageValue = { app: appInView, path };
35 setDrawerLocalStorageKey(item, ID);
36 } else if (hasSetAppInView.current) {
37 // When closing the drawer, clean up the value from the drawer local storage item
38 removeItem(getLocalStorageUserDrawerKey(ID));
44 void handleSetLocalStorage();
45 }, [appInView, drawerIsReady]);
47 return { setDrawerLocalStorageKey };
50 export default useDrawerLocalStorage;