Files
sorsfonalak/services/frontend/src/components/Tabs.tsx
T

74 lines
2.1 KiB
TypeScript
Raw Normal View History

"use client";
import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";
export type Tab = { id: string; label: string; content: ReactNode };
/**
* Tabs with the chosen one kept in the URL hash (#matrix), so a reload or a
* shared link opens the same tab. Hidden panels stay mounted: a running
* analysis keeps polling while another tab is open.
*/
export function Tabs({ tabs, label }: { tabs: Tab[]; label: string }) {
const [active, setActive] = useState(tabs[0]?.id);
const buttons = useRef<(HTMLButtonElement | null)[]>([]);
useEffect(() => {
const fromHash = window.location.hash.slice(1);
if (tabs.some((t) => t.id === fromHash)) setActive(fromHash);
}, [tabs]);
function choose(id: string) {
setActive(id);
history.replaceState(null, "", `#${id}`);
}
function onKey(e: KeyboardEvent, i: number) {
const step = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
const to = e.key === "Home" ? 0 : e.key === "End" ? tabs.length - 1 : step ? (i + step + tabs.length) % tabs.length : -1;
if (to < 0) return;
e.preventDefault();
choose(tabs[to].id);
buttons.current[to]?.focus();
}
return (
<div className="tabs">
<div className="tab-list" role="tablist" aria-label={label}>
{tabs.map((t, i) => (
<button
key={t.id}
ref={(el) => {
buttons.current[i] = el;
}}
type="button"
role="tab"
id={`tab-${t.id}`}
aria-controls={`panel-${t.id}`}
aria-selected={active === t.id}
tabIndex={active === t.id ? 0 : -1}
className="tab"
onClick={() => choose(t.id)}
onKeyDown={(e) => onKey(e, i)}
>
{t.label}
</button>
))}
</div>
{tabs.map((t) => (
<div
key={t.id}
role="tabpanel"
id={`panel-${t.id}`}
aria-labelledby={`tab-${t.id}`}
hidden={active !== t.id}
className="tab-panel"
tabIndex={0}
>
{t.content}
</div>
))}
</div>
);
}