| 1 | import { useEffect } from 'react' |
| 2 | import { useLocation } from 'wouter' |
| 3 | import { removeStarting } from './misc' |
| 4 | |
| 5 | export function useRoutedTab(basePath: string, tabPaths: readonly string[]) { |
| 6 | const [pathname, navigate] = useLocation() |
| 7 | const prefix = `/${basePath}/` |
| 8 | const tab = Math.max(0, tabPaths.indexOf(removeStarting(prefix, pathname))) |
| 9 | |
| 10 | useEffect(() => { |
| 11 | const wanted = `/${basePath}/${tabPaths[tab]}` |
| 12 | // replace bare/unknown tab URLs so refresh and history stay aligned with the visible tab |
| 13 | if (pathname !== wanted) |
| 14 | navigate(wanted, { replace: true }) |
| 15 | }, [basePath, navigate, pathname, tab, tabPaths]) |
| 16 | |
| 17 | return [tab, setTab] as const |
| 18 | |
| 19 | function setTab(i: number) { |
| 20 | navigate(`/${basePath}/${tabPaths[i]}`) |
| 21 | } |
| 22 | } |