| 1 |
import { useEffect, useState } from 'react'; |
| 2 |
import type { PressEvent } from 'react-aria-components'; |
| 3 |
import { TabsContext, LinkContext, Tabs } from 'react-aria-components'; |
| 4 |
import { Tab } from '../types'; |
| 5 |
|
| 6 |
/** |
| 7 |
* @since 4.4.0 |
| 8 |
*/ |
| 9 |
export default function TabsRouter({ children, tabDefinitions }: { children: React.ReactNode, tabDefinitions: Tab[] }) { |
| 10 |
const [selectedKey, onSelectionChange] = useState(tabDefinitions[0].id); |
| 11 |
|
| 12 |
const onPress = (e: PressEvent) => { |
| 13 |
onSelectionChange(e.target.getAttribute('data-href')); |
| 14 |
}; |
| 15 |
|
| 16 |
const getTabFromURL = () => { |
| 17 |
const urlParams = new URLSearchParams(window.location.search); |
| 18 |
const tabId = urlParams.get('tab') || selectedKey; |
| 19 |
return tabDefinitions.find((tab) => tab.id === tabId); |
| 20 |
}; |
| 21 |
|
| 22 |
const handleTabNavigation = (tabId: string) => { |
| 23 |
const newTab = tabDefinitions.find((tab) => tab.id === tabId); |
| 24 |
|
| 25 |
if (!newTab) { |
| 26 |
return; |
| 27 |
} |
| 28 |
|
| 29 |
const urlParams = new URLSearchParams(window.location.search); |
| 30 |
urlParams.set('tab', newTab.id); |
| 31 |
|
| 32 |
window.history.pushState(null, newTab.title, `${window.location.pathname}?${urlParams.toString()}`); |
| 33 |
|
| 34 |
onSelectionChange(newTab.id); |
| 35 |
}; |
| 36 |
|
| 37 |
const handleUrlTabParamOnFirstLoad = () => { |
| 38 |
const activeTab = tabDefinitions.find((tab) => tab.id === selectedKey); |
| 39 |
const urlParams = new URLSearchParams(window.location.search); |
| 40 |
// Add the 'tab' parameter only if it's not in the URL yet |
| 41 |
if (!urlParams.has('tab')) { |
| 42 |
urlParams.set('tab', selectedKey); |
| 43 |
window.history.replaceState(null, activeTab?.title, `${window.location.pathname}?${urlParams.toString()}`); |
| 44 |
} else { |
| 45 |
onSelectionChange(getTabFromURL()?.id); |
| 46 |
} |
| 47 |
}; |
| 48 |
|
| 49 |
useEffect(() => { |
| 50 |
handleUrlTabParamOnFirstLoad(); |
| 51 |
|
| 52 |
const handlePopState = () => onSelectionChange(getTabFromURL()?.id); |
| 53 |
|
| 54 |
// Updates state based on URL when user navigates with "Back" or "Forward" buttons |
| 55 |
window.addEventListener('popstate', handlePopState); |
| 56 |
|
| 57 |
// Cleanup listener on unmount |
| 58 |
return () => { |
| 59 |
window.removeEventListener('popstate', handlePopState); |
| 60 |
}; |
| 61 |
}, []); |
| 62 |
|
| 63 |
return ( |
| 64 |
<TabsContext.Provider value={{ selectedKey, onSelectionChange: handleTabNavigation }}> |
| 65 |
<LinkContext.Provider value={{ onPress }}> |
| 66 |
<Tabs> |
| 67 |
{children} |
| 68 |
</Tabs> |
| 69 |
</LinkContext.Provider> |
| 70 |
</TabsContext.Provider> |
| 71 |
); |
| 72 |
} |
| 73 |
|