RendyUI 中文

Components / Dialog

Dialog

Overlays · React / TypeScript Free

Recorded demo

Dialog preview

Source

dialog.tsx
"use client";

/**
 * Dialog — replica of the public UI Stacks spec.
 * Original implementation written from the public API docs.
 */
import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { Loader2, X } from "lucide-react";
import { cn, useControllable, useFocusTrap } from "../internal";

export interface DialogProps {
  kind?: "standard" | "confirm" | "destructive";
  size?: "sm" | "md" | "lg" | "xl";
  title?: string;
  description?: string;
  children?: React.ReactNode;
  trigger?: React.ReactNode;
  triggerClassName?: string;
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  confirmLabel?: string;
  cancelLabel?: string;
  onConfirm?: () => void | Promise<void>;
  onCancel?: () => void;
  icon?: React.ReactNode | null;
  footer?: React.ReactNode | null;
}

const SIZES = {
  sm: "max-w-[400px]",
  md: "max-w-[480px]",
  lg: "max-w-[640px]",
  xl: "max-w-[800px]",
} as const;

const DEFAULT_CONFIRM = {
  standard: "Save",
  confirm: "Confirm",
  destructive: "Delete",
} as const;

/**
 * Dialog: a modal that scales in over a fading backdrop. Escape or a
 * backdrop click closes it and focus returns to the trigger.
 */
export function Dialog({
  kind = "standard",
  size = "md",
  title,
  description,
  children,
  trigger,
  triggerClassName,
  open,
  defaultOpen = false,
  onOpenChange,
  confirmLabel,
  cancelLabel = "Cancel",
  onConfirm,
  onCancel,
  icon,
  footer,
}: DialogProps) {
  const reduce = useReducedMotion();
  const [isOpen, setOpen] = useControllable(open, defaultOpen, onOpenChange);
  const [busy, setBusy] = React.useState(false);
  const panelRef = React.useRef<HTMLDivElement>(null);
  const triggerRef = React.useRef<HTMLButtonElement>(null);
  const titleId = React.useId();
  const descId = React.useId();

  useFocusTrap(panelRef, isOpen);

  React.useEffect(() => {
    if (!isOpen) return;
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        close();
      }
    };
    document.addEventListener("keydown", onKeyDown);
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = previousOverflow;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

  const close = React.useCallback(() => {
    setOpen(false);
    onCancel?.();
    window.requestAnimationFrame(() => triggerRef.current?.focus());
  }, [setOpen, onCancel]);

  const runConfirm = async () => {
    if (!onConfirm) {
      close();
      return;
    }
    try {
      setBusy(true);
      await onConfirm();
      close();
    } finally {
      setBusy(false);
    }
  };

  const tone =
    kind === "destructive" ? "bg-danger-soft text-danger" : "bg-subtle text-fg-muted";

  return (
    <>
      {trigger !== undefined ? (
        <button
          ref={triggerRef}
          type="button"
          onClick={() => setOpen(true)}
          className={cn(
            "inline-flex items-center gap-2 rounded-[8px] border border-border bg-surface px-3 text-[14px] font-medium text-fg",
            "shadow-[var(--shadow-btn-secondary)] transition-colors hover:bg-subtle",
            "outline-none focus-visible:ring-2 focus-visible:ring-select/60",
            triggerClassName,
          )}
        >
          {trigger}
        </button>
      ) : null}

      <AnimatePresence>
        {isOpen ? (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
            <motion.div
              initial={reduce ? false : { opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={reduce ? undefined : { opacity: 0 }}
              transition={{ duration: 0.18 }}
              onClick={close}
              className="absolute inset-0 bg-[var(--scrim)] backdrop-blur-[2px]"
              aria-hidden
            />
            <motion.div
              ref={panelRef}
              role="dialog"
              aria-modal="true"
              aria-labelledby={title ? titleId : undefined}
              aria-describedby={description ? descId : undefined}
              initial={reduce ? false : { opacity: 0, scale: 0.94, y: 8 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={reduce ? undefined : { opacity: 0, scale: 0.96, y: 6 }}
              transition={{ duration: 0.2, ease: [0.2, 0, 0, 1] }}
              className={cn(
                "relative w-full overflow-hidden rounded-[16px] bg-surface shadow-[var(--shadow-overlay)]",
                SIZES[size],
              )}
            >
              <div className={cn(size === "lg" || size === "xl" ? "p-6" : "p-5")}>
                <div className="flex items-start gap-3">
                  {icon !== null ? (
                    <span className={cn("grid size-9 shrink-0 place-items-center rounded-[10px]", tone)}>
                      {icon ?? (
                        <svg viewBox="0 0 24 24" className="size-5" fill="none" stroke="currentColor" strokeWidth={1.75}>
                          <circle cx="12" cy="12" r="9" />
                          <path d="M12 8h.01M11 12h1v4h1" strokeLinecap="round" />
                        </svg>
                      )}
                    </span>
                  ) : null}
                  <div className="min-w-0 flex-1">
                    {title ? (
                      <h2 id={titleId} className="text-[16px] font-semibold leading-6 text-fg">
                        {title}
                      </h2>
                    ) : null}
                    {description ? (
                      <p id={descId} className="mt-1 text-[13.5px] leading-5 text-fg-muted">
                        {description}
                      </p>
                    ) : null}
                  </div>
                  <button
                    type="button"
                    onClick={close}
                    aria-label="Close"
                    className="grid size-7 shrink-0 place-items-center rounded-full text-fg-subtle transition-colors hover:bg-subtle hover:text-fg"
                  >
                    <X className="size-4" aria-hidden />
                  </button>
                </div>
                {children ? <div className="mt-4">{children}</div> : null}
              </div>

              {footer !== null ? (
                <div
                  className={cn(
                    "flex items-center justify-end gap-2 border-t border-border px-5 py-3",
                    (size === "lg" || size === "xl") && "bg-subtle",
                  )}
                >
                  {footer ?? (
                    <>
                      <button
                        type="button"
                        onClick={close}
                        className="inline-flex h-9 items-center rounded-[8px] border border-border bg-surface px-3.5 text-[13.5px] font-medium text-fg shadow-[var(--shadow-btn-secondary)] transition-colors hover:bg-subtle"
                      >
                        {cancelLabel}
                      </button>
                      <button
                        type="button"
                        onClick={runConfirm}
                        disabled={busy}
                        className={cn(
                          "inline-flex h-9 items-center gap-2 rounded-[8px] px-3.5 text-[13.5px] font-medium shadow-[var(--shadow-btn-primary)] transition-opacity hover:opacity-90",
                          "disabled:opacity-60",
                          kind === "destructive"
                            ? "bg-[var(--danger-solid)] text-white"
                            : "bg-[var(--feature)] text-[var(--on-feature)]",
                        )}
                      >
                        {busy ? <Loader2 className="size-4 animate-spin" aria-hidden /> : null}
                        {confirmLabel ?? DEFAULT_CONFIRM[kind]}
                      </button>
                    </>
                  )}
                </div>
              ) : null}
            </motion.div>
          </div>
        ) : null}
      </AnimatePresence>
    </>
  );
}

export default Dialog;

Usage

Add the TSX to your React project and install the required dependencies. Styles use Tailwind CSS and theme tokens。

Package dependencies · lucide-react、motion、react

Shared source · internal.ts

Props

NameTypeDescription
`kind``"standard" \| "confirm" \| "destructive"`Info tile and close button, question tile, or a red tile with a red confirm button.
`size``"sm" \| "md" \| "lg" \| "xl"`400, 480, 640 or 800 wide; lg and xl put the actions on a tinted band.
`title / description``string`The heading and one or two sentences under it.
`children``ReactNode`The body: a form, a summary, anything.
`trigger / triggerClassName``ReactNode / string`Content and classes of the button that opens it.
`open / defaultOpen / onOpenChange``boolean / boolean / (open) => void`Controlled or uncontrolled.
`confirmLabel / cancelLabel``string`Confirm defaults to Save, Confirm or Delete.
`onConfirm``() => void \| Promise<void>`Return a promise to show a spinner; it closes when the promise resolves.
`onCancel``() => void`Cancel, Escape, the close button or a backdrop click.
`icon / footer``ReactNode`Replace the tile glyph or the buttons; null hides them.