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, 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 (
{items.map((item, index) => { const isSelected = item.id === selected; return ( ); })}
{items.map((item) => ( ))}
); }