diff --git a/packages/edit-site/src/components/dataviews/dataviews.js b/packages/edit-site/src/components/dataviews/dataviews.js index 13e27ddfacae5..0131040bf83af 100644 --- a/packages/edit-site/src/components/dataviews/dataviews.js +++ b/packages/edit-site/src/components/dataviews/dataviews.js @@ -32,6 +32,8 @@ import ViewActions from './view-actions'; import TextFilter from './text-filter'; import { moreVertical } from '@wordpress/icons'; +const EMPTY_OBJECT = {}; + export default function DataViews( { actions, data, @@ -44,7 +46,7 @@ export default function DataViews( { } ) { const columns = useMemo( () => { const _columns = [ ...fields ]; - if ( actions && actions.length ) { + if ( actions?.length ) { _columns.push( { header: { __( 'Actions' ) }, id: 'actions', @@ -83,6 +85,19 @@ export default function DataViews( { return _columns; }, [ fields, actions ] ); + const columnVisibility = useMemo( () => { + if ( ! view.hiddenFields?.length ) { + return; + } + return view.hiddenFields.reduce( + ( accumulator, fieldId ) => ( { + ...accumulator, + [ fieldId ]: false, + } ), + {} + ); + }, [ view.hiddenFields ] ); + const dataView = useReactTable( { data, columns, @@ -104,6 +119,7 @@ export default function DataViews( { pageIndex: view.page, pageSize: view.perPage, }, + columnVisibility: columnVisibility ?? EMPTY_OBJECT, }, onSortingChange: ( sortingUpdater ) => { onChangeView( ( currentView ) => { @@ -135,6 +151,27 @@ export default function DataViews( { }; } ); }, + onColumnVisibilityChange: ( columnVisibilityUpdater ) => { + onChangeView( ( currentView ) => { + const hiddenFields = Object.entries( + columnVisibilityUpdater() + ).reduce( + ( accumulator, [ fieldId, value ] ) => { + if ( value ) { + return accumulator.filter( + ( id ) => id !== fieldId + ); + } + return [ ...accumulator, fieldId ]; + }, + [ ...( currentView.hiddenFields || [] ) ] + ); + return { + ...currentView, + hiddenFields, + }; + } ); + }, onGlobalFilterChange: ( value ) => { onChangeView( { ...view, search: value, page: 0 } ); }, diff --git a/packages/edit-site/src/components/dataviews/view-actions.js b/packages/edit-site/src/components/dataviews/view-actions.js index 1ede6ebcd8b75..ab9f3be88c200 100644 --- a/packages/edit-site/src/components/dataviews/view-actions.js +++ b/packages/edit-site/src/components/dataviews/view-actions.js @@ -102,10 +102,10 @@ function PageSizeMenu( { dataView } ) { } function FieldsVisibilityMenu( { dataView } ) { - const hideableFields = dataView + const hidableFields = dataView .getAllColumns() .filter( ( columnn ) => columnn.getCanHide() ); - if ( ! hideableFields?.length ) { + if ( ! hidableFields?.length ) { return null; } return ( @@ -118,7 +118,7 @@ function FieldsVisibilityMenu( { dataView } ) { } > - { hideableFields?.map( ( field ) => { + { hidableFields?.map( ( field ) => { return (