From 869f9a7e6e00d6166dd978372768aa917862ebee Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 23 Feb 2024 15:05:18 +0100 Subject: [PATCH] Improve selection logic. --- packages/dataviews/src/bulk-actions.js | 36 ++++++++++++++++++++++---- packages/dataviews/src/dataviews.js | 2 +- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/dataviews/src/bulk-actions.js b/packages/dataviews/src/bulk-actions.js index 1569940ce45d3..5e4139fe0622e 100644 --- a/packages/dataviews/src/bulk-actions.js +++ b/packages/dataviews/src/bulk-actions.js @@ -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 @@ -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; } @@ -181,7 +207,7 @@ export default function BulkActions( { disabled={ areAllSelected } hideOnClick={ false } onClick={ () => { - onSelectionChange( data ); + onSelectionChange( selectableItems ); } } suffix={ numberSelectableItems } > diff --git a/packages/dataviews/src/dataviews.js b/packages/dataviews/src/dataviews.js index e1fc7e973f4f2..9bcf531006406 100644 --- a/packages/dataviews/src/dataviews.js +++ b/packages/dataviews/src/dataviews.js @@ -119,7 +119,7 @@ export default function DataViews( { /> { [ LAYOUT_TABLE, LAYOUT_GRID ].includes( view.type ) && - hasPossibleBulkAction( + hasPossibleBulkAction && (