Skip to content

Commit

Permalink
Transform page list to list
Browse files Browse the repository at this point in the history
  • Loading branch information
benazeer-ben committed Feb 10, 2025
1 parent 1a0b2fc commit 62bf9c2
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
59 changes: 57 additions & 2 deletions packages/block-library/src/page-list/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -258,6 +258,7 @@ export default function PageListEdit( {
hasDraggedChild,
isChildOfNavigation,
} = useSelect(
// eslint-disable-next-line no-shadow
( select ) => {
const {
getBlockParentsByBlockName,
Expand Down Expand Up @@ -406,3 +407,57 @@ export default function PageListEdit( {
</>
);
}
export const transforms = {
to: [
{
type: 'block',
blocks: [ 'core/list' ],
transform: () => {
const pages = select( coreStore ).getEntityRecords(
'postType',
'page',
{
per_page: -1,
status: 'publish',
}
);

if ( ! pages || pages.length === 0 ) {
return createBlock( 'core/list', {
ordered: false,
} );
}

const createListItems = ( parentId = 0 ) => {
return pages
.filter( ( page ) => page.parent === parentId )
.map( ( page ) => {
const childItems = createListItems( page.id );
const listItem = createBlock( 'core/list-item', {
content: `<a href="${ page.link }">${ page.title.rendered }</a>`,
} );
if ( childItems.length > 0 ) {
const subList = createBlock(
'core/list',
{},
childItems
);
listItem.innerBlocks = [ subList ];
}
return listItem;
} );
};

const innerBlocks = createListItems();

return createBlock(
'core/list',
{
ordered: false,
},
innerBlocks
);
},
},
],
};
3 changes: 2 additions & 1 deletion packages/block-library/src/page-list/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -18,6 +18,7 @@ export const settings = {
icon: pages,
example: {},
edit,
transforms,
};

export const init = () => initBlock( { name, metadata, settings } );

0 comments on commit 62bf9c2

Please sign in to comment.