-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathTabs.tsx
More file actions
89 lines (80 loc) · 2.62 KB
/
Copy pathTabs.tsx
File metadata and controls
89 lines (80 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { useCallback, useId, useSyncExternalStore } from "react";
import styles from "./Tabs.module.scss"
export default function Tabs(props: {
queryKey: string;
defaultTab: string;
[key: `tab.${string}`]: React.ReactNode;
[key: `panel.${string}`]: React.ReactNode;
}) {
if (!props.queryKey || !props.defaultTab) {
throw new Error("props.queryKey and props.defaultTab are required")
}
const [selectedTab, setSelectedTab] = useSearchParamsState(props.queryKey);
const selectedTabWithDefault = selectedTab ?? props.defaultTab;
const tabs = Object.entries(props).filter(([key]) => key.startsWith("tab."));
const panels = Object.entries(props).filter(([key]) =>
key.startsWith("panel."),
);
const baseId = useId();
return (
<div className={styles["tabs"]}>
<div className={styles["tab-list"]} role="tablist">
{tabs.map(([key, element]) => {
const tabName = key.replace(/^tab\./, "");
return (
<button
key={key}
id={`${baseId}-tab-${tabName}`}
type="button"
role="tab"
aria-controls={`${baseId}-panel-${tabName}`}
aria-selected={selectedTabWithDefault === tabName}
onClick={() => {
setSelectedTab(tabName)
}}
>
{element}
</button>
);
})}
</div>
<div className={styles["panel-list"]}>
{panels.map(([key, element]) => {
const tabName = key.replace(/^panel\./, "");
return (
<div
key={key}
id={`${baseId}-panel-${tabName}`}
role="tabpanel"
aria-labelledby={`${baseId}-tab-${tabName}`}
hidden={selectedTabWithDefault !== tabName}
>
{element}
</div>
);
})}
</div>
</div>
);
}
const searchParamsChange = new EventTarget();
function useSearchParamsState(queryKey: string) {
const value = useSyncExternalStore(
(onStorechange) => {
searchParamsChange.addEventListener("change", onStorechange);
return () => searchParamsChange.removeEventListener("change", onStorechange);
},
() => {
const url = new URL(location.href);
return url.searchParams.get(queryKey);
},
() => null
);
const setValue = useCallback((newValue: string) => {
const url = new URL(location.href);
url.searchParams.set(queryKey, newValue);
history.replaceState(null, "", url.href);
searchParamsChange.dispatchEvent(new Event("change"));
}, [queryKey]);
return [value, setValue] as const;
}