Repository Public
1"use client";2import { useId, useRef, type KeyboardEvent, type ReactNode } from "react";34export interface TabDef { id: string; label: ReactNode; panel: ReactNode }56/** WAI-ARIA tabs: arrow keys move between tabs, Home/End jump, only the active tab is in the tab order. */7export function Tabs({ tabs, active, onChange, label, className = "" }: { tabs: TabDef[]; active: string; onChange: (id: string) => void; label: string; className?: string }) {8 const base = useId();9 const refs = useRef<Record<string, HTMLButtonElement | null>>({});10 const onKey = (e: KeyboardEvent) => {11 const i = tabs.findIndex((t) => t.id === active);12 let j = -1;13 if (e.key === "ArrowRight") j = (i + 1) % tabs.length;14 else if (e.key === "ArrowLeft") j = (i - 1 + tabs.length) % tabs.length;15 else if (e.key === "Home") j = 0;16 else if (e.key === "End") j = tabs.length - 1;17 if (j < 0) return;18 e.preventDefault();19 onChange(tabs[j]!.id);20 refs.current[tabs[j]!.id]?.focus();21 };22 return (23 <div className={className}>24 <div role="tablist" aria-label={label} onKeyDown={onKey} className="flex gap-1 overflow-x-auto border-b border-line">25 {tabs.map((t) => (26 <button key={t.id} ref={(el) => { refs.current[t.id] = el; }} role="tab" type="button" id={`${base}-t-${t.id}`} aria-selected={t.id === active} aria-controls={`${base}-p-${t.id}`} tabIndex={t.id === active ? 0 : -1} onClick={() => onChange(t.id)}27 className="-mb-px inline-flex min-h-11 shrink-0 items-center gap-1.5 border-b-2 border-transparent px-2.5 text-[0.9rem] text-muted aria-selected:border-blue aria-selected:font-semibold aria-selected:text-fg">28 {t.label}29 </button>30 ))}31 </div>32 {tabs.map((t) => (33 <div key={t.id} role="tabpanel" id={`${base}-p-${t.id}`} aria-labelledby={`${base}-t-${t.id}`} hidden={t.id !== active} tabIndex={0} className="pt-4">34 {t.id === active && t.panel}35 </div>36 ))}37 </div>38 );39}40