import clsx from "clsx"; import { Checkbox as CheckboxPrimitive, Label as LabelPrimitive, } from "radix-ui"; import * as React from "react"; import { useGetSet } from "../../hooks"; import { useGetKey } from "../../hooks/useGetKey"; import { useDebugEvents } from "../../utils"; import { composeEventHandlers } from "../../utils/composeEvents"; import * as styles from "./styles.module.css"; export interface CheckboxProps extends CheckboxPrimitive.CheckboxProps { "data-id": string; required?: boolean; size?: "xs" | "sm" | "md" | "lg"; variant?: "solid" | "outline" | "subtle"; } export const Checkbox = React.forwardRef(function Checkbox( args: CheckboxProps, ref, ) { const { defaultChecked, onChange, onFocus, onBlur, children, disabled, required, size = "md", variant = "solid", ...rest } = args; const id = React.useId(); const key = useGetKey(rest); const inputRef = React.useRef(null); const initialValue = React.useMemo( () => ({ value: defaultChecked }), [defaultChecked], ); const [{ value }, setState] = useGetSet<{ value?: boolean | "indeterminate"; focused?: boolean; }>(key, initialValue); const { className, onChange: handleChange, ...props } = useDebugEvents( Object.assign(rest, { onFocus: composeEventHandlers( (event: React.ChangeEvent) => { setState({ focused: true }); }, onFocus, ), onChange: composeEventHandlers((value: boolean) => { setState({ value }); }, onChange), onBlur: composeEventHandlers( (event: React.ChangeEvent) => { setState({ focused: false }); }, onBlur, ), }), ); React.useEffect(() => { const parentForm = inputRef.current?.form; const handler = () => { setState({ value: !!defaultChecked }); }; parentForm?.addEventListener("reset", handler); return () => { parentForm?.removeEventListener("reset", handler); }; }, []); return ( <> e.stopPropagation()} data-component="Checkbox$Brevity" {...props} > {value === "indeterminate" ? ( ) : value ? ( ) : null} {children && ( {children} )} ); });