Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/dataviews/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
Expand Down
17 changes: 15 additions & 2 deletions packages/dataviews/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -783,6 +795,7 @@ The following `DataViews` properties are **not supported** by `DataViewsPicker`:
- `renderItemLink`
- `onClickItem`
- `getItemLevel`
- `getItemParentId`
- `header`

## `DataForm`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export default function DataViewsLayout( { className }: DataViewsLayoutProps ) {
fields,
getItemId,
getItemLevel,
getItemParentId,
hasInitiallyLoaded,
isLoading,
view,
Expand Down Expand Up @@ -67,6 +68,7 @@ export default function DataViewsLayout( { className }: DataViewsLayoutProps ) {
fields={ fields }
getItemId={ getItemId }
getItemLevel={ getItemLevel }
getItemParentId={ getItemParentId }
isLoading={ isLoading }
onChangeView={ onChangeView }
onChangeSelection={ onChangeSelection }
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
Expand Down Expand Up @@ -260,6 +282,7 @@ function ViewTable< Item >( {
fields,
getItemId,
getItemLevel,
getItemParentId,
isLoading = false,
onChangeView,
onChangeSelection,
Expand All @@ -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,
Expand Down Expand Up @@ -655,19 +686,13 @@ function ViewTable< Item >( {
) : (
<tbody>
{ hasData &&
data.map( ( item, index ) => {
const id =
getItemId( item ) || index.toString();
rows.map( ( row, index ) => {
const { id, item, level } = row;
return (
<TableRow
key={ getItemId( item ) }
key={ id }
item={ item }
level={
view.showLevels &&
typeof getItemLevel === 'function'
? getItemLevel( item )
: undefined
}
level={ level }
hasBulkActions={ hasBulkActions }
actions={ actions }
fields={ fields }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest';
import getHierarchicalRows from '../get-hierarchical-rows';

type Item = {
id: string;
parentId?: string;
};

const getItemId = ( item: Item ) => 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 )
);
} );
} );
2 changes: 2 additions & 0 deletions packages/dataviews/src/dataviews/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ function DataViews< Item >( {
data,
getItemId = defaultGetItemId,
getItemLevel,
getItemParentId,
isLoading = false,
paginationInfo,
defaultLayouts: defaultLayoutsProperty = DEFAULT_LAYOUTS,
Expand Down Expand Up @@ -240,6 +241,7 @@ function DataViews< Item >( {
setOpenedFilter,
getItemId,
getItemLevel,
getItemParentId,
isItemClickable,
onClickItem,
renderItemLink,
Expand Down
Loading
Loading