// @flow strict import * as React from 'react'; import type {GroupAlign} from '../../types/common'; import classify from '../../utils/classify'; import {Icon} from '../Icon'; import css from './Checkbox.module.css'; type ClassNames = $ReadOnly<{ wrapper?: string, checkboxSquare?: string, label?: string, }>; /* Note: An indeterminate state has a higher priority. If true checkbox would be in an indeterminate state. If indeterminate is false, it will owner checked value. */ export type CheckboxProps = { name?: string, value?: string, children?: React.Node, checked?: boolean, indeterminate?: boolean, focused?: boolean, disabled?: boolean, error?: boolean, onChange?: ( {value: string, checked: boolean}, ?SyntheticEvent, ) => mixed, align?: GroupAlign, classNames?: ClassNames, tabIndex?: number, ariaLabel?: string, }; export const Checkbox: React$AbstractComponent< CheckboxProps, HTMLInputElement, > = React.forwardRef( ( { name = 'checkbox', value = '', children, checked = false, indeterminate = false, focused = false, disabled = false, error = false, onChange, align, classNames, tabIndex = 0, ariaLabel = '', }: CheckboxProps, forwardRef, ): React.Node => { const checkboxInput = React.createRef(); React.useImperativeHandle(forwardRef, () => checkboxInput.current); const handleOnClick = (event) => { if (!disabled) { onChange && onChange( { value, checked: !checked, }, event, ); } }; React.useEffect(() => { if (checkboxInput.current && focused) { checkboxInput.current.focus(); } }, [focused]); React.useEffect(() => { if (checkboxInput.current && indeterminate) { checkboxInput.current.indeterminate = true; } if (checkboxInput.current && !indeterminate) { checkboxInput.current.indeterminate = false; } }, [indeterminate]); return (
{indeterminate && ( )} {checked && !indeterminate && ( )} {React.Children.count(children) > 0 && (
{children}
)}
); }, );