[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/blocks/ -> navigation.php (source)

   1  <?php
   2  /**
   3   * Server-side rendering of the `core/navigation` block.
   4   *
   5   * @package WordPress
   6   */
   7  
   8  /**
   9   * Helper functions used to render the navigation block.
  10   *
  11   * @since 6.5.0
  12   */
  13  class WP_Navigation_Block_Renderer {
  14  
  15      /**
  16       * Used to determine whether or not a navigation has submenus.
  17       *
  18       * @since 6.5.0
  19       */
  20      private static $has_submenus = false;
  21  
  22      /**
  23       * Used to determine which blocks need an <li> wrapper.
  24       *
  25       * @since 6.5.0
  26       *
  27       * @var array
  28       */
  29      private static $needs_list_item_wrapper = array(
  30          'core/site-title',
  31          'core/site-logo',
  32          'core/social-links',
  33      );
  34  
  35      /**
  36       * Keeps track of all the navigation names that have been seen.
  37       *
  38       * @since 6.5.0
  39       *
  40       * @var array
  41       */
  42      private static $seen_menu_names = array();
  43  
  44      /**
  45       * Returns whether or not this is responsive navigation.
  46       *
  47       * @since 6.5.0
  48       *
  49       * @param array $attributes The block attributes.
  50       * @return bool Returns whether or not this is responsive navigation.
  51       */
  52  	private static function is_responsive( $attributes ) {
  53          /**
  54           * This is for backwards compatibility after the `isResponsive` attribute was been removed.
  55           */
  56  
  57          $has_old_responsive_attribute = ! empty( $attributes['isResponsive'] ) && $attributes['isResponsive'];
  58          return isset( $attributes['overlayMenu'] ) && 'never' !== $attributes['overlayMenu'] || $has_old_responsive_attribute;
  59      }
  60  
  61      /**
  62       * Returns whether or not a navigation has a submenu.
  63       *
  64       * @since 6.5.0
  65       *
  66       * @param WP_Block_List $inner_blocks The list of inner blocks.
  67       * @return bool Returns whether or not a navigation has a submenu and also sets the member variable.
  68       */
  69  	private static function has_submenus( $inner_blocks ) {
  70          if ( true === static::$has_submenus ) {
  71              return static::$has_submenus;
  72          }
  73  
  74          foreach ( $inner_blocks as $inner_block ) {
  75              // If this is a page list then work out if any of the pages have children.
  76              if ( 'core/page-list' === $inner_block->name ) {
  77                  $all_pages = get_pages(
  78                      array(
  79                          'sort_column' => 'menu_order,post_title',
  80                          'order'       => 'asc',
  81                      )
  82                  );
  83                  foreach ( (array) $all_pages as $page ) {
  84                      if ( $page->post_parent ) {
  85                          static::$has_submenus = true;
  86                          break;
  87                      }
  88                  }
  89              }
  90              // If this is a navigation submenu then we know we have submenus.
  91              if ( 'core/navigation-submenu' === $inner_block->name ) {
  92                  static::$has_submenus = true;
  93                  break;
  94              }
  95          }
  96  
  97          return static::$has_submenus;
  98      }
  99  
 100      /**
 101       * Determine whether the navigation blocks is interactive.
 102       *
 103       * @since 6.5.0
 104       *
 105       * @param array         $attributes   The block attributes.
 106       * @param WP_Block_List $inner_blocks The list of inner blocks.
 107       * @return bool Returns whether or not to load the view script.
 108       */
 109  	private static function is_interactive( $attributes, $inner_blocks ) {
 110          $has_submenus       = static::has_submenus( $inner_blocks );
 111          $is_responsive_menu = static::is_responsive( $attributes );
 112          return ( $has_submenus && ( $attributes['openSubmenusOnClick'] || $attributes['showSubmenuIcon'] ) ) || $is_responsive_menu;
 113      }
 114  
 115      /**
 116       * Returns whether or not a block needs a list item wrapper.
 117       *
 118       * @since 6.5.0
 119       *
 120       * @param WP_Block $block The block.
 121       * @return bool Returns whether or not a block needs a list item wrapper.
 122       */
 123  	private static function does_block_need_a_list_item_wrapper( $block ) {
 124  
 125          /**
 126           * Filter the list of blocks that need a list item wrapper.
 127           *
 128           * Affords the ability to customize which blocks need a list item wrapper when rendered
 129           * within a core/navigation block.
 130           * This is useful for blocks that are not list items but should be wrapped in a list
 131           * item when used as a child of a navigation block.
 132           *
 133           * @since 6.5.0
 134           *
 135           * @param array $needs_list_item_wrapper The list of blocks that need a list item wrapper.
 136           * @return array The list of blocks that need a list item wrapper.
 137           */
 138          $needs_list_item_wrapper = apply_filters( 'block_core_navigation_listable_blocks', static::$needs_list_item_wrapper );
 139  
 140          return in_array( $block->name, $needs_list_item_wrapper, true );
 141      }
 142  
 143      /**
 144       * Returns the markup for a single inner block.
 145       *
 146       * @since 6.5.0
 147       *
 148       * @param WP_Block $inner_block The inner block.
 149       * @return string Returns the markup for a single inner block.
 150       */
 151  	private static function get_markup_for_inner_block( $inner_block ) {
 152          $inner_block_content = $inner_block->render();
 153          if ( ! empty( $inner_block_content ) ) {
 154              if ( static::does_block_need_a_list_item_wrapper( $inner_block ) ) {
 155                  return '<li class="wp-block-navigation-item">' . $inner_block_content . '</li>';
 156              }
 157          }
 158  
 159          return $inner_block_content;
 160      }
 161  
 162      /**
 163       * Returns the html for the inner blocks of the navigation block.
 164       *
 165       * @since 6.5.0
 166       *
 167       * @param array         $attributes   The block attributes.
 168       * @param WP_Block_List $inner_blocks The list of inner blocks.
 169       * @return string Returns the html for the inner blocks of the navigation block.
 170       */
 171  	private static function get_inner_blocks_html( $attributes, $inner_blocks ) {
 172          $has_submenus   = static::has_submenus( $inner_blocks );
 173          $is_interactive = static::is_interactive( $attributes, $inner_blocks );
 174  
 175          $style                = static::get_styles( $attributes );
 176          $class                = static::get_classes( $attributes );
 177          $container_attributes = get_block_wrapper_attributes(
 178              array(
 179                  'class' => 'wp-block-navigation__container ' . $class,
 180                  'style' => $style,
 181              )
 182          );
 183  
 184          $inner_blocks_html = '';
 185          $is_list_open      = false;
 186  
 187          foreach ( $inner_blocks as $inner_block ) {
 188              $inner_block_markup = static::get_markup_for_inner_block( $inner_block );
 189              $p                  = new WP_HTML_Tag_Processor( $inner_block_markup );
 190              $is_list_item       = $p->next_tag( 'LI' );
 191  
 192              if ( $is_list_item && ! $is_list_open ) {
 193                  $is_list_open       = true;
 194                  $inner_blocks_html .= sprintf(
 195                      '<ul %1$s>',
 196                      $container_attributes
 197                  );
 198              }
 199  
 200              if ( ! $is_list_item && $is_list_open ) {
 201                  $is_list_open       = false;
 202                  $inner_blocks_html .= '</ul>';
 203              }
 204  
 205              $inner_blocks_html .= $inner_block_markup;
 206          }
 207  
 208          if ( $is_list_open ) {
 209              $inner_blocks_html .= '</ul>';
 210          }
 211  
 212          // Add directives to the submenu if needed.
 213          if ( $has_submenus && $is_interactive ) {
 214              $tags              = new WP_HTML_Tag_Processor( $inner_blocks_html );
 215              $inner_blocks_html = block_core_navigation_add_directives_to_submenu( $tags, $attributes );
 216          }
 217  
 218          return $inner_blocks_html;
 219      }
 220  
 221      /**
 222       * Gets the inner blocks for the navigation block from the navigation post.
 223       *
 224       * @since 6.5.0
 225       *
 226       * @param array $attributes The block attributes.
 227       * @return WP_Block_List Returns the inner blocks for the navigation block.
 228       */
 229  	private static function get_inner_blocks_from_navigation_post( $attributes ) {
 230          $navigation_post = get_post( $attributes['ref'] );
 231          if ( ! isset( $navigation_post ) ) {
 232              return new WP_Block_List( array(), $attributes );
 233          }
 234  
 235          // Only published posts are valid. If this is changed then a corresponding change
 236          // must also be implemented in `use-navigation-menu.js`.
 237          if ( 'publish' === $navigation_post->post_status ) {
 238              $parsed_blocks = parse_blocks( $navigation_post->post_content );
 239  
 240              // 'parse_blocks' includes a null block with '\n\n' as the content when
 241              // it encounters whitespace. This code strips it.
 242              $blocks = block_core_navigation_filter_out_empty_blocks( $parsed_blocks );
 243  
 244              // Run Block Hooks algorithm to inject hooked blocks.
 245              $markup         = block_core_navigation_insert_hooked_blocks( $blocks, $navigation_post );
 246              $root_nav_block = parse_blocks( $markup )[0];
 247  
 248              $blocks = isset( $root_nav_block['innerBlocks'] ) ? $root_nav_block['innerBlocks'] : $blocks;
 249  
 250              // TODO - this uses the full navigation block attributes for the
 251              // context which could be refined.
 252              return new WP_Block_List( $blocks, $attributes );
 253          }
 254      }
 255  
 256      /**
 257       * Gets the inner blocks for the navigation block from the fallback.
 258       *
 259       * @since 6.5.0
 260       *
 261       * @param array $attributes The block attributes.
 262       * @return WP_Block_List Returns the inner blocks for the navigation block.
 263       */
 264  	private static function get_inner_blocks_from_fallback( $attributes ) {
 265          $fallback_blocks = block_core_navigation_get_fallback_blocks();
 266  
 267          // Fallback my have been filtered so do basic test for validity.
 268          if ( empty( $fallback_blocks ) || ! is_array( $fallback_blocks ) ) {
 269              return new WP_Block_List( array(), $attributes );
 270          }
 271  
 272          return new WP_Block_List( $fallback_blocks, $attributes );
 273      }
 274  
 275      /**
 276       * Gets the inner blocks for the navigation block.
 277       *
 278       * @since 6.5.0
 279       *
 280       * @param array    $attributes The block attributes.
 281       * @param WP_Block $block The parsed block.
 282       * @return WP_Block_List Returns the inner blocks for the navigation block.
 283       */
 284  	private static function get_inner_blocks( $attributes, $block ) {
 285          $inner_blocks = $block->inner_blocks;
 286  
 287          // Ensure that blocks saved with the legacy ref attribute name (navigationMenuId) continue to render.
 288          if ( array_key_exists( 'navigationMenuId', $attributes ) ) {
 289              $attributes['ref'] = $attributes['navigationMenuId'];
 290          }
 291  
 292          // If:
 293          // - the gutenberg plugin is active
 294          // - `__unstableLocation` is defined
 295          // - we have menu items at the defined location
 296          // - we don't have a relationship to a `wp_navigation` Post (via `ref`).
 297          // ...then create inner blocks from the classic menu assigned to that location.
 298          if (
 299              defined( 'IS_GUTENBERG_PLUGIN' ) && IS_GUTENBERG_PLUGIN &&
 300              array_key_exists( '__unstableLocation', $attributes ) &&
 301              ! array_key_exists( 'ref', $attributes ) &&
 302              ! empty( block_core_navigation_get_menu_items_at_location( $attributes['__unstableLocation'] ) )
 303          ) {
 304              $inner_blocks = block_core_navigation_get_inner_blocks_from_unstable_location( $attributes );
 305          }
 306  
 307          // Load inner blocks from the navigation post.
 308          if ( array_key_exists( 'ref', $attributes ) ) {
 309              $inner_blocks = static::get_inner_blocks_from_navigation_post( $attributes );
 310          }
 311  
 312          // If there are no inner blocks then fallback to rendering an appropriate fallback.
 313          if ( empty( $inner_blocks ) ) {
 314              $inner_blocks = static::get_inner_blocks_from_fallback( $attributes );
 315          }
 316  
 317          /**
 318           * Filter navigation block $inner_blocks.
 319           * Allows modification of a navigation block menu items.
 320           *
 321           * @since 6.1.0
 322           *
 323           * @param \WP_Block_List $inner_blocks
 324           */
 325          $inner_blocks = apply_filters( 'block_core_navigation_render_inner_blocks', $inner_blocks );
 326  
 327          $post_ids = block_core_navigation_get_post_ids( $inner_blocks );
 328          if ( $post_ids ) {
 329              _prime_post_caches( $post_ids, false, false );
 330          }
 331  
 332          return $inner_blocks;
 333      }
 334  
 335      /**
 336       * Gets the name of the current navigation, if it has one.
 337       *
 338       * @since 6.5.0
 339       *
 340       * @param array $attributes The block attributes.
 341       * @return string Returns the name of the navigation.
 342       */
 343  	private static function get_navigation_name( $attributes ) {
 344  
 345          $navigation_name = $attributes['ariaLabel'] ?? '';
 346  
 347          // Load the navigation post.
 348          if ( array_key_exists( 'ref', $attributes ) ) {
 349              $navigation_post = get_post( $attributes['ref'] );
 350              if ( ! isset( $navigation_post ) ) {
 351                  return $navigation_name;
 352              }
 353  
 354              // Only published posts are valid. If this is changed then a corresponding change
 355              // must also be implemented in `use-navigation-menu.js`.
 356              if ( 'publish' === $navigation_post->post_status ) {
 357                  $navigation_name = $navigation_post->post_title;
 358  
 359                  // This is used to count the number of times a navigation name has been seen,
 360                  // so that we can ensure every navigation has a unique id.
 361                  if ( isset( static::$seen_menu_names[ $navigation_name ] ) ) {
 362                      ++static::$seen_menu_names[ $navigation_name ];
 363                  } else {
 364                      static::$seen_menu_names[ $navigation_name ] = 1;
 365                  }
 366              }
 367          }
 368  
 369          return $navigation_name;
 370      }
 371  
 372      /**
 373       * Returns the layout class for the navigation block.
 374       *
 375       * @since 6.5.0
 376       *
 377       * @param array $attributes The block attributes.
 378       * @return string Returns the layout class for the navigation block.
 379       */
 380  	private static function get_layout_class( $attributes ) {
 381          $layout_justification = array(
 382              'left'          => 'items-justified-left',
 383              'right'         => 'items-justified-right',
 384              'center'        => 'items-justified-center',
 385              'space-between' => 'items-justified-space-between',
 386          );
 387  
 388          $layout_class = '';
 389          if (
 390              isset( $attributes['layout']['justifyContent'] ) &&
 391              isset( $layout_justification[ $attributes['layout']['justifyContent'] ] )
 392          ) {
 393              $layout_class .= $layout_justification[ $attributes['layout']['justifyContent'] ];
 394          }
 395          if ( isset( $attributes['layout']['orientation'] ) && 'vertical' === $attributes['layout']['orientation'] ) {
 396              $layout_class .= ' is-vertical';
 397          }
 398  
 399          if ( isset( $attributes['layout']['flexWrap'] ) && 'nowrap' === $attributes['layout']['flexWrap'] ) {
 400              $layout_class .= ' no-wrap';
 401          }
 402          return $layout_class;
 403      }
 404  
 405      /**
 406       * Return classes for the navigation block.
 407       *
 408       * @since 6.5.0
 409       *
 410       * @param array $attributes The block attributes.
 411       * @return string Returns the classes for the navigation block.
 412       */
 413  	private static function get_classes( $attributes ) {
 414          // Restore legacy classnames for submenu positioning.
 415          $layout_class       = static::get_layout_class( $attributes );
 416          $colors             = block_core_navigation_build_css_colors( $attributes );
 417          $font_sizes         = block_core_navigation_build_css_font_sizes( $attributes );
 418          $is_responsive_menu = static::is_responsive( $attributes );
 419  
 420          // Manually add block support text decoration as CSS class.
 421          $text_decoration       = $attributes['style']['typography']['textDecoration'] ?? null;
 422          $text_decoration_class = sprintf( 'has-text-decoration-%s', $text_decoration );
 423  
 424          $classes = array_merge(
 425              $colors['css_classes'],
 426              $font_sizes['css_classes'],
 427              $is_responsive_menu ? array( 'is-responsive' ) : array(),
 428              $layout_class ? array( $layout_class ) : array(),
 429              $text_decoration ? array( $text_decoration_class ) : array()
 430          );
 431          return implode( ' ', $classes );
 432      }
 433  
 434      /**
 435       * Get styles for the navigation block.
 436       *
 437       * @since 6.5.0
 438       *
 439       * @param array $attributes The block attributes.
 440       * @return string Returns the styles for the navigation block.
 441       */
 442  	private static function get_styles( $attributes ) {
 443          $colors       = block_core_navigation_build_css_colors( $attributes );
 444          $font_sizes   = block_core_navigation_build_css_font_sizes( $attributes );
 445          $block_styles = isset( $attributes['styles'] ) ? $attributes['styles'] : '';
 446          return $block_styles . $colors['inline_styles'] . $font_sizes['inline_styles'];
 447      }
 448  
 449      /**
 450       * Get the responsive container markup
 451       *
 452       * @since 6.5.0
 453       *
 454       * @param array         $attributes The block attributes.
 455       * @param WP_Block_List $inner_blocks The list of inner blocks.
 456       * @param string        $inner_blocks_html The markup for the inner blocks.
 457       * @return string Returns the container markup.
 458       */
 459  	private static function get_responsive_container_markup( $attributes, $inner_blocks, $inner_blocks_html ) {
 460          $is_interactive  = static::is_interactive( $attributes, $inner_blocks );
 461          $colors          = block_core_navigation_build_css_colors( $attributes );
 462          $modal_unique_id = wp_unique_id( 'modal-' );
 463  
 464          $is_hidden_by_default = isset( $attributes['overlayMenu'] ) && 'always' === $attributes['overlayMenu'];
 465  
 466          $responsive_container_classes = array(
 467              'wp-block-navigation__responsive-container',
 468              $is_hidden_by_default ? 'hidden-by-default' : '',
 469              implode( ' ', $colors['overlay_css_classes'] ),
 470          );
 471          $open_button_classes          = array(
 472              'wp-block-navigation__responsive-container-open',
 473              $is_hidden_by_default ? 'always-shown' : '',
 474          );
 475  
 476          $should_display_icon_label = isset( $attributes['hasIcon'] ) && true === $attributes['hasIcon'];
 477          $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>';
 478          if ( isset( $attributes['icon'] ) ) {
 479              if ( 'menu' === $attributes['icon'] ) {
 480                  $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>';
 481              }
 482          }
 483          $toggle_button_content       = $should_display_icon_label ? $toggle_button_icon : __( 'Menu' );
 484          $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.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z"></path></svg>';
 485          $toggle_close_button_content = $should_display_icon_label ? $toggle_close_button_icon : __( 'Close' );
 486          $toggle_aria_label_open      = $should_display_icon_label ? 'aria-label="' . __( 'Open menu' ) . '"' : ''; // Open button label.
 487          $toggle_aria_label_close     = $should_display_icon_label ? 'aria-label="' . __( 'Close menu' ) . '"' : ''; // Close button label.
 488  
 489          // Add Interactivity API directives to the markup if needed.
 490          $open_button_directives          = '';
 491          $responsive_container_directives = '';
 492          $responsive_dialog_directives    = '';
 493          $close_button_directives         = '';
 494          if ( $is_interactive ) {
 495              $open_button_directives                  = '
 496                  data-wp-on-async--click="actions.openMenuOnClick"
 497                  data-wp-on--keydown="actions.handleMenuKeydown"
 498              ';
 499              $responsive_container_directives         = '
 500                  data-wp-class--has-modal-open="state.isMenuOpen"
 501                  data-wp-class--is-menu-open="state.isMenuOpen"
 502                  data-wp-watch="callbacks.initMenu"
 503                  data-wp-on--keydown="actions.handleMenuKeydown"
 504                  data-wp-on-async--focusout="actions.handleMenuFocusout"
 505                  tabindex="-1"
 506              ';
 507              $responsive_dialog_directives            = '
 508                  data-wp-bind--aria-modal="state.ariaModal"
 509                  data-wp-bind--aria-label="state.ariaLabel"
 510                  data-wp-bind--role="state.roleAttribute"
 511              ';
 512              $close_button_directives                 = '
 513                  data-wp-on-async--click="actions.closeMenuOnClick"
 514              ';
 515              $responsive_container_content_directives = '
 516                  data-wp-watch="callbacks.focusFirstElement"
 517              ';
 518          }
 519  
 520          $overlay_inline_styles = esc_attr( safecss_filter_attr( $colors['overlay_inline_styles'] ) );
 521  
 522          return sprintf(
 523              '<button aria-haspopup="dialog" %3$s class="%6$s" %10$s>%8$s</button>
 524                  <div class="%5$s" %7$s id="%1$s" %11$s>
 525                      <div class="wp-block-navigation__responsive-close" tabindex="-1">
 526                          <div class="wp-block-navigation__responsive-dialog" %12$s>
 527                              <button %4$s class="wp-block-navigation__responsive-container-close" %13$s>%9$s</button>
 528                              <div class="wp-block-navigation__responsive-container-content" %14$s id="%1$s-content">
 529                                  %2$s
 530                              </div>
 531                          </div>
 532                      </div>
 533                  </div>',
 534              esc_attr( $modal_unique_id ),
 535              $inner_blocks_html,
 536              $toggle_aria_label_open,
 537              $toggle_aria_label_close,
 538              esc_attr( implode( ' ', $responsive_container_classes ) ),
 539              esc_attr( implode( ' ', $open_button_classes ) ),
 540              ( ! empty( $overlay_inline_styles ) ) ? "style=\"$overlay_inline_styles\"" : '',
 541              $toggle_button_content,
 542              $toggle_close_button_content,
 543              $open_button_directives,
 544              $responsive_container_directives,
 545              $responsive_dialog_directives,
 546              $close_button_directives,
 547              $responsive_container_content_directives
 548          );
 549      }
 550  
 551      /**
 552       * Get the wrapper attributes
 553       *
 554       * @since 6.5.0
 555       *
 556       * @param array         $attributes    The block attributes.
 557       * @param WP_Block_List $inner_blocks  A list of inner blocks.
 558       * @return string Returns the navigation block markup.
 559       */
 560  	private static function get_nav_wrapper_attributes( $attributes, $inner_blocks ) {
 561          $nav_menu_name      = static::get_unique_navigation_name( $attributes );
 562          $is_interactive     = static::is_interactive( $attributes, $inner_blocks );
 563          $is_responsive_menu = static::is_responsive( $attributes );
 564          $style              = static::get_styles( $attributes );
 565          $class              = static::get_classes( $attributes );
 566          $wrapper_attributes = get_block_wrapper_attributes(
 567              array(
 568                  'class'      => $class,
 569                  'style'      => $style,
 570                  'aria-label' => $nav_menu_name,
 571              )
 572          );
 573  
 574          if ( $is_responsive_menu ) {
 575              $nav_element_directives = static::get_nav_element_directives( $is_interactive );
 576              $wrapper_attributes    .= ' ' . $nav_element_directives;
 577          }
 578  
 579          return $wrapper_attributes;
 580      }
 581  
 582      /**
 583       * Gets the nav element directives.
 584       *
 585       * @since 6.5.0
 586       *
 587       * @param bool $is_interactive Whether the block is interactive.
 588       * @return string the directives for the navigation element.
 589       */
 590  	private static function get_nav_element_directives( $is_interactive ) {
 591          if ( ! $is_interactive ) {
 592              return '';
 593          }
 594          // When adding to this array be mindful of security concerns.
 595          $nav_element_context    = wp_interactivity_data_wp_context(
 596              array(
 597                  'overlayOpenedBy' => array(
 598                      'click' => false,
 599                      'hover' => false,
 600                      'focus' => false,
 601                  ),
 602                  'type'            => 'overlay',
 603                  'roleAttribute'   => '',
 604                  'ariaLabel'       => __( 'Menu' ),
 605              )
 606          );
 607          $nav_element_directives = '
 608           data-wp-interactive="core/navigation" '
 609          . $nav_element_context;
 610  
 611          return $nav_element_directives;
 612      }
 613  
 614      /**
 615       * Handle view script module loading.
 616       *
 617       * @since 6.5.0
 618       *
 619       * @param array         $attributes   The block attributes.
 620       * @param WP_Block      $block        The parsed block.
 621       * @param WP_Block_List $inner_blocks The list of inner blocks.
 622       */
 623  	private static function handle_view_script_module_loading( $attributes, $block, $inner_blocks ) {
 624          if ( static::is_interactive( $attributes, $inner_blocks ) ) {
 625              wp_enqueue_script_module( '@wordpress/block-library/navigation/view' );
 626          }
 627      }
 628  
 629      /**
 630       * Returns the markup for the navigation block.
 631       *
 632       * @since 6.5.0
 633       *
 634       * @param array         $attributes The block attributes.
 635       * @param WP_Block_List $inner_blocks The list of inner blocks.
 636       * @return string Returns the navigation wrapper markup.
 637       */
 638  	private static function get_wrapper_markup( $attributes, $inner_blocks ) {
 639          $inner_blocks_html = static::get_inner_blocks_html( $attributes, $inner_blocks );
 640          if ( static::is_responsive( $attributes ) ) {
 641              return static::get_responsive_container_markup( $attributes, $inner_blocks, $inner_blocks_html );
 642          }
 643          return $inner_blocks_html;
 644      }
 645  
 646      /**
 647       * Returns a unique name for the navigation.
 648       *
 649       * @since 6.5.0
 650       *
 651       * @param array $attributes The block attributes.
 652       * @return string Returns a unique name for the navigation.
 653       */
 654  	private static function get_unique_navigation_name( $attributes ) {
 655          $nav_menu_name = static::get_navigation_name( $attributes );
 656  
 657          // If the menu name has been used previously then append an ID
 658          // to the name to ensure uniqueness across a given post.
 659          if ( isset( static::$seen_menu_names[ $nav_menu_name ] ) && static::$seen_menu_names[ $nav_menu_name ] > 1 ) {
 660              $count         = static::$seen_menu_names[ $nav_menu_name ];
 661              $nav_menu_name = $nav_menu_name . ' ' . ( $count );
 662          }
 663  
 664          return $nav_menu_name;
 665      }
 666  
 667      /**
 668       * Renders the navigation block.
 669       *
 670       * @since 6.5.0
 671       *
 672       * @param array    $attributes The block attributes.
 673       * @param string   $content    The saved content.
 674       * @param WP_Block $block      The parsed block.
 675       * @return string Returns the navigation block markup.
 676       */
 677  	public static function render( $attributes, $content, $block ) {
 678          /**
 679           * Deprecated:
 680           * The rgbTextColor and rgbBackgroundColor attributes
 681           * have been deprecated in favor of
 682           * customTextColor and customBackgroundColor ones.
 683           * Move the values from old attrs to the new ones.
 684           */
 685          if ( isset( $attributes['rgbTextColor'] ) && empty( $attributes['textColor'] ) ) {
 686              $attributes['customTextColor'] = $attributes['rgbTextColor'];
 687          }
 688  
 689          if ( isset( $attributes['rgbBackgroundColor'] ) && empty( $attributes['backgroundColor'] ) ) {
 690              $attributes['customBackgroundColor'] = $attributes['rgbBackgroundColor'];
 691          }
 692  
 693          unset( $attributes['rgbTextColor'], $attributes['rgbBackgroundColor'] );
 694  
 695          $inner_blocks = static::get_inner_blocks( $attributes, $block );
 696          // Prevent navigation blocks referencing themselves from rendering.
 697          if ( block_core_navigation_block_contains_core_navigation( $inner_blocks ) ) {
 698              return '';
 699          }
 700  
 701          static::handle_view_script_module_loading( $attributes, $block, $inner_blocks );
 702  
 703          return sprintf(
 704              '<nav %1$s>%2$s</nav>',
 705              static::get_nav_wrapper_attributes( $attributes, $inner_blocks ),
 706              static::get_wrapper_markup( $attributes, $inner_blocks )
 707          );
 708      }
 709  }
 710  
 711  // These functions are used for the __unstableLocation feature and only active
 712  // when the gutenberg plugin is active.
 713  if ( defined( 'IS_GUTENBERG_PLUGIN' ) && IS_GUTENBERG_PLUGIN ) {
 714      /**
 715       * Returns the menu items for a WordPress menu location.
 716       *
 717       * @since 5.9.0
 718       *
 719       * @param string $location The menu location.
 720       * @return array Menu items for the location.
 721       */
 722      function block_core_navigation_get_menu_items_at_location( $location ) {
 723          if ( empty( $location ) ) {
 724              return;
 725          }
 726  
 727          // Build menu data. The following approximates the code in
 728          // `wp_nav_menu()` and `gutenberg_output_block_nav_menu`.
 729  
 730          // Find the location in the list of locations, returning early if the
 731          // location can't be found.
 732          $locations = get_nav_menu_locations();
 733          if ( ! isset( $locations[ $location ] ) ) {
 734              return;
 735          }
 736  
 737          // Get the menu from the location, returning early if there is no
 738          // menu or there was an error.
 739          $menu = wp_get_nav_menu_object( $locations[ $location ] );
 740          if ( ! $menu || is_wp_error( $menu ) ) {
 741              return;
 742          }
 743  
 744          $menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'update_post_term_cache' => false ) );
 745          _wp_menu_item_classes_by_context( $menu_items );
 746  
 747          return $menu_items;
 748      }
 749  
 750  
 751      /**
 752       * Sorts a standard array of menu items into a nested structure keyed by the
 753       * id of the parent menu.
 754       *
 755       * @since 5.9.0
 756       *
 757       * @param array $menu_items Menu items to sort.
 758       * @return array An array keyed by the id of the parent menu where each element
 759       *               is an array of menu items that belong to that parent.
 760       */
 761      function block_core_navigation_sort_menu_items_by_parent_id( $menu_items ) {
 762          $sorted_menu_items = array();
 763          foreach ( (array) $menu_items as $menu_item ) {
 764              $sorted_menu_items[ $menu_item->menu_order ] = $menu_item;
 765          }
 766          unset( $menu_items, $menu_item );
 767  
 768          $menu_items_by_parent_id = array();
 769          foreach ( $sorted_menu_items as $menu_item ) {
 770              $menu_items_by_parent_id[ $menu_item->menu_item_parent ][] = $menu_item;
 771          }
 772  
 773          return $menu_items_by_parent_id;
 774      }
 775  
 776      /**
 777       * Gets the inner blocks for the navigation block from the unstable location attribute.
 778       *
 779       * @since 6.5.0
 780       *
 781       * @param array $attributes The block attributes.
 782       * @return WP_Block_List Returns the inner blocks for the navigation block.
 783       */
 784      function block_core_navigation_get_inner_blocks_from_unstable_location( $attributes ) {
 785          $menu_items = block_core_navigation_get_menu_items_at_location( $attributes['__unstableLocation'] );
 786          if ( empty( $menu_items ) ) {
 787              return new WP_Block_List( array(), $attributes );
 788          }
 789  
 790          $menu_items_by_parent_id = block_core_navigation_sort_menu_items_by_parent_id( $menu_items );
 791          $parsed_blocks           = block_core_navigation_parse_blocks_from_menu_items( $menu_items_by_parent_id[0], $menu_items_by_parent_id );
 792          return new WP_Block_List( $parsed_blocks, $attributes );
 793      }
 794  }
 795  
 796  /**
 797   * Add Interactivity API directives to the navigation-submenu and page-list
 798   * blocks markup using the Tag Processor.
 799   *
 800   * @since 6.3.0
 801   *
 802   * @param WP_HTML_Tag_Processor $tags             Markup of the navigation block.
 803   * @param array                 $block_attributes Block attributes.
 804   *
 805   * @return string Submenu markup with the directives injected.
 806   */
 807  function block_core_navigation_add_directives_to_submenu( $tags, $block_attributes ) {
 808      while ( $tags->next_tag(
 809          array(
 810              'tag_name'   => 'LI',
 811              'class_name' => 'has-child',
 812          )
 813      ) ) {
 814          // Add directives to the parent `<li>`.
 815          $tags->set_attribute( 'data-wp-interactive', 'core/navigation' );
 816          $tags->set_attribute( 'data-wp-context', '{ "submenuOpenedBy": { "click": false, "hover": false, "focus": false }, "type": "submenu" }' );
 817          $tags->set_attribute( 'data-wp-watch', 'callbacks.initMenu' );
 818          $tags->set_attribute( 'data-wp-on--focusout', 'actions.handleMenuFocusout' );
 819          $tags->set_attribute( 'data-wp-on--keydown', 'actions.handleMenuKeydown' );
 820  
 821          // This is a fix for Safari. Without it, Safari doesn't change the active
 822          // element when the user clicks on a button. It can be removed once we add
 823          // an overlay to capture the clicks, instead of relying on the focusout
 824          // event.
 825          $tags->set_attribute( 'tabindex', '-1' );
 826  
 827          if ( ! isset( $block_attributes['openSubmenusOnClick'] ) || false === $block_attributes['openSubmenusOnClick'] ) {
 828              $tags->set_attribute( 'data-wp-on-async--mouseenter', 'actions.openMenuOnHover' );
 829              $tags->set_attribute( 'data-wp-on-async--mouseleave', 'actions.closeMenuOnHover' );
 830          }
 831  
 832          // Add directives to the toggle submenu button.
 833          if ( $tags->next_tag(
 834              array(
 835                  'tag_name'   => 'BUTTON',
 836                  'class_name' => 'wp-block-navigation-submenu__toggle',
 837              )
 838          ) ) {
 839              $tags->set_attribute( 'data-wp-on-async--click', 'actions.toggleMenuOnClick' );
 840              $tags->set_attribute( 'data-wp-bind--aria-expanded', 'state.isMenuOpen' );
 841              // The `aria-expanded` attribute for SSR is already added in the submenu block.
 842          }
 843          // Add directives to the submenu.
 844          if ( $tags->next_tag(
 845              array(
 846                  'tag_name'   => 'UL',
 847                  'class_name' => 'wp-block-navigation__submenu-container',
 848              )
 849          ) ) {
 850              $tags->set_attribute( 'data-wp-on-async--focus', 'actions.openMenuOnFocus' );
 851          }
 852  
 853          // Iterate through subitems if exist.
 854          block_core_navigation_add_directives_to_submenu( $tags, $block_attributes );
 855      }
 856      return $tags->get_updated_html();
 857  }
 858  
 859  /**
 860   * Build an array with CSS classes and inline styles defining the colors
 861   * which will be applied to the navigation markup in the front-end.
 862   *
 863   * @since 5.9.0
 864   *
 865   * @param array $attributes Navigation block attributes.
 866   *
 867   * @return array Colors CSS classes and inline styles.
 868   */
 869  function block_core_navigation_build_css_colors( $attributes ) {
 870      $colors = array(
 871          'css_classes'           => array(),
 872          'inline_styles'         => '',
 873          'overlay_css_classes'   => array(),
 874          'overlay_inline_styles' => '',
 875      );
 876  
 877      // Text color.
 878      $has_named_text_color  = array_key_exists( 'textColor', $attributes );
 879      $has_custom_text_color = array_key_exists( 'customTextColor', $attributes );
 880  
 881      // If has text color.
 882      if ( $has_custom_text_color || $has_named_text_color ) {
 883          // Add has-text-color class.
 884          $colors['css_classes'][] = 'has-text-color';
 885      }
 886  
 887      if ( $has_named_text_color ) {
 888          // Add the color class.
 889          $colors['css_classes'][] = sprintf( 'has-%s-color', $attributes['textColor'] );
 890      } elseif ( $has_custom_text_color ) {
 891          // Add the custom color inline style.
 892          $colors['inline_styles'] .= sprintf( 'color: %s;', $attributes['customTextColor'] );
 893      }
 894  
 895      // Background color.
 896      $has_named_background_color  = array_key_exists( 'backgroundColor', $attributes );
 897      $has_custom_background_color = array_key_exists( 'customBackgroundColor', $attributes );
 898  
 899      // If has background color.
 900      if ( $has_custom_background_color || $has_named_background_color ) {
 901          // Add has-background class.
 902          $colors['css_classes'][] = 'has-background';
 903      }
 904  
 905      if ( $has_named_background_color ) {
 906          // Add the background-color class.
 907          $colors['css_classes'][] = sprintf( 'has-%s-background-color', $attributes['backgroundColor'] );
 908      } elseif ( $has_custom_background_color ) {
 909          // Add the custom background-color inline style.
 910          $colors['inline_styles'] .= sprintf( 'background-color: %s;', $attributes['customBackgroundColor'] );
 911      }
 912  
 913      // Overlay text color.
 914      $has_named_overlay_text_color  = array_key_exists( 'overlayTextColor', $attributes );
 915      $has_custom_overlay_text_color = array_key_exists( 'customOverlayTextColor', $attributes );
 916  
 917      // If has overlay text color.
 918      if ( $has_custom_overlay_text_color || $has_named_overlay_text_color ) {
 919          // Add has-text-color class.
 920          $colors['overlay_css_classes'][] = 'has-text-color';
 921      }
 922  
 923      if ( $has_named_overlay_text_color ) {
 924          // Add the overlay color class.
 925          $colors['overlay_css_classes'][] = sprintf( 'has-%s-color', $attributes['overlayTextColor'] );
 926      } elseif ( $has_custom_overlay_text_color ) {
 927          // Add the custom overlay color inline style.
 928          $colors['overlay_inline_styles'] .= sprintf( 'color: %s;', $attributes['customOverlayTextColor'] );
 929      }
 930  
 931      // Overlay background color.
 932      $has_named_overlay_background_color  = array_key_exists( 'overlayBackgroundColor', $attributes );
 933      $has_custom_overlay_background_color = array_key_exists( 'customOverlayBackgroundColor', $attributes );
 934  
 935      // If has overlay background color.
 936      if ( $has_custom_overlay_background_color || $has_named_overlay_background_color ) {
 937          // Add has-background class.
 938          $colors['overlay_css_classes'][] = 'has-background';
 939      }
 940  
 941      if ( $has_named_overlay_background_color ) {
 942          // Add the overlay background-color class.
 943          $colors['overlay_css_classes'][] = sprintf( 'has-%s-background-color', $attributes['overlayBackgroundColor'] );
 944      } elseif ( $has_custom_overlay_background_color ) {
 945          // Add the custom overlay background-color inline style.
 946          $colors['overlay_inline_styles'] .= sprintf( 'background-color: %s;', $attributes['customOverlayBackgroundColor'] );
 947      }
 948  
 949      return $colors;
 950  }
 951  
 952  /**
 953   * Build an array with CSS classes and inline styles defining the font sizes
 954   * which will be applied to the navigation markup in the front-end.
 955   *
 956   * @since 5.9.0
 957   *
 958   * @param array $attributes Navigation block attributes.
 959   *
 960   * @return array Font size CSS classes and inline styles.
 961   */
 962  function block_core_navigation_build_css_font_sizes( $attributes ) {
 963      // CSS classes.
 964      $font_sizes = array(
 965          'css_classes'   => array(),
 966          'inline_styles' => '',
 967      );
 968  
 969      $has_named_font_size  = array_key_exists( 'fontSize', $attributes );
 970      $has_custom_font_size = array_key_exists( 'customFontSize', $attributes );
 971  
 972      if ( $has_named_font_size ) {
 973          // Add the font size class.
 974          $font_sizes['css_classes'][] = sprintf( 'has-%s-font-size', $attributes['fontSize'] );
 975      } elseif ( $has_custom_font_size ) {
 976          // Add the custom font size inline style.
 977          $font_sizes['inline_styles'] = sprintf( 'font-size: %spx;', $attributes['customFontSize'] );
 978      }
 979  
 980      return $font_sizes;
 981  }
 982  
 983  /**
 984   * Returns the top-level submenu SVG chevron icon.
 985   *
 986   * @since 5.9.0
 987   *
 988   * @return string
 989   */
 990  function block_core_navigation_render_submenu_icon() {
 991      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>';
 992  }
 993  
 994  /**
 995   * Filter out empty "null" blocks from the block list.
 996   * 'parse_blocks' includes a null block with '\n\n' as the content when
 997   * it encounters whitespace. This is not a bug but rather how the parser
 998   * is designed.
 999   *
1000   * @since 5.9.0
1001   *
1002   * @param array $parsed_blocks the parsed blocks to be normalized.
1003   * @return array the normalized parsed blocks.
1004   */
1005  function block_core_navigation_filter_out_empty_blocks( $parsed_blocks ) {
1006      $filtered = array_filter(
1007          $parsed_blocks,
1008          static function ( $block ) {
1009              return isset( $block['blockName'] );
1010          }
1011      );
1012  
1013      // Reset keys.
1014      return array_values( $filtered );
1015  }
1016  
1017  /**
1018   * Returns true if the navigation block contains a nested navigation block.
1019   *
1020   * @since 6.2.0
1021   *
1022   * @param WP_Block_List $inner_blocks Inner block instance to be normalized.
1023   * @return bool true if the navigation block contains a nested navigation block.
1024   */
1025  function block_core_navigation_block_contains_core_navigation( $inner_blocks ) {
1026      foreach ( $inner_blocks as $block ) {
1027          if ( 'core/navigation' === $block->name ) {
1028              return true;
1029          }
1030          if ( $block->inner_blocks && block_core_navigation_block_contains_core_navigation( $block->inner_blocks ) ) {
1031              return true;
1032          }
1033      }
1034  
1035      return false;
1036  }
1037  
1038  /**
1039   * Retrieves the appropriate fallback to be used on the front of the
1040   * site when there is no menu assigned to the Nav block.
1041   *
1042   * This aims to mirror how the fallback mechanic for wp_nav_menu works.
1043   * See https://developer.wordpress.org/reference/functions/wp_nav_menu/#more-information.
1044   *
1045   * @since 5.9.0
1046   *
1047   * @return array the array of blocks to be used as a fallback.
1048   */
1049  function block_core_navigation_get_fallback_blocks() {
1050      $page_list_fallback = array(
1051          array(
1052              'blockName'    => 'core/page-list',
1053              'innerContent' => array(),
1054              'attrs'        => array(),
1055          ),
1056      );
1057  
1058      $registry = WP_Block_Type_Registry::get_instance();
1059  
1060      // If `core/page-list` is not registered then return empty blocks.
1061      $fallback_blocks = $registry->is_registered( 'core/page-list' ) ? $page_list_fallback : array();
1062      $navigation_post = WP_Navigation_Fallback::get_fallback();
1063  
1064      // Use the first non-empty Navigation as fallback if available.
1065      if ( $navigation_post ) {
1066          $parsed_blocks  = parse_blocks( $navigation_post->post_content );
1067          $maybe_fallback = block_core_navigation_filter_out_empty_blocks( $parsed_blocks );
1068  
1069          // Normalizing blocks may result in an empty array of blocks if they were all `null` blocks.
1070          // In this case default to the (Page List) fallback.
1071          $fallback_blocks = ! empty( $maybe_fallback ) ? $maybe_fallback : $fallback_blocks;
1072  
1073          // Run Block Hooks algorithm to inject hooked blocks.
1074          // We have to run it here because we need the post ID of the Navigation block to track ignored hooked blocks.
1075          $markup = block_core_navigation_insert_hooked_blocks( $fallback_blocks, $navigation_post );
1076          $blocks = parse_blocks( $markup );
1077  
1078          if ( isset( $blocks[0]['innerBlocks'] ) ) {
1079              $fallback_blocks = $blocks[0]['innerBlocks'];
1080          }
1081      }
1082  
1083      /**
1084       * Filters the fallback experience for the Navigation block.
1085       *
1086       * Returning a falsey value will opt out of the fallback and cause the block not to render.
1087       * To customise the blocks provided return an array of blocks - these should be valid
1088       * children of the `core/navigation` block.
1089       *
1090       * @since 5.9.0
1091       *
1092       * @param array[] $fallback_blocks default fallback blocks provided by the default block mechanic.
1093       */
1094      return apply_filters( 'block_core_navigation_render_fallback', $fallback_blocks );
1095  }
1096  
1097  /**
1098   * Iterate through all inner blocks recursively and get navigation link block's post IDs.
1099   *
1100   * @since 6.0.0
1101   *
1102   * @param WP_Block_List $inner_blocks Block list class instance.
1103   *
1104   * @return array Array of post IDs.
1105   */
1106  function block_core_navigation_get_post_ids( $inner_blocks ) {
1107      $post_ids = array_map( 'block_core_navigation_from_block_get_post_ids', iterator_to_array( $inner_blocks ) );
1108      return array_unique( array_merge( ...$post_ids ) );
1109  }
1110  
1111  /**
1112   * Get post IDs from a navigation link block instance.
1113   *
1114   * @since 6.0.0
1115   *
1116   * @param WP_Block $block Instance of a block.
1117   *
1118   * @return array Array of post IDs.
1119   */
1120  function block_core_navigation_from_block_get_post_ids( $block ) {
1121      $post_ids = array();
1122  
1123      if ( $block->inner_blocks ) {
1124          $post_ids = block_core_navigation_get_post_ids( $block->inner_blocks );
1125      }
1126  
1127      if ( 'core/navigation-link' === $block->name || 'core/navigation-submenu' === $block->name ) {
1128          if ( $block->attributes && isset( $block->attributes['kind'] ) && 'post-type' === $block->attributes['kind'] && isset( $block->attributes['id'] ) ) {
1129              $post_ids[] = $block->attributes['id'];
1130          }
1131      }
1132  
1133      return $post_ids;
1134  }
1135  
1136  /**
1137   * Renders the `core/navigation` block on server.
1138   *
1139   * @since 5.9.0
1140   *
1141   * @param array    $attributes The block attributes.
1142   * @param string   $content    The saved content.
1143   * @param WP_Block $block      The parsed block.
1144   *
1145   * @return string Returns the navigation block markup.
1146   */
1147  function render_block_core_navigation( $attributes, $content, $block ) {
1148      return WP_Navigation_Block_Renderer::render( $attributes, $content, $block );
1149  }
1150  
1151  /**
1152   * Register the navigation block.
1153   *
1154   * @since 5.9.0
1155   *
1156   * @uses render_block_core_navigation()
1157   * @throws WP_Error An WP_Error exception parsing the block definition.
1158   */
1159  function register_block_core_navigation() {
1160      register_block_type_from_metadata(
1161          __DIR__ . '/navigation',
1162          array(
1163              'render_callback' => 'render_block_core_navigation',
1164          )
1165      );
1166  }
1167  
1168  add_action( 'init', 'register_block_core_navigation' );
1169  
1170  /**
1171   * Filter that changes the parsed attribute values of navigation blocks contain typographic presets to contain the values directly.
1172   *
1173   * @since 5.9.0
1174   *
1175   * @param array $parsed_block The block being rendered.
1176   *
1177   * @return array The block being rendered without typographic presets.
1178   */
1179  function block_core_navigation_typographic_presets_backcompatibility( $parsed_block ) {
1180      if ( 'core/navigation' === $parsed_block['blockName'] ) {
1181          $attribute_to_prefix_map = array(
1182              'fontStyle'      => 'var:preset|font-style|',
1183              'fontWeight'     => 'var:preset|font-weight|',
1184              'textDecoration' => 'var:preset|text-decoration|',
1185              'textTransform'  => 'var:preset|text-transform|',
1186          );
1187          foreach ( $attribute_to_prefix_map as $style_attribute => $prefix ) {
1188              if ( ! empty( $parsed_block['attrs']['style']['typography'][ $style_attribute ] ) ) {
1189                  $prefix_len      = strlen( $prefix );
1190                  $attribute_value = &$parsed_block['attrs']['style']['typography'][ $style_attribute ];
1191                  if ( 0 === strncmp( $attribute_value, $prefix, $prefix_len ) ) {
1192                      $attribute_value = substr( $attribute_value, $prefix_len );
1193                  }
1194                  if ( 'textDecoration' === $style_attribute && 'strikethrough' === $attribute_value ) {
1195                      $attribute_value = 'line-through';
1196                  }
1197              }
1198          }
1199      }
1200  
1201      return $parsed_block;
1202  }
1203  
1204  add_filter( 'render_block_data', 'block_core_navigation_typographic_presets_backcompatibility' );
1205  
1206  /**
1207   * Turns menu item data into a nested array of parsed blocks
1208   *
1209   * @since 5.9.0
1210   *
1211   * @deprecated 6.3.0 Use WP_Navigation_Fallback::parse_blocks_from_menu_items() instead.
1212   *
1213   * @param array $menu_items               An array of menu items that represent
1214   *                                        an individual level of a menu.
1215   * @param array $menu_items_by_parent_id  An array keyed by the id of the
1216   *                                        parent menu where each element is an
1217   *                                        array of menu items that belong to
1218   *                                        that parent.
1219   * @return array An array of parsed block data.
1220   */
1221  function block_core_navigation_parse_blocks_from_menu_items( $menu_items, $menu_items_by_parent_id ) {
1222  
1223      _deprecated_function( __FUNCTION__, '6.3.0', 'WP_Navigation_Fallback::parse_blocks_from_menu_items' );
1224  
1225      if ( empty( $menu_items ) ) {
1226          return array();
1227      }
1228  
1229      $blocks = array();
1230  
1231      foreach ( $menu_items as $menu_item ) {
1232          $class_name       = ! empty( $menu_item->classes ) ? implode( ' ', (array) $menu_item->classes ) : null;
1233          $id               = ( null !== $menu_item->object_id && 'custom' !== $menu_item->object ) ? $menu_item->object_id : null;
1234          $opens_in_new_tab = null !== $menu_item->target && '_blank' === $menu_item->target;
1235          $rel              = ( null !== $menu_item->xfn && '' !== $menu_item->xfn ) ? $menu_item->xfn : null;
1236          $kind             = null !== $menu_item->type ? str_replace( '_', '-', $menu_item->type ) : 'custom';
1237  
1238          $block = array(
1239              'blockName' => isset( $menu_items_by_parent_id[ $menu_item->ID ] ) ? 'core/navigation-submenu' : 'core/navigation-link',
1240              'attrs'     => array(
1241                  'className'     => $class_name,
1242                  'description'   => $menu_item->description,
1243                  'id'            => $id,
1244                  'kind'          => $kind,
1245                  'label'         => $menu_item->title,
1246                  'opensInNewTab' => $opens_in_new_tab,
1247                  'rel'           => $rel,
1248                  'title'         => $menu_item->attr_title,
1249                  'type'          => $menu_item->object,
1250                  'url'           => $menu_item->url,
1251              ),
1252          );
1253  
1254          $block['innerBlocks']  = isset( $menu_items_by_parent_id[ $menu_item->ID ] )
1255              ? block_core_navigation_parse_blocks_from_menu_items( $menu_items_by_parent_id[ $menu_item->ID ], $menu_items_by_parent_id )
1256              : array();
1257          $block['innerContent'] = array_map( 'serialize_block', $block['innerBlocks'] );
1258  
1259          $blocks[] = $block;
1260      }
1261  
1262      return $blocks;
1263  }
1264  
1265  /**
1266   * Get the classic navigation menu to use as a fallback.
1267   *
1268   * @since 6.2.0
1269   *
1270   * @deprecated 6.3.0 Use WP_Navigation_Fallback::get_classic_menu_fallback() instead.
1271   *
1272   * @return object WP_Term The classic navigation.
1273   */
1274  function block_core_navigation_get_classic_menu_fallback() {
1275  
1276      _deprecated_function( __FUNCTION__, '6.3.0', 'WP_Navigation_Fallback::get_classic_menu_fallback' );
1277  
1278      $classic_nav_menus = wp_get_nav_menus();
1279  
1280      // If menus exist.
1281      if ( $classic_nav_menus && ! is_wp_error( $classic_nav_menus ) ) {
1282          // Handles simple use case where user has a classic menu and switches to a block theme.
1283  
1284          // Returns the menu assigned to location `primary`.
1285          $locations = get_nav_menu_locations();
1286          if ( isset( $locations['primary'] ) ) {
1287              $primary_menu = wp_get_nav_menu_object( $locations['primary'] );
1288              if ( $primary_menu ) {
1289                  return $primary_menu;
1290              }
1291          }
1292  
1293          // Returns a menu if `primary` is its slug.
1294          foreach ( $classic_nav_menus as $classic_nav_menu ) {
1295              if ( 'primary' === $classic_nav_menu->slug ) {
1296                  return $classic_nav_menu;
1297              }
1298          }
1299  
1300          // Otherwise return the most recently created classic menu.
1301          usort(
1302              $classic_nav_menus,
1303              static function ( $a, $b ) {
1304                  return $b->term_id - $a->term_id;
1305              }
1306          );
1307          return $classic_nav_menus[0];
1308      }
1309  }
1310  
1311  /**
1312   * Converts a classic navigation to blocks.
1313   *
1314   * @since 6.2.0
1315   *
1316   * @deprecated 6.3.0 Use WP_Navigation_Fallback::get_classic_menu_fallback_blocks() instead.
1317   *
1318   * @param  object $classic_nav_menu WP_Term The classic navigation object to convert.
1319   * @return array the normalized parsed blocks.
1320   */
1321  function block_core_navigation_get_classic_menu_fallback_blocks( $classic_nav_menu ) {
1322  
1323      _deprecated_function( __FUNCTION__, '6.3.0', 'WP_Navigation_Fallback::get_classic_menu_fallback_blocks' );
1324  
1325      // BEGIN: Code that already exists in wp_nav_menu().
1326      $menu_items = wp_get_nav_menu_items( $classic_nav_menu->term_id, array( 'update_post_term_cache' => false ) );
1327  
1328      // Set up the $menu_item variables.
1329      _wp_menu_item_classes_by_context( $menu_items );
1330  
1331      $sorted_menu_items = array();
1332      foreach ( (array) $menu_items as $menu_item ) {
1333          $sorted_menu_items[ $menu_item->menu_order ] = $menu_item;
1334      }
1335  
1336      unset( $menu_items, $menu_item );
1337  
1338      // END: Code that already exists in wp_nav_menu().
1339  
1340      $menu_items_by_parent_id = array();
1341      foreach ( $sorted_menu_items as $menu_item ) {
1342          $menu_items_by_parent_id[ $menu_item->menu_item_parent ][] = $menu_item;
1343      }
1344  
1345      $inner_blocks = block_core_navigation_parse_blocks_from_menu_items(
1346          isset( $menu_items_by_parent_id[0] )
1347              ? $menu_items_by_parent_id[0]
1348              : array(),
1349          $menu_items_by_parent_id
1350      );
1351  
1352      return serialize_blocks( $inner_blocks );
1353  }
1354  
1355  /**
1356   * If there's a classic menu then use it as a fallback.
1357   *
1358   * @since 6.2.0
1359   *
1360   * @deprecated 6.3.0 Use WP_Navigation_Fallback::create_classic_menu_fallback() instead.
1361   *
1362   * @return array the normalized parsed blocks.
1363   */
1364  function block_core_navigation_maybe_use_classic_menu_fallback() {
1365  
1366      _deprecated_function( __FUNCTION__, '6.3.0', 'WP_Navigation_Fallback::create_classic_menu_fallback' );
1367  
1368      // See if we have a classic menu.
1369      $classic_nav_menu = block_core_navigation_get_classic_menu_fallback();
1370  
1371      if ( ! $classic_nav_menu ) {
1372          return;
1373      }
1374  
1375      // If we have a classic menu then convert it to blocks.
1376      $classic_nav_menu_blocks = block_core_navigation_get_classic_menu_fallback_blocks( $classic_nav_menu );
1377  
1378      if ( empty( $classic_nav_menu_blocks ) ) {
1379          return;
1380      }
1381  
1382      // Create a new navigation menu from the classic menu.
1383      $wp_insert_post_result = wp_insert_post(
1384          array(
1385              'post_content' => $classic_nav_menu_blocks,
1386              'post_title'   => $classic_nav_menu->name,
1387              'post_name'    => $classic_nav_menu->slug,
1388              'post_status'  => 'publish',
1389              'post_type'    => 'wp_navigation',
1390          ),
1391          true // So that we can check whether the result is an error.
1392      );
1393  
1394      if ( is_wp_error( $wp_insert_post_result ) ) {
1395          return;
1396      }
1397  
1398      // Fetch the most recently published navigation which will be the classic one created above.
1399      return block_core_navigation_get_most_recently_published_navigation();
1400  }
1401  
1402  /**
1403   * Finds the most recently published `wp_navigation` Post.
1404   *
1405   * @since 6.1.0
1406   *
1407   * @deprecated 6.3.0 Use WP_Navigation_Fallback::get_most_recently_published_navigation() instead.
1408   *
1409   * @return WP_Post|null the first non-empty Navigation or null.
1410   */
1411  function block_core_navigation_get_most_recently_published_navigation() {
1412  
1413      _deprecated_function( __FUNCTION__, '6.3.0', 'WP_Navigation_Fallback::get_most_recently_published_navigation' );
1414  
1415      // Default to the most recently created menu.
1416      $parsed_args = array(
1417          'post_type'              => 'wp_navigation',
1418          'no_found_rows'          => true,
1419          'update_post_meta_cache' => false,
1420          'update_post_term_cache' => false,
1421          'order'                  => 'DESC',
1422          'orderby'                => 'date',
1423          'post_status'            => 'publish',
1424          'posts_per_page'         => 1, // get only the most recent.
1425      );
1426  
1427      $navigation_post = new WP_Query( $parsed_args );
1428      if ( count( $navigation_post->posts ) > 0 ) {
1429          return $navigation_post->posts[0];
1430      }
1431  
1432      return null;
1433  }
1434  
1435  /**
1436   * Accepts the serialized markup of a block and its inner blocks, and returns serialized markup of the inner blocks.
1437   *
1438   * @since 6.5.0
1439   *
1440   * @param string $serialized_block The serialized markup of a block and its inner blocks.
1441   * @return string
1442   */
1443  function block_core_navigation_remove_serialized_parent_block( $serialized_block ) {
1444      $start = strpos( $serialized_block, '-->' ) + strlen( '-->' );
1445      $end   = strrpos( $serialized_block, '<!--' );
1446      return substr( $serialized_block, $start, $end - $start );
1447  }
1448  
1449  /**
1450   * Mock a parsed block for the Navigation block given its inner blocks and the `wp_navigation` post object.
1451   * The `wp_navigation` post's `_wp_ignored_hooked_blocks` meta is queried to add the `metadata.ignoredHookedBlocks` attribute.
1452   *
1453   * @since 6.5.0
1454   *
1455   * @param array   $inner_blocks Parsed inner blocks of a Navigation block.
1456   * @param WP_Post $post         `wp_navigation` post object corresponding to the block.
1457   *
1458   * @return array the normalized parsed blocks.
1459   */
1460  function block_core_navigation_mock_parsed_block( $inner_blocks, $post ) {
1461      $attributes = array();
1462  
1463      if ( isset( $post->ID ) ) {
1464          $ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1465          if ( ! empty( $ignored_hooked_blocks ) ) {
1466              $ignored_hooked_blocks  = json_decode( $ignored_hooked_blocks, true );
1467              $attributes['metadata'] = array(
1468                  'ignoredHookedBlocks' => $ignored_hooked_blocks,
1469              );
1470          }
1471      }
1472  
1473      $mock_anchor_parent_block = array(
1474          'blockName'    => 'core/navigation',
1475          'attrs'        => $attributes,
1476          'innerBlocks'  => $inner_blocks,
1477          'innerContent' => array_fill( 0, count( $inner_blocks ), null ),
1478      );
1479  
1480      return $mock_anchor_parent_block;
1481  }
1482  
1483  /**
1484   * Insert hooked blocks into a Navigation block.
1485   *
1486   * Given a Navigation block's inner blocks and its corresponding `wp_navigation` post object,
1487   * this function inserts hooked blocks into it, and returns the serialized inner blocks in a
1488   * mock Navigation block wrapper.
1489   *
1490   * If there are any hooked blocks that need to be inserted as the Navigation block's first or last
1491   * children, the `wp_navigation` post's `_wp_ignored_hooked_blocks` meta is checked to see if any
1492   * of those hooked blocks should be exempted from insertion.
1493   *
1494   * @since 6.5.0
1495   *
1496   * @param array   $inner_blocks Parsed inner blocks of a Navigation block.
1497   * @param WP_Post $post         `wp_navigation` post object corresponding to the block.
1498   * @return string Serialized inner blocks in mock Navigation block wrapper, with hooked blocks inserted, if any.
1499   */
1500  function block_core_navigation_insert_hooked_blocks( $inner_blocks, $post ) {
1501      $mock_navigation_block = block_core_navigation_mock_parsed_block( $inner_blocks, $post );
1502  
1503      if ( function_exists( 'apply_block_hooks_to_content' ) ) {
1504          $mock_navigation_block_markup = serialize_block( $mock_navigation_block );
1505          return apply_block_hooks_to_content( $mock_navigation_block_markup, $post, 'insert_hooked_blocks' );
1506      }
1507  
1508      $hooked_blocks        = get_hooked_blocks();
1509      $before_block_visitor = null;
1510      $after_block_visitor  = null;
1511  
1512      if ( ! empty( $hooked_blocks ) || has_filter( 'hooked_block_types' ) ) {
1513          $before_block_visitor = make_before_block_visitor( $hooked_blocks, $post, 'insert_hooked_blocks' );
1514          $after_block_visitor  = make_after_block_visitor( $hooked_blocks, $post, 'insert_hooked_blocks' );
1515      }
1516  
1517      return traverse_and_serialize_block( $mock_navigation_block, $before_block_visitor, $after_block_visitor );
1518  }
1519  
1520  /**
1521   * Insert ignoredHookedBlocks meta into the Navigation block and its inner blocks.
1522   *
1523   * Given a Navigation block's inner blocks and its corresponding `wp_navigation` post object,
1524   * this function inserts ignoredHookedBlocks meta into it, and returns the serialized inner blocks in a
1525   * mock Navigation block wrapper.
1526   *
1527   * @since 6.5.0
1528   *
1529   * @param array   $inner_blocks Parsed inner blocks of a Navigation block.
1530   * @param WP_Post $post         `wp_navigation` post object corresponding to the block.
1531   * @return string Serialized inner blocks in mock Navigation block wrapper, with hooked blocks inserted, if any.
1532   */
1533  function block_core_navigation_set_ignored_hooked_blocks_metadata( $inner_blocks, $post ) {
1534      $mock_navigation_block = block_core_navigation_mock_parsed_block( $inner_blocks, $post );
1535      $hooked_blocks         = get_hooked_blocks();
1536      $before_block_visitor  = null;
1537      $after_block_visitor   = null;
1538  
1539      if ( ! empty( $hooked_blocks ) || has_filter( 'hooked_block_types' ) ) {
1540          $before_block_visitor = make_before_block_visitor( $hooked_blocks, $post, 'set_ignored_hooked_blocks_metadata' );
1541          $after_block_visitor  = make_after_block_visitor( $hooked_blocks, $post, 'set_ignored_hooked_blocks_metadata' );
1542      }
1543  
1544      return traverse_and_serialize_block( $mock_navigation_block, $before_block_visitor, $after_block_visitor );
1545  }
1546  
1547  /**
1548   * Updates the post meta with the list of ignored hooked blocks when the navigation is created or updated via the REST API.
1549   *
1550   * @access private
1551   * @since 6.5.0
1552   *
1553   * @param stdClass $post Post object.
1554   * @return stdClass The updated post object.
1555   */
1556  function block_core_navigation_update_ignore_hooked_blocks_meta( $post ) {
1557      /*
1558       * In this scenario the user has likely tried to create a navigation via the REST API.
1559       * In which case we won't have a post ID to work with and store meta against.
1560       */
1561      if ( empty( $post->ID ) ) {
1562          return $post;
1563      }
1564  
1565      /**
1566       * Skip meta generation when consumers intentionally update specific Navigation fields
1567       * and omit the content update.
1568       */
1569      if ( ! isset( $post->post_content ) ) {
1570          return $post;
1571      }
1572  
1573      /*
1574       * We run the Block Hooks mechanism to inject the `metadata.ignoredHookedBlocks` attribute into
1575       * all anchor blocks. For the root level, we create a mock Navigation and extract them from there.
1576       */
1577      $blocks = parse_blocks( $post->post_content );
1578  
1579      /*
1580       * Block Hooks logic requires a `WP_Post` object (rather than the `stdClass` with the updates that
1581       * we're getting from the `rest_pre_insert_wp_navigation` filter) as its second argument (to be
1582       * used as context for hooked blocks insertion).
1583       * We thus have to look it up from the DB,based on `$post->ID`.
1584       */
1585      $markup = block_core_navigation_set_ignored_hooked_blocks_metadata( $blocks, get_post( $post->ID ) );
1586  
1587      $root_nav_block        = parse_blocks( $markup )[0];
1588      $ignored_hooked_blocks = isset( $root_nav_block['attrs']['metadata']['ignoredHookedBlocks'] )
1589          ? $root_nav_block['attrs']['metadata']['ignoredHookedBlocks']
1590          : array();
1591  
1592      if ( ! empty( $ignored_hooked_blocks ) ) {
1593          $existing_ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1594          if ( ! empty( $existing_ignored_hooked_blocks ) ) {
1595              $existing_ignored_hooked_blocks = json_decode( $existing_ignored_hooked_blocks, true );
1596              $ignored_hooked_blocks          = array_unique( array_merge( $ignored_hooked_blocks, $existing_ignored_hooked_blocks ) );
1597          }
1598          update_post_meta( $post->ID, '_wp_ignored_hooked_blocks', json_encode( $ignored_hooked_blocks ) );
1599      }
1600  
1601      $post->post_content = block_core_navigation_remove_serialized_parent_block( $markup );
1602      return $post;
1603  }
1604  
1605  /*
1606   * Before adding our filter, we verify if it's already added in Core.
1607   * However, during the build process, Gutenberg automatically prefixes our functions with "gutenberg_".
1608   * Therefore, we concatenate the Core's function name to circumvent this prefix for our check.
1609   */
1610  $rest_insert_wp_navigation_core_callback = 'block_core_navigation_' . 'update_ignore_hooked_blocks_meta'; // phpcs:ignore Generic.Strings.UnnecessaryStringConcat.Found
1611  
1612  /*
1613   * Do not add the `block_core_navigation_update_ignore_hooked_blocks_meta` filter in the following cases:
1614   * - If Core has added the `update_ignored_hooked_blocks_postmeta` filter already (WP >= 6.6);
1615   * - or if the `$rest_insert_wp_navigation_core_callback` filter has already been added.
1616   */
1617  if (
1618      ! has_filter( 'rest_pre_insert_wp_navigation', 'update_ignored_hooked_blocks_postmeta' ) &&
1619      ! has_filter( 'rest_pre_insert_wp_navigation', $rest_insert_wp_navigation_core_callback )
1620  ) {
1621      add_filter( 'rest_pre_insert_wp_navigation', 'block_core_navigation_update_ignore_hooked_blocks_meta' );
1622  }
1623  
1624  /**
1625   * Hooks into the REST API response for the core/navigation block and adds the first and last inner blocks.
1626   *
1627   * @since 6.5.0
1628   *
1629   * @param WP_REST_Response $response The response object.
1630   * @param WP_Post          $post     Post object.
1631   * @return WP_REST_Response The response object.
1632   */
1633  function block_core_navigation_insert_hooked_blocks_into_rest_response( $response, $post ) {
1634      if ( ! isset( $response->data['content']['raw'] ) || ! isset( $response->data['content']['rendered'] ) ) {
1635          return $response;
1636      }
1637      $parsed_blocks = parse_blocks( $response->data['content']['raw'] );
1638      $content       = block_core_navigation_insert_hooked_blocks( $parsed_blocks, $post );
1639  
1640      // Remove mock Navigation block wrapper.
1641      $content = block_core_navigation_remove_serialized_parent_block( $content );
1642  
1643      $response->data['content']['raw'] = $content;
1644  
1645      /** This filter is documented in wp-includes/post-template.php */
1646      $response->data['content']['rendered'] = apply_filters( 'the_content', $content );
1647  
1648      return $response;
1649  }
1650  
1651  /*
1652   *  Before adding our filter, we verify if it's already added in Core.
1653   * However, during the build process, Gutenberg automatically prefixes our functions with "gutenberg_".
1654   * Therefore, we concatenate the Core's function name to circumvent this prefix for our check.
1655   */
1656  $rest_prepare_wp_navigation_core_callback = 'block_core_navigation_' . 'insert_hooked_blocks_into_rest_response';
1657  
1658  /*
1659   * Do not add the `block_core_navigation_insert_hooked_blocks_into_rest_response` filter in the following cases:
1660   * - If Core has added the `insert_hooked_blocks_into_rest_response` filter already (WP >= 6.6);
1661   * - or if the `$rest_prepare_wp_navigation_core_callback` filter has already been added.
1662   */
1663  if (
1664      ! has_filter( 'rest_prepare_wp_navigation', 'insert_hooked_blocks_into_rest_response' ) &&
1665      ! has_filter( 'rest_prepare_wp_navigation', $rest_prepare_wp_navigation_core_callback )
1666  ) {
1667      add_filter( 'rest_prepare_wp_navigation', 'block_core_navigation_insert_hooked_blocks_into_rest_response', 10, 3 );
1668  }


Generated : Tue Dec 24 08:20:01 2024 Cross-referenced by PHPXref