89 lines
2.7 KiB
TypeScript
89 lines
2.7 KiB
TypeScript
import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
|
import { tabKeyTarget } from "./tab-keys";
|
|
import styles from "./tabs.module.css";
|
|
|
|
export type TabItem = {
|
|
id: string;
|
|
label: string;
|
|
content: ReactNode;
|
|
};
|
|
|
|
type TabsProps = {
|
|
/** Accessible name of the tab list. */
|
|
label: string;
|
|
items: readonly TabItem[];
|
|
/** Controlled selection; omit to let the component keep it. */
|
|
value?: string | undefined;
|
|
defaultValue?: string | undefined;
|
|
onChange?: ((id: string) => void) | undefined;
|
|
};
|
|
|
|
/**
|
|
* Tabs (WAI-ARIA tabs pattern with automatic activation). Only the selected
|
|
* tab is in the tab order; arrow keys, Home, and End move between tabs.
|
|
* Inactive panels stay mounted with the hidden attribute, so form state in a
|
|
* panel survives switching tabs.
|
|
*/
|
|
export function Tabs({ label, items, value, defaultValue, onChange }: TabsProps) {
|
|
const baseId = useId();
|
|
const [ownValue, setOwnValue] = useState(defaultValue ?? items[0]?.id);
|
|
const selected = value ?? ownValue;
|
|
const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
|
|
|
|
function select(id: string) {
|
|
if (value === undefined) setOwnValue(id);
|
|
onChange?.(id);
|
|
}
|
|
|
|
function handleKeyDown(event: KeyboardEvent<HTMLButtonElement>, index: number) {
|
|
const target = tabKeyTarget(event.key, index, items.length);
|
|
const item = target === null ? undefined : items[target];
|
|
if (target === null || !item) return;
|
|
event.preventDefault();
|
|
select(item.id);
|
|
tabRefs.current[target]?.focus();
|
|
}
|
|
|
|
return (
|
|
<div className={styles.root}>
|
|
<div className={styles.list} role="tablist" aria-label={label}>
|
|
{items.map((item, index) => {
|
|
const isSelected = item.id === selected;
|
|
return (
|
|
<button
|
|
key={item.id}
|
|
ref={(element) => {
|
|
tabRefs.current[index] = element;
|
|
}}
|
|
type="button"
|
|
role="tab"
|
|
id={`${baseId}-tab-${item.id}`}
|
|
className={styles.tab}
|
|
aria-selected={isSelected}
|
|
aria-controls={`${baseId}-panel-${item.id}`}
|
|
tabIndex={isSelected ? 0 : -1}
|
|
onClick={() => select(item.id)}
|
|
onKeyDown={(event) => handleKeyDown(event, index)}
|
|
>
|
|
{item.label}
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
{items.map((item) => (
|
|
<div
|
|
key={item.id}
|
|
role="tabpanel"
|
|
id={`${baseId}-panel-${item.id}`}
|
|
className={styles.panel}
|
|
aria-labelledby={`${baseId}-tab-${item.id}`}
|
|
hidden={item.id !== selected}
|
|
tabIndex={0}
|
|
>
|
|
{item.content}
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|