import type { LucideIcon } from 'lucide-react'; import type { KeyboardEvent, ReactNode } from 'react'; import { useEffect, useRef, useState } from 'react'; import { cn } from '@/lib/utils'; export type SectionTab = { key: string; label: string; icon: LucideIcon; /** A small number after the label, such as how many tiles there are. */ count?: number; /** Something in this tab needs fixing, such as a field the save refused. */ hasError?: boolean; content: ReactNode; }; /** * The look shared by every tab row in the app (Design, Settings, the store menu, Appearance): flat cells, and the * open one filled with the border colour. Put it on the row's buttons or links. */ export function tabClass(selected: boolean): string { return cn( 'flex shrink-0 items-center px-4 py-3 text-sm whitespace-nowrap transition-colors duration-200 focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none focus-visible:ring-inset motion-reduce:transition-none', selected ? 'bg-border font-medium text-foreground' : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground', ); } /** The row around the tabs: a bordered strip that slides sideways on phones. */ export const tabRowClass = 'flex [scrollbar-width:none] overflow-x-auto rounded-xl border'; /** A tab's icon and words. They rise in each time the tab opens. */ export function TabLabel({ icon: Icon, label, selected, count, hasError, errorTest, }: { icon: LucideIcon; label: string; selected: boolean; count?: number; hasError?: boolean; errorTest?: string; }) { return ( // A new key when the tab opens, so the label rises in each time. ); } function storageKey(name: string): string { return `section-tabs:${name}:${window.location.pathname}`; } /** The tab named in the address (#contact), else the one last open on this page. */ function startingTab(name: string, tabs: SectionTab[]): string { const keys = tabs.map((tab) => tab.key); const hash = window.location.hash.slice(1); if (keys.includes(hash)) { return hash; } try { const saved = window.sessionStorage.getItem(storageKey(name)); if (saved && keys.includes(saved)) { return saved; } } catch { // Storage can be blocked; the first tab is fine. } return keys[0] ?? ''; } /** * Sections of a page as one row of tabs, one open at a time (the Design tab, Settings). * - Every panel stays mounted, so half-typed changes survive switching tabs and the page's form still sends them. * - The open tab is remembered for this browser tab, so saving (which reloads the page) keeps you where you were. * - A link to an id inside a tab (#payments, #pickup) opens that tab and scrolls to it. * - When a save is refused, the first tab with a problem opens. */ export default function SectionTabs({ name, label, tabs, panelClassName, onChange, }: { /** Short page name, used for ids and to remember the open tab. */ name: string; /** What the row is, for screen readers. */ label: string; tabs: SectionTab[]; panelClassName?: string; onChange?: (key: string) => void; }) { const [active, setActive] = useState(() => startingTab(name, tabs)); const buttons = useRef>({}); const onChangeRef = useRef(onChange); const current = tabs.some((tab) => tab.key === active) ? active : (tabs[0]?.key ?? ''); useEffect(() => { onChangeRef.current = onChange; }, [onChange]); useEffect(() => { try { window.sessionStorage.setItem(storageKey(name), current); } catch { // Not remembered; nothing else changes. } onChangeRef.current?.(current); }, [name, current]); // Links such as Settings#payments: open the tab holding that id, then scroll to it. useEffect(() => { function openFromHash() { const id = window.location.hash.slice(1); const target = id ? document.getElementById(id) : null; const panel = target?.closest( `[data-section-tabs="${name}"] [role="tabpanel"]`, ); if (!target || !panel?.dataset.tabKey) { return; } setActive(panel.dataset.tabKey); requestAnimationFrame(() => target.scrollIntoView({ block: 'start' }), ); } openFromHash(); window.addEventListener('hashchange', openFromHash); return () => window.removeEventListener('hashchange', openFromHash); }, [name]); // A refused save: show the first tab with a problem, unless the open one has one. const errorKeys = tabs .filter((tab) => tab.hasError) .map((tab) => tab.key) .join(','); useEffect(() => { const withErrors = errorKeys === '' ? [] : errorKeys.split(','); if (withErrors.length > 0) { setActive((open) => withErrors.includes(open) ? open : withErrors[0], ); } }, [errorKeys]); // Arrow keys move along the row, like any tab list. function onKeyDown(event: KeyboardEvent) { const index = tabs.findIndex((tab) => tab.key === current); const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0; const target = event.key === 'Home' ? tabs[0] : event.key === 'End' ? tabs[tabs.length - 1] : step !== 0 ? tabs[(index + step + tabs.length) % tabs.length] : undefined; if (!target) { return; } event.preventDefault(); setActive(target.key); buttons.current[target.key]?.focus(); } if (tabs.length === 0) { return null; } return (
{ const key = (event.target as HTMLElement).closest( '[role="tabpanel"]', )?.dataset.tabKey; if (key) { setActive(key); } }} >
{tabs.map((tab) => { const selected = tab.key === current; return ( ); })}
{tabs.map((tab) => ( ))}
); }