UNPKG

@base-ui-components/react

Version:

Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.

84 lines (82 loc) 3.07 kB
"use strict"; 'use client'; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default; Object.defineProperty(exports, "__esModule", { value: true }); exports.useCheckboxGroupParent = useCheckboxGroupParent; var React = _interopRequireWildcard(require("react")); var _useEventCallback = require("@base-ui-components/utils/useEventCallback"); var _useBaseUiId = require("../utils/useBaseUiId"); const EMPTY = []; function useCheckboxGroupParent(params) { const { allValues = EMPTY, value = EMPTY, onValueChange: onValueChangeProp } = params; const uncontrolledStateRef = React.useRef(value); const disabledStatesRef = React.useRef(new Map()); const [status, setStatus] = React.useState('mixed'); const id = (0, _useBaseUiId.useBaseUiId)(); const checked = value.length === allValues.length; const indeterminate = value.length !== allValues.length && value.length > 0; const onValueChange = (0, _useEventCallback.useEventCallback)(onValueChangeProp); const getParentProps = React.useCallback(() => ({ id, indeterminate, checked, 'aria-controls': allValues.map(v => `${id}-${v}`).join(' '), onCheckedChange(_, event) { const uncontrolledState = uncontrolledStateRef.current; // None except the disabled ones that are checked, which can't be changed. const none = allValues.filter(v => disabledStatesRef.current.get(v) && uncontrolledState.includes(v)); // "All" that are valid: // - any that aren't disabled // - disabled ones that are checked const all = allValues.filter(v => !disabledStatesRef.current.get(v) || disabledStatesRef.current.get(v) && uncontrolledState.includes(v)); const allOnOrOff = uncontrolledState.length === all.length || uncontrolledState.length === 0; if (allOnOrOff) { if (value.length === all.length) { onValueChange(none, event); } else { onValueChange(all, event); } return; } if (status === 'mixed') { onValueChange(all, event); setStatus('on'); } else if (status === 'on') { onValueChange(none, event); setStatus('off'); } else if (status === 'off') { onValueChange(uncontrolledState, event); setStatus('mixed'); } } }), [allValues, checked, id, indeterminate, onValueChange, status, value.length]); const getChildProps = React.useCallback(name => ({ name, id: `${id}-${name}`, checked: value.includes(name), onCheckedChange(nextChecked, event) { const newValue = value.slice(); if (nextChecked) { newValue.push(name); } else { newValue.splice(newValue.indexOf(name), 1); } uncontrolledStateRef.current = newValue; onValueChange(newValue, event); setStatus('mixed'); } }), [id, onValueChange, value]); return React.useMemo(() => ({ id, indeterminate, getParentProps, getChildProps, disabledStatesRef }), [id, indeterminate, getParentProps, getChildProps]); }