SunUI
創始會員NT$2,490 終身更新,1月11日截止取得席位
免費點按

載入按鈕

自己管理非同步狀態的送出按鈕:onClick 回傳 Promise,就會進入載入中,成功時畫出勾勾、失敗時顯示重試文字,一段時間後回到原狀。

適合使用的時機

  • 呼叫 API 的訂閱、付款、套用折扣碼或儲存按鈕
  • 大家常因為沒反應而按兩次的表單送出

注意事項

  • 成功的勾勾本身就是完整的確認,不要再疊加慶祝效果
  • 結果若從 websocket 或輪詢回來,請自己傳 state

交給你的 agent 安裝

一次複製就包含安裝指令、使用時機、props 與設計規則。貼進 Claude Code、Cursor 或 Codex 即可。

用 CLI 安裝

使用 shadcn CLI。原始碼會複製到你的專案裡,每一行都由你掌握。

$ npx shadcn@latest add https://sunui.synvize.com/r/loading-button.json

或手動安裝

  1. 1. 安裝相依套件。
    $ npm install clsx tailwind-merge framer-motion
  2. 2. 如果還沒有,在 lib/utils.ts 加上 cn 輔助函式。沒有用 shadcn/ui?再加上 sunui-theme.css 提供顏色變數(做法)。然後複製元件程式碼。
    loading-button.tsx
    "use client";
    
    import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
    import { useEffect, useRef, useState, type ButtonHTMLAttributes, type ReactNode } from "react";
    
    import { cn } from "@/lib/utils";
    
    /** Brand accent: follows the theme's --primary by default; buyers set --sunui-spot to use their own brand colour. Used only for selection, offers and current progress */
    const spotFill = "bg-[color:var(--sunui-spot,var(--primary))] text-[color:var(--sunui-spot-foreground,var(--primary-foreground))]";
    
    const springs = {
      snappy: { type: "spring", stiffness: 520, damping: 34 },
      gentle: { type: "spring", stiffness: 240, damping: 30 },
    } as const;
    
    export type LoadingButtonState = "idle" | "loading" | "success" | "error";
    
    export interface LoadingButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onClick" | "children" | "onAnimationStart" | "onDrag" | "onDragStart" | "onDragEnd"> {
      children: ReactNode;
      /** When it returns a Promise, switches loading → success (resolve) or error (reject) automatically */
      onClick?: () => unknown;
      /** Controlled state; when given, the component stops managing it itself */
      state?: LoadingButtonState;
      successLabel?: ReactNode;
      errorLabel?: ReactNode;
      /** Text screen readers read while loading */
      loadingLabel?: string;
      /** shrink: shrinks to a circle while loading; inline: keeps its width and the spinner appears before the text */
      loadingStyle?: "shrink" | "inline";
      /** Milliseconds before returning to idle after success or failure; 0 stays on the result */
      resetAfter?: number;
      variant?: "primary" | "paper";
    }
    
    function Spinner({ className }: { className?: string }) {
      return (
        <svg viewBox="0 0 24 24" fill="none" className={cn("size-4 animate-spin", className)} aria-hidden="true">
          <circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity="0.25" strokeWidth="2" />
          <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
        </svg>
      );
    }
    
    function Check({ reduce }: { reduce: boolean | null }) {
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="size-4" aria-hidden="true">
          <motion.path d="M5 12.5l4.5 4.5L19 7.5" initial={{ pathLength: reduce ? 1 : 0 }} animate={{ pathLength: 1 }} transition={{ duration: reduce ? 0 : 0.28, ease: "easeOut" }} />
        </svg>
      );
    }
    
    export function LoadingButton({
      children,
      onClick,
      state: stateProp,
      successLabel = "Done",
      errorLabel = "Try again",
      loadingLabel = "Loading",
      loadingStyle = "shrink",
      resetAfter = 2000,
      variant = "primary",
      className,
      disabled,
      type = "button",
      ...rest
    }: LoadingButtonProps) {
      const reduce = useReducedMotion();
      const [inner, setInner] = useState<LoadingButtonState>("idle");
      const state = stateProp ?? inner;
      const alive = useRef(true);
      const timer = useRef<number | undefined>(undefined);
    
      useEffect(() => {
        alive.current = true;
        return () => {
          alive.current = false;
          window.clearTimeout(timer.current);
        };
      }, []);
    
      useEffect(() => {
        if (stateProp !== undefined || resetAfter <= 0 || (state !== "success" && state !== "error")) return;
        timer.current = window.setTimeout(() => alive.current && setInner("idle"), resetAfter);
        return () => window.clearTimeout(timer.current);
      }, [state, stateProp, resetAfter]);
    
      const handle = async () => {
        if (state === "loading") return;
        const result = onClick?.();
        if (stateProp !== undefined || !(result instanceof Promise)) return;
        setInner("loading");
        try {
          await result;
          if (alive.current) setInner("success");
        } catch {
          if (alive.current) setInner("error");
        }
      };
    
      const shrunk = loadingStyle === "shrink" && state === "loading";
      const t = reduce ? { duration: 0 } : springs.gentle;
      const fade = reduce ? { duration: 0 } : { duration: 0.14 };
    
      return (
        <motion.button
          {...rest}
          type={type}
          layout={!reduce}
          transition={t}
          onClick={handle}
          disabled={disabled}
          aria-busy={state === "loading" || undefined}
          aria-disabled={state === "loading" || undefined}
          whileTap={reduce || state === "loading" ? undefined : { scale: 0.97 }}
          style={{ borderRadius: shrunk ? 999 : 6 }}
          className={cn(
            "relative inline-flex h-10 items-center justify-center overflow-hidden whitespace-nowrap text-sm font-medium outline-offset-2 focus-visible:outline-2 disabled:pointer-events-none disabled:opacity-50",
            shrunk ? "w-10 px-0" : "px-4",
            variant === "primary" && state !== "error" && spotFill,
            variant === "paper" && "border border-foreground/10 bg-card text-foreground",
            state === "error" && "bg-destructive text-white",
            className,
          )}
        >
          <AnimatePresence mode="popLayout" initial={false}>
            <motion.span
              key={shrunk ? "spin" : state}
              initial={{ opacity: 0, y: reduce ? 0 : 6 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: reduce ? 0 : -6 }}
              transition={fade}
              className="inline-flex items-center gap-2"
            >
              {shrunk ? (
                <Spinner />
              ) : state === "loading" ? (
                <>
                  <Spinner />
                  {children}
                </>
              ) : state === "success" ? (
                <>
                  <Check reduce={reduce} />
                  {successLabel}
                </>
              ) : state === "error" ? (
                errorLabel
              ) : (
                children
              )}
            </motion.span>
          </AnimatePresence>
          <span className="sr-only" aria-live="polite">
            {state === "loading" ? loadingLabel : state === "success" ? successLabel : state === "error" ? errorLabel : ""}
          </span>
        </motion.button>
      );
    }