2022-04-14 10:14:23 +00:00
|
|
|
import clsx from 'clsx';
|
|
|
|
import { ReactNode } from 'react';
|
|
|
|
|
|
|
|
import styles from './NavTabs.module.css';
|
|
|
|
|
2022-09-13 13:56:38 +00:00
|
|
|
export interface Option<T extends string | number = string> {
|
2022-04-14 10:14:23 +00:00
|
|
|
label: string | ReactNode;
|
|
|
|
children?: ReactNode;
|
2022-09-13 13:56:38 +00:00
|
|
|
id: T;
|
2022-04-14 10:14:23 +00:00
|
|
|
}
|
|
|
|
|
2022-09-13 13:56:38 +00:00
|
|
|
interface Props<T extends string | number> {
|
|
|
|
options: Option<T>[];
|
|
|
|
selectedId?: T;
|
|
|
|
onSelect?(id: T): void;
|
|
|
|
disabled?: boolean;
|
2022-04-14 10:14:23 +00:00
|
|
|
}
|
|
|
|
|
2022-09-13 13:56:38 +00:00
|
|
|
export function NavTabs<T extends string | number = string>({
|
|
|
|
options,
|
|
|
|
selectedId,
|
|
|
|
onSelect = () => {},
|
|
|
|
disabled,
|
|
|
|
}: Props<T>) {
|
2022-04-14 10:14:23 +00:00
|
|
|
const selected = options.find((option) => option.id === selectedId);
|
|
|
|
|
|
|
|
return (
|
2022-08-11 20:43:01 +00:00
|
|
|
<div className="nav-container">
|
2022-04-14 10:14:23 +00:00
|
|
|
<ul className="nav nav-tabs">
|
|
|
|
{options.map((option) => (
|
|
|
|
<li
|
|
|
|
className={clsx({
|
|
|
|
active: option.id === selectedId,
|
|
|
|
[styles.parent]: !option.children,
|
2022-09-18 11:42:18 +00:00
|
|
|
disabled,
|
2022-04-14 10:14:23 +00:00
|
|
|
})}
|
|
|
|
key={option.id}
|
|
|
|
>
|
|
|
|
{/* rule disabled because `nav-tabs` requires an anchor */}
|
|
|
|
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
|
|
|
|
<a
|
|
|
|
onClick={() => handleSelect(option)}
|
|
|
|
onKeyDown={(e) => {
|
|
|
|
if (e.key === 'Enter' || e.key === ' ') {
|
|
|
|
handleSelect(option);
|
|
|
|
}
|
|
|
|
}}
|
|
|
|
role="button"
|
|
|
|
tabIndex={0}
|
|
|
|
>
|
|
|
|
{option.label}
|
|
|
|
</a>
|
|
|
|
</li>
|
|
|
|
))}
|
|
|
|
</ul>
|
|
|
|
{selected && selected.children && (
|
2022-09-18 11:42:18 +00:00
|
|
|
<div className="tab-content mt-3">{selected.children}</div>
|
2022-04-14 10:14:23 +00:00
|
|
|
)}
|
2022-08-11 20:43:01 +00:00
|
|
|
</div>
|
2022-04-14 10:14:23 +00:00
|
|
|
);
|
|
|
|
|
2022-09-13 13:56:38 +00:00
|
|
|
function handleSelect(option: Option<T>) {
|
|
|
|
if (disabled) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-04-14 10:14:23 +00:00
|
|
|
if (option.children) {
|
|
|
|
onSelect(option.id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|