import {__, sprintf} from '@wordpress/i18n'; import {useContext, useEffect, useState} from 'react'; import {CheckboxContext} from '@givewp/components/ListTable/ListTablePage'; import styles from './BulkActionCheckbox.module.scss'; export const BulkActionCheckbox = ({id, name, singleName}) => { const checkboxRefs = useContext(CheckboxContext); // add this element's ref to the list of checkboxes, so we can access them imperatively const updateCheckboxRefs = (node: HTMLInputElement) => { if (node !== null && !checkboxRefs?.current.includes(node)) { checkboxRefs?.current.push(node); } }; useEffect(() => { // cleanup function to remove the ref checked value when the component unmounts return () => { checkboxRefs.current.forEach((checkbox) => { checkbox.checked = false; }); checkboxRefs.current = checkboxRefs.current.filter((checkbox) => checkbox.dataset.id === id); }; }, []); return ( <> ); }; export const BulkActionCheckboxAll = ({pluralName, data}) => { const checkboxRefs = useContext(CheckboxContext); const [checked, setChecked] = useState(false); // reset the 'Select all' checkbox when table contents change useEffect(() => { setChecked(false); }, [data]); return ( <> toggleAllRowCheckboxes(event, checkboxRefs, setChecked, checked)} checked={checked} /> ); }; const toggleAllRowCheckboxes: ToggleAllRowCheckboxesProps = (_event, checkboxRefs, setChecked, checked) => { checkboxRefs.current.forEach((checkbox) => { checkbox.checked = !checked; }); setChecked(!checked); }; type CheckboxContextProps = { current: HTMLInputElement[]; }; interface ToggleAllRowCheckboxesProps { ( event: React.ChangeEvent, checkboxRefs: CheckboxContextProps, setChecked: React.Dispatch>, checked: boolean ): void; }