Skip to content

Commit

Permalink
Navigation: Handle block menu items
Browse files Browse the repository at this point in the history
Handle menu items with type = 'block' when creating a Navigation block
from an existing menu.
  • Loading branch information
noisysocks committed Sep 1, 2020
1 parent dda3a9c commit 511a998
Showing 1 changed file with 44 additions and 18 deletions.
62 changes: 44 additions & 18 deletions packages/block-library/src/navigation/placeholder.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
/**
* External dependencies
*/
import { some } from 'lodash';
import classnames from 'classnames';

/**
* WordPress dependencies
*/
import { createBlock } from '@wordpress/blocks';
import { createBlock, parse } from '@wordpress/blocks';
import {
Button,
CustomSelectControl,
Expand Down Expand Up @@ -76,26 +77,51 @@ function getSelectedMenu( selectedCreateOption ) {
/**
* A recursive function that maps menu item nodes to blocks.
*
* @param {Object[]} nodes An array of menu items.
*
* @param {Object[]} menuItems An array of menu items.
* @return {WPBlock[]} An array of blocks.
*/
function mapMenuItemsToBlocks( nodes ) {
return nodes.map( ( { title, type, link: url, id, children } ) => {
const innerBlocks =
children && children.length ? mapMenuItemsToBlocks( children ) : [];
function mapMenuItemsToBlocks( menuItems ) {
return menuItems.map( ( menuItem ) => {
if ( menuItem.type === 'block' ) {
const [ block ] = parse( menuItem.content.raw );

return createBlock(
'core/navigation-link',
{
type,
id,
url,
label: ! title.rendered ? __( '(no title)' ) : title.rendered,
opensInNewTab: false,
},
innerBlocks
);
if ( ! block ) {
return createBlock( 'core/freeform', {
content: menuItem.content,
} );
}

return block;
}

const attributes = {
label: ! menuItem.title.rendered
? __( '(no title)' )
: menuItem.title.rendered,
opensInNewTab: menuItem.target === '_blank',
};

if ( menuItem.url ) {
attributes.url = menuItem.url;
}

if ( menuItem.description ) {
attributes.description = menuItem.description;
}

if ( menuItem.xfn?.length && some( menuItem.xfn ) ) {
attributes.rel = menuItem.xfn.join( ' ' );
}

if ( menuItem.classes?.length && some( menuItem.classes ) ) {
attributes.className = menuItem.classes.join( ' ' );
}

const innerBlocks = menuItem.children?.length
? mapMenuItemsToBlocks( menuItem.children )
: [];

return createBlock( 'core/navigation-link', attributes, innerBlocks );
} );
}

Expand Down

0 comments on commit 511a998

Please sign in to comment.