BulkActionCheckbox.tsx
3 years ago
BulkActionSelect.module.scss
3 years ago
BulkActionSelect.tsx
3 years ago
BulkActionCheckbox.tsx
78 lines
| 1 | import {__, sprintf} from '@wordpress/i18n'; |
| 2 | import {useCallback, useContext, useEffect, useState} from 'react'; |
| 3 | import {CheckboxContext} from '@givewp/components/ListTable/ListTablePage'; |
| 4 | |
| 5 | export const BulkActionCheckbox = ({id, name, singleName, data}) => { |
| 6 | const checkboxRefs = useContext(CheckboxContext); |
| 7 | // add this element's ref to the list of checkboxes so we can access them imperatively |
| 8 | const updateCheckboxRefs = useCallback( |
| 9 | (node) => { |
| 10 | if (node !== null && ! checkboxRefs?.current.includes(node)) { |
| 11 | checkboxRefs?.current.push(node); |
| 12 | } |
| 13 | }, |
| 14 | [data] |
| 15 | ); |
| 16 | |
| 17 | useEffect(() => { |
| 18 | // cleanup function to remove the ref checked value when the component unmounts |
| 19 | return () => { |
| 20 | checkboxRefs.current.forEach((checkbox) => { |
| 21 | checkbox.checked = false; |
| 22 | }); |
| 23 | checkboxRefs.current = checkboxRefs.current.filter((checkbox) => checkbox.dataset.id === id); |
| 24 | }; |
| 25 | }, []); |
| 26 | return ( |
| 27 | <> |
| 28 | <label |
| 29 | htmlFor={`giveListTableSelect${id}`} |
| 30 | id={`giveListTableSelect${id}-Label`} |
| 31 | className="give-visually-hidden" |
| 32 | > |
| 33 | {sprintf(__('Select %1s %2s', 'give'), singleName, id)} |
| 34 | </label> |
| 35 | <input |
| 36 | ref={updateCheckboxRefs} |
| 37 | className="giveListTableSelect" |
| 38 | data-id={id} |
| 39 | data-name={name ? name : null} |
| 40 | id={`giveListTableSelect${id}`} |
| 41 | aria-labelledby={`giveListTableSelect${id}-Label`} |
| 42 | type="checkbox" |
| 43 | /> |
| 44 | </> |
| 45 | ); |
| 46 | }; |
| 47 | |
| 48 | export const BulkActionCheckboxAll = ({pluralName, data}) => { |
| 49 | const checkboxRefs = useContext(CheckboxContext); |
| 50 | const [checked, setChecked] = useState(false); |
| 51 | // reset the 'Select all' checkbox when table contents change |
| 52 | useEffect(() => { |
| 53 | setChecked(false); |
| 54 | }, [data]); |
| 55 | return ( |
| 56 | <> |
| 57 | <label htmlFor="giveListTableSelectAll" id="giveListTableSelectAll-Label" className="give-visually-hidden"> |
| 58 | {sprintf(__('Select all %s', 'give'), pluralName)} |
| 59 | </label> |
| 60 | <input |
| 61 | id="giveListTableSelectAll" |
| 62 | type="checkbox" |
| 63 | className="giveListTableSelect" |
| 64 | aria-labelledby="giveListTableSelectAll-Label" |
| 65 | onChange={(event) => toggleAllRowCheckboxes(event, checkboxRefs, setChecked, checked)} |
| 66 | checked={checked} |
| 67 | /> |
| 68 | </> |
| 69 | ); |
| 70 | }; |
| 71 | |
| 72 | const toggleAllRowCheckboxes = (event, checkboxRefs, setChecked, checked) => { |
| 73 | checkboxRefs.current.forEach((checkbox) => { |
| 74 | checkbox.checked = !checked; |
| 75 | }); |
| 76 | setChecked(!checked); |
| 77 | }; |
| 78 |