Skip to content

Commit

Permalink
Improve selection logic.
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgefilipecosta committed Feb 23, 2024
1 parent cfe0688 commit 869f9a7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
36 changes: 31 additions & 5 deletions packages/dataviews/src/bulk-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
Modal,
} from '@wordpress/components';
import { __, sprintf, _n } from '@wordpress/i18n';
import { useMemo, useState, useCallback } from '@wordpress/element';
import { useMemo, useState, useCallback, useEffect } from '@wordpress/element';

/**
* Internal dependencies
Expand Down Expand Up @@ -125,21 +125,47 @@ export default function BulkActions( {
() => actions.filter( ( action ) => action.supportsBulk ),
[ actions ]
);
const areAllSelected = selection && selection.length === data.length;
const [ isMenuOpen, onMenuOpenChange ] = useState( false );
const [ actionWithModal, setActionWithModal ] = useState();
const numberSelectableItems = useMemo( () => {
const selectableItems = useMemo( () => {
return data.filter( ( item ) => {
return bulkActions.some( ( action ) => action.isEligible( item ) );
} ).length;
} );
}, [ data, bulkActions ] );

const numberSelectableItems = selectableItems.length;
const areAllSelected =
selection && selection.length === numberSelectableItems;

const selectedItems = useMemo( () => {
return data.filter( ( item ) =>
selection.includes( getItemId( item ) )
);
}, [ selection, data, getItemId ] );

const hasNonSelectableItemSelected = useMemo( () => {
return selectedItems.some( ( item ) => {
return ! selectableItems.includes( item );
} );
}, [ selectedItems, selectableItems ] );
useEffect( () => {
if ( hasNonSelectableItemSelected ) {
onSelectionChange(
selectedItems.filter( ( selectedItem ) => {
return selectableItems.some( ( item ) => {
return getItemId( selectedItem ) === getItemId( item );
} );
} )
);
}
}, [
hasNonSelectableItemSelected,
selectedItems,
selectableItems,
getItemId,
onSelectionChange,
] );

if ( bulkActions.length === 0 ) {
return null;
}
Expand Down Expand Up @@ -181,7 +207,7 @@ export default function BulkActions( {
disabled={ areAllSelected }
hideOnClick={ false }
onClick={ () => {
onSelectionChange( data );
onSelectionChange( selectableItems );
} }
suffix={ numberSelectableItems }
>
Expand Down
2 changes: 1 addition & 1 deletion packages/dataviews/src/dataviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export default function DataViews( {
/>
</HStack>
{ [ LAYOUT_TABLE, LAYOUT_GRID ].includes( view.type ) &&
hasPossibleBulkAction(
hasPossibleBulkAction && (
<BulkActions
actions={ actions }
data={ data }
Expand Down

0 comments on commit 869f9a7

Please sign in to comment.