Skip to content

Commit

Permalink
DataViews: add control to reset all filters at once (WordPress#55955)
Browse files Browse the repository at this point in the history
* Add reset filters button

* Set proper spacing/alignment for control

* Fix lint

* Also reset search

* Disable reset button if no filters active

* Properly manage keys

* Managed undefined visibleFilters
  • Loading branch information
oandregal authored Nov 8, 2023
1 parent a522e39 commit e50aabe
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 21 deletions.
58 changes: 37 additions & 21 deletions packages/edit-site/src/components/dataviews/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { __ } from '@wordpress/i18n';
* Internal dependencies
*/
import { default as InFilter, OPERATOR_IN } from './in-filter';
import ResetFilters from './reset-filters';

const VALID_OPERATORS = [ OPERATOR_IN ];

export default function Filters( { fields, view, onChangeView } ) {
Expand Down Expand Up @@ -34,27 +36,41 @@ export default function Filters( { fields, view, onChangeView } ) {
} );
} );

return view.visibleFilters?.map( ( fieldName ) => {
const visibleFiltersForField = filtersRegistered.filter(
( f ) => f.field === fieldName
);
const visibleFilters = view.visibleFilters
?.map( ( fieldName ) => {
const visibleFiltersForField = filtersRegistered.filter(
( f ) => f.field === fieldName
);

if ( visibleFiltersForField.length === 0 ) {
return null;
}

return visibleFiltersForField.map( ( filter ) => {
if ( OPERATOR_IN === filter.operator ) {
return (
<InFilter
key={ fieldName }
filter={ visibleFiltersForField[ 0 ] }
view={ view }
onChangeView={ onChangeView }
/>
);
if ( visibleFiltersForField.length === 0 ) {
return null;
}
return null;
} );
} );

return visibleFiltersForField.map( ( filter ) => {
if ( OPERATOR_IN === filter.operator ) {
return (
<InFilter
key={ fieldName + '.' + filter.operator }
filter={ visibleFiltersForField[ 0 ] }
view={ view }
onChangeView={ onChangeView }
/>
);
}
return null;
} );
} )
.filter( Boolean );

if ( visibleFilters?.length > 0 ) {
visibleFilters.push(
<ResetFilters
key="reset-filters"
view={ view }
onChangeView={ onChangeView }
/>
);
}

return visibleFilters;
}
26 changes: 26 additions & 0 deletions packages/edit-site/src/components/dataviews/reset-filters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* WordPress dependencies
*/
import { BaseControl, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

export default ( { view, onChangeView } ) => {
return (
<BaseControl>
<Button
disabled={ view.search === '' && view.filters?.length === 0 }
variant="tertiary"
onClick={ () => {
onChangeView( ( currentView ) => ( {
...currentView,
page: 1,
search: '',
filters: [],
} ) );
} }
>
{ __( 'Reset filters' ) }
</Button>
</BaseControl>
);
};

0 comments on commit e50aabe

Please sign in to comment.