"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. */ /** Opens a tab from anywhere on the page (also when the hash is already that tab). */ export function openTab(id: string) { history.replaceState(null, "", `#${id}`); window.dispatchEvent(new HashChangeEvent("hashchange")); } export function Tabs({ tabs, label }: { tabs: Tab[]; label: string }) { const [active, setActive] = useState(tabs[0]?.id); const buttons = useRef<(HTMLButtonElement | null)[]>([]); const root = useRef(null); // A link to # (on load, or from elsewhere on the page) opens that tab and scrolls to it. useEffect(() => { const open = () => { const id = window.location.hash.slice(1); if (!tabs.some((t) => t.id === id)) return; setActive(id); root.current?.scrollIntoView({ behavior: "smooth", block: "start" }); }; open(); window.addEventListener("hashchange", open); return () => window.removeEventListener("hashchange", open); }, [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 (
{tabs.map((t, i) => ( ))}
{tabs.map((t) => ( ))}
); }