70 lines
2.9 KiB
TypeScript
70 lines
2.9 KiB
TypeScript
/**
|
|
* 通用按钮的样式与属性适配层。variant表达视觉语义,size控制尺寸;点击、禁用和表单行为由调用方传入。
|
|
* 可通过asChild复用子元素,避免链接外再套按钮;这里不保存业务状态,也不默认指定button的type。
|
|
*/
|
|
import * as React from "react";
|
|
import { Slot } from "@radix-ui/react-slot";
|
|
import { cva, type VariantProps } from "class-variance-authority";
|
|
|
|
import { cn } from "@/lib/utils";
|
|
|
|
/** 将基础交互样式、语义变体和尺寸变体组合成className;未指定时使用default/default。
|
|
* focus-visible提供键盘焦点反馈,disabled类限制指针交互并淡化外观,内嵌SVG统一尺寸。 */
|
|
const buttonVariants = cva(
|
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
|
{
|
|
variants: {
|
|
variant: {
|
|
default:
|
|
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
|
|
destructive:
|
|
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
|
|
outline:
|
|
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
|
|
secondary:
|
|
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
|
|
ghost: "hover:bg-accent hover:text-accent-foreground",
|
|
link: "text-primary underline-offset-4 hover:underline",
|
|
},
|
|
size: {
|
|
default: "h-9 px-4 py-2",
|
|
sm: "h-8 rounded-md px-3 text-xs",
|
|
lg: "h-10 rounded-md px-8",
|
|
icon: "h-9 w-9",
|
|
},
|
|
},
|
|
defaultVariants: {
|
|
variant: "default",
|
|
size: "default",
|
|
},
|
|
},
|
|
);
|
|
|
|
/** 在原生button属性上增加样式变体和asChild;ref仍按按钮声明,实际宿主由asChild决定。 */
|
|
export interface ButtonProps
|
|
extends
|
|
React.ButtonHTMLAttributes<HTMLButtonElement>,
|
|
VariantProps<typeof buttonVariants> {
|
|
asChild?: boolean;
|
|
}
|
|
|
|
/** 转发ref和剩余原生属性,供调用方设置事件、可访问名称、disabled和表单属性。
|
|
* Slot把属性合并到唯一子元素;使用链接等宿主时,其语义及行为由该子元素承担。 */
|
|
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|
({ className, variant, size, asChild = false, ...props }, ref) => {
|
|
// 只选择宿主,不另包一层DOM;cn合并变体和调用方样式,业务逻辑不进入这个封装。
|
|
const Comp = asChild ? Slot : "button";
|
|
return (
|
|
<Comp
|
|
className={cn(buttonVariants({ variant, size, className }))}
|
|
ref={ref}
|
|
{...props}
|
|
/>
|
|
);
|
|
},
|
|
);
|
|
// forwardRef生成包装组件后补显示名,便于React开发工具定位。
|
|
Button.displayName = "Button";
|
|
|
|
export { Button, buttonVariants };
|