| 1 |
import { useContext } from 'react'; |
| 2 |
|
| 3 |
import { Context } from './table-context'; |
| 4 |
import { arrayToClassName } from 'elementor-app/utils/utils.js'; |
| 5 |
|
| 6 |
import Checkbox from 'elementor-app/ui/atoms/checkbox'; |
| 7 |
|
| 8 |
export default function TableCheckbox( props ) { |
| 9 |
const context = useContext( Context ), |
| 10 |
{ selected, disabled, setSelected } = context || {}, |
| 11 |
isSelectAllCheckbox = Object.prototype.hasOwnProperty.call( props, 'allSelectedCount' ), |
| 12 |
isAllSelected = selected.length === props.allSelectedCount, |
| 13 |
isIndeterminate = isSelectAllCheckbox ? ! ! ( ( selected.length - disabled.length ) && ! isAllSelected ) : false, |
| 14 |
isSelected = isSelectAllCheckbox ? isAllSelected : selected.includes( props.index ), |
| 15 |
isDisabled = ! isSelectAllCheckbox ? disabled.includes( props.index ) : null, |
| 16 |
onSelectAll = () => { |
| 17 |
setSelected( () => { |
| 18 |
if ( isAllSelected || isIndeterminate ) { |
| 19 |
// Disabled checkboxes should not be unchecked. |
| 20 |
return disabled.length ? [ ...disabled ] : []; |
| 21 |
} |
| 22 |
|
| 23 |
return Array( props.allSelectedCount ) |
| 24 |
.fill( true ) |
| 25 |
.map( ( value, index ) => index ); |
| 26 |
} ); |
| 27 |
}, |
| 28 |
onSelectRow = () => { |
| 29 |
setSelected( ( prevState ) => { |
| 30 |
const currentSelections = [ ...prevState ], |
| 31 |
currentIndexPosition = currentSelections.indexOf( props.index ); |
| 32 |
|
| 33 |
if ( currentIndexPosition > -1 ) { |
| 34 |
currentSelections.splice( currentIndexPosition, 1 ); |
| 35 |
} else { |
| 36 |
currentSelections.push( props.index ); |
| 37 |
} |
| 38 |
|
| 39 |
return currentSelections; |
| 40 |
} ); |
| 41 |
}, |
| 42 |
onChange = () => isSelectAllCheckbox ? onSelectAll() : onSelectRow(); |
| 43 |
|
| 44 |
return ( |
| 45 |
<Checkbox |
| 46 |
checked={ isSelected } |
| 47 |
indeterminate={ isIndeterminate } |
| 48 |
onChange={ onChange } |
| 49 |
disabled={ isDisabled } |
| 50 |
className={ arrayToClassName( [ 'eps-table__checkbox', props.className ] ) } |
| 51 |
/> |
| 52 |
); |
| 53 |
} |
| 54 |
|
| 55 |
TableCheckbox.propTypes = { |
| 56 |
className: PropTypes.string, |
| 57 |
index: PropTypes.number, |
| 58 |
initialChecked: PropTypes.bool, |
| 59 |
allSelectedCount: PropTypes.number, |
| 60 |
}; |
| 61 |
|