import { useEffect } from 'react'; import { useSetAtom } from 'jotai'; import { useLocation } from 'react-router-dom'; import { useNavToActivePathAtom } from '../state/hooks/navToActivePath'; // `pathPrefix` gates the atom write to URLs that actually belong to this nav. // Consumers (Direct in particular) can be mounted continuously by the mobile // tab pager even while the URL points at a sibling tab — without the prefix // guard, the «direct» entry in the persisted atom would be overwritten with // «/channels/» or «/bots/» on every tab switch. export const useNavToActivePathMapper = (navId: string, pathPrefix?: string) => { const location = useLocation(); const setNavToActivePath = useSetAtom(useNavToActivePathAtom()); useEffect(() => { const { pathname, search, hash } = location; if (pathPrefix && !pathname.startsWith(pathPrefix)) return; setNavToActivePath({ type: 'PUT', navId, path: { pathname, search, hash }, }); }, [location, setNavToActivePath, navId, pathPrefix]); };