diff --git a/packages/dataviews/CHANGELOG.md b/packages/dataviews/CHANGELOG.md index 47424489f1bd87..10da451e33143d 100644 --- a/packages/dataviews/CHANGELOG.md +++ b/packages/dataviews/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Enhancements + +- DataViews: Add `getItemParentId` support for hierarchical table rows ([#83241](https://github.com/WordPress/gutenberg/pull/83241)). + ### Bug Fixes - Grid layout: when the title is hidden (`showTitle: false`) and items are clickable, label each item's clickable media area with its title instead of the generic "Navigate to item" ([#82639](https://github.com/WordPress/gutenberg/pull/82639)). diff --git a/packages/dataviews/README.md b/packages/dataviews/README.md index d41b0a2a1093bd..5fd2ad5087c6ab 100644 --- a/packages/dataviews/README.md +++ b/packages/dataviews/README.md @@ -117,7 +117,7 @@ Example: #### `getItemLevel`: `function` -A function that receives an item and returns its hierarchical level. It's optional, but this property must be passed for DataViews to display the hierarchical levels of the data if `view.showLevels` is true. +A function that receives an item and returns its hierarchical level. It's optional. DataViews uses it to indent table rows when `view.showLevels` is true and either `getItemParentId` is not provided or `view.groupBy` is set. Example: @@ -128,6 +128,18 @@ Example: } ``` +#### `getItemParentId`: `function` + +A function that receives an item and returns its parent's unique id, or `null`/`undefined` for a root item. When `view.showLevels` is true and `view.groupBy` is not set, the table orders loaded items by these relationships and calculates their indentation. Items with an unloaded parent are treated as roots. DataViews does not fetch missing items. + +Example: + +```js +{ + getItemParentId={ ( item ) => item.parentId } +} +``` + #### `fields`: `Object[]` The fields describe the visible items for each record in the dataset and how they behave (how to sort them, display them, etc.). See "Fields API" for a description of every property. @@ -237,7 +249,7 @@ Properties: - `showTitle`: Whether the title should be shown in the UI. `true` by default. - `showMedia`: Whether the media should be shown in the UI. `true` by default. - `showDescription`: Whether the description should be shown in the UI. `true` by default. -- `showLevels`: Whether to display the hierarchical levels for the data. `false` by default. See related `getItemLevel` DataView prop. +- `showLevels`: Whether to display the hierarchical levels for the data. `false` by default. See the related `getItemParentId` and `getItemLevel` DataViews props. - `groupBy`: - `field`: the field used for grouping the dataset. @@ -783,6 +795,7 @@ The following `DataViews` properties are **not supported** by `DataViewsPicker`: - `renderItemLink` - `onClickItem` - `getItemLevel` +- `getItemParentId` - `header` ## `DataForm` diff --git a/packages/dataviews/src/components/dataviews-context/index.ts b/packages/dataviews/src/components/dataviews-context/index.ts index d55f0cc5fdef52..24facf9e63999d 100644 --- a/packages/dataviews/src/components/dataviews-context/index.ts +++ b/packages/dataviews/src/components/dataviews-context/index.ts @@ -27,6 +27,7 @@ type DataViewsContextType< Item > = { setOpenedFilter: ( openedFilter: string | null ) => void; getItemId: ( item: Item ) => string; getItemLevel?: ( item: Item ) => number; + getItemParentId?: ( item: Item ) => string | number | null | undefined; onClickItem?: ( item: Item ) => void; renderItemLink?: ( props: { diff --git a/packages/dataviews/src/components/dataviews-layout/index.tsx b/packages/dataviews/src/components/dataviews-layout/index.tsx index 92c62f5ce3e469..bc90a6b24dba06 100644 --- a/packages/dataviews/src/components/dataviews-layout/index.tsx +++ b/packages/dataviews/src/components/dataviews-layout/index.tsx @@ -18,6 +18,7 @@ export default function DataViewsLayout( { className }: DataViewsLayoutProps ) { fields, getItemId, getItemLevel, + getItemParentId, hasInitiallyLoaded, isLoading, view, @@ -67,6 +68,7 @@ export default function DataViewsLayout( { className }: DataViewsLayoutProps ) { fields={ fields } getItemId={ getItemId } getItemLevel={ getItemLevel } + getItemParentId={ getItemParentId } isLoading={ isLoading } onChangeView={ onChangeView } onChangeSelection={ onChangeSelection } diff --git a/packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.ts b/packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.ts new file mode 100644 index 00000000000000..a939d1245bb739 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.ts @@ -0,0 +1,89 @@ +export interface HierarchicalRow< Item > { + item: Item; + id: string; + level: number; +} + +type Row< Item > = HierarchicalRow< Item > & { + parentId?: string; +}; + +/** + * Orders loaded items by parent while preserving their order among siblings. + * Missing parents, self-parenting items, and cycles are rendered as roots so + * malformed or partially loaded data never disappears. + * + * @param items Loaded items. + * @param getItemId Returns an item's unique identifier. + * @param getItemParentId Returns an item's parent identifier. + */ +export default function getHierarchicalRows< Item >( + items: Item[], + getItemId: ( item: Item ) => string, + getItemParentId: ( item: Item ) => string | number | null | undefined +): HierarchicalRow< Item >[] { + const rows: Row< Item >[] = items.map( ( item, index ) => { + const parentId = getItemParentId( item ); + return { + item, + id: getItemId( item ) || index.toString(), + level: 0, + parentId: + parentId === null || parentId === undefined + ? undefined + : parentId.toString(), + }; + } ); + const rowById = new Map( rows.map( ( row ) => [ row.id, row ] ) ); + const childrenByParentId = new Map< string, Row< Item >[] >(); + const roots: Row< Item >[] = []; + + for ( const row of rows ) { + if ( + ! row.parentId || + row.parentId === row.id || + ! rowById.has( row.parentId ) + ) { + roots.push( row ); + continue; + } + const children = childrenByParentId.get( row.parentId ) ?? []; + children.push( row ); + childrenByParentId.set( row.parentId, children ); + } + + const result: HierarchicalRow< Item >[] = []; + const visited = new Set< string >(); + const appendTree = ( root: Row< Item > ) => { + const stack = [ { row: root, level: 0 } ]; + while ( stack.length ) { + const current = stack.pop()!; + if ( visited.has( current.row.id ) ) { + continue; + } + visited.add( current.row.id ); + result.push( { + item: current.row.item, + id: current.row.id, + level: current.level, + } ); + + const children = childrenByParentId.get( current.row.id ) ?? []; + for ( let index = children.length - 1; index >= 0; index-- ) { + stack.push( { + row: children[ index ], + level: current.level + 1, + } ); + } + } + }; + + roots.forEach( appendTree ); + rows.forEach( ( row ) => { + if ( ! visited.has( row.id ) ) { + appendTree( row ); + } + } ); + + return result; +} diff --git a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx index 019801af7d130f..1cfeeed332b769 100644 --- a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx @@ -30,6 +30,9 @@ import type { import type { SetSelection } from '../../../types/private'; import ColumnHeaderMenu from './column-header-menu'; import ColumnPrimary from './column-primary'; +import getHierarchicalRows, { + type HierarchicalRow, +} from './get-hierarchical-rows'; import { useScrollState } from './use-scroll-state'; import getDataByGroup from '../utils/get-data-by-group'; import getTableColumns from '../utils/get-table-columns'; @@ -50,6 +53,25 @@ function getEffectiveAlign( return undefined; } +function getRows< Item >( + items: Item[], + getItemId: ( item: Item ) => string, + getItemLevel: ( ( item: Item ) => number ) | undefined, + getItemParentId: + ( ( item: Item ) => string | number | null | undefined ) | undefined, + showLevels: boolean | undefined +): HierarchicalRow< Item >[] { + if ( showLevels && getItemParentId ) { + return getHierarchicalRows( items, getItemId, getItemParentId ); + } + + return items.map( ( item, index ) => ( { + item, + id: getItemId( item ) || index.toString(), + level: showLevels && getItemLevel ? getItemLevel( item ) : 0, + } ) ); +} + interface TableColumnFieldProps< Item > { fields: NormalizedField< Item >[]; column: string; @@ -260,6 +282,7 @@ function ViewTable< Item >( { fields, getItemId, getItemLevel, + getItemParentId, isLoading = false, onChangeView, onChangeSelection, @@ -278,11 +301,19 @@ function ViewTable< Item >( { ? fields.find( ( f ) => f.id === view.groupBy?.field ) : null; const dataByGroup = groupField ? getDataByGroup( data, groupField ) : null; - // When grouping is enabled the rendered order is by group rather than the - // order of `data`; ranges follow what the user sees. + const rows = dataByGroup + ? [] + : getRows( + data, + getItemId, + getItemLevel, + getItemParentId, + view.showLevels + ); + // Selection ranges follow the rendered hierarchy and group order. const orderedData = dataByGroup ? Array.from( dataByGroup.values() ).flat() - : data; + : rows.map( ( row ) => row.item ); const { getSelectionProps } = useSelectionProps( { data: orderedData, getItemId, @@ -655,19 +686,13 @@ function ViewTable< Item >( { ) : ( { hasData && - data.map( ( item, index ) => { - const id = - getItemId( item ) || index.toString(); + rows.map( ( row, index ) => { + const { id, item, level } = row; return ( item.id; +const getItemParentId = ( item: Item ) => item.parentId; + +describe( 'getHierarchicalRows', () => { + it( 'orders loaded items by parent while preserving sibling order and computing depth', () => { + const rows = getHierarchicalRows( + [ + { id: 'child-2', parentId: 'root' }, + { id: 'root' }, + { id: 'child-1', parentId: 'root' }, + { id: 'grandchild', parentId: 'child-1' }, + { id: 'other-root' }, + ], + getItemId, + getItemParentId + ); + + expect( rows.map( ( { id, level } ) => ( { id, level } ) ) ).toEqual( [ + { id: 'root', level: 0 }, + { id: 'child-2', level: 1 }, + { id: 'child-1', level: 1 }, + { id: 'grandchild', level: 2 }, + { id: 'other-root', level: 0 }, + ] ); + } ); + + it( 'returns missing-parent, self-parenting, and cyclic items exactly once', () => { + const items = [ + { id: 'orphan', parentId: 'missing' }, + { id: 'self', parentId: 'self' }, + { id: 'cycle-a', parentId: 'cycle-b' }, + { id: 'cycle-b', parentId: 'cycle-a' }, + ]; + + const rows = getHierarchicalRows( items, getItemId, getItemParentId ); + + expect( rows.map( ( row ) => row.item ) ).toHaveLength( items.length ); + expect( new Set( rows.map( ( row ) => row.item ) ) ).toEqual( + new Set( items ) + ); + } ); +} ); diff --git a/packages/dataviews/src/dataviews/index.tsx b/packages/dataviews/src/dataviews/index.tsx index 96a6d62324188d..b9d31ded0e0a16 100644 --- a/packages/dataviews/src/dataviews/index.tsx +++ b/packages/dataviews/src/dataviews/index.tsx @@ -96,6 +96,7 @@ function DataViews< Item >( { data, getItemId = defaultGetItemId, getItemLevel, + getItemParentId, isLoading = false, paginationInfo, defaultLayouts: defaultLayoutsProperty = DEFAULT_LAYOUTS, @@ -240,6 +241,7 @@ function DataViews< Item >( { setOpenedFilter, getItemId, getItemLevel, + getItemParentId, isItemClickable, onClickItem, renderItemLink, diff --git a/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx b/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx index 9c4e6ccda47a7c..5698729f313c11 100644 --- a/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx +++ b/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx @@ -3,62 +3,7 @@ import DataViews from '../index'; import { LAYOUT_TABLE } from '../../constants'; import filterSortAndPaginate from '../../utils/filter-sort-and-paginate'; import type { View } from '../../types'; -import { data as allData, fields, type SpaceObject } from './fixtures'; - -/** - * Simulates what the WordPress REST API does for `orderby_hierarchy` (see - * Gutenberg_Hierarchical_Sort in lib/experimental): filter and sort the whole - * list first, then order it depth-first so that each item sits right below - * its parent, then paginate. - * - * Siblings keep the sort order. Items whose parent is not in the filtered - * list come after all the root trees, grouped by parent, and keep their own - * level so they stay indented as deep as they really are. - */ -function sortByHierarchy( items: SpaceObject[], view: View ) { - const { data: sortedItems } = filterSortAndPaginate( - items, - { ...view, page: undefined, perPage: undefined }, - fields - ); - - let orderedItems = sortedItems; - if ( view.showLevels ) { - // Children grouped by parent, in the order the parents first appear. - const childrenByParent = new Map< number | null, SpaceObject[] >(); - sortedItems.forEach( ( item ) => { - childrenByParent.set( item.parent, [ - ...( childrenByParent.get( item.parent ) ?? [] ), - item, - ] ); - } ); - - orderedItems = []; - const visit = ( parent: number | null ) => { - ( childrenByParent.get( parent ) ?? [] ).forEach( ( item ) => { - orderedItems.push( item ); - visit( item.id ); - } ); - // Once visited, a group must not be emitted again as an orphan group. - childrenByParent.delete( parent ); - }; - - // Roots and their descendants first. - visit( null ); - // Then the items whose parent is not in the list, grouped by parent. - Array.from( childrenByParent.keys() ).forEach( visit ); - } - - const page = view.page ?? 1; - const perPage = view.perPage ?? orderedItems.length; - return { - data: orderedItems.slice( ( page - 1 ) * perPage, page * perPage ), - paginationInfo: { - totalItems: orderedItems.length, - totalPages: Math.ceil( orderedItems.length / perPage ), - }, - }; -} +import { data as allData, fields } from './fixtures'; const HierarchicalLevelsComponent = ( { showLevels = true, @@ -79,7 +24,7 @@ const HierarchicalLevelsComponent = ( { }, titleField: 'title', mediaField: 'image', - showLevels: true, + showLevels, } ); useEffect( () => { @@ -89,12 +34,16 @@ const HierarchicalLevelsComponent = ( { } ) ); }, [ showLevels ] ); - const { data, paginationInfo } = sortByHierarchy( allData, view ); + const { data, paginationInfo } = filterSortAndPaginate( + allData, + view, + fields + ); return ( item.id.toString() } - getItemLevel={ ( item ) => item.level } + getItemParentId={ ( item ) => item.parent } data={ data } paginationInfo={ paginationInfo } view={ view } diff --git a/packages/dataviews/src/dataviews/stories/index.story.tsx b/packages/dataviews/src/dataviews/stories/index.story.tsx index 651a362cf3767f..1bf6a680de1c00 100644 --- a/packages/dataviews/src/dataviews/stories/index.story.tsx +++ b/packages/dataviews/src/dataviews/stories/index.story.tsx @@ -249,7 +249,7 @@ export const HierarchicalLevels = { showLevels: { control: 'boolean', description: - 'Whether the table indents each item by its level (`view.showLevels`). When enabled, each item is placed below its parent; when disabled, items follow the sort order only', + 'Whether the table orders and indents loaded items using their parent relationships (`view.showLevels`). When disabled, items follow the sort order only', }, }, }; diff --git a/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx b/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx index 47d797bb30cf65..9323ab84f65fd3 100644 --- a/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx +++ b/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx @@ -174,6 +174,50 @@ describe( 'DataViews component', () => { expect( screen.getByText( 'No results' ) ).toBeInTheDocument(); } ); + it( 'orders and indents loaded items from their parent ids', () => { + render( + + item.id === 2 ? 1 : undefined + } + view={ { + ...DEFAULT_VIEW, + fields: [], + showLevels: true, + titleField: 'title', + } } + /> + ); + + const rows = screen.getAllByRole( 'row' ).slice( 1 ); + expect( rows[ 0 ] ).toHaveTextContent( 'Parent' ); + expect( rows[ 1 ] ).toHaveTextContent( '— Child' ); + } ); + + it( 'keeps getItemLevel indentation when no parent callback exists', () => { + render( + item.id - 1 } + view={ { + ...DEFAULT_VIEW, + fields: [], + showLevels: true, + titleField: 'title', + } } + /> + ); + + expect( screen.getByText( '—' ) ).toBeInTheDocument(); + } ); + it( 'should filter results by "search" text, if field has enableGlobalSearch set to true', async () => { const fieldsWithSearch = [ { diff --git a/packages/dataviews/src/types/dataviews.ts b/packages/dataviews/src/types/dataviews.ts index fd4a54d484508c..fa3f436862d4d4 100644 --- a/packages/dataviews/src/types/dataviews.ts +++ b/packages/dataviews/src/types/dataviews.ts @@ -141,6 +141,14 @@ export type DataViewsProps< Item > = { */ getItemLevel?: ( item: Item ) => number; + /** + * Returns the unique identifier of an item's parent. When provided, the + * view's `showLevels` option is enabled, and items aren't grouped, loaded + * table items are ordered by their parent relationships and their + * hierarchical depth is calculated. + */ + getItemParentId?: ( item: Item ) => string | number | null | undefined; + /** * Custom component tree rendered instead of the default layout * composition, using the internal `DataViews.*` sub-components. @@ -787,6 +795,13 @@ export interface ViewBaseProps< Item > { */ getItemLevel?: ( item: Item ) => number; + /** + * Returns the unique identifier of an item's parent. Used by the table + * layout when the view's `showLevels` option is enabled and items aren't + * grouped. + */ + getItemParentId?: ( item: Item ) => string | number | null | undefined; + /** * Whether the data is loading, in which case a loading state is shown. */ @@ -851,7 +866,7 @@ export interface ViewBaseProps< Item > { * The props passed to every picker layout component. Same as * `ViewBaseProps`, minus the props pickers don't support: the item-click * ones (`onClickItem`, `renderItemLink`, `isItemClickable`) and the - * hierarchy one (`getItemLevel`). + * hierarchy ones (`getItemLevel`, `getItemParentId`). */ export type ViewPickerBaseProps< Item > = Omit< ViewBaseProps< Item >, @@ -862,6 +877,7 @@ export type ViewPickerBaseProps< Item > = Omit< | 'onClickItem' | 'renderItemLink' | 'getItemLevel' + | 'getItemParentId' > & { /** * The current view configuration. diff --git a/storybook/components-manifest.yml b/storybook/components-manifest.yml index d3a943932976b2..88e5fb706ceb3e 100644 --- a/storybook/components-manifest.yml +++ b/storybook/components-manifest.yml @@ -473,6 +473,7 @@ - fields - getItemId - getItemLevel + - getItemParentId - header - isItemClickable - isLoading