SPB Git

Repository Public

overlay.tsx 8.7 KB 207 lines tsx

1"use client";2import { useEffect, useId, useRef, useState, type ReactNode } from "react";3import { useI18n } from "@/i18n";4import { cx } from "./cx";5import { Button, IconButton, type ButtonProps } from "./core";6import { Icon, type IconName } from "./Icon";78interface DialogProps {9  open: boolean;10  onClose: () => void;11  title: string;12  description?: ReactNode;13  children?: ReactNode;14  footer?: ReactNode;15  size?: "md" | "wide" | "xwide";16  /** false: Esc / backdrop do not close (destructive confirmations in progress). */17  dismissable?: boolean;18  variant?: "dialog" | "drawer";19  className?: string;20  hideHeader?: boolean;21}2223/** Modal built on the native <dialog>: focus trap, inert background, Esc handling and focus restore are native. */24export function Dialog({ open, onClose, title, description, children, footer, size = "md", dismissable = true, variant = "dialog", className, hideHeader }: DialogProps) {25  const { t } = useI18n();26  const ref = useRef<HTMLDialogElement>(null);27  const titleId = useId();28  const descId = useId();29  useEffect(() => {30    const el = ref.current;31    if (!open || !el) return;32    // The element is unmounted when `open` turns false, so the platform's own focus restoration never runs:33    // remember what had focus and give it back on close.34    const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;35    if (!el.open) el.showModal();36    return () => {37      if (el.open) el.close();38      if (previous?.isConnected) previous.focus();39    };40  }, [open]);41  if (!open) return null;42  return (43    <dialog44      ref={ref}45      className={cx("mcc-dialog", variant === "drawer" && "mcc-drawer", size !== "md" && size, className)}46      aria-labelledby={titleId}47      aria-describedby={description ? descId : undefined}48      onCancel={(e) => {49        e.preventDefault();50        if (dismissable) onClose();51      }}52      onClose={() => onClose()}53      onMouseDown={(e) => {54        if (dismissable && e.target === e.currentTarget) onClose();55      }}56    >57      <div className={hideHeader ? "sr-only" : "mcc-dialog-head"}>58        <div className="grow">59          <h2 id={titleId}>{title}</h2>60          {description ? <p id={descId}>{description}</p> : null}61        </div>62        {dismissable && !hideHeader ? <IconButton icon="close" label={t("common.close")} onClick={onClose} tip={false} /> : null}63      </div>64      {children !== undefined ? (hideHeader ? children : <div className="mcc-dialog-body">{children}</div>) : null}65      {footer ? <div className="mcc-dialog-foot">{footer}</div> : null}66    </dialog>67  );68}6970export function Drawer(props: Omit<DialogProps, "variant">) {71  return <Dialog {...props} variant="drawer" />;72}7374/** Confirmation dialog. The confirm button never has initial focus for dangerous actions. */75export function ConfirmDialog({ open, onClose, onConfirm, title, body, confirmLabel, danger, busy, error }: { open: boolean; onClose: () => void; onConfirm: () => void; title: string; body?: ReactNode; confirmLabel: string; danger?: boolean; busy?: boolean; error?: ReactNode }) {76  const { t } = useI18n();77  return (78    <Dialog79      open={open}80      onClose={onClose}81      title={title}82      description={body}83      dismissable={!busy}84      footer={85        <>86          <Button onClick={onClose} disabled={busy} autoFocus={danger}>{t("common.cancel")}</Button>87          <Button variant={danger ? "danger" : "primary"} onClick={onConfirm} loading={busy} autoFocus={!danger}>{confirmLabel}</Button>88        </>89      }90    >91      {error}92    </Dialog>93  );94}9596export interface MenuItem {97  id: string;98  label: string;99  icon?: IconName;100  danger?: boolean;101  disabled?: boolean;102  hint?: string;103  onSelect?: () => void;104  href?: string;105  separatorBefore?: boolean;106}107108/** Menu button (WAI-ARIA menu pattern): arrows / Home / End move, Enter activates, Esc closes and restores focus. */109export function Menu({ label, items, trigger, align = "right", header }: { label: string; items: MenuItem[]; trigger: (props: ButtonProps & { ref: React.Ref<HTMLButtonElement> }) => ReactNode; align?: "left" | "right"; header?: ReactNode }) {110  const [open, setOpen] = useState(false);111  const wrap = useRef<HTMLSpanElement>(null);112  const btn = useRef<HTMLButtonElement>(null);113  const list = useRef<HTMLDivElement>(null);114  const id = useId();115116  useEffect(() => {117    if (!open) return;118    const onDown = (e: MouseEvent) => {119      if (!wrap.current?.contains(e.target as Node)) setOpen(false);120    };121    document.addEventListener("mousedown", onDown);122    list.current?.querySelector<HTMLElement>('[role="menuitem"]:not(:disabled)')?.focus();123    return () => document.removeEventListener("mousedown", onDown);124  }, [open]);125126  const close = (refocus: boolean) => {127    setOpen(false);128    if (refocus) btn.current?.focus();129  };130  const onKey = (e: React.KeyboardEvent) => {131    const nodes = Array.from(list.current?.querySelectorAll<HTMLElement>('[role="menuitem"]:not(:disabled)') ?? []);132    const i = nodes.indexOf(document.activeElement as HTMLElement);133    const go = (n: number) => {134      e.preventDefault();135      nodes[(n + nodes.length) % nodes.length]?.focus();136    };137    if (e.key === "ArrowDown") go(i + 1);138    else if (e.key === "ArrowUp") go(i - 1);139    else if (e.key === "Home") go(0);140    else if (e.key === "End") go(nodes.length - 1);141    else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); close(true); }142    else if (e.key === "Tab") close(false);143  };144145  return (146    <span className="mcc-pop-anchor" ref={wrap}>147      {trigger({ ref: btn, "aria-haspopup": "menu", "aria-expanded": open, "aria-controls": open ? id : undefined, "aria-label": label, onClick: () => setOpen((o) => !o), onKeyDown: (e) => { if (e.key === "ArrowDown" && !open) { e.preventDefault(); setOpen(true); } } })}148      {open ? (149        <div className={cx("mcc-pop", align)} id={id} role="menu" aria-label={label} ref={list} onKeyDown={onKey}>150          {header}151          {items.map((it) => (152            <div key={it.id} role="none">153              {it.separatorBefore ? <div className="mcc-menu-sep" role="separator" /> : null}154              {it.href ? (155                <a role="menuitem" className={cx("mcc-menu-item", it.danger && "danger")} href={it.href} tabIndex={-1} onClick={() => close(false)}>156                  {it.icon ? <Icon name={it.icon} size={15} /> : null}<span className="grow">{it.label}</span>{it.hint ? <span className="faint">{it.hint}</span> : null}157                </a>158              ) : (159                <button type="button" role="menuitem" className={cx("mcc-menu-item", it.danger && "danger")} disabled={it.disabled} tabIndex={-1} onClick={() => { close(true); it.onSelect?.(); }}>160                  {it.icon ? <Icon name={it.icon} size={15} /> : null}<span className="grow">{it.label}</span>{it.hint ? <span className="faint">{it.hint}</span> : null}161                </button>162              )}163            </div>164          ))}165        </div>166      ) : null}167    </span>168  );169}170171export interface TabDef<V extends string> {172  id: V;173  label: string;174  count?: number | undefined;175}176/** Tabs with roving tabindex. Pair with <TabPanel>. */177export function Tabs<V extends string>({ label, tabs, value, onChange, idPrefix }: { label: string; tabs: readonly TabDef<V>[]; value: V; onChange: (v: V) => void; idPrefix: string }) {178  const refs = useRef(new Map<string, HTMLButtonElement>());179  const focusTab = (i: number) => {180    const tab = tabs[(i + tabs.length) % tabs.length];181    if (!tab) return;182    onChange(tab.id);183    refs.current.get(tab.id)?.focus();184  };185  return (186    <div role="tablist" aria-label={label} className="mcc-tabs"187      onKeyDown={(e) => {188        const i = tabs.findIndex((x) => x.id === value);189        if (e.key === "ArrowRight") { e.preventDefault(); focusTab(i + 1); }190        else if (e.key === "ArrowLeft") { e.preventDefault(); focusTab(i - 1); }191        else if (e.key === "Home") { e.preventDefault(); focusTab(0); }192        else if (e.key === "End") { e.preventDefault(); focusTab(tabs.length - 1); }193      }}>194      {tabs.map((tab) => (195        <button key={tab.id} type="button" role="tab" id={`${idPrefix}-tab-${tab.id}`} aria-selected={tab.id === value} aria-controls={`${idPrefix}-panel-${tab.id}`} tabIndex={tab.id === value ? 0 : -1} className="mcc-tab" onClick={() => onChange(tab.id)}196          ref={(el) => { if (el) refs.current.set(tab.id, el); else refs.current.delete(tab.id); }}>197          {tab.label}198          {tab.count !== undefined ? <span className="mcc-count">{tab.count}</span> : null}199        </button>200      ))}201    </div>202  );203}204export function TabPanel({ idPrefix, id, children }: { idPrefix: string; id: string; children: ReactNode }) {205  return <div role="tabpanel" id={`${idPrefix}-panel-${id}`} aria-labelledby={`${idPrefix}-tab-${id}`} tabIndex={0} className="stack-lg">{children}</div>;206}207
Files main
Menu

Theme