diff --git a/packages/block-library/src/page-list/edit.js b/packages/block-library/src/page-list/edit.js index 8f1409f864f9b..3dc8503a1d000 100644 --- a/packages/block-library/src/page-list/edit.js +++ b/packages/block-library/src/page-list/edit.js @@ -27,8 +27,8 @@ import { } from '@wordpress/components'; import { __, sprintf } from '@wordpress/i18n'; import { useMemo, useState, useEffect, useCallback } from '@wordpress/element'; -import { useEntityRecords } from '@wordpress/core-data'; -import { useSelect, useDispatch } from '@wordpress/data'; +import { useEntityRecords, store as coreStore } from '@wordpress/core-data'; +import { useSelect, useDispatch, select } from '@wordpress/data'; /** * Internal dependencies @@ -258,6 +258,7 @@ export default function PageListEdit( { hasDraggedChild, isChildOfNavigation, } = useSelect( + // eslint-disable-next-line no-shadow ( select ) => { const { getBlockParentsByBlockName, @@ -404,3 +405,66 @@ export default function PageListEdit( { ); } +export const transforms = { + to: [ + { + type: 'block', + blocks: [ 'core/navigation' ], + transform: () => { + // Fetch published pages synchronously. + const pages = select( coreStore ).getEntityRecords( + 'postType', + 'page', + { + per_page: -1, + status: 'publish', + } + ); + + // Handle the case where no pages are fetched. + if ( ! pages || pages.length === 0 ) { + return createBlock( 'core/navigation', { + itemsJustification: 'left', + } ); + } + + // Generate navigation links with proper hierarchy for parent-child pages. + const createNavigationLinkBlocks = ( parentId = 0 ) => { + return pages + .filter( ( page ) => page.parent === parentId ) + .map( ( page ) => { + const childBlocks = createNavigationLinkBlocks( + page.id + ); + + return createBlock( + 'core/navigation-link', + { + label: page.title.rendered, + url: page.link, + kind: 'post-type', + type: 'page', + id: page.id, + opensInNewTab: false, + }, + childBlocks // Add child blocks for hierarchical pages. + ); + } ); + }; + + // Create top-level navigation links. + const navigationLinkBlocks = createNavigationLinkBlocks(); + + // Return the Navigation block with the generated links. + return createBlock( + 'core/navigation', + { + itemsJustification: 'left', + isResponsive: true, + }, + navigationLinkBlocks + ); + }, + }, + ], +}; diff --git a/packages/block-library/src/page-list/index.js b/packages/block-library/src/page-list/index.js index 4a128e7da58a8..76628fd3228f5 100644 --- a/packages/block-library/src/page-list/index.js +++ b/packages/block-library/src/page-list/index.js @@ -8,7 +8,7 @@ import { pages } from '@wordpress/icons'; */ import initBlock from '../utils/init-block'; import metadata from './block.json'; -import edit from './edit.js'; +import edit, { transforms } from './edit.js'; const { name } = metadata; @@ -18,6 +18,7 @@ export const settings = { icon: pages, example: {}, edit, + transforms, }; export const init = () => initBlock( { name, metadata, settings } );