PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 4.18.0
GiveWP – Donation Plugin and Fundraising Platform v4.18.0
4.18.0 4.17.0 4.16.9 4.16.8.1 4.16.8 4.16.7.2 4.16.7.1 4.16.7 4.16.6.1 4.16.6 4.16.5.1 4.16.5 4.16.4 4.16.3 4.16.2 4.16.1 4.16.0 4.15.5 4.15.4 4.15.3 4.15.2 4.15.1 4.15.0 2.3.0 2.3.1 All 257 releases
give / src / Views / Components / AdminDetailsPage / Tabs / Router.tsx

Router.tsx in GiveWP – Donation Plugin and Fundraising Platform 4.18.0, at src/Views/Components/AdminDetailsPage/Tabs/Router.tsx

73 lines 2.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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