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 (