"use client"; import React, { forwardRef } from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/utils/cn"; /** * Checkbox 复选框组件 * * Design System 中的复选框组件,支持多种状态和尺寸。 * * @example * ```tsx * // 默认复选框 * 同意条款 * * // 受控组件 * * 同意条款 * * * // 错误状态 * 必选项 * ``` */ /** * 复选框变体样式 */ const checkboxVariants = cva( // 基础样式 "peer h-4 w-4 shrink-0 rounded border-2 transition-all duration-250 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50", { variants: { variant: { default: "border-gray-300 checked:bg-primary-500 checked:border-primary-500", success: "border-gray-300 checked:bg-success-500 checked:border-success-500", warning: "border-gray-300 checked:bg-warning-500 checked:border-warning-500", error: "border-gray-300 checked:bg-error-500 checked:border-error-500", }, size: { sm: "h-3.5 w-3.5", md: "h-4 w-4", lg: "h-5 w-5", }, error: { true: "border-error-500", false: "", }, }, defaultVariants: { variant: "default", size: "md", error: false, }, } ); export type CheckboxVariant = VariantProps["variant"]; export type CheckboxSize = VariantProps["size"]; export interface CheckboxProps extends Omit, "size">, VariantProps { // 标签文本 label?: React.ReactNode; // 标签位置 labelPosition?: "left" | "right"; // 自定义复选框类名 checkboxClassName?: string; } /** * Checkbox 复选框组件 */ export const Checkbox = forwardRef( ( { variant = "default", size = "md", error = false, label, labelPosition = "right", className, checkboxClassName, disabled, ...props }, ref ) => { const checkboxId = React.useId(); const renderCheckbox = () => ( ); const renderLabel = () => { if (!label) return null; return ( ); }; if (!label) { return renderCheckbox(); } return (
{labelPosition === "left" && renderLabel()} {renderCheckbox()} {labelPosition === "right" && renderLabel()}
); } ); Checkbox.displayName = "Checkbox"; /** * CheckboxGroup - 复选框组 */ export interface CheckboxGroupProps { children: React.ReactNode; label?: string; error?: string; required?: boolean; className?: string; } export function CheckboxGroup({ children, label, error, required, className, }: CheckboxGroupProps) { return (
{label && (
{label} {required && *}
)}
{children}
{error &&

{error}

}
); }