← full-stack-fastapi-template  /  frontend/src/components/ui/loading-button.tsx

1
import { Slot, Slottable } from "@radix-ui/react-slot"
2
import { cva, type VariantProps } from "class-variance-authority"
3
import { Loader2 } from "lucide-react"
4
import { cn } from "@/lib/utils"
5
6
const buttonVariants = cva(
7
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
8
  {
9
    variants: {
10
      variant: {
11
        default:
12
          "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
13
        destructive:
14
          "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
15
        outline:
16
          "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
17
        secondary:
18
          "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
19
        ghost:
20
          "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
21
        link: "text-primary underline-offset-4 hover:underline",
22
      },
23
      size: {
24
        default: "h-9 px-4 py-2 has-[>svg]:px-3",
25
        sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
26
        lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
27
        icon: "size-9",
28
      },
29
    },
30
    defaultVariants: {
31
      variant: "default",
32
      size: "default",
33
    },
34
  },
35
)
36
37
export interface ButtonProps
38
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
39
  VariantProps<typeof buttonVariants> {
40
  asChild?: boolean
41
  loading?: boolean
42
}
43
44
function LoadingButton({
45
  className,
46
  loading = false,
47
  children,
48
  disabled,
49
  variant,
50
  size,
51
  asChild = false,
52
  ...props
53
}: ButtonProps) {
54
  const Comp = asChild ? Slot : "button"
55
  return (
56
    <Comp
57
      className={cn(buttonVariants({ variant, size, className }))}
58
      disabled={loading || disabled}
59
      {...props}
60
    >
61
      {loading && <Loader2 className="mr-2 h-5 w-5 animate-spin" />}
62
      <Slottable>{children}</Slottable>
63
    </Comp>
64
  )
65
}
66
67
export { buttonVariants, LoadingButton }
68