RendyUI 中文

Components / Form wizard

Form wizard

Navigation · React / TypeScript Free

Recorded demo

Form wizard preview

Source

form-wizard.tsx
"use client";

/**
 * Form wizard — 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 { Check } from "lucide-react";
import { cn, useControllable } from "../internal";

export type FormWizardErrors = Record<string, string>;

export type FormWizardValidate = () => FormWizardErrors | Promise<FormWizardErrors>;

export type FormWizardContent =
  | React.ReactNode
  | ((context: { errors: FormWizardErrors }) => React.ReactNode);

export type FormWizardSummaryRow = {
  label: string;
  value: React.ReactNode;
};

export type FormWizardStep = {
  id: string;
  title: string;
  description?: string;
  /** A node, or a function that receives { errors } to show under each field. */
  content: FormWizardContent;
  validate?: FormWizardValidate;
  summary?: FormWizardSummaryRow[];
};

export type FormWizardCompleteAction = { label: string; onClick?: () => void } | React.ReactNode;

export type FormWizardComplete = {
  title: React.ReactNode;
  description?: React.ReactNode;
  action?: FormWizardCompleteAction;
};

export interface FormWizardHandle {
  next: () => void;
  back: () => void;
  goTo: (id: string) => void;
  reset: () => void;
}

export interface FormWizardProps {
  steps: FormWizardStep[];
  /** Keys are the fields' element ids; the first invalid one takes focus. */
  validate?: FormWizardValidate;
  /** Rows on the review step. */
  summary?: FormWizardSummaryRow[];
  /** The current step id; the review step is "review". */
  step?: string;
  defaultStep?: string;
  onStepChange?: (id: string) => void;
  /** Adds the last step with every summary and Edit links. */
  review?: boolean | { title?: string; description?: string };
  onSubmit?: () => void | Promise<unknown>;
  /** What replaces the steps after a successful submit. */
  complete?: FormWizardComplete;
  /** A heading above the step header, with "Step 2 of 4". */
  title?: React.ReactNode;
  description?: React.ReactNode;
  continueLabel?: string;
  backLabel?: string;
  submitLabel?: string;
  /** Drive it from code; next and goTo validate first. */
  ref?: React.Ref<FormWizardHandle>;
  className?: string;
}

const FOCUS = "outline-none focus-visible:ring-2 focus-visible:ring-[var(--select)]/60";
const REVIEW_ID = "review";

function sameErrors(a: FormWizardErrors, b: FormWizardErrors) {
  const aKeys = Object.keys(a);
  const bKeys = Object.keys(b);
  if (aKeys.length !== bKeys.length) return false;
  return aKeys.every((key) => a[key] === b[key]);
}

function isActionObject(action: unknown): action is { label: string; onClick?: () => void } {
  return (
    typeof action === "object" &&
    action !== null &&
    "label" in action &&
    typeof (action as { label: unknown }).label === "string"
  );
}

function useMediaQuery(query: string) {
  const [matches, setMatches] = React.useState(false);
  React.useEffect(() => {
    const mql = window.matchMedia(query);
    const sync = () => setMatches(mql.matches);
    sync();
    mql.addEventListener("change", sync);
    return () => mql.removeEventListener("change", sync);
  }, [query]);
  return matches;
}

/**
 * Form wizard: a multi-step form in one card. Each step validates before
 * moving on, the first invalid field takes focus and a review step lists
 * every answer with Edit links back.
 */
export function FormWizard({
  steps,
  validate,
  summary,
  step: stepProp,
  defaultStep,
  onStepChange,
  review = false,
  onSubmit,
  complete,
  title,
  description,
  continueLabel = "Continue",
  backLabel = "Back",
  submitLabel = "Submit",
  ref,
  className,
}: FormWizardProps) {
  const reduce = Boolean(useReducedMotion());
  const uid = React.useId().replace(/[^a-zA-Z0-9]/g, "");
  const narrow = useMediaQuery("(max-width: 447px)");

  const reviewTitle =
    review && typeof review === "object" && review.title ? review.title : "Review";
  const reviewDescription =
    review && typeof review === "object" ? review.description : undefined;

  const allSteps = React.useMemo<FormWizardStep[]>(() => {
    if (!review) return steps;
    return [
      ...steps,
      {
        id: REVIEW_ID,
        title: reviewTitle,
        description: reviewDescription,
        content: null,
      },
    ];
  }, [steps, review, reviewTitle, reviewDescription]);

  const [step, setStep] = useControllable(
    stepProp,
    defaultStep ?? steps[0]?.id ?? REVIEW_ID,
    onStepChange,
  );
  const [errors, setErrors] = React.useState<FormWizardErrors>({});
  const [attempted, setAttempted] = React.useState(false);
  const [checking, setChecking] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState<string | null>(null);
  const [done, setDone] = React.useState(false);
  const [direction, setDirection] = React.useState(1);
  const [editOrigin, setEditOrigin] = React.useState<string | null>(null);

  const asyncValidators = React.useRef<Set<FormWizardValidate>>(new Set());
  const firstRender = React.useRef(true);

  const current = allSteps.find((entry) => entry.id === step) ?? allSteps[0];
  const currentIndex = Math.max(
    0,
    allSteps.findIndex((entry) => entry.id === current?.id),
  );
  const isReviewStep = current?.id === REVIEW_ID;
  const isLast = currentIndex === allSteps.length - 1;

  const focusWhenReady = React.useCallback(
    (id: string) => {
      let attempts = 0;
      const tick = () => {
        const node = document.getElementById(id);
        if (node) {
          node.focus();
          return;
        }
        if (attempts < 40) {
          attempts += 1;
          window.requestAnimationFrame(tick);
        }
      };
      tick();
    },
    [],
  );

  const navigate = React.useCallback(
    (id: string, dir: number, from?: string | null) => {
      setDirection(dir);
      setErrors({});
      setAttempted(false);
      setSubmitError(null);
      setEditOrigin(from ?? null);
      setStep(id);
    },
    [setStep],
  );

  const collectErrors = React.useCallback(async (): Promise<FormWizardErrors> => {
    const merged: FormWizardErrors = {};
    const runners: Array<FormWizardValidate | undefined> = [current?.validate, validate];
    for (const runner of runners) {
      if (!runner) continue;
      const result = runner();
      if (result instanceof Promise) {
        asyncValidators.current.add(runner);
        setChecking(true);
        try {
          Object.assign(merged, await result);
        } finally {
          setChecking(false);
        }
      } else {
        Object.assign(merged, result);
      }
    }
    return merged;
  }, [current, validate]);

  // After a failed Continue a synchronous validate runs on every render, so
  // messages clear as they are fixed.
  const runSyncValidators = React.useCallback(() => {
    const next: FormWizardErrors = {};
    for (const runner of [current?.validate, validate]) {
      if (!runner || asyncValidators.current.has(runner)) continue;
      const result = runner();
      if (result instanceof Promise) continue;
      Object.assign(next, result);
    }
    setErrors((prev) => (sameErrors(prev, next) ? prev : next));
  }, [current, validate]);

  React.useEffect(() => {
    if (!attempted) return;
    runSyncValidators();
  });

  // Focus the new step's heading after every move.
  React.useEffect(() => {
    if (firstRender.current) {
      firstRender.current = false;
      return;
    }
    if (!current?.id) return;
    focusWhenReady(`${uid}-${current.id}-panel-heading`);
  }, [current?.id, uid, focusWhenReady]);

  const focusFirstError = (fieldId: string) => {
    const node = document.getElementById(fieldId);
    if (node instanceof HTMLElement) {
      node.focus();
      return;
    }
    if (current?.id) focusWhenReady(`${uid}-${current.id}-panel-heading`);
  };

  const handleSubmit = React.useCallback(async () => {
    if (submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    try {
      if (onSubmit) await onSubmit();
      setDone(true);
      focusWhenReady(`${uid}-done-heading`);
    } catch (error) {
      setSubmitError(error instanceof Error ? error.message : String(error));
    } finally {
      setSubmitting(false);
    }
  }, [onSubmit, submitting, uid, focusWhenReady]);

  const handleContinue = React.useCallback(async () => {
    if (checking || submitting) return;
    const result = await collectErrors();
    const keys = Object.keys(result);
    if (keys.length > 0) {
      setErrors(result);
      setAttempted(true);
      focusFirstError(keys[0]);
      return;
    }
    setErrors({});
    setAttempted(false);
    const index = allSteps.findIndex((entry) => entry.id === current?.id);
    if (index < 0 || index === allSteps.length - 1) {
      await handleSubmit();
      return;
    }
    navigate(allSteps[index + 1].id, 1);
  }, [
    allSteps,
    checking,
    collectErrors,
    current?.id,
    handleSubmit,
    navigate,
    submitting,
  ]);

  const handleBack = React.useCallback(() => {
    if (editOrigin) {
      navigate(editOrigin, -1);
      return;
    }
    const index = allSteps.findIndex((entry) => entry.id === current?.id);
    if (index <= 0) return;
    navigate(allSteps[index - 1].id, -1);
  }, [allSteps, current?.id, editOrigin, navigate]);

  const goToWithValidation = React.useCallback(
    async (id: string) => {
      const result = await collectErrors();
      if (Object.keys(result).length > 0) {
        setErrors(result);
        setAttempted(true);
        focusFirstError(Object.keys(result)[0]);
        return;
      }
      const index = allSteps.findIndex((entry) => entry.id === id);
      const from = allSteps.findIndex((entry) => entry.id === current?.id);
      navigate(id, index >= from ? 1 : -1);
    },
    [allSteps, collectErrors, current?.id, navigate],
  );

  const reset = React.useCallback(() => {
    setErrors({});
    setAttempted(false);
    setSubmitError(null);
    setDone(false);
    setEditOrigin(null);
    setDirection(-1);
    setStep(allSteps[0]?.id ?? REVIEW_ID);
  }, [allSteps, setStep]);

  const handle = React.useMemo<FormWizardHandle>(
    () => ({
      next: () => {
        void handleContinue();
      },
      back: () => {
        handleBack();
      },
      goTo: (id: string) => {
        void goToWithValidation(id);
      },
      reset,
    }),
    [handleContinue, handleBack, goToWithValidation, reset],
  );

  React.useImperativeHandle(ref, () => handle, [handle]);

  const content =
    typeof current?.content === "function"
      ? current.content({ errors })
      : (current?.content ?? null);

  const firstError = Object.entries(errors)[0];
  const headingId = `${uid}-${current?.id}-panel-heading`;

  const reviewContent = (
    <div className="flex flex-col gap-4">
      {summary && summary.length > 0 ? (
        <dl className="flex flex-col">
          {summary.map((row) => (
            <div
              key={row.label}
              className="flex items-baseline justify-between gap-4 border-b border-border py-2 last:border-b-0"
            >
              <dt className="text-[12.5px] text-fg-muted">{row.label}</dt>
              <dd className="text-[13px] font-medium text-fg">{row.value}</dd>
            </div>
          ))}
        </dl>
      ) : null}

      {steps.map((entry) => {
        const rows = entry.summary ?? [];
        return (
          <div key={entry.id}>
            <div className="flex items-center justify-between gap-3">
              <h3 className="text-[13px] font-semibold text-fg">{entry.title}</h3>
              <button
                type="button"
                aria-label={`Edit ${entry.title}`}
                onClick={() => navigate(entry.id, -1, REVIEW_ID)}
                className={cn(
                  "rounded-[7px] px-1.5 py-0.5 text-[12.5px] font-medium text-[var(--select-text)] hover:bg-subtle",
                  FOCUS,
                )}
              >
                Edit
              </button>
            </div>
            {rows.length > 0 ? (
              <dl className="mt-1 flex flex-col">
                {rows.map((row) => (
                  <div
                    key={row.label}
                    className="flex items-baseline justify-between gap-4 border-b border-border py-1.5 last:border-b-0"
                  >
                    <dt className="text-[12.5px] text-fg-muted">{row.label}</dt>
                    <dd className="text-[13px] text-fg">{row.value}</dd>
                  </div>
                ))}
              </dl>
            ) : null}
          </div>
        );
      })}
    </div>
  );

  const renderCompleteAction = () => {
    const action = complete?.action;
    if (action === undefined || action === null) return null;
    if (React.isValidElement(action)) return action;
    if (typeof action === "string" || typeof action === "number") {
      return <span className="text-[13px] text-fg-muted">{action}</span>;
    }
    if (isActionObject(action)) {
      return (
        <button
          type="button"
          onClick={action.onClick}
          className={cn(
            "inline-flex h-9 items-center rounded-full bg-[var(--feature)] px-4 text-[13px] font-medium text-[var(--on-feature)] shadow-[var(--shadow-btn-primary)]",
            FOCUS,
          )}
        >
          {action.label}
        </button>
      );
    }
    return null;
  };

  return (
    <div
      className={cn(
        "w-full max-w-[520px] rounded-[16px] border border-border bg-surface p-5 shadow-[var(--shadow-card)]",
        className,
      )}
    >
      {title || description ? (
        <div className="flex items-start justify-between gap-4">
          <div className="min-w-0">
            {title ? <h2 className="text-[15px] font-semibold text-fg">{title}</h2> : null}
            {description ? (
              <p className="mt-0.5 text-[12.5px] text-fg-muted">{description}</p>
            ) : null}
          </div>
          <span className="shrink-0 text-[12.5px] text-fg-subtle">
            Step {currentIndex + 1} of {allSteps.length}
          </span>
        </div>
      ) : null}

      {done ? (
        <div className="mt-4 flex flex-col items-start gap-2 pb-2">
          <h2
            id={`${uid}-done-heading`}
            tabIndex={-1}
            className="text-[16px] font-semibold tracking-tight text-fg outline-none focus-visible:ring-2 focus-visible:ring-[var(--select)]/60"
          >
            {complete?.title ?? "All done"}
          </h2>
          {complete?.description ? (
            <p className="text-[13px] text-fg-muted">{complete.description}</p>
          ) : null}
          {renderCompleteAction()}
        </div>
      ) : (
        <>
          <nav aria-label="Steps" className="mt-4">
            <ol className="flex flex-wrap items-center gap-4">
              {allSteps.map((entry, index) => {
                const state =
                  index === currentIndex ? "current" : index < currentIndex ? "done" : "not started";
                return (
                  <li key={entry.id}>
                    <button
                      type="button"
                      aria-current={state === "current" ? "step" : undefined}
                      aria-label={`${index + 1}. ${entry.title}, ${state}`}
                      onClick={() => navigate(entry.id, index >= currentIndex ? 1 : -1)}
                      className={cn(
                        "flex items-center gap-1.5 rounded-[8px] text-[12.5px]",
                        state === "current"
                          ? "font-medium text-fg"
                          : "text-fg-subtle hover:text-fg-muted",
                        FOCUS,
                      )}
                    >
                      {state === "done" ? (
                        <span className="grid size-5 place-items-center rounded-full bg-subtle text-fg">
                          <Check className="size-3" aria-hidden />
                        </span>
                      ) : state === "current" ? (
                        <span className="grid size-5 place-items-center rounded-full border border-[var(--select)] text-[11px] font-semibold text-[var(--select-text)]">
                          {index + 1}
                        </span>
                      ) : (
                        <span className="text-[11.5px] tabular-nums">{index + 1}</span>
                      )}
                      <span>{entry.title}</span>
                    </button>
                  </li>
                );
              })}
            </ol>
          </nav>

          <motion.div initial={false} animate={{ height: "auto" }} className="overflow-hidden">
            <AnimatePresence mode="wait" initial={false} custom={direction}>
              <motion.div
                key={current?.id}
                custom={direction}
                role="group"
                aria-labelledby={headingId}
                onInput={() => {
                  if (attempted) runSyncValidators();
                }}
                initial={reduce ? { opacity: 0 } : { opacity: 0, x: direction * 28 }}
                animate={{ opacity: 1, x: 0 }}
                exit={reduce ? { opacity: 0 } : { opacity: 0, x: direction * -28 }}
                transition={{ duration: 0.2, ease: [0.2, 0, 0, 1] }}
                className="pt-4"
              >
                <h3
                  id={headingId}
                  tabIndex={-1}
                  className={cn(
                    "text-[14px] font-semibold tracking-tight text-fg outline-none focus-visible:ring-2 focus-visible:ring-[var(--select)]/60",
                    narrow && current?.description ? "sr-only" : "",
                  )}
                >
                  {current?.title}
                </h3>
                {current?.description ? (
                  <p className="mt-0.5 text-[12.5px] text-fg-muted">{current.description}</p>
                ) : null}

                {firstError ? (
                  <p role="alert" className="mt-2 text-[12.5px] text-danger">
                    {firstError[1]}
                  </p>
                ) : null}

                <div className="mt-3">{isReviewStep ? reviewContent : content}</div>
              </motion.div>
            </AnimatePresence>
          </motion.div>

          <div className="mt-5 flex items-center justify-between gap-3">
            <div className="min-w-0 text-[12.5px] text-danger">
              {submitError ? (
                <span role="alert">{submitError}</span>
              ) : null}
            </div>
            <div className="flex shrink-0 items-center gap-2">
              {currentIndex > 0 || editOrigin ? (
                <button
                  type="button"
                  onClick={handleBack}
                  className={cn(
                    "inline-flex h-9 items-center rounded-full border border-border bg-surface px-3.5 text-[13px] font-medium text-fg shadow-[var(--shadow-btn-secondary)] hover:bg-subtle",
                    FOCUS,
                  )}
                >
                  {editOrigin ? "Back to review" : backLabel}
                </button>
              ) : null}
              {isLast ? (
                <button
                  type="button"
                  disabled={submitting}
                  onClick={() => {
                    void handleSubmit();
                  }}
                  className={cn(
                    "inline-flex h-9 items-center rounded-full bg-[var(--feature)] px-4 text-[13px] font-medium text-[var(--on-feature)] shadow-[var(--shadow-btn-primary)] disabled:opacity-60",
                    FOCUS,
                  )}
                >
                  {submitting ? "Submitting…" : submitLabel}
                </button>
              ) : (
                <button
                  type="button"
                  disabled={checking}
                  onClick={() => {
                    void handleContinue();
                  }}
                  className={cn(
                    "inline-flex h-9 items-center rounded-full bg-[var(--feature)] px-4 text-[13px] font-medium text-[var(--on-feature)] shadow-[var(--shadow-btn-primary)] disabled:opacity-60",
                    FOCUS,
                  )}
                >
                  {checking ? "Checking…" : continueLabel}
                </button>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

export default FormWizard;

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
`steps``{ id; title; description?; content; validate?; summary? }[]`content can be a function that gets { errors } to show under each field.
`validate``() => Record<fieldId, message> \| Promise<…>`Keys are the fields' element ids; the first invalid one takes focus. After a failed Continue a synchronous validate runs on every render, so messages clear as they are fixed. A promise shows Checking.
`summary``{ label; value }[]`Rows on the review step.
`step / defaultStep / onStepChange``string / string / (id) => void`The current step id; the review step is “review”.
`review``boolean \| { title?; description? }`Adds the last step with every summary and Edit links; Edit opens the step with a Back to review button.
`onSubmit``() => void \| Promise`A promise shows Submitting; a rejection shows its message in the footer.
`complete``{ title; description?; action? }`What replaces the steps after a successful submit.
`title / description``ReactNode`A heading above the step header, with “Step 2 of 4”.
`continueLabel / backLabel / submitLabel``string`Continue, Back, Submit.
`ref``Ref<{ next; back; goTo; reset }>`Drive it from code; next and goTo validate first.
`className``string`