105 lines
3.7 KiB
TypeScript
105 lines
3.7 KiB
TypeScript
import { useRef, type KeyboardEvent, type ReactNode } from 'react';
|
|
|
|
export interface ContactTab<T extends string> {
|
|
id: T;
|
|
label: string;
|
|
panel: ReactNode;
|
|
}
|
|
|
|
interface Props<T extends string> {
|
|
tabs: ContactTab<T>[];
|
|
value: T;
|
|
onChange: (id: T) => void;
|
|
'aria-label': string;
|
|
}
|
|
|
|
/**
|
|
* Accessible tabs (WAI-ARIA tabs pattern, automatic activation): role=tablist/tab/tabpanel, roving tabindex,
|
|
* Left/Right/Home/End move and select. Only the selected panel is rendered.
|
|
*/
|
|
export function ContactTabs<T extends string>({ tabs, value, onChange, ...rest }: Props<T>) {
|
|
const refs = useRef<Record<string, HTMLButtonElement | null>>({});
|
|
const index = tabs.findIndex((tab) => tab.id === value);
|
|
|
|
const move = (to: number) => {
|
|
const next = tabs[(to + tabs.length) % tabs.length];
|
|
onChange(next.id);
|
|
refs.current[next.id]?.focus();
|
|
};
|
|
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
switch (event.key) {
|
|
case 'ArrowRight':
|
|
event.preventDefault();
|
|
move(index + 1);
|
|
break;
|
|
case 'ArrowLeft':
|
|
event.preventDefault();
|
|
move(index - 1);
|
|
break;
|
|
case 'Home':
|
|
event.preventDefault();
|
|
move(0);
|
|
break;
|
|
case 'End':
|
|
event.preventDefault();
|
|
move(tabs.length - 1);
|
|
break;
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<div
|
|
role="tablist"
|
|
aria-label={rest['aria-label']}
|
|
className="flex gap-1 border-b"
|
|
onKeyDown={onKeyDown}
|
|
>
|
|
{tabs.map((tab) => {
|
|
const selected = tab.id === value;
|
|
return (
|
|
<button
|
|
key={tab.id}
|
|
ref={(el) => {
|
|
refs.current[tab.id] = el;
|
|
}}
|
|
type="button"
|
|
role="tab"
|
|
id={`contact-tab-${tab.id}`}
|
|
aria-selected={selected}
|
|
aria-controls={`contact-panel-${tab.id}`}
|
|
tabIndex={selected ? 0 : -1}
|
|
onClick={() => onChange(tab.id)}
|
|
data-testid={`contact-tab-${tab.id}`}
|
|
className={`-mb-px min-h-11 border-b-2 px-4 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${
|
|
selected
|
|
? 'border-primary text-foreground'
|
|
: 'border-transparent text-muted-foreground hover:text-foreground'
|
|
}`}
|
|
>
|
|
{tab.label}
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
{tabs.map(
|
|
(tab) =>
|
|
tab.id === value && (
|
|
<div
|
|
key={tab.id}
|
|
role="tabpanel"
|
|
id={`contact-panel-${tab.id}`}
|
|
aria-labelledby={`contact-tab-${tab.id}`}
|
|
tabIndex={0}
|
|
className="space-y-4 focus-visible:outline-none"
|
|
data-testid={`contact-panel-${tab.id}`}
|
|
>
|
|
{tab.panel}
|
|
</div>
|
|
),
|
|
)}
|
|
</div>
|
|
);
|
|
}
|