From 93563503e433271d933a503bd47bbaa140032e51 Mon Sep 17 00:00:00 2001 From: Tung Du Date: Mon, 21 Sep 2026 12:03:04 +0700 Subject: [PATCH 1/8] feat: add DataViews parent relationships --- packages/dataviews/README.md | 17 +++- .../src/components/dataviews-context/index.ts | 1 + .../src/components/dataviews-layout/index.tsx | 2 + .../table/get-hierarchical-rows.test.ts | 52 +++++++++++ .../table/get-hierarchical-rows.ts | 89 ++++++++++++++++++ .../dataviews-layouts/table/index.tsx | 90 +++++++++++++------ packages/dataviews/src/dataviews/index.tsx | 2 + .../dataviews/stories/hierarchical-levels.tsx | 65 ++------------ .../src/dataviews/stories/index.story.tsx | 2 +- .../dataviews/test/dataviews.jsdom.test.tsx | 44 +++++++++ packages/dataviews/src/types/dataviews.ts | 16 +++- 11 files changed, 289 insertions(+), 91 deletions(-) create mode 100644 packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.test.ts create mode 100644 packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.ts diff --git a/packages/dataviews/README.md b/packages/dataviews/README.md index d41b0a2a1093bd..b9006f06cb8d54 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 `getItemParentId` is not provided. 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, 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.test.ts b/packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.test.ts new file mode 100644 index 00000000000000..65bd4d811e9e8b --- /dev/null +++ b/packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.test.ts @@ -0,0 +1,52 @@ +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, cyclic, and duplicate-id 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' }, + { id: 'duplicate' }, + { id: 'duplicate' }, + ]; + + 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/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..628a7fd9cce589 --- /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< Row< Item > >(); + const appendTree = ( root: Row< Item > ) => { + const stack = [ { row: root, level: 0 } ]; + while ( stack.length ) { + const current = stack.pop()!; + if ( visited.has( current.row ) ) { + continue; + } + visited.add( current.row ); + 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 ) ) { + 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..5c9d62c3993a90 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,33 @@ 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 orderedData = dataByGroup - ? Array.from( dataByGroup.values() ).flat() - : data; + const rowsByGroup = dataByGroup + ? new Map( + Array.from( dataByGroup.entries() ).map( + ( [ groupName, groupItems ] ) => [ + groupName, + getRows( + groupItems, + getItemId, + getItemLevel, + getItemParentId, + view.showLevels + ), + ] + ) + ) + : null; + const rows = rowsByGroup + ? Array.from( rowsByGroup.values() ).flat() + : getRows( + data, + getItemId, + getItemLevel, + getItemParentId, + view.showLevels + ); + // Selection ranges follow the rendered hierarchy and group order. + const orderedData = rows.map( ( row ) => row.item ); const { getSelectionProps } = useSelectionProps( { data: orderedData, getItemId, @@ -583,9 +628,9 @@ function ViewTable< Item >( { { /* Render grouped data if groupBy is specified */ } - { hasData && groupField && dataByGroup ? ( - Array.from( dataByGroup.entries() ).map( - ( [ groupName, groupItems ] ) => ( + { hasData && groupField && rowsByGroup ? ( + Array.from( rowsByGroup.entries() ).map( + ( [ groupName, groupRows ] ) => ( ( { ) } - { groupItems.map( ( item, index ) => { - const id = - getItemId( item ) || index.toString(); + { groupRows.map( ( row ) => { + const { id, item, level } = row; return ( ( { ) : ( { hasData && - data.map( ( item, index ) => { - const id = - getItemId( item ) || index.toString(); + rows.map( ( row, index ) => { + const { id, item, level } = row; return ( ( { 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..b46a095e9af54c 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, @@ -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..2893e696b9bed1 100644 --- a/packages/dataviews/src/types/dataviews.ts +++ b/packages/dataviews/src/types/dataviews.ts @@ -141,6 +141,13 @@ export type DataViewsProps< Item > = { */ getItemLevel?: ( item: Item ) => number; + /** + * Returns the unique identifier of an item's parent. When provided and the + * view's `showLevels` option is enabled, 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 +794,12 @@ 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. + */ + getItemParentId?: ( item: Item ) => string | number | null | undefined; + /** * Whether the data is loading, in which case a loading state is shown. */ @@ -851,7 +864,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 +875,7 @@ export type ViewPickerBaseProps< Item > = Omit< | 'onClickItem' | 'renderItemLink' | 'getItemLevel' + | 'getItemParentId' > & { /** * The current view configuration. From ccc9c93fb97e66da12aec79fd03c08943a928ea6 Mon Sep 17 00:00:00 2001 From: Tung Du Date: Mon, 21 Sep 2026 12:04:53 +0700 Subject: [PATCH 2/8] docs: update DataViews changelog --- packages/dataviews/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/dataviews/CHANGELOG.md b/packages/dataviews/CHANGELOG.md index 47424489f1bd87..e160b1f917ff51 100644 --- a/packages/dataviews/CHANGELOG.md +++ b/packages/dataviews/CHANGELOG.md @@ -55,6 +55,7 @@ ### Enhancements +- DataViews: Add `getItemParentId` to order and indent loaded table items from their parent relationships ([#83241](https://github.com/WordPress/gutenberg/pull/83241)). - DataForm: Add a `showPlaceholderIfEmpty` option to the `panel` layout, which shows the field's `placeholder` in the summary when the value is empty ([#82527](https://github.com/WordPress/gutenberg/pull/82527)). - Give unselected multi-selection filter indicators solid, themed backgrounds. ([#82391](https://github.com/WordPress/gutenberg/pull/82391)) - Validated form controls: Use `--wpds-color-stroke-interactive-error` for the invalid-state focus ring and border ([#82410](https://github.com/WordPress/gutenberg/pull/82410)). From 9cbab14806b6852b8de1962357e8482e114c2f2e Mon Sep 17 00:00:00 2001 From: Tung Du Date: Mon, 21 Sep 2026 12:41:30 +0700 Subject: [PATCH 3/8] test: add grouped hierarchy story --- .../dataviews/stories/hierarchical-levels.tsx | 18 +++++++++++++++-- .../src/dataviews/stories/index.story.tsx | 20 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx b/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx index b46a095e9af54c..a9709f30501a0d 100644 --- a/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx +++ b/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx @@ -7,8 +7,10 @@ import { data as allData, fields } from './fixtures'; const HierarchicalLevelsComponent = ( { showLevels = true, + groupBy = false, }: { showLevels?: boolean; + groupBy?: boolean; } ) => { const [ view, setView ] = useState< View >( { type: LAYOUT_TABLE, @@ -24,15 +26,27 @@ const HierarchicalLevelsComponent = ( { }, titleField: 'title', mediaField: 'image', - showLevels: true, + showLevels, + groupBy: groupBy + ? { + field: 'isPlanet', + direction: 'asc', + } + : undefined, } ); useEffect( () => { setView( ( prevView ) => ( { ...prevView, showLevels, + groupBy: groupBy + ? { + field: 'isPlanet', + direction: 'asc', + } + : undefined, } ) ); - }, [ showLevels ] ); + }, [ groupBy, showLevels ] ); const { data, paginationInfo } = filterSortAndPaginate( allData, diff --git a/packages/dataviews/src/dataviews/stories/index.story.tsx b/packages/dataviews/src/dataviews/stories/index.story.tsx index 1bf6a680de1c00..88fb63bb0f83ee 100644 --- a/packages/dataviews/src/dataviews/stories/index.story.tsx +++ b/packages/dataviews/src/dataviews/stories/index.story.tsx @@ -254,6 +254,26 @@ export const HierarchicalLevels = { }, }; +export const GroupedHierarchicalLevels = { + render: HierarchicalLevelsComponent, + args: { + showLevels: true, + groupBy: true, + }, + argTypes: { + showLevels: { + control: 'boolean', + description: + 'Whether the table orders and indents loaded items using their parent relationships', + }, + groupBy: { + control: 'boolean', + description: + 'Whether items are grouped by "Is Planet". Parent relationships are resolved within each group, so an item whose parent is in another group renders as a root', + }, + }, +}; + export const Empty = { render: EmptyComponent, args: { From ea0d3ca3d2441c115ebf6d9ba0553c2089341e0e Mon Sep 17 00:00:00 2001 From: Tung Du Date: Mon, 21 Sep 2026 13:03:01 +0700 Subject: [PATCH 4/8] fix: keep parent hierarchy ungrouped --- packages/dataviews/CHANGELOG.md | 2 +- packages/dataviews/README.md | 4 +-- .../dataviews-layouts/table/index.tsx | 24 +++++++------ .../dataviews/stories/hierarchical-levels.tsx | 16 +-------- .../src/dataviews/stories/index.story.tsx | 20 ----------- .../dataviews/test/dataviews.jsdom.test.tsx | 26 ++++++++++++++ packages/dataviews/src/types/dataviews.ts | 35 +++++++++---------- 7 files changed, 60 insertions(+), 67 deletions(-) diff --git a/packages/dataviews/CHANGELOG.md b/packages/dataviews/CHANGELOG.md index e160b1f917ff51..b6a0b637517c7f 100644 --- a/packages/dataviews/CHANGELOG.md +++ b/packages/dataviews/CHANGELOG.md @@ -55,7 +55,7 @@ ### Enhancements -- DataViews: Add `getItemParentId` to order and indent loaded table items from their parent relationships ([#83241](https://github.com/WordPress/gutenberg/pull/83241)). +- DataViews: Add `getItemParentId` support for hierarchical table rows ([#83241](https://github.com/WordPress/gutenberg/pull/83241)). - DataForm: Add a `showPlaceholderIfEmpty` option to the `panel` layout, which shows the field's `placeholder` in the summary when the value is empty ([#82527](https://github.com/WordPress/gutenberg/pull/82527)). - Give unselected multi-selection filter indicators solid, themed backgrounds. ([#82391](https://github.com/WordPress/gutenberg/pull/82391)) - Validated form controls: Use `--wpds-color-stroke-interactive-error` for the invalid-state focus ring and border ([#82410](https://github.com/WordPress/gutenberg/pull/82410)). diff --git a/packages/dataviews/README.md b/packages/dataviews/README.md index b9006f06cb8d54..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. DataViews uses it to indent table rows when `view.showLevels` is true and `getItemParentId` is not provided. +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: @@ -130,7 +130,7 @@ 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, 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. +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: diff --git a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx index 5c9d62c3993a90..75ba1773dd5939 100644 --- a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx @@ -58,7 +58,8 @@ function getRows< Item >( getItemId: ( item: Item ) => string, getItemLevel: ( ( item: Item ) => number ) | undefined, getItemParentId: - ( ( item: Item ) => string | number | null | undefined ) | undefined, + | ( ( item: Item ) => string | number | null | undefined ) + | undefined, showLevels: boolean | undefined ): HierarchicalRow< Item >[] { if ( showLevels && getItemParentId ) { @@ -301,6 +302,8 @@ function ViewTable< Item >( { ? fields.find( ( f ) => f.id === view.groupBy?.field ) : null; const dataByGroup = groupField ? getDataByGroup( data, groupField ) : null; + // Parent-based hierarchy is not supported with grouping. Preserve the + // existing group order and `getItemLevel` indentation. const rowsByGroup = dataByGroup ? new Map( Array.from( dataByGroup.entries() ).map( @@ -310,12 +313,12 @@ function ViewTable< Item >( { groupItems, getItemId, getItemLevel, - getItemParentId, + undefined, view.showLevels ), ] ) - ) + ) : null; const rows = rowsByGroup ? Array.from( rowsByGroup.values() ).flat() @@ -325,7 +328,7 @@ function ViewTable< Item >( { getItemLevel, getItemParentId, view.showLevels - ); + ); // Selection ranges follow the rendered hierarchy and group order. const orderedData = rows.map( ( row ) => row.item ); const { getSelectionProps } = useSelectionProps( { @@ -550,15 +553,15 @@ function ViewTable< Item >( { canMove={ false } canInsertLeft={ isRtl - ? ( view.layout?.enableMoving ?? - true ) + ? view.layout?.enableMoving ?? + true : false } canInsertRight={ isRtl ? false - : ( view.layout?.enableMoving ?? - true ) + : view.layout?.enableMoving ?? + true } /> ) } @@ -614,7 +617,8 @@ function ViewTable< Item >( { className={ clsx( 'dataviews-view-table__actions-column', { - 'dataviews-view-table__actions-column--sticky': true, + 'dataviews-view-table__actions-column--sticky': + true, 'dataviews-view-table__actions-column--stuck': ! isHorizontalScrollEnd, } @@ -649,7 +653,7 @@ function ViewTable< Item >( { __( '%1$s: %2$s' ), groupField.label, groupName - ) } + ) } { groupRows.map( ( row ) => { diff --git a/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx b/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx index a9709f30501a0d..5698729f313c11 100644 --- a/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx +++ b/packages/dataviews/src/dataviews/stories/hierarchical-levels.tsx @@ -7,10 +7,8 @@ import { data as allData, fields } from './fixtures'; const HierarchicalLevelsComponent = ( { showLevels = true, - groupBy = false, }: { showLevels?: boolean; - groupBy?: boolean; } ) => { const [ view, setView ] = useState< View >( { type: LAYOUT_TABLE, @@ -27,26 +25,14 @@ const HierarchicalLevelsComponent = ( { titleField: 'title', mediaField: 'image', showLevels, - groupBy: groupBy - ? { - field: 'isPlanet', - direction: 'asc', - } - : undefined, } ); useEffect( () => { setView( ( prevView ) => ( { ...prevView, showLevels, - groupBy: groupBy - ? { - field: 'isPlanet', - direction: 'asc', - } - : undefined, } ) ); - }, [ groupBy, showLevels ] ); + }, [ showLevels ] ); const { data, paginationInfo } = filterSortAndPaginate( allData, diff --git a/packages/dataviews/src/dataviews/stories/index.story.tsx b/packages/dataviews/src/dataviews/stories/index.story.tsx index 88fb63bb0f83ee..1bf6a680de1c00 100644 --- a/packages/dataviews/src/dataviews/stories/index.story.tsx +++ b/packages/dataviews/src/dataviews/stories/index.story.tsx @@ -254,26 +254,6 @@ export const HierarchicalLevels = { }, }; -export const GroupedHierarchicalLevels = { - render: HierarchicalLevelsComponent, - args: { - showLevels: true, - groupBy: true, - }, - argTypes: { - showLevels: { - control: 'boolean', - description: - 'Whether the table orders and indents loaded items using their parent relationships', - }, - groupBy: { - control: 'boolean', - description: - 'Whether items are grouped by "Is Planet". Parent relationships are resolved within each group, so an item whose parent is in another group renders as a root', - }, - }, -}; - export const Empty = { render: EmptyComponent, args: { diff --git a/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx b/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx index 9323ab84f65fd3..6a08df7f2e2b00 100644 --- a/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx +++ b/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx @@ -198,6 +198,32 @@ describe( 'DataViews component', () => { expect( rows[ 1 ] ).toHaveTextContent( '— Child' ); } ); + it( 'keeps grouped rows in group order and uses getItemLevel', () => { + render( + ( item.id === 2 ? 1 : 0 ) } + getItemParentId={ ( item ) => + item.id === 2 ? 1 : undefined + } + view={ { + ...DEFAULT_VIEW, + fields: [], + groupBy: { field: 'author', direction: 'asc' }, + showLevels: true, + titleField: 'title', + } } + /> + ); + + const rows = screen.getAllByRole( 'row' ); + expect( rows[ 2 ] ).toHaveTextContent( '— Child' ); + expect( rows[ 3 ] ).toHaveTextContent( 'Parent' ); + } ); + it( 'keeps getItemLevel indentation when no parent callback exists', () => { render( = { getItemLevel?: ( item: Item ) => number; /** - * Returns the unique identifier of an item's parent. When provided and the - * view's `showLevels` option is enabled, loaded table items are ordered by - * their parent relationships and their hierarchical depth is calculated. + * 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; @@ -191,14 +192,14 @@ export type DataViewsProps< Item > = { * have a string `id` property, which is used by default. */ getItemId?: ( item: Item ) => string; - } + } : { /** * Returns a unique id for an item. Required when items have no * string `id` property. */ getItemId: ( item: Item ) => string; - } ); + } ); /** * The filters applied to the dataset. @@ -741,7 +742,8 @@ export interface ActionModal< Item > extends ActionBase< Item > { * The focus on mount property of the modal. */ modalFocusOnMount?: - Parameters< typeof useFocusOnMount >[ 0 ] | 'firstContentElement'; + | Parameters< typeof useFocusOnMount >[ 0 ] + | 'firstContentElement'; } export interface ActionButton< Item > extends ActionBase< Item > { @@ -796,7 +798,8 @@ export interface ViewBaseProps< Item > { /** * Returns the unique identifier of an item's parent. Used by the table - * layout when the view's `showLevels` option is enabled. + * layout when the view's `showLevels` option is enabled and items aren't + * grouped. */ getItemParentId?: ( item: Item ) => string | number | null | undefined; @@ -916,30 +919,24 @@ export interface ViewGridProps< Item > extends ViewBaseProps< Item > { view: ViewGrid; } -export interface ViewPickerGridProps< Item > extends Omit< - ViewPickerBaseProps< Item >, - 'view' -> { +export interface ViewPickerGridProps< Item > + extends Omit< ViewPickerBaseProps< Item >, 'view' > { /** * The current view configuration, narrowed to the picker grid layout. */ view: ViewPickerGrid; } -export interface ViewPickerTableProps< Item > extends Omit< - ViewPickerBaseProps< Item >, - 'view' -> { +export interface ViewPickerTableProps< Item > + extends Omit< ViewPickerBaseProps< Item >, 'view' > { /** * The current view configuration, narrowed to the picker table layout. */ view: ViewPickerTable; } -export interface ViewPickerActivityProps< Item > extends Omit< - ViewPickerBaseProps< Item >, - 'view' -> { +export interface ViewPickerActivityProps< Item > + extends Omit< ViewPickerBaseProps< Item >, 'view' > { /** * The current view configuration, narrowed to the picker activity layout. */ From 7f336fb71a3647752ccd8b9db0d231667a270d25 Mon Sep 17 00:00:00 2001 From: Tung Du Date: Mon, 21 Sep 2026 13:45:25 +0700 Subject: [PATCH 5/8] refactor: simplify hierarchy handling --- .../table/get-hierarchical-rows.ts | 8 ++-- .../dataviews-layouts/table/index.tsx | 47 ++++++++----------- .../get-hierarchical-rows.ts} | 6 +-- .../dataviews/test/dataviews.jsdom.test.tsx | 26 ---------- 4 files changed, 25 insertions(+), 62 deletions(-) rename packages/dataviews/src/components/dataviews-layouts/table/{get-hierarchical-rows.test.ts => test/get-hierarchical-rows.ts} (86%) 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 index 628a7fd9cce589..a939d1245bb739 100644 --- a/packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.ts +++ b/packages/dataviews/src/components/dataviews-layouts/table/get-hierarchical-rows.ts @@ -53,15 +53,15 @@ export default function getHierarchicalRows< Item >( } const result: HierarchicalRow< Item >[] = []; - const visited = new Set< Row< 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 ) ) { + if ( visited.has( current.row.id ) ) { continue; } - visited.add( current.row ); + visited.add( current.row.id ); result.push( { item: current.row.item, id: current.row.id, @@ -80,7 +80,7 @@ export default function getHierarchicalRows< Item >( roots.forEach( appendTree ); rows.forEach( ( row ) => { - if ( ! visited.has( row ) ) { + if ( ! visited.has( row.id ) ) { appendTree( row ); } } ); diff --git a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx index 75ba1773dd5939..249d7ff5d6e1e2 100644 --- a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx @@ -302,26 +302,8 @@ function ViewTable< Item >( { ? fields.find( ( f ) => f.id === view.groupBy?.field ) : null; const dataByGroup = groupField ? getDataByGroup( data, groupField ) : null; - // Parent-based hierarchy is not supported with grouping. Preserve the - // existing group order and `getItemLevel` indentation. - const rowsByGroup = dataByGroup - ? new Map( - Array.from( dataByGroup.entries() ).map( - ( [ groupName, groupItems ] ) => [ - groupName, - getRows( - groupItems, - getItemId, - getItemLevel, - undefined, - view.showLevels - ), - ] - ) - ) - : null; - const rows = rowsByGroup - ? Array.from( rowsByGroup.values() ).flat() + const rows = dataByGroup + ? [] : getRows( data, getItemId, @@ -330,7 +312,9 @@ function ViewTable< Item >( { view.showLevels ); // Selection ranges follow the rendered hierarchy and group order. - const orderedData = rows.map( ( row ) => row.item ); + const orderedData = dataByGroup + ? Array.from( dataByGroup.values() ).flat() + : rows.map( ( row ) => row.item ); const { getSelectionProps } = useSelectionProps( { data: orderedData, getItemId, @@ -632,9 +616,9 @@ function ViewTable< Item >( { { /* Render grouped data if groupBy is specified */ } - { hasData && groupField && rowsByGroup ? ( - Array.from( rowsByGroup.entries() ).map( - ( [ groupName, groupRows ] ) => ( + { hasData && groupField && dataByGroup ? ( + Array.from( dataByGroup.entries() ).map( + ( [ groupName, groupItems ] ) => ( ( { ) } - { groupRows.map( ( row ) => { - const { id, item, level } = row; + { groupItems.map( ( item, index ) => { + const id = + getItemId( item ) || index.toString(); return ( { ] ); } ); - it( 'returns missing-parent, self-parenting, cyclic, and duplicate-id items exactly once', () => { + 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' }, - { id: 'duplicate' }, - { id: 'duplicate' }, ]; const rows = getHierarchicalRows( items, getItemId, getItemParentId ); diff --git a/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx b/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx index 6a08df7f2e2b00..9323ab84f65fd3 100644 --- a/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx +++ b/packages/dataviews/src/dataviews/test/dataviews.jsdom.test.tsx @@ -198,32 +198,6 @@ describe( 'DataViews component', () => { expect( rows[ 1 ] ).toHaveTextContent( '— Child' ); } ); - it( 'keeps grouped rows in group order and uses getItemLevel', () => { - render( - ( item.id === 2 ? 1 : 0 ) } - getItemParentId={ ( item ) => - item.id === 2 ? 1 : undefined - } - view={ { - ...DEFAULT_VIEW, - fields: [], - groupBy: { field: 'author', direction: 'asc' }, - showLevels: true, - titleField: 'title', - } } - /> - ); - - const rows = screen.getAllByRole( 'row' ); - expect( rows[ 2 ] ).toHaveTextContent( '— Child' ); - expect( rows[ 3 ] ).toHaveTextContent( 'Parent' ); - } ); - it( 'keeps getItemLevel indentation when no parent callback exists', () => { render( Date: Tue, 22 Sep 2026 10:16:51 +0700 Subject: [PATCH 6/8] docs: move DataViews changelog entry --- packages/dataviews/CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/dataviews/CHANGELOG.md b/packages/dataviews/CHANGELOG.md index b6a0b637517c7f..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)). @@ -55,7 +59,6 @@ ### Enhancements -- DataViews: Add `getItemParentId` support for hierarchical table rows ([#83241](https://github.com/WordPress/gutenberg/pull/83241)). - DataForm: Add a `showPlaceholderIfEmpty` option to the `panel` layout, which shows the field's `placeholder` in the summary when the value is empty ([#82527](https://github.com/WordPress/gutenberg/pull/82527)). - Give unselected multi-selection filter indicators solid, themed backgrounds. ([#82391](https://github.com/WordPress/gutenberg/pull/82391)) - Validated form controls: Use `--wpds-color-stroke-interactive-error` for the invalid-state focus ring and border ([#82410](https://github.com/WordPress/gutenberg/pull/82410)). From d4158d0ec1a8c610f9ab422790537e8c499bc0cd Mon Sep 17 00:00:00 2001 From: Tung Du Date: Tue, 22 Sep 2026 10:52:31 +0700 Subject: [PATCH 7/8] docs: update Storybook component manifest --- storybook/components-manifest.yml | 1 + 1 file changed, 1 insertion(+) 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 From 907ed4034892bf0b266be228294434f3c50fc3cc Mon Sep 17 00:00:00 2001 From: Tung Du Date: Tue, 22 Sep 2026 11:07:40 +0700 Subject: [PATCH 8/8] chore: format DataViews hierarchy changes --- .../dataviews-layouts/table/index.tsx | 18 ++++++------- packages/dataviews/src/types/dataviews.ts | 25 +++++++++++-------- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx index 249d7ff5d6e1e2..1cfeeed332b769 100644 --- a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx @@ -58,8 +58,7 @@ function getRows< Item >( getItemId: ( item: Item ) => string, getItemLevel: ( ( item: Item ) => number ) | undefined, getItemParentId: - | ( ( item: Item ) => string | number | null | undefined ) - | undefined, + ( ( item: Item ) => string | number | null | undefined ) | undefined, showLevels: boolean | undefined ): HierarchicalRow< Item >[] { if ( showLevels && getItemParentId ) { @@ -310,7 +309,7 @@ function ViewTable< Item >( { getItemLevel, getItemParentId, view.showLevels - ); + ); // Selection ranges follow the rendered hierarchy and group order. const orderedData = dataByGroup ? Array.from( dataByGroup.values() ).flat() @@ -537,15 +536,15 @@ function ViewTable< Item >( { canMove={ false } canInsertLeft={ isRtl - ? view.layout?.enableMoving ?? - true + ? ( view.layout?.enableMoving ?? + true ) : false } canInsertRight={ isRtl ? false - : view.layout?.enableMoving ?? - true + : ( view.layout?.enableMoving ?? + true ) } /> ) } @@ -601,8 +600,7 @@ function ViewTable< Item >( { className={ clsx( 'dataviews-view-table__actions-column', { - 'dataviews-view-table__actions-column--sticky': - true, + 'dataviews-view-table__actions-column--sticky': true, 'dataviews-view-table__actions-column--stuck': ! isHorizontalScrollEnd, } @@ -637,7 +635,7 @@ function ViewTable< Item >( { __( '%1$s: %2$s' ), groupField.label, groupName - ) } + ) } { groupItems.map( ( item, index ) => { diff --git a/packages/dataviews/src/types/dataviews.ts b/packages/dataviews/src/types/dataviews.ts index def9e48ab66bcf..fa3f436862d4d4 100644 --- a/packages/dataviews/src/types/dataviews.ts +++ b/packages/dataviews/src/types/dataviews.ts @@ -192,14 +192,14 @@ export type DataViewsProps< Item > = { * have a string `id` property, which is used by default. */ getItemId?: ( item: Item ) => string; - } + } : { /** * Returns a unique id for an item. Required when items have no * string `id` property. */ getItemId: ( item: Item ) => string; - } ); + } ); /** * The filters applied to the dataset. @@ -742,8 +742,7 @@ export interface ActionModal< Item > extends ActionBase< Item > { * The focus on mount property of the modal. */ modalFocusOnMount?: - | Parameters< typeof useFocusOnMount >[ 0 ] - | 'firstContentElement'; + Parameters< typeof useFocusOnMount >[ 0 ] | 'firstContentElement'; } export interface ActionButton< Item > extends ActionBase< Item > { @@ -919,24 +918,30 @@ export interface ViewGridProps< Item > extends ViewBaseProps< Item > { view: ViewGrid; } -export interface ViewPickerGridProps< Item > - extends Omit< ViewPickerBaseProps< Item >, 'view' > { +export interface ViewPickerGridProps< Item > extends Omit< + ViewPickerBaseProps< Item >, + 'view' +> { /** * The current view configuration, narrowed to the picker grid layout. */ view: ViewPickerGrid; } -export interface ViewPickerTableProps< Item > - extends Omit< ViewPickerBaseProps< Item >, 'view' > { +export interface ViewPickerTableProps< Item > extends Omit< + ViewPickerBaseProps< Item >, + 'view' +> { /** * The current view configuration, narrowed to the picker table layout. */ view: ViewPickerTable; } -export interface ViewPickerActivityProps< Item > - extends Omit< ViewPickerBaseProps< Item >, 'view' > { +export interface ViewPickerActivityProps< Item > extends Omit< + ViewPickerBaseProps< Item >, + 'view' +> { /** * The current view configuration, narrowed to the picker activity layout. */