-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathuse-navigation-menu-content.js
98 lines (79 loc) · 2.46 KB
/
use-navigation-menu-content.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* WordPress dependencies
*/
import { parse } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import TemplatePartNavigationMenus from './template-part-navigation-menus';
import useEditedEntityRecord from '../use-edited-entity-record';
import { TEMPLATE_PART_POST_TYPE } from '../../utils/constants';
function getBlocksFromRecord( record ) {
if ( record?.blocks ) {
return record?.blocks;
}
return record?.content && typeof record.content !== 'function'
? parse( record.content )
: [];
}
/**
* Retrieves a list of specific blocks from a given tree of blocks.
*
* @param {string} targetBlockType The name of the block type to find.
* @param {Array} blocks A list of blocks from a template part entity.
*
* @return {Array} A list of any navigation blocks found in the blocks.
*/
function getBlocksOfTypeFromBlocks( targetBlockType, blocks ) {
if ( ! targetBlockType || ! blocks?.length ) {
return [];
}
const findInBlocks = ( _blocks ) => {
if ( ! _blocks ) {
return [];
}
const navigationBlocks = [];
for ( const block of _blocks ) {
if ( block.name === targetBlockType ) {
navigationBlocks.push( block );
}
if ( block?.innerBlocks ) {
const innerNavigationBlocks = findInBlocks( block.innerBlocks );
if ( innerNavigationBlocks.length ) {
navigationBlocks.push( ...innerNavigationBlocks );
}
}
}
return navigationBlocks;
};
return findInBlocks( blocks );
}
export default function useNavigationMenuContent( postType, postId ) {
const { record } = useEditedEntityRecord( postType, postId );
// Only managing navigation menus in template parts is supported
// to match previous behaviour. This could potentially be expanded
// to patterns as well.
if ( postType !== TEMPLATE_PART_POST_TYPE ) {
return;
}
const blocks = getBlocksFromRecord( record );
const navigationBlocks = getBlocksOfTypeFromBlocks(
'core/navigation',
blocks
);
if ( ! navigationBlocks.length ) {
return;
}
const navigationMenuIds = navigationBlocks?.map(
( block ) => block.attributes.ref
);
// Dedupe the Navigation blocks, as you can have multiple navigation blocks in the template.
// Also, filter out undefined values, as blocks don't have an id when initially added.
const uniqueNavigationMenuIds = [ ...new Set( navigationMenuIds ) ].filter(
( menuId ) => menuId
);
if ( ! uniqueNavigationMenuIds?.length ) {
return;
}
return <TemplatePartNavigationMenus menus={ uniqueNavigationMenuIds } />;
}