| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292 |
- 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.
- <span
- key={selected ? 'open' : 'closed'}
- className={cn(
- 'flex items-center gap-2',
- selected &&
- 'animate-in duration-300 fade-in-50 slide-in-from-bottom-1 motion-reduce:animate-none',
- )}
- >
- <Icon className="size-4" aria-hidden="true" />
- {label}
- {count !== undefined && count > 0 && (
- <span className="text-muted-foreground tabular-nums">
- {count}
- </span>
- )}
- {hasError && (
- <span
- className="size-1.5 rounded-full bg-red-600"
- data-test={errorTest}
- >
- <span className="sr-only">(needs fixing)</span>
- </span>
- )}
- </span>
- );
- }
-
- 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<Record<string, HTMLButtonElement | null>>({});
- 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<HTMLElement>(
- `[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<HTMLDivElement>) {
- 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 (
- <div
- className="rounded-xl border"
- data-section-tabs={name}
- data-test={`${name}-tabs`}
- // A browser check refused a field in a closed tab: open that tab so the field can be seen and fixed.
- onInvalidCapture={(event) => {
- const key = (event.target as HTMLElement).closest<HTMLElement>(
- '[role="tabpanel"]',
- )?.dataset.tabKey;
-
- if (key) {
- setActive(key);
- }
- }}
- >
- <div
- role="tablist"
- aria-label={label}
- onKeyDown={onKeyDown}
- className={cn(
- tabRowClass,
- 'rounded-none rounded-t-xl border-0 border-b',
- )}
- >
- {tabs.map((tab) => {
- const selected = tab.key === current;
-
- return (
- <button
- key={tab.key}
- ref={(element) => {
- buttons.current[tab.key] = element;
- }}
- type="button"
- role="tab"
- id={`${name}-tab-${tab.key}`}
- aria-selected={selected}
- aria-controls={`${name}-panel-${tab.key}`}
- tabIndex={selected ? 0 : -1}
- onClick={() => setActive(tab.key)}
- data-test={`${name}-tab-${tab.key}`}
- className={tabClass(selected)}
- >
- <TabLabel
- icon={tab.icon}
- label={tab.label}
- selected={selected}
- count={tab.count}
- hasError={tab.hasError}
- errorTest={`${name}-tab-error`}
- />
- </button>
- );
- })}
- </div>
-
- {tabs.map((tab) => (
- <div
- key={tab.key}
- role="tabpanel"
- id={`${name}-panel-${tab.key}`}
- aria-labelledby={`${name}-tab-${tab.key}`}
- data-tab-key={tab.key}
- hidden={tab.key !== current}
- // Rises in each time it is shown: a hidden element replays its animation when it appears.
- className={cn(
- 'animate-in p-4 duration-300 fade-in slide-in-from-bottom-2 motion-reduce:animate-none',
- panelClassName,
- )}
- >
- {tab.content}
- </div>
- ))}
- </div>
- );
- }
|