navigation.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/navigation` block.
  4. *
  5. * @package WordPress
  6. */
  7. // These functions are used for the __unstableLocation feature and only active
  8. // when the gutenberg plugin is active.
  9. if ( defined( 'IS_GUTENBERG_PLUGIN' ) && IS_GUTENBERG_PLUGIN ) {
  10. /**
  11. * Returns the menu items for a WordPress menu location.
  12. *
  13. * @param string $location The menu location.
  14. * @return array Menu items for the location.
  15. */
  16. function block_core_navigation_get_menu_items_at_location( $location ) {
  17. if ( empty( $location ) ) {
  18. return;
  19. }
  20. // Build menu data. The following approximates the code in
  21. // `wp_nav_menu()` and `gutenberg_output_block_nav_menu`.
  22. // Find the location in the list of locations, returning early if the
  23. // location can't be found.
  24. $locations = get_nav_menu_locations();
  25. if ( ! isset( $locations[ $location ] ) ) {
  26. return;
  27. }
  28. // Get the menu from the location, returning early if there is no
  29. // menu or there was an error.
  30. $menu = wp_get_nav_menu_object( $locations[ $location ] );
  31. if ( ! $menu || is_wp_error( $menu ) ) {
  32. return;
  33. }
  34. $menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'update_post_term_cache' => false ) );
  35. _wp_menu_item_classes_by_context( $menu_items );
  36. return $menu_items;
  37. }
  38. /**
  39. * Sorts a standard array of menu items into a nested structure keyed by the
  40. * id of the parent menu.
  41. *
  42. * @param array $menu_items Menu items to sort.
  43. * @return array An array keyed by the id of the parent menu where each element
  44. * is an array of menu items that belong to that parent.
  45. */
  46. function block_core_navigation_sort_menu_items_by_parent_id( $menu_items ) {
  47. $sorted_menu_items = array();
  48. foreach ( (array) $menu_items as $menu_item ) {
  49. $sorted_menu_items[ $menu_item->menu_order ] = $menu_item;
  50. }
  51. unset( $menu_items, $menu_item );
  52. $menu_items_by_parent_id = array();
  53. foreach ( $sorted_menu_items as $menu_item ) {
  54. $menu_items_by_parent_id[ $menu_item->menu_item_parent ][] = $menu_item;
  55. }
  56. return $menu_items_by_parent_id;
  57. }
  58. /**
  59. * Turns menu item data into a nested array of parsed blocks
  60. *
  61. * @param array $menu_items An array of menu items that represent
  62. * an individual level of a menu.
  63. * @param array $menu_items_by_parent_id An array keyed by the id of the
  64. * parent menu where each element is an
  65. * array of menu items that belong to
  66. * that parent.
  67. * @return array An array of parsed block data.
  68. */
  69. function block_core_navigation_parse_blocks_from_menu_items( $menu_items, $menu_items_by_parent_id ) {
  70. if ( empty( $menu_items ) ) {
  71. return array();
  72. }
  73. $blocks = array();
  74. foreach ( $menu_items as $menu_item ) {
  75. $class_name = ! empty( $menu_item->classes ) ? implode( ' ', (array) $menu_item->classes ) : null;
  76. $id = ( null !== $menu_item->object_id && 'custom' !== $menu_item->object ) ? $menu_item->object_id : null;
  77. $opens_in_new_tab = null !== $menu_item->target && '_blank' === $menu_item->target;
  78. $rel = ( null !== $menu_item->xfn && '' !== $menu_item->xfn ) ? $menu_item->xfn : null;
  79. $kind = null !== $menu_item->type ? str_replace( '_', '-', $menu_item->type ) : 'custom';
  80. $block = array(
  81. 'blockName' => isset( $menu_items_by_parent_id[ $menu_item->ID ] ) ? 'core/navigation-submenu' : 'core/navigation-link',
  82. 'attrs' => array(
  83. 'className' => $class_name,
  84. 'description' => $menu_item->description,
  85. 'id' => $id,
  86. 'kind' => $kind,
  87. 'label' => $menu_item->title,
  88. 'opensInNewTab' => $opens_in_new_tab,
  89. 'rel' => $rel,
  90. 'title' => $menu_item->attr_title,
  91. 'type' => $menu_item->object,
  92. 'url' => $menu_item->url,
  93. ),
  94. );
  95. $block['innerBlocks'] = isset( $menu_items_by_parent_id[ $menu_item->ID ] )
  96. ? block_core_navigation_parse_blocks_from_menu_items( $menu_items_by_parent_id[ $menu_item->ID ], $menu_items_by_parent_id )
  97. : array();
  98. $block['innerContent'] = array_map( 'serialize_block', $block['innerBlocks'] );
  99. $blocks[] = $block;
  100. }
  101. return $blocks;
  102. }
  103. }
  104. /**
  105. * Build an array with CSS classes and inline styles defining the colors
  106. * which will be applied to the navigation markup in the front-end.
  107. *
  108. * @param array $attributes Navigation block attributes.
  109. *
  110. * @return array Colors CSS classes and inline styles.
  111. */
  112. function block_core_navigation_build_css_colors( $attributes ) {
  113. $colors = array(
  114. 'css_classes' => array(),
  115. 'inline_styles' => '',
  116. 'overlay_css_classes' => array(),
  117. 'overlay_inline_styles' => '',
  118. );
  119. // Text color.
  120. $has_named_text_color = array_key_exists( 'textColor', $attributes );
  121. $has_custom_text_color = array_key_exists( 'customTextColor', $attributes );
  122. // If has text color.
  123. if ( $has_custom_text_color || $has_named_text_color ) {
  124. // Add has-text-color class.
  125. $colors['css_classes'][] = 'has-text-color';
  126. }
  127. if ( $has_named_text_color ) {
  128. // Add the color class.
  129. $colors['css_classes'][] = sprintf( 'has-%s-color', $attributes['textColor'] );
  130. } elseif ( $has_custom_text_color ) {
  131. // Add the custom color inline style.
  132. $colors['inline_styles'] .= sprintf( 'color: %s;', $attributes['customTextColor'] );
  133. }
  134. // Background color.
  135. $has_named_background_color = array_key_exists( 'backgroundColor', $attributes );
  136. $has_custom_background_color = array_key_exists( 'customBackgroundColor', $attributes );
  137. // If has background color.
  138. if ( $has_custom_background_color || $has_named_background_color ) {
  139. // Add has-background class.
  140. $colors['css_classes'][] = 'has-background';
  141. }
  142. if ( $has_named_background_color ) {
  143. // Add the background-color class.
  144. $colors['css_classes'][] = sprintf( 'has-%s-background-color', $attributes['backgroundColor'] );
  145. } elseif ( $has_custom_background_color ) {
  146. // Add the custom background-color inline style.
  147. $colors['inline_styles'] .= sprintf( 'background-color: %s;', $attributes['customBackgroundColor'] );
  148. }
  149. // Overlay text color.
  150. $has_named_overlay_text_color = array_key_exists( 'overlayTextColor', $attributes );
  151. $has_custom_overlay_text_color = array_key_exists( 'customOverlayTextColor', $attributes );
  152. // If has overlay text color.
  153. if ( $has_custom_overlay_text_color || $has_named_overlay_text_color ) {
  154. // Add has-text-color class.
  155. $colors['overlay_css_classes'][] = 'has-text-color';
  156. }
  157. if ( $has_named_overlay_text_color ) {
  158. // Add the overlay color class.
  159. $colors['overlay_css_classes'][] = sprintf( 'has-%s-color', $attributes['overlayTextColor'] );
  160. } elseif ( $has_custom_overlay_text_color ) {
  161. // Add the custom overlay color inline style.
  162. $colors['overlay_inline_styles'] .= sprintf( 'color: %s;', $attributes['customOverlayTextColor'] );
  163. }
  164. // Overlay background color.
  165. $has_named_overlay_background_color = array_key_exists( 'overlayBackgroundColor', $attributes );
  166. $has_custom_overlay_background_color = array_key_exists( 'customOverlayBackgroundColor', $attributes );
  167. // If has overlay background color.
  168. if ( $has_custom_overlay_background_color || $has_named_overlay_background_color ) {
  169. // Add has-background class.
  170. $colors['overlay_css_classes'][] = 'has-background';
  171. }
  172. if ( $has_named_overlay_background_color ) {
  173. // Add the overlay background-color class.
  174. $colors['overlay_css_classes'][] = sprintf( 'has-%s-background-color', $attributes['overlayBackgroundColor'] );
  175. } elseif ( $has_custom_overlay_background_color ) {
  176. // Add the custom overlay background-color inline style.
  177. $colors['overlay_inline_styles'] .= sprintf( 'background-color: %s;', $attributes['customOverlayBackgroundColor'] );
  178. }
  179. return $colors;
  180. }
  181. /**
  182. * Build an array with CSS classes and inline styles defining the font sizes
  183. * which will be applied to the navigation markup in the front-end.
  184. *
  185. * @param array $attributes Navigation block attributes.
  186. *
  187. * @return array Font size CSS classes and inline styles.
  188. */
  189. function block_core_navigation_build_css_font_sizes( $attributes ) {
  190. // CSS classes.
  191. $font_sizes = array(
  192. 'css_classes' => array(),
  193. 'inline_styles' => '',
  194. );
  195. $has_named_font_size = array_key_exists( 'fontSize', $attributes );
  196. $has_custom_font_size = array_key_exists( 'customFontSize', $attributes );
  197. if ( $has_named_font_size ) {
  198. // Add the font size class.
  199. $font_sizes['css_classes'][] = sprintf( 'has-%s-font-size', $attributes['fontSize'] );
  200. } elseif ( $has_custom_font_size ) {
  201. // Add the custom font size inline style.
  202. $font_sizes['inline_styles'] = sprintf( 'font-size: %spx;', $attributes['customFontSize'] );
  203. }
  204. return $font_sizes;
  205. }
  206. /**
  207. * Returns the top-level submenu SVG chevron icon.
  208. *
  209. * @return string
  210. */
  211. function block_core_navigation_render_submenu_icon() {
  212. return '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true" focusable="false"><path d="M1.50002 4L6.00002 8L10.5 4" stroke-width="1.5"></path></svg>';
  213. }
  214. /**
  215. * Finds the most recently published `wp_navigation` Post.
  216. *
  217. * @return WP_Post|null the first non-empty Navigation or null.
  218. */
  219. function block_core_navigation_get_most_recently_published_navigation() {
  220. // We default to the most recently created menu.
  221. $parsed_args = array(
  222. 'post_type' => 'wp_navigation',
  223. 'no_found_rows' => true,
  224. 'order' => 'DESC',
  225. 'orderby' => 'date',
  226. 'post_status' => 'publish',
  227. 'posts_per_page' => 1, // get only the most recent.
  228. );
  229. $navigation_post = new WP_Query( $parsed_args );
  230. if ( count( $navigation_post->posts ) > 0 ) {
  231. return $navigation_post->posts[0];
  232. }
  233. return null;
  234. }
  235. /**
  236. * Filter out empty "null" blocks from the block list.
  237. * 'parse_blocks' includes a null block with '\n\n' as the content when
  238. * it encounters whitespace. This is not a bug but rather how the parser
  239. * is designed.
  240. *
  241. * @param array $parsed_blocks the parsed blocks to be normalized.
  242. * @return array the normalized parsed blocks.
  243. */
  244. function block_core_navigation_filter_out_empty_blocks( $parsed_blocks ) {
  245. $filtered = array_filter(
  246. $parsed_blocks,
  247. function( $block ) {
  248. return isset( $block['blockName'] );
  249. }
  250. );
  251. // Reset keys.
  252. return array_values( $filtered );
  253. }
  254. /**
  255. * Retrieves the appropriate fallback to be used on the front of the
  256. * site when there is no menu assigned to the Nav block.
  257. *
  258. * This aims to mirror how the fallback mechanic for wp_nav_menu works.
  259. * See https://developer.wordpress.org/reference/functions/wp_nav_menu/#more-information.
  260. *
  261. * @return array the array of blocks to be used as a fallback.
  262. */
  263. function block_core_navigation_get_fallback_blocks() {
  264. $page_list_fallback = array(
  265. array(
  266. 'blockName' => 'core/page-list',
  267. ),
  268. );
  269. $registry = WP_Block_Type_Registry::get_instance();
  270. // If `core/page-list` is not registered then return empty blocks.
  271. $fallback_blocks = $registry->is_registered( 'core/page-list' ) ? $page_list_fallback : array();
  272. // Default to a list of Pages.
  273. $navigation_post = block_core_navigation_get_most_recently_published_navigation();
  274. // Prefer using the first non-empty Navigation as fallback if available.
  275. if ( $navigation_post ) {
  276. $maybe_fallback = block_core_navigation_filter_out_empty_blocks( parse_blocks( $navigation_post->post_content ) );
  277. // Normalizing blocks may result in an empty array of blocks if they were all `null` blocks.
  278. // In this case default to the (Page List) fallback.
  279. $fallback_blocks = ! empty( $maybe_fallback ) ? $maybe_fallback : $fallback_blocks;
  280. }
  281. /**
  282. * Filters the fallback experience for the Navigation block.
  283. *
  284. * Returning a falsey value will opt out of the fallback and cause the block not to render.
  285. * To customise the blocks provided return an array of blocks - these should be valid
  286. * children of the `core/navigation` block.
  287. *
  288. * @since 5.9.0
  289. *
  290. * @param array[] default fallback blocks provided by the default block mechanic.
  291. */
  292. return apply_filters( 'block_core_navigation_render_fallback', $fallback_blocks );
  293. }
  294. /**
  295. * Iterate through all inner blocks recursively and get navigation link block's post IDs.
  296. *
  297. * @param WP_Block_List $inner_blocks Block list class instance.
  298. *
  299. * @return array Array of post IDs.
  300. */
  301. function block_core_navigation_get_post_ids( $inner_blocks ) {
  302. $post_ids = array_map( 'block_core_navigation_from_block_get_post_ids', iterator_to_array( $inner_blocks ) );
  303. return array_unique( array_merge( ...$post_ids ) );
  304. }
  305. /**
  306. * Get post IDs from a navigation link block instance.
  307. *
  308. * @param WP_Block $block Instance of a block.
  309. *
  310. * @return array Array of post IDs.
  311. */
  312. function block_core_navigation_from_block_get_post_ids( $block ) {
  313. $post_ids = array();
  314. if ( $block->inner_blocks ) {
  315. $post_ids = block_core_navigation_get_post_ids( $block->inner_blocks );
  316. }
  317. if ( 'core/navigation-link' === $block->name || 'core/navigation-submenu' === $block->name ) {
  318. if ( $block->attributes && isset( $block->attributes['kind'] ) && 'post-type' === $block->attributes['kind'] && isset( $block->attributes['id'] ) ) {
  319. $post_ids[] = $block->attributes['id'];
  320. }
  321. }
  322. return $post_ids;
  323. }
  324. /**
  325. * Renders the `core/navigation` block on server.
  326. *
  327. * @param array $attributes The block attributes.
  328. * @param string $content The saved content.
  329. * @param WP_Block $block The parsed block.
  330. *
  331. * @return string Returns the post content with the legacy widget added.
  332. */
  333. function render_block_core_navigation( $attributes, $content, $block ) {
  334. static $seen_menu_names = array();
  335. // Flag used to indicate whether the rendered output is considered to be
  336. // a fallback (i.e. the block has no menu associated with it).
  337. $is_fallback = false;
  338. $nav_menu_name = '';
  339. /**
  340. * Deprecated:
  341. * The rgbTextColor and rgbBackgroundColor attributes
  342. * have been deprecated in favor of
  343. * customTextColor and customBackgroundColor ones.
  344. * Move the values from old attrs to the new ones.
  345. */
  346. if ( isset( $attributes['rgbTextColor'] ) && empty( $attributes['textColor'] ) ) {
  347. $attributes['customTextColor'] = $attributes['rgbTextColor'];
  348. }
  349. if ( isset( $attributes['rgbBackgroundColor'] ) && empty( $attributes['backgroundColor'] ) ) {
  350. $attributes['customBackgroundColor'] = $attributes['rgbBackgroundColor'];
  351. }
  352. unset( $attributes['rgbTextColor'], $attributes['rgbBackgroundColor'] );
  353. /**
  354. * This is for backwards compatibility after `isResponsive` attribute has been removed.
  355. */
  356. $has_old_responsive_attribute = ! empty( $attributes['isResponsive'] ) && $attributes['isResponsive'];
  357. $is_responsive_menu = isset( $attributes['overlayMenu'] ) && 'never' !== $attributes['overlayMenu'] || $has_old_responsive_attribute;
  358. $should_load_view_script = ! wp_script_is( 'wp-block-navigation-view' ) && ( $is_responsive_menu || $attributes['openSubmenusOnClick'] || $attributes['showSubmenuIcon'] );
  359. if ( $should_load_view_script ) {
  360. wp_enqueue_script( 'wp-block-navigation-view' );
  361. }
  362. $should_load_modal_view_script = isset( $attributes['overlayMenu'] ) && 'never' !== $attributes['overlayMenu'];
  363. if ( $should_load_modal_view_script ) {
  364. wp_enqueue_script( 'wp-block-navigation-view-modal' );
  365. }
  366. $inner_blocks = $block->inner_blocks;
  367. // Ensure that blocks saved with the legacy ref attribute name (navigationMenuId) continue to render.
  368. if ( array_key_exists( 'navigationMenuId', $attributes ) ) {
  369. $attributes['ref'] = $attributes['navigationMenuId'];
  370. }
  371. // If:
  372. // - the gutenberg plugin is active
  373. // - `__unstableLocation` is defined
  374. // - we have menu items at the defined location
  375. // - we don't have a relationship to a `wp_navigation` Post (via `ref`).
  376. // ...then create inner blocks from the classic menu assigned to that location.
  377. if (
  378. defined( 'IS_GUTENBERG_PLUGIN' ) && IS_GUTENBERG_PLUGIN &&
  379. array_key_exists( '__unstableLocation', $attributes ) &&
  380. ! array_key_exists( 'ref', $attributes ) &&
  381. ! empty( block_core_navigation_get_menu_items_at_location( $attributes['__unstableLocation'] ) )
  382. ) {
  383. $menu_items = block_core_navigation_get_menu_items_at_location( $attributes['__unstableLocation'] );
  384. if ( empty( $menu_items ) ) {
  385. return '';
  386. }
  387. $menu_items_by_parent_id = block_core_navigation_sort_menu_items_by_parent_id( $menu_items );
  388. $parsed_blocks = block_core_navigation_parse_blocks_from_menu_items( $menu_items_by_parent_id[0], $menu_items_by_parent_id );
  389. $inner_blocks = new WP_Block_List( $parsed_blocks, $attributes );
  390. }
  391. // Load inner blocks from the navigation post.
  392. if ( array_key_exists( 'ref', $attributes ) ) {
  393. $navigation_post = get_post( $attributes['ref'] );
  394. if ( ! isset( $navigation_post ) ) {
  395. return '';
  396. }
  397. // Only published posts are valid. If this is changed then a corresponding change
  398. // must also be implemented in `use-navigation-menu.js`.
  399. if ( 'publish' === $navigation_post->post_status ) {
  400. $nav_menu_name = $navigation_post->post_title;
  401. if ( isset( $seen_menu_names[ $nav_menu_name ] ) ) {
  402. ++$seen_menu_names[ $nav_menu_name ];
  403. } else {
  404. $seen_menu_names[ $nav_menu_name ] = 1;
  405. }
  406. $parsed_blocks = parse_blocks( $navigation_post->post_content );
  407. // 'parse_blocks' includes a null block with '\n\n' as the content when
  408. // it encounters whitespace. This code strips it.
  409. $compacted_blocks = block_core_navigation_filter_out_empty_blocks( $parsed_blocks );
  410. // TODO - this uses the full navigation block attributes for the
  411. // context which could be refined.
  412. $inner_blocks = new WP_Block_List( $compacted_blocks, $attributes );
  413. }
  414. }
  415. // If there are no inner blocks then fallback to rendering an appropriate fallback.
  416. if ( empty( $inner_blocks ) ) {
  417. $is_fallback = true; // indicate we are rendering the fallback.
  418. $fallback_blocks = block_core_navigation_get_fallback_blocks();
  419. // Fallback my have been filtered so do basic test for validity.
  420. if ( empty( $fallback_blocks ) || ! is_array( $fallback_blocks ) ) {
  421. return '';
  422. }
  423. $inner_blocks = new WP_Block_List( $fallback_blocks, $attributes );
  424. }
  425. /**
  426. * Filter navigation block $inner_blocks.
  427. * Allows modification of a navigation block menu items.
  428. *
  429. * @since 6.1.0
  430. *
  431. * @param \WP_Block_List $inner_blocks
  432. */
  433. $inner_blocks = apply_filters( 'block_core_navigation_render_inner_blocks', $inner_blocks );
  434. $layout_justification = array(
  435. 'left' => 'items-justified-left',
  436. 'right' => 'items-justified-right',
  437. 'center' => 'items-justified-center',
  438. 'space-between' => 'items-justified-space-between',
  439. );
  440. // Restore legacy classnames for submenu positioning.
  441. $layout_class = '';
  442. if ( isset( $attributes['layout']['justifyContent'] ) ) {
  443. $layout_class .= $layout_justification[ $attributes['layout']['justifyContent'] ];
  444. }
  445. if ( isset( $attributes['layout']['orientation'] ) && 'vertical' === $attributes['layout']['orientation'] ) {
  446. $layout_class .= ' is-vertical';
  447. }
  448. if ( isset( $attributes['layout']['flexWrap'] ) && 'nowrap' === $attributes['layout']['flexWrap'] ) {
  449. $layout_class .= ' no-wrap';
  450. }
  451. // Manually add block support text decoration as CSS class.
  452. $text_decoration = _wp_array_get( $attributes, array( 'style', 'typography', 'textDecoration' ), null );
  453. $text_decoration_class = sprintf( 'has-text-decoration-%s', $text_decoration );
  454. $colors = block_core_navigation_build_css_colors( $attributes );
  455. $font_sizes = block_core_navigation_build_css_font_sizes( $attributes );
  456. $classes = array_merge(
  457. $colors['css_classes'],
  458. $font_sizes['css_classes'],
  459. $is_responsive_menu ? array( 'is-responsive' ) : array(),
  460. $layout_class ? array( $layout_class ) : array(),
  461. $is_fallback ? array( 'is-fallback' ) : array(),
  462. $text_decoration ? array( $text_decoration_class ) : array()
  463. );
  464. $post_ids = block_core_navigation_get_post_ids( $inner_blocks );
  465. if ( $post_ids ) {
  466. _prime_post_caches( $post_ids, false, false );
  467. }
  468. $inner_blocks_html = '';
  469. $is_list_open = false;
  470. foreach ( $inner_blocks as $inner_block ) {
  471. if ( ( 'core/navigation-link' === $inner_block->name || 'core/home-link' === $inner_block->name || 'core/site-title' === $inner_block->name || 'core/site-logo' === $inner_block->name || 'core/navigation-submenu' === $inner_block->name ) && ! $is_list_open ) {
  472. $is_list_open = true;
  473. $inner_blocks_html .= '<ul class="wp-block-navigation__container">';
  474. }
  475. if ( 'core/navigation-link' !== $inner_block->name && 'core/home-link' !== $inner_block->name && 'core/site-title' !== $inner_block->name && 'core/site-logo' !== $inner_block->name && 'core/navigation-submenu' !== $inner_block->name && $is_list_open ) {
  476. $is_list_open = false;
  477. $inner_blocks_html .= '</ul>';
  478. }
  479. $inner_block_content = $inner_block->render();
  480. if ( 'core/site-title' === $inner_block->name || ( 'core/site-logo' === $inner_block->name && $inner_block_content ) ) {
  481. $inner_blocks_html .= '<li class="wp-block-navigation-item">' . $inner_block_content . '</li>';
  482. } else {
  483. $inner_blocks_html .= $inner_block_content;
  484. }
  485. }
  486. if ( $is_list_open ) {
  487. $inner_blocks_html .= '</ul>';
  488. }
  489. $block_styles = isset( $attributes['styles'] ) ? $attributes['styles'] : '';
  490. // If the menu name has been used previously then append an ID
  491. // to the name to ensure uniqueness across a given post.
  492. if ( isset( $seen_menu_names[ $nav_menu_name ] ) && $seen_menu_names[ $nav_menu_name ] > 1 ) {
  493. $count = $seen_menu_names[ $nav_menu_name ];
  494. $nav_menu_name = $nav_menu_name . ' ' . ( $count );
  495. }
  496. $wrapper_attributes = get_block_wrapper_attributes(
  497. array(
  498. 'class' => implode( ' ', $classes ),
  499. 'style' => $block_styles . $colors['inline_styles'] . $font_sizes['inline_styles'],
  500. 'aria-label' => $nav_menu_name,
  501. )
  502. );
  503. $modal_unique_id = wp_unique_id( 'modal-' );
  504. // Determine whether or not navigation elements should be wrapped in the markup required to make it responsive,
  505. // return early if they don't.
  506. if ( ! $is_responsive_menu ) {
  507. return sprintf(
  508. '<nav %1$s>%2$s</nav>',
  509. $wrapper_attributes,
  510. $inner_blocks_html
  511. );
  512. }
  513. $is_hidden_by_default = isset( $attributes['overlayMenu'] ) && 'always' === $attributes['overlayMenu'];
  514. $responsive_container_classes = array(
  515. 'wp-block-navigation__responsive-container',
  516. $is_hidden_by_default ? 'hidden-by-default' : '',
  517. implode( ' ', $colors['overlay_css_classes'] ),
  518. );
  519. $open_button_classes = array(
  520. 'wp-block-navigation__responsive-container-open',
  521. $is_hidden_by_default ? 'always-shown' : '',
  522. );
  523. $should_display_icon_label = isset( $attributes['hasIcon'] ) && true === $attributes['hasIcon'];
  524. $toggle_button_icon = '<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="4" y="7.5" width="16" height="1.5" /><rect x="4" y="15" width="16" height="1.5" /></svg>';
  525. if ( isset( $attributes['icon'] ) ) {
  526. if ( 'menu' === $attributes['icon'] ) {
  527. $toggle_button_icon = '<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 5v1.5h14V5H5zm0 7.8h14v-1.5H5v1.5zM5 19h14v-1.5H5V19z" /></svg>';
  528. }
  529. }
  530. $toggle_button_content = $should_display_icon_label ? $toggle_button_icon : __( 'Menu' );
  531. $toggle_close_button_icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false"><path d="M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"></path></svg>';
  532. $toggle_close_button_content = $should_display_icon_label ? $toggle_close_button_icon : __( 'Close' );
  533. $toggle_aria_label_open = $should_display_icon_label ? 'aria-label="' . __( 'Open menu' ) . '"' : ''; // Open button label.
  534. $toggle_aria_label_close = $should_display_icon_label ? 'aria-label="' . __( 'Close menu' ) . '"' : ''; // Close button label.
  535. $responsive_container_markup = sprintf(
  536. '<button aria-haspopup="true" %3$s class="%6$s" data-micromodal-trigger="%1$s">%9$s</button>
  537. <div class="%5$s" style="%7$s" id="%1$s">
  538. <div class="wp-block-navigation__responsive-close" tabindex="-1" data-micromodal-close>
  539. <div class="wp-block-navigation__responsive-dialog" aria-label="%8$s">
  540. <button %4$s data-micromodal-close class="wp-block-navigation__responsive-container-close">%10$s</button>
  541. <div class="wp-block-navigation__responsive-container-content" id="%1$s-content">
  542. %2$s
  543. </div>
  544. </div>
  545. </div>
  546. </div>',
  547. esc_attr( $modal_unique_id ),
  548. $inner_blocks_html,
  549. $toggle_aria_label_open,
  550. $toggle_aria_label_close,
  551. esc_attr( implode( ' ', $responsive_container_classes ) ),
  552. esc_attr( implode( ' ', $open_button_classes ) ),
  553. esc_attr( safecss_filter_attr( $colors['overlay_inline_styles'] ) ),
  554. __( 'Menu' ),
  555. $toggle_button_content,
  556. $toggle_close_button_content
  557. );
  558. return sprintf(
  559. '<nav %1$s>%2$s</nav>',
  560. $wrapper_attributes,
  561. $responsive_container_markup
  562. );
  563. }
  564. /**
  565. * Register the navigation block.
  566. *
  567. * @uses render_block_core_navigation()
  568. * @throws WP_Error An WP_Error exception parsing the block definition.
  569. */
  570. function register_block_core_navigation() {
  571. register_block_type_from_metadata(
  572. __DIR__ . '/navigation',
  573. array(
  574. 'render_callback' => 'render_block_core_navigation',
  575. )
  576. );
  577. }
  578. add_action( 'init', 'register_block_core_navigation' );
  579. /**
  580. * Filter that changes the parsed attribute values of navigation blocks contain typographic presets to contain the values directly.
  581. *
  582. * @param array $parsed_block The block being rendered.
  583. *
  584. * @return array The block being rendered without typographic presets.
  585. */
  586. function block_core_navigation_typographic_presets_backcompatibility( $parsed_block ) {
  587. if ( 'core/navigation' === $parsed_block['blockName'] ) {
  588. $attribute_to_prefix_map = array(
  589. 'fontStyle' => 'var:preset|font-style|',
  590. 'fontWeight' => 'var:preset|font-weight|',
  591. 'textDecoration' => 'var:preset|text-decoration|',
  592. 'textTransform' => 'var:preset|text-transform|',
  593. );
  594. foreach ( $attribute_to_prefix_map as $style_attribute => $prefix ) {
  595. if ( ! empty( $parsed_block['attrs']['style']['typography'][ $style_attribute ] ) ) {
  596. $prefix_len = strlen( $prefix );
  597. $attribute_value = &$parsed_block['attrs']['style']['typography'][ $style_attribute ];
  598. if ( 0 === strncmp( $attribute_value, $prefix, $prefix_len ) ) {
  599. $attribute_value = substr( $attribute_value, $prefix_len );
  600. }
  601. if ( 'textDecoration' === $style_attribute && 'strikethrough' === $attribute_value ) {
  602. $attribute_value = 'line-through';
  603. }
  604. }
  605. }
  606. }
  607. return $parsed_block;
  608. }
  609. add_filter( 'render_block_data', 'block_core_navigation_typographic_presets_backcompatibility' );