[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-admin/js/ -> nav-menu.js (source)

   1  /**
   2   * WordPress Administration Navigation Menu
   3   * Interface JS functions
   4   *
   5   * @version 2.0.0
   6   *
   7   * @package WordPress
   8   * @output wp-admin/js/nav-menu.js
   9   */
  10  
  11  /* global menus, postboxes, columns, isRtl, ajaxurl, wpNavMenu */
  12  
  13  /**
  14   * @param {JQueryStatic} $ The jQuery object.
  15   */
  16  (function($) {
  17  
  18      var api;
  19  
  20      /**
  21       * Contains all the functions to handle WordPress navigation menus administration.
  22       *
  23       * @namespace wpNavMenu
  24       */
  25      api = window.wpNavMenu = {
  26  
  27          options : {
  28              menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
  29              globalMaxDepth:  11,
  30              sortableItems:   '> *',
  31              targetTolerance: 0
  32          },
  33  
  34          menuList : undefined,    // Set in init.
  35          targetList : undefined, // Set in init.
  36          menusChanged : false,
  37          isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
  38          negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
  39          lastSearch: '',
  40  
  41          // Functions that run on init.
  42          init : function() {
  43              api.menuList = $('#menu-to-edit');
  44              api.targetList = api.menuList;
  45  
  46              this.jQueryExtensions();
  47  
  48              this.attachMenuEditListeners();
  49  
  50              this.attachBulkSelectButtonListeners();
  51              this.attachMenuCheckBoxListeners();
  52              this.attachMenuItemDeleteButton();
  53              this.attachPendingMenuItemsListForDeletion();
  54  
  55              this.attachQuickSearchListeners();
  56              this.attachThemeLocationsListeners();
  57              this.attachMenuSaveSubmitListeners();
  58  
  59              this.attachTabsPanelListeners();
  60  
  61              this.attachUnsavedChangesListener();
  62  
  63              if ( api.menuList.length )
  64                  this.initSortables();
  65  
  66              if ( menus.oneThemeLocationNoMenus )
  67                  $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom );
  68  
  69              this.initManageLocations();
  70  
  71              this.initAccessibility();
  72  
  73              this.initToggles();
  74  
  75              this.initPreviewing();
  76          },
  77  
  78          jQueryExtensions : function() {
  79              // jQuery extensions.
  80              $.fn.extend({
  81                  menuItemDepth : function() {
  82                      var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
  83                      return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
  84                  },
  85                  updateDepthClass : function(current, prev) {
  86                      return this.each(function(){
  87                          var t = $(this);
  88                          prev = prev || t.menuItemDepth();
  89                          $(this).removeClass('menu-item-depth-'+ prev )
  90                              .addClass('menu-item-depth-'+ current );
  91                      });
  92                  },
  93                  shiftDepthClass : function(change) {
  94                      return this.each(function(){
  95                          var t = $(this),
  96                              depth = t.menuItemDepth(),
  97                              newDepth = depth + change;
  98  
  99                          t.removeClass( 'menu-item-depth-'+ depth )
 100                              .addClass( 'menu-item-depth-'+ ( newDepth ) );
 101  
 102                          if ( 0 === newDepth ) {
 103                              t.find( '.is-submenu' ).hide();
 104                          }
 105                      });
 106                  },
 107                  childMenuItems : function() {
 108                      var result = $();
 109                      this.each(function(){
 110                          var t = $(this), depth = t.menuItemDepth(), next = t.next( '.menu-item' );
 111                          while( next.length && next.menuItemDepth() > depth ) {
 112                              result = result.add( next );
 113                              next = next.next( '.menu-item' );
 114                          }
 115                      });
 116                      return result;
 117                  },
 118                  shiftHorizontally : function( dir ) {
 119                      return this.each(function(){
 120                          var t = $(this),
 121                              depth = t.menuItemDepth(),
 122                              newDepth = depth + dir;
 123  
 124                          // Change .menu-item-depth-n class.
 125                          t.moveHorizontally( newDepth, depth );
 126                      });
 127                  },
 128                  moveHorizontally : function( newDepth, depth ) {
 129                      return this.each(function(){
 130                          var t = $(this),
 131                              children = t.childMenuItems(),
 132                              diff = newDepth - depth,
 133                              subItemText = t.find('.is-submenu');
 134  
 135                          // Change .menu-item-depth-n class.
 136                          t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId();
 137  
 138                          // If it has children, move those too.
 139                          if ( children ) {
 140                              children.each(function() {
 141                                  var t = $(this),
 142                                      thisDepth = t.menuItemDepth(),
 143                                      newDepth = thisDepth + diff;
 144                                  t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId();
 145                              });
 146                          }
 147  
 148                          // Show "Sub item" helper text.
 149                          if (0 === newDepth)
 150                              subItemText.hide();
 151                          else
 152                              subItemText.show();
 153                      });
 154                  },
 155                  updateParentMenuItemDBId : function() {
 156                      return this.each(function(){
 157                          var item = $(this),
 158                              input = item.find( '.menu-item-data-parent-id' ),
 159                              depth = parseInt( item.menuItemDepth(), 10 ),
 160                              parentDepth = depth - 1,
 161                              parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first();
 162  
 163                          if ( 0 === depth ) { // Item is on the top level, has no parent.
 164                              input.val(0);
 165                          } else { // Find the parent item, and retrieve its object id.
 166                              input.val( parent.find( '.menu-item-data-db-id' ).val() );
 167                          }
 168                      });
 169                  },
 170                  hideAdvancedMenuItemFields : function() {
 171                      return this.each(function(){
 172                          var that = $(this);
 173                          $('.hide-column-tog').not(':checked').each(function(){
 174                              that.find('.field-' + $(this).val() ).addClass('hidden-field');
 175                          });
 176                      });
 177                  },
 178                  /**
 179                   * Adds selected menu items to the menu.
 180                   *
 181                   * @ignore
 182                   *
 183                   * @param {Function} processMethod The method to use for adding the menu items. Defaults to api.addMenuItemToBottom.
 184                   */
 185                  addSelectedToMenu : function(processMethod) {
 186                      if ( 0 === $('#menu-to-edit').length ) {
 187                          return false;
 188                      }
 189  
 190                      return this.each(function() {
 191                          var t = $(this), menuItems = {},
 192                              checkboxes = ( menus.oneThemeLocationNoMenus && 0 === t.find( '.tabs-panel-active .categorychecklist li input:checked' ).length ) ? t.find( '#page-all li input[type="checkbox"]' ) : t.find( '.tabs-panel-active .categorychecklist li input:checked' ),
 193                              re = /menu-item\[([^\]]*)/;
 194  
 195                          processMethod = processMethod || api.addMenuItemToBottom;
 196  
 197                          // If no items are checked, bail.
 198                          if ( !checkboxes.length )
 199                              return false;
 200  
 201                          // Show the Ajax spinner.
 202                          t.find( '.button-controls .spinner' ).addClass( 'is-active' );
 203  
 204                          // Retrieve menu item data.
 205                          $(checkboxes).each(function(){
 206                              var t = $(this),
 207                                  listItemDBIDMatch = re.exec( t.attr('name') ),
 208                                  listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
 209  
 210                              if ( this.className && -1 != this.className.indexOf('add-to-top') )
 211                                  processMethod = api.addMenuItemToTop;
 212                              menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
 213                          });
 214  
 215                          // Add the items.
 216                          api.addItemToMenu(menuItems, processMethod, function(){
 217                              // Deselect the items and hide the Ajax spinner.
 218                              checkboxes.prop( 'checked', false );
 219                              t.find( '.button-controls .select-all' ).prop( 'checked', false );
 220                              t.find( '.button-controls .spinner' ).removeClass( 'is-active' );
 221                              t.updateParentDropdown();
 222                              t.updateOrderDropdown();
 223                          });
 224                      });
 225                  },
 226                  getItemData : function( itemType, id ) {
 227                      itemType = itemType || 'menu-item';
 228  
 229                      var itemData = {}, i,
 230                      fields = [
 231                          'menu-item-db-id',
 232                          'menu-item-object-id',
 233                          'menu-item-object',
 234                          'menu-item-parent-id',
 235                          'menu-item-position',
 236                          'menu-item-type',
 237                          'menu-item-title',
 238                          'menu-item-url',
 239                          'menu-item-description',
 240                          'menu-item-attr-title',
 241                          'menu-item-target',
 242                          'menu-item-classes',
 243                          'menu-item-xfn'
 244                      ];
 245  
 246                      if( !id && itemType == 'menu-item' ) {
 247                          id = this.find('.menu-item-data-db-id').val();
 248                      }
 249  
 250                      if( !id ) return itemData;
 251  
 252                      this.find('input').each(function() {
 253                          var field;
 254                          i = fields.length;
 255                          while ( i-- ) {
 256                              if( itemType == 'menu-item' )
 257                                  field = fields[i] + '[' + id + ']';
 258                              else if( itemType == 'add-menu-item' )
 259                                  field = 'menu-item[' + id + '][' + fields[i] + ']';
 260  
 261                              if (
 262                                  this.name &&
 263                                  field == this.name
 264                              ) {
 265                                  itemData[fields[i]] = this.value;
 266                              }
 267                          }
 268                      });
 269  
 270                      return itemData;
 271                  },
 272                  setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
 273                      itemType = itemType || 'menu-item';
 274  
 275                      if( !id && itemType == 'menu-item' ) {
 276                          id = $('.menu-item-data-db-id', this).val();
 277                      }
 278  
 279                      if( !id ) return this;
 280  
 281                      this.find('input').each(function() {
 282                          var t = $(this), field;
 283                          $.each( itemData, function( attr, val ) {
 284                              if( itemType == 'menu-item' )
 285                                  field = attr + '[' + id + ']';
 286                              else if( itemType == 'add-menu-item' )
 287                                  field = 'menu-item[' + id + '][' + attr + ']';
 288  
 289                              if ( field == t.attr('name') ) {
 290                                  t.val( val );
 291                              }
 292                          });
 293                      });
 294                      return this;
 295                  },
 296                  updateParentDropdown : function() {
 297                      return this.each(function(){
 298                          var menuItems = $( '#menu-to-edit li' ),
 299                              parentDropdowns = $( '.edit-menu-item-parent' );
 300  
 301                          $.each( parentDropdowns, function() {
 302                              var parentDropdown = $( this ),
 303                                  currentItemID = parseInt( parentDropdown.closest( 'li.menu-item' ).find( '.menu-item-data-db-id' ).val() ),
 304                                  currentParentID = parseInt( parentDropdown.closest( 'li.menu-item' ).find( '.menu-item-data-parent-id' ).val() ),
 305                                  currentItem = parentDropdown.closest( 'li.menu-item' ),
 306                                  currentMenuItemChild = currentItem.childMenuItems(),
 307                                  excludeMenuItem =  /** @type {number[]} */ [ currentItemID ];
 308  
 309                              parentDropdown.empty();
 310  
 311                              if ( currentMenuItemChild.length > 0 ) {
 312                                  $.each( currentMenuItemChild, function(){
 313                                      var childItem = $(this),
 314                                          childID = parseInt( childItem.find( '.menu-item-data-db-id' ).val() );
 315  
 316                                      excludeMenuItem.push( childID );
 317                                  });
 318                              }
 319  
 320                              parentDropdown.append(
 321                                  $( '<option>', {
 322                                      value: '0',
 323                                      selected: currentParentID === 0,
 324                                      text: wp.i18n._x( 'No Parent', 'menu item without a parent in navigation menu' ),
 325                                  } )
 326                              );
 327  
 328                              $.each( menuItems, function() {
 329                                  var menuItem = $(this),
 330                                  menuID = parseInt( menuItem.find( '.menu-item-data-db-id' ).val() ),
 331                                  menuTitle = menuItem.find( '.edit-menu-item-title' ).val();
 332  
 333                                  if ( ! excludeMenuItem.includes( menuID ) ) {
 334                                      parentDropdown.append(
 335                                          $( '<option>', {
 336                                              value: menuID.toString(),
 337                                              selected: currentParentID === menuID,
 338                                              text: menuTitle,
 339                                          } )
 340                                      );
 341                                  }
 342                              });
 343                          });
 344  
 345                      });
 346                  },
 347                  updateOrderDropdown : function() {
 348                      return this.each( function() {
 349                          var itemPosition,
 350                              orderDropdowns = $( '.edit-menu-item-order' );
 351  
 352                          $.each( orderDropdowns, function() {
 353                              var orderDropdown = $( this ),
 354                                  menuItem = orderDropdown.closest( 'li.menu-item' ).first(),
 355                                  depth = menuItem.menuItemDepth(),
 356                                  isPrimaryMenuItem = ( 0 === depth );
 357  
 358                              orderDropdown.empty();
 359  
 360                              if ( isPrimaryMenuItem ) {
 361                                  var primaryItems = $( '.menu-item-depth-0' ),
 362                                      totalMenuItems = primaryItems.length;
 363  
 364                                  itemPosition = primaryItems.index( menuItem ) + 1;
 365  
 366                                  for ( let i = 1; i < totalMenuItems + 1; i++ ) {
 367                                      var itemString = wp.i18n.sprintf(
 368                                          /* translators: 1: The current menu item number, 2: The total number of menu items. */
 369                                          wp.i18n._x( '%1$s of %2$s', 'part of a total number of menu items' ),
 370                                          i,
 371                                          totalMenuItems
 372                                      );
 373                                      orderDropdown.append(
 374                                          $( '<option>', {
 375                                              selected: i === itemPosition,
 376                                              value: i.toString(),
 377                                              text: itemString,
 378                                          } )
 379                                      );
 380                                  }
 381  
 382                              } else {
 383                                  var parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).first(),
 384                                      parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
 385                                      subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
 386                                      totalSubMenuItems = subItems.length;
 387  
 388                                  itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
 389  
 390                                  for ( let i = 1; i < totalSubMenuItems + 1; i++ ) {
 391                                      var submenuString = wp.i18n.sprintf(
 392                                          /* translators: 1: The current submenu item number, 2: The total number of submenu items. */
 393                                          wp.i18n._x( '%1$s of %2$s', 'part of a total number of menu items' ),
 394                                          i,
 395                                          totalSubMenuItems
 396                                      );
 397                                      orderDropdown.append(
 398                                          $( '<option>', {
 399                                              selected: i === itemPosition,
 400                                              value: i.toString(),
 401                                              text: submenuString,
 402                                          } )
 403                                      );
 404                                  }
 405  
 406                              }
 407                          });
 408  
 409                      });
 410                  }
 411              });
 412          },
 413  
 414          countMenuItems : function( depth ) {
 415              return $( '.menu-item-depth-' + depth ).length;
 416          },
 417  
 418          moveMenuItem : function( $this, dir ) {
 419              var items, newItemPosition, newDepth,
 420                  menuItems = $( '#menu-to-edit li' ),
 421                  menuItemsCount = menuItems.length,
 422                  thisItem = $this.parents( 'li.menu-item' ),
 423                  thisItemChildren = thisItem.childMenuItems(),
 424                  thisItemData = thisItem.getItemData(),
 425                  thisItemDepth = parseInt( thisItem.menuItemDepth(), 10 ),
 426                  thisItemPosition = parseInt( thisItem.index(), 10 ),
 427                  nextItem = thisItem.next(),
 428                  nextItemChildren = nextItem.childMenuItems(),
 429                  nextItemDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1,
 430                  prevItem = thisItem.prev(),
 431                  prevItemDepth = parseInt( prevItem.menuItemDepth(), 10 ),
 432                  prevItemId = prevItem.getItemData()['menu-item-db-id'],
 433                  a11ySpeech = menus[ 'moved' + dir.charAt(0).toUpperCase() + dir.slice(1) ];
 434  
 435              switch ( dir ) {
 436              case 'up':
 437                  newItemPosition = thisItemPosition - 1;
 438  
 439                  // Already at top.
 440                  if ( 0 === thisItemPosition )
 441                      break;
 442  
 443                  // If a sub item is moved to top, shift it to 0 depth.
 444                  if ( 0 === newItemPosition && 0 !== thisItemDepth )
 445                      thisItem.moveHorizontally( 0, thisItemDepth );
 446  
 447                  // If prev item is sub item, shift to match depth.
 448                  if ( 0 !== prevItemDepth )
 449                      thisItem.moveHorizontally( prevItemDepth, thisItemDepth );
 450  
 451                  // Does this item have sub items?
 452                  if ( thisItemChildren ) {
 453                      items = thisItem.add( thisItemChildren );
 454                      // Move the entire block.
 455                      items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
 456                  } else {
 457                      thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
 458                  }
 459                  break;
 460              case 'down':
 461                  // Does this item have sub items?
 462                  if ( thisItemChildren ) {
 463                      items = thisItem.add( thisItemChildren ),
 464                          nextItem = menuItems.eq( items.length + thisItemPosition ),
 465                          nextItemChildren = 0 !== nextItem.childMenuItems().length;
 466  
 467                      if ( nextItemChildren ) {
 468                          newDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1;
 469                          thisItem.moveHorizontally( newDepth, thisItemDepth );
 470                      }
 471  
 472                      // Have we reached the bottom?
 473                      if ( menuItemsCount === thisItemPosition + items.length )
 474                          break;
 475  
 476                      items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId();
 477                  } else {
 478                      // If next item has sub items, shift depth.
 479                      if ( 0 !== nextItemChildren.length )
 480                          thisItem.moveHorizontally( nextItemDepth, thisItemDepth );
 481  
 482                      // Have we reached the bottom?
 483                      if ( menuItemsCount === thisItemPosition + 1 )
 484                          break;
 485                      thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId();
 486                  }
 487                  break;
 488              case 'top':
 489                  // Already at top.
 490                  if ( 0 === thisItemPosition )
 491                      break;
 492                  // Does this item have sub items?
 493                  if ( thisItemChildren ) {
 494                      items = thisItem.add( thisItemChildren );
 495                      // Move the entire block.
 496                      items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
 497                  } else {
 498                      thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
 499                  }
 500                  break;
 501              case 'left':
 502                  // As far left as possible.
 503                  if ( 0 === thisItemDepth )
 504                      break;
 505                  thisItem.shiftHorizontally( -1 );
 506                  break;
 507              case 'right':
 508                  // Can't be sub item at top.
 509                  if ( 0 === thisItemPosition )
 510                      break;
 511                  // Already sub item of prevItem.
 512                  if ( thisItemData['menu-item-parent-id'] === prevItemId )
 513                      break;
 514                  thisItem.shiftHorizontally( 1 );
 515                  break;
 516              }
 517              $this.trigger( 'focus' );
 518              api.registerChange();
 519              api.refreshKeyboardAccessibility();
 520              api.refreshAdvancedAccessibility();
 521              thisItem.updateParentDropdown();
 522              thisItem.updateOrderDropdown();
 523  
 524              if ( a11ySpeech ) {
 525                  wp.a11y.speak( a11ySpeech );
 526              }
 527          },
 528  
 529          initAccessibility : function() {
 530              var menu = $( '#menu-to-edit' );
 531  
 532              api.refreshKeyboardAccessibility();
 533              api.refreshAdvancedAccessibility();
 534  
 535              // Refresh the accessibility when the user comes close to the item in any way.
 536              menu.on( 'mouseenter.refreshAccessibility focus.refreshAccessibility touchstart.refreshAccessibility' , '.menu-item' , function(){
 537                  api.refreshAdvancedAccessibilityOfItem( $( this ).find( 'a.item-edit' ) );
 538              } );
 539  
 540              // We have to update on click as well because we might hover first, change the item, and then click.
 541              menu.on( 'click', 'a.item-edit', function() {
 542                  api.refreshAdvancedAccessibilityOfItem( $( this ) );
 543              } );
 544  
 545              // Links for moving items.
 546              menu.on( 'click', '.menus-move', function () {
 547                  var $this = $( this ),
 548                      dir = $this.data( 'dir' );
 549  
 550                  if ( 'undefined' !== typeof dir ) {
 551                      api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), dir );
 552                  }
 553              });
 554  
 555              // Set menu parents data for all menu items.
 556              menu.updateParentDropdown();
 557  
 558              // Set menu order data for all menu items.
 559              menu.updateOrderDropdown();
 560  
 561              // Update menu item parent when value is changed.
 562              menu.on( 'change', '.edit-menu-item-parent', function() {
 563                  api.changeMenuParent( $( this ) );
 564              });
 565  
 566              // Update menu item order when value is changed.
 567              menu.on( 'change', '.edit-menu-item-order', function() {
 568                  api.changeMenuOrder( $( this ) );
 569              });
 570          },
 571  
 572          /**
 573           * changeMenuParent( [parentDropdown] )
 574           *
 575           * @since 6.7.0
 576           *
 577           * @param {Object} parentDropdown select field
 578           */
 579          changeMenuParent : function( parentDropdown ) {
 580              var menuItemNewPosition,
 581                  menuItems = $( '#menu-to-edit li' ),
 582                  $this = $( parentDropdown ),
 583                  newParentID = $this.val(),
 584                  menuItem = $this.closest( 'li.menu-item' ).first(),
 585                  menuItemOldDepth = menuItem.menuItemDepth(),
 586                  menuItemChildren = menuItem.childMenuItems(),
 587                  menuItemNoChildren = parseInt( menuItem.childMenuItems().length, 10 ),
 588                  parentItem = $( '#menu-item-' + newParentID ),
 589                  parentItemDepth = parentItem.menuItemDepth(),
 590                  menuItemNewDepth = parseInt( parentItemDepth ) + 1;
 591  
 592              if ( newParentID == 0 ) {
 593                  menuItemNewDepth = 0;
 594              }
 595  
 596              menuItem.find( '.menu-item-data-parent-id' ).val( newParentID );
 597              menuItem.moveHorizontally( menuItemNewDepth, menuItemOldDepth );
 598  
 599              if ( menuItemNoChildren > 0 ) {
 600                  menuItem = menuItem.add( menuItemChildren );
 601              }
 602              menuItem.detach();
 603  
 604              menuItems = $( '#menu-to-edit li' );
 605  
 606              var    parentItemPosition = parseInt( parentItem.index(), 10 ),
 607                  parentItemNoChild = parseInt( parentItem.childMenuItems().length, 10 );
 608  
 609              if ( parentItemNoChild > 0 ){
 610                  menuItemNewPosition = parentItemPosition + parentItemNoChild;
 611              } else {
 612                  menuItemNewPosition = parentItemPosition;
 613              }
 614  
 615              if ( newParentID == 0 ) {
 616                  menuItemNewPosition = menuItems.length - 1;
 617              }
 618  
 619              menuItem.insertAfter( menuItems.eq( menuItemNewPosition ) ).updateParentMenuItemDBId().updateParentDropdown().updateOrderDropdown();
 620  
 621              api.registerChange();
 622              api.refreshKeyboardAccessibility();
 623              api.refreshAdvancedAccessibility();
 624              $this.trigger( 'focus' );
 625              wp.a11y.speak( menus.parentUpdated, 'polite' );
 626          },
 627  
 628          /**
 629           * changeMenuOrder( [OrderDropdown] )
 630           *
 631           * @since 6.7.0
 632           *
 633           * @param {Object} orderDropdown select field
 634           */
 635          changeMenuOrder : function( orderDropdown ) {
 636              var menuItems = $( '#menu-to-edit li' ),
 637                  $this = $( orderDropdown ),
 638                  newOrderID = parseInt( $this.val(), 10),
 639                  menuItem = $this.closest( 'li.menu-item' ).first(),
 640                  menuItemChildren = menuItem.childMenuItems(),
 641                  menuItemNoChildren = menuItemChildren.length,
 642                  menuItemCurrentPosition = parseInt( menuItem.index(), 10 ),
 643                  parentItemID = menuItem.find( '.menu-item-data-parent-id' ).val(),
 644                  subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemID + '"]' ),
 645                  currentItemAtPosition = $(subItems[newOrderID - 1]).closest( 'li.menu-item' );
 646  
 647              if ( menuItemNoChildren > 0 ) {
 648                  menuItem = menuItem.add( menuItemChildren );
 649              }
 650  
 651              var currentItemNoChildren = currentItemAtPosition.childMenuItems().length,
 652                  currentItemPosition = parseInt( currentItemAtPosition.index(), 10 );
 653  
 654              menuItems = $( '#menu-to-edit li' );
 655  
 656              var    menuItemNewPosition = currentItemPosition;
 657  
 658              if(menuItemCurrentPosition > menuItemNewPosition){
 659                  menuItemNewPosition = currentItemPosition;
 660                  menuItem.detach().insertBefore( menuItems.eq( menuItemNewPosition ) ).updateOrderDropdown();
 661              } else {
 662                  menuItemNewPosition = menuItemNewPosition + currentItemNoChildren;
 663                  menuItem.detach().insertAfter( menuItems.eq( menuItemNewPosition ) ).updateOrderDropdown();
 664              }
 665  
 666              api.registerChange();
 667              api.refreshKeyboardAccessibility();
 668              api.refreshAdvancedAccessibility();
 669              $this.trigger( 'focus' );
 670              wp.a11y.speak( menus.orderUpdated, 'polite' );
 671          },
 672  
 673          /**
 674           * refreshAdvancedAccessibilityOfItem( [itemToRefresh] )
 675           *
 676           * Refreshes advanced accessibility buttons for one menu item.
 677           * Shows or hides buttons based on the location of the menu item.
 678           *
 679           * @param {Object} itemToRefresh The menu item that might need its advanced accessibility buttons refreshed
 680           */
 681          refreshAdvancedAccessibilityOfItem : function( itemToRefresh ) {
 682  
 683              // Only refresh accessibility when necessary.
 684              if ( true !== $( itemToRefresh ).data( 'needs_accessibility_refresh' ) ) {
 685                  return;
 686              }
 687  
 688              var thisLink, thisLinkText, primaryItems, itemPosition, title,
 689                  parentItem, parentItemId, parentItemName, subItems, totalSubItems,
 690                  $this = $( itemToRefresh ),
 691                  menuItem = $this.closest( 'li.menu-item' ).first(),
 692                  depth = menuItem.menuItemDepth(),
 693                  isPrimaryMenuItem = ( 0 === depth ),
 694                  itemName = $this.closest( '.menu-item-handle' ).find( '.menu-item-title' ).text(),
 695                  menuItemType = $this.closest( '.menu-item-handle' ).find( '.item-controls' ).find( '.item-type' ).text(),
 696                  position = parseInt( menuItem.index(), 10 ),
 697                  prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1, 10 ),
 698                  prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(),
 699                  prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(),
 700                  totalMenuItems = $('#menu-to-edit li').length,
 701                  hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length;
 702  
 703                  menuItem.find( '.field-move' ).toggle( totalMenuItems > 1 );
 704  
 705              // Where can they move this menu item?
 706              if ( 0 !== position ) {
 707                  thisLink = menuItem.find( '.menus-move-up' );
 708                  thisLink.attr( 'aria-label', menus.moveUp ).css( 'display', 'inline' );
 709              }
 710  
 711              if ( 0 !== position && isPrimaryMenuItem ) {
 712                  thisLink = menuItem.find( '.menus-move-top' );
 713                  thisLink.attr( 'aria-label', menus.moveToTop ).css( 'display', 'inline' );
 714              }
 715  
 716              if ( position + 1 !== totalMenuItems && 0 !== position ) {
 717                  thisLink = menuItem.find( '.menus-move-down' );
 718                  thisLink.attr( 'aria-label', menus.moveDown ).css( 'display', 'inline' );
 719              }
 720  
 721              if ( 0 === position && 0 !== hasSameDepthSibling ) {
 722                  thisLink = menuItem.find( '.menus-move-down' );
 723                  thisLink.attr( 'aria-label', menus.moveDown ).css( 'display', 'inline' );
 724              }
 725  
 726              if ( ! isPrimaryMenuItem ) {
 727                  thisLink = menuItem.find( '.menus-move-left' ),
 728                  thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft );
 729                  thisLink.attr( 'aria-label', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).text( thisLinkText ).css( 'display', 'inline' );
 730              }
 731  
 732              if ( 0 !== position ) {
 733                  if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) {
 734                      thisLink = menuItem.find( '.menus-move-right' ),
 735                      thisLinkText = menus.under.replace( '%s', prevItemNameRight );
 736                      thisLink.attr( 'aria-label', menus.moveUnder.replace( '%s', prevItemNameRight ) ).text( thisLinkText ).css( 'display', 'inline' );
 737                  }
 738              }
 739  
 740              if ( isPrimaryMenuItem ) {
 741                  primaryItems = $( '.menu-item-depth-0' ),
 742                  itemPosition = primaryItems.index( menuItem ) + 1,
 743                  totalMenuItems = primaryItems.length,
 744                  // String together help text for primary menu items.
 745                  title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$s', menuItemType ).replace( '%3$d', itemPosition ).replace( '%4$d', totalMenuItems );
 746              } else {
 747                  parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).first(),
 748                  parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
 749                  parentItemName = parentItem.find( '.menu-item-title' ).text(),
 750                  subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
 751                  totalSubItems = subItems.length,
 752                  itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
 753  
 754                  // String together help text for sub menu items.
 755                  if ( depth < 2 ) {
 756                      title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$s', menuItemType ).replace( '%3$d', itemPosition ).replace( '%4$d', totalSubItems ).replace( '%5$s', parentItemName );
 757                  } else {
 758                      title = menus.subMenuMoreDepthFocus.replace( '%1$s', itemName ).replace( '%2$s', menuItemType ).replace( '%3$d', itemPosition ).replace( '%4$d', totalSubItems ).replace( '%5$s', parentItemName ).replace( '%6$d', depth );
 759                  }
 760              }
 761  
 762              $this.attr( 'aria-label', title );
 763  
 764              // Mark this item's accessibility as refreshed.
 765              $this.data( 'needs_accessibility_refresh', false );
 766          },
 767  
 768          /**
 769           * refreshAdvancedAccessibility
 770           *
 771           * Hides all advanced accessibility buttons and marks them for refreshing.
 772           */
 773          refreshAdvancedAccessibility : function() {
 774  
 775              // Hide all the move buttons by default.
 776              $( '.menu-item-settings .field-move .menus-move' ).hide();
 777  
 778              // Mark all menu items as unprocessed.
 779              $( 'a.item-edit' ).data( 'needs_accessibility_refresh', true );
 780  
 781              // All open items have to be refreshed or they will show no links.
 782              $( '.menu-item-edit-active a.item-edit' ).each( function() {
 783                  api.refreshAdvancedAccessibilityOfItem( this );
 784              } );
 785          },
 786  
 787          refreshKeyboardAccessibility : function() {
 788              $( 'a.item-edit' ).off( 'focus' ).on( 'focus', function(){
 789                  $(this).off( 'keydown' ).on( 'keydown', function(e){
 790  
 791                      var arrows,
 792                          $this = $( this ),
 793                          thisItem = $this.parents( 'li.menu-item' ),
 794                          thisItemData = thisItem.getItemData();
 795  
 796                      // Bail if it's not an arrow key.
 797                      if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
 798                          return;
 799  
 800                      // Avoid multiple keydown events.
 801                      $this.off('keydown');
 802  
 803                      // Bail if there is only one menu item.
 804                      if ( 1 === $('#menu-to-edit li').length )
 805                          return;
 806  
 807                      // If RTL, swap left/right arrows.
 808                      arrows = { '38': 'up', '40': 'down', '37': 'left', '39': 'right' };
 809                      if ( $('body').hasClass('rtl') )
 810                          arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
 811  
 812                      switch ( arrows[e.which] ) {
 813                      case 'up':
 814                          api.moveMenuItem( $this, 'up' );
 815                          break;
 816                      case 'down':
 817                          api.moveMenuItem( $this, 'down' );
 818                          break;
 819                      case 'left':
 820                          api.moveMenuItem( $this, 'left' );
 821                          break;
 822                      case 'right':
 823                          api.moveMenuItem( $this, 'right' );
 824                          break;
 825                      }
 826                      // Put focus back on same menu item.
 827                      $( '#edit-' + thisItemData['menu-item-db-id'] ).trigger( 'focus' );
 828                      return false;
 829                  });
 830              });
 831          },
 832  
 833          initPreviewing : function() {
 834              // Update the item handle title when the navigation label is changed.
 835              $( '#menu-to-edit' ).on( 'change input', '.edit-menu-item-title', function(e) {
 836                  var input = $( e.currentTarget ), title, titleEl;
 837                  title = input.val();
 838                  titleEl = input.closest( '.menu-item' ).find( '.menu-item-title' );
 839                  // Don't update to empty title.
 840                  if ( title ) {
 841                      titleEl.text( title ).removeClass( 'no-title' );
 842                  } else {
 843                      titleEl.text( wp.i18n._x( '(no label)', 'missing menu item navigation label' ) ).addClass( 'no-title' );
 844                  }
 845              } );
 846          },
 847  
 848          initToggles : function() {
 849              // Init postboxes.
 850              postboxes.add_postbox_toggles('nav-menus');
 851  
 852              // Adjust columns functions for menus UI.
 853              columns.useCheckboxesForHidden();
 854              columns.checked = function(field) {
 855                  $('.field-' + field).removeClass('hidden-field');
 856              };
 857              columns.unchecked = function(field) {
 858                  $('.field-' + field).addClass('hidden-field');
 859              };
 860              // Hide fields.
 861              api.menuList.hideAdvancedMenuItemFields();
 862  
 863              $('.hide-postbox-tog').on( 'click', function () {
 864                  var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
 865                  $.post(ajaxurl, {
 866                      action: 'closed-postboxes',
 867                      hidden: hidden,
 868                      closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
 869                      page: 'nav-menus'
 870                  });
 871              });
 872          },
 873  
 874          initSortables : function() {
 875              var currentDepth = 0, originalDepth, minDepth, maxDepth,
 876                  prev, next, prevBottom, nextThreshold, helperHeight, transport,
 877                  menuEdge = api.menuList.offset().left,
 878                  body = $('body'), maxChildDepth,
 879                  menuMaxDepth = initialMenuMaxDepth();
 880  
 881              if( 0 !== $( '#menu-to-edit li' ).length )
 882                  $( '.drag-instructions' ).show();
 883  
 884              // Use the right edge if RTL.
 885              menuEdge += api.isRTL ? api.menuList.width() : 0;
 886  
 887              api.menuList.sortable({
 888                  handle: '.menu-item-handle',
 889                  placeholder: 'sortable-placeholder',
 890                  items: api.options.sortableItems,
 891                  start: function(e, ui) {
 892                      var height, width, parent, children, tempHolder;
 893  
 894                      // Handle placement for RTL orientation.
 895                      if ( api.isRTL )
 896                          ui.item[0].style.right = 'auto';
 897  
 898                      transport = ui.item.children('.menu-item-transport');
 899  
 900                      // Set depths. currentDepth must be set before children are located.
 901                      originalDepth = ui.item.menuItemDepth();
 902                      updateCurrentDepth(ui, originalDepth);
 903  
 904                      // Attach child elements to parent.
 905                      // Skip the placeholder.
 906                      parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
 907                      children = parent.childMenuItems();
 908                      transport.append( children );
 909  
 910                      // Update the height of the placeholder to match the moving item.
 911                      height = transport.outerHeight();
 912                      // If there are children, account for distance between top of children and parent.
 913                      height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
 914                      height += ui.helper.outerHeight();
 915                      helperHeight = height;
 916                      height -= 2;                                              // Subtract 2 for borders.
 917                      ui.placeholder.height(height);
 918  
 919                      // Update the width of the placeholder to match the moving item.
 920                      maxChildDepth = originalDepth;
 921                      children.each(function(){
 922                          var depth = $(this).menuItemDepth();
 923                          maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
 924                      });
 925                      width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width.
 926                      width += api.depthToPx(maxChildDepth - originalDepth);    // Account for children.
 927                      width -= 2;                                               // Subtract 2 for borders.
 928                      ui.placeholder.width(width);
 929  
 930                      // Update the list of menu items.
 931                      tempHolder = ui.placeholder.next( '.menu-item' );
 932                      tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder.
 933                      ui.placeholder.detach();         // Detach or jQuery UI will think the placeholder is a menu item.
 934                      $(this).sortable( 'refresh' );   // The children aren't sortable. We should let jQuery UI know.
 935                      ui.item.after( ui.placeholder ); // Reattach the placeholder.
 936                      tempHolder.css('margin-top', 0); // Reset the margin.
 937  
 938                      // Now that the element is complete, we can update...
 939                      updateSharedVars(ui);
 940                  },
 941                  stop: function(e, ui) {
 942                      var children, subMenuTitle,
 943                          depthChange = currentDepth - originalDepth;
 944  
 945                      // Return child elements to the list.
 946                      children = transport.children().insertAfter(ui.item);
 947  
 948                      // Add "sub menu" description.
 949                      subMenuTitle = ui.item.find( '.item-title .is-submenu' );
 950                      if ( 0 < currentDepth )
 951                          subMenuTitle.show();
 952                      else
 953                          subMenuTitle.hide();
 954  
 955                      // Update depth classes.
 956                      if ( 0 !== depthChange ) {
 957                          ui.item.updateDepthClass( currentDepth );
 958                          children.shiftDepthClass( depthChange );
 959                          updateMenuMaxDepth( depthChange );
 960                      }
 961                      // Register a change.
 962                      api.registerChange();
 963                      // Update the item data.
 964                      ui.item.updateParentMenuItemDBId();
 965  
 966                      // Address sortable's incorrectly-calculated top in Opera.
 967                      ui.item[0].style.top = 0;
 968  
 969                      // Handle drop placement for rtl orientation.
 970                      if ( api.isRTL ) {
 971                          ui.item[0].style.left = 'auto';
 972                          ui.item[0].style.right = 0;
 973                      }
 974  
 975                      api.refreshKeyboardAccessibility();
 976                      api.refreshAdvancedAccessibility();
 977                      ui.item.updateParentDropdown();
 978                      ui.item.updateOrderDropdown();
 979                      api.refreshAdvancedAccessibilityOfItem( ui.item.find( 'a.item-edit' ) );
 980                  },
 981                  change: function(e, ui) {
 982                      // Make sure the placeholder is inside the menu.
 983                      // Otherwise fix it, or we're in trouble.
 984                      if( ! ui.placeholder.parent().hasClass('menu') )
 985                          (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
 986  
 987                      updateSharedVars(ui);
 988                  },
 989                  sort: function(e, ui) {
 990                      var offset = ui.helper.offset(),
 991                          edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
 992                          depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
 993  
 994                      /*
 995                       * Check and correct if depth is not within range.
 996                       * Also, if the dragged element is dragged upwards over an item,
 997                       * shift the placeholder to a child position.
 998                       */
 999                      if ( depth > maxDepth || offset.top < ( prevBottom - api.options.targetTolerance ) ) {
1000                          depth = maxDepth;
1001                      } else if ( depth < minDepth ) {
1002                          depth = minDepth;
1003                      }
1004  
1005                      if( depth != currentDepth )
1006                          updateCurrentDepth(ui, depth);
1007  
1008                      // If we overlap the next element, manually shift downwards.
1009                      if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
1010                          next.after( ui.placeholder );
1011                          updateSharedVars( ui );
1012                          $( this ).sortable( 'refreshPositions' );
1013                      }
1014                  }
1015              });
1016  
1017  			function updateSharedVars(ui) {
1018                  var depth;
1019  
1020                  prev = ui.placeholder.prev( '.menu-item' );
1021                  next = ui.placeholder.next( '.menu-item' );
1022  
1023                  // Make sure we don't select the moving item.
1024                  if( prev[0] == ui.item[0] ) prev = prev.prev( '.menu-item' );
1025                  if( next[0] == ui.item[0] ) next = next.next( '.menu-item' );
1026  
1027                  prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
1028                  nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
1029                  minDepth = (next.length) ? next.menuItemDepth() : 0;
1030  
1031                  if( prev.length )
1032                      maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
1033                  else
1034                      maxDepth = 0;
1035              }
1036  
1037  			function updateCurrentDepth(ui, depth) {
1038                  ui.placeholder.updateDepthClass( depth, currentDepth );
1039                  currentDepth = depth;
1040              }
1041  
1042  			function initialMenuMaxDepth() {
1043                  if( ! body[0].className ) return 0;
1044                  var match = body[0].className.match(/menu-max-depth-(\d+)/);
1045                  return match && match[1] ? parseInt( match[1], 10 ) : 0;
1046              }
1047  
1048  			function updateMenuMaxDepth( depthChange ) {
1049                  var depth, newDepth = menuMaxDepth;
1050                  if ( depthChange === 0 ) {
1051                      return;
1052                  } else if ( depthChange > 0 ) {
1053                      depth = maxChildDepth + depthChange;
1054                      if( depth > menuMaxDepth )
1055                          newDepth = depth;
1056                  } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
1057                      while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
1058                          newDepth--;
1059                  }
1060                  // Update the depth class.
1061                  body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
1062                  menuMaxDepth = newDepth;
1063              }
1064          },
1065  
1066          initManageLocations : function () {
1067              $('#menu-locations-wrap form').on( 'submit', function(){
1068                  window.onbeforeunload = null;
1069              });
1070              $('.menu-location-menus select').on('change', function () {
1071                  var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
1072                  if ($(this).find('option:selected').data('orig'))
1073                      editLink.show();
1074                  else
1075                      editLink.hide();
1076              });
1077          },
1078  
1079          attachMenuEditListeners : function() {
1080              var that = this;
1081              $('#update-nav-menu').on('click', function(e) {
1082                  if ( e.target && e.target.className ) {
1083                      if ( -1 != e.target.className.indexOf('item-edit') ) {
1084                          return that.eventOnClickEditLink(e.target);
1085                      } else if ( -1 != e.target.className.indexOf('menu-save') ) {
1086                          return that.eventOnClickMenuSave(e.target);
1087                      } else if ( -1 != e.target.className.indexOf('menu-delete') ) {
1088                          return that.eventOnClickMenuDelete(e.target);
1089                      } else if ( -1 != e.target.className.indexOf('item-delete') ) {
1090                          return that.eventOnClickMenuItemDelete(e.target);
1091                      } else if ( -1 != e.target.className.indexOf('item-cancel') ) {
1092                          return that.eventOnClickCancelLink(e.target);
1093                      }
1094                  }
1095              });
1096  
1097              $( '#menu-name' ).on( 'input', _.debounce( function () {
1098                  var menuName = $( document.getElementById( 'menu-name' ) ),
1099                      menuNameVal = menuName.val();
1100  
1101                  if ( ! menuNameVal || ! menuNameVal.replace( /\s+/, '' ) ) {
1102                      // Add warning for invalid menu name.
1103                      menuName.parent().addClass( 'form-invalid' );
1104                  } else {
1105                      // Remove warning for valid menu name.
1106                      menuName.parent().removeClass( 'form-invalid' );
1107                  }
1108              }, 500 ) );
1109  
1110              $('#add-custom-links input[type="text"]').on( 'keypress', function(e){
1111                  $( '#customlinkdiv' ).removeClass( 'form-invalid' );
1112                  $( '#custom-menu-item-url' ).removeAttr( 'aria-invalid' ).removeAttr( 'aria-describedby' );
1113                  $( '#custom-url-error' ).hide();
1114  
1115                  if ( e.keyCode === 13 ) {
1116                      e.preventDefault();
1117                      $( '#submit-customlinkdiv' ).trigger( 'click' );
1118                  }
1119              });
1120  
1121              $( '#submit-customlinkdiv' ).on( 'click', function (e) {
1122                  var urlInput = $( '#custom-menu-item-url' ),
1123                      url = urlInput.val().trim(),
1124                      errorMessage = $( '#custom-url-error' ),
1125                      urlWrap = $( '#menu-item-url-wrap' ),
1126                      urlRegex;
1127  
1128                  // Hide the error message initially
1129                  errorMessage.hide();
1130                  urlWrap.removeClass( 'has-error' );
1131  
1132                  /*
1133                   * Allow URLs including:
1134                   * - http://example.com/
1135                   * - //example.com
1136                   * - /directory/
1137                   * - ?query-param
1138                   * - #target
1139                   * - mailto:foo@example.com
1140                   *
1141                   * Any further validation will be handled on the server when the setting is attempted to be saved,
1142                   * so this pattern does not need to be complete.
1143                   */
1144                  urlRegex = /^((\w+:)?\/\/\w.*|\w+:(?!\/\/$)|\/|\?|#)/;
1145                  if ( ! urlRegex.test( url ) ) {
1146                      e.preventDefault();
1147                      urlInput.addClass( 'form-invalid' )
1148                          .attr( 'aria-invalid', 'true' )
1149                          .attr( 'aria-describedby', 'custom-url-error' );
1150  
1151                      errorMessage.show();
1152                      var errorText = errorMessage.text();
1153                      urlWrap.addClass( 'has-error' );
1154                      // Announce error message via screen reader
1155                      wp.a11y.speak( errorText, 'assertive' );
1156                  }
1157              });
1158          },
1159  
1160          /**
1161           * Handle toggling bulk selection checkboxes for menu items.
1162           *
1163           * @since 5.8.0
1164           */
1165          attachBulkSelectButtonListeners : function() {
1166              var that = this;
1167  
1168              $( '.bulk-select-switcher' ).on( 'change', function() {
1169                  if ( this.checked ) {
1170                      $( '.bulk-select-switcher' ).prop( 'checked', true );
1171                      that.enableBulkSelection();
1172                  } else {
1173                      $( '.bulk-select-switcher' ).prop( 'checked', false );
1174                      that.disableBulkSelection();
1175                  }
1176              });
1177          },
1178  
1179          /**
1180           * Enable bulk selection checkboxes for menu items.
1181           *
1182           * @since 5.8.0
1183           */
1184          enableBulkSelection : function() {
1185              var checkbox = $( '#menu-to-edit .menu-item-checkbox' );
1186  
1187              $( '#menu-to-edit' ).addClass( 'bulk-selection' );
1188              $( '#nav-menu-bulk-actions-top' ).addClass( 'bulk-selection' );
1189              $( '#nav-menu-bulk-actions-bottom' ).addClass( 'bulk-selection' );
1190  
1191              $.each( checkbox, function() {
1192                  $(this).prop( 'disabled', false );
1193              });
1194          },
1195  
1196          /**
1197           * Disable bulk selection checkboxes for menu items.
1198           *
1199           * @since 5.8.0
1200           */
1201          disableBulkSelection : function() {
1202              var checkbox = $( '#menu-to-edit .menu-item-checkbox' );
1203  
1204              $( '#menu-to-edit' ).removeClass( 'bulk-selection' );
1205              $( '#nav-menu-bulk-actions-top' ).removeClass( 'bulk-selection' );
1206              $( '#nav-menu-bulk-actions-bottom' ).removeClass( 'bulk-selection' );
1207  
1208              if ( $( '.menu-items-delete' ).is( '[aria-describedby="pending-menu-items-to-delete"]' ) ) {
1209                  $( '.menu-items-delete' ).removeAttr( 'aria-describedby' );
1210              }
1211  
1212              $.each( checkbox, function() {
1213                  $(this).prop( 'disabled', true ).prop( 'checked', false );
1214              });
1215  
1216              $( '.menu-items-delete' ).addClass( 'disabled' );
1217              $( '#pending-menu-items-to-delete ul' ).empty();
1218          },
1219  
1220          /**
1221           * Listen for state changes on bulk action checkboxes.
1222           *
1223           * @since 5.8.0
1224           */
1225          attachMenuCheckBoxListeners : function() {
1226              var that = this;
1227  
1228              $( '#menu-to-edit' ).on( 'change', '.menu-item-checkbox', function() {
1229                  that.setRemoveSelectedButtonStatus();
1230              });
1231          },
1232  
1233          /**
1234           * Create delete button to remove menu items from collection.
1235           *
1236           * @since 5.8.0
1237           */
1238          attachMenuItemDeleteButton : function() {
1239              var that = this;
1240  
1241              $( document ).on( 'click', '.menu-items-delete', function( e ) {
1242                  var itemsPendingDeletion, itemsPendingDeletionList, deletionSpeech;
1243  
1244                  e.preventDefault();
1245  
1246                  if ( ! $(this).hasClass( 'disabled' ) ) {
1247                      $.each( $( '.menu-item-checkbox:checked' ), function( index, element ) {
1248                          $( element ).parents( 'li' ).find( 'a.item-delete' ).trigger( 'click' );
1249                      });
1250  
1251                      $( '.menu-items-delete' ).addClass( 'disabled' );
1252                      $( '.bulk-select-switcher' ).prop( 'checked', false );
1253  
1254                      itemsPendingDeletion     = '';
1255                      itemsPendingDeletionList = $( '#pending-menu-items-to-delete ul li' );
1256  
1257                      $.each( itemsPendingDeletionList, function( index, element ) {
1258                          var itemName = $( element ).find( '.pending-menu-item-name' ).text();
1259                          var itemSpeech = menus.menuItemDeletion.replace( '%s', itemName );
1260  
1261                          itemsPendingDeletion += itemSpeech;
1262                          if ( ( index + 1 ) < itemsPendingDeletionList.length ) {
1263                              itemsPendingDeletion += ', ';
1264                          }
1265                      });
1266  
1267                      deletionSpeech = menus.itemsDeleted.replace( '%s', itemsPendingDeletion );
1268                      wp.a11y.speak( deletionSpeech, 'polite' );
1269                      that.disableBulkSelection();
1270                      $( '#menu-to-edit' ).updateParentDropdown();
1271                      $( '#menu-to-edit' ).updateOrderDropdown();
1272                  }
1273              });
1274          },
1275  
1276          /**
1277           * List menu items awaiting deletion.
1278           *
1279           * @since 5.8.0
1280           */
1281          attachPendingMenuItemsListForDeletion : function() {
1282              $( '#post-body-content' ).on( 'change', '.menu-item-checkbox', function() {
1283                  var menuItemName, menuItemType, menuItemID, listedMenuItem;
1284  
1285                  if ( ! $( '.menu-items-delete' ).is( '[aria-describedby="pending-menu-items-to-delete"]' ) ) {
1286                      $( '.menu-items-delete' ).attr( 'aria-describedby', 'pending-menu-items-to-delete' );
1287                  }
1288  
1289                  menuItemName = $(this).next().text();
1290                  menuItemType = $(this).parent().next( '.item-controls' ).find( '.item-type' ).text();
1291                  menuItemID   = $(this).attr( 'data-menu-item-id' );
1292  
1293                  listedMenuItem = $( '#pending-menu-items-to-delete ul' ).find( '[data-menu-item-id=' + menuItemID + ']' );
1294                  if ( listedMenuItem.length > 0 ) {
1295                      listedMenuItem.remove();
1296                  }
1297  
1298                  if ( this.checked === true ) {
1299                      const $li = $( '<li>', { 'data-menu-item-id': menuItemID } );
1300                      $li.append( $( '<span>', {
1301                          'class': 'pending-menu-item-name',
1302                          text: menuItemName
1303                      } ) );
1304                      $li.append( ' ' );
1305                      $li.append( $( '<span>', {
1306                          'class': 'pending-menu-item-type',
1307                          text: '(' + menuItemType + ')',
1308                      } ) );
1309                      $li.append( $( '<span>', { 'class': 'separator' } ) );
1310                      $( '#pending-menu-items-to-delete ul' ).append( $li );
1311                  }
1312  
1313                  $( '#pending-menu-items-to-delete li .separator' ).html( ', ' );
1314                  $( '#pending-menu-items-to-delete li .separator' ).last().html( '.' );
1315              });
1316          },
1317  
1318          /**
1319           * Set status of bulk delete checkbox.
1320           *
1321           * @since 5.8.0
1322           */
1323          setBulkDeleteCheckboxStatus : function() {
1324              var that = this;
1325              var checkbox = $( '#menu-to-edit .menu-item-checkbox' );
1326  
1327              $.each( checkbox, function() {
1328                  if ( $(this).prop( 'disabled' ) ) {
1329                      $(this).prop( 'disabled', false );
1330                  } else {
1331                      $(this).prop( 'disabled', true );
1332                  }
1333  
1334                  if ( $(this).is( ':checked' ) ) {
1335                      $(this).prop( 'checked', false );
1336                  }
1337              });
1338  
1339              that.setRemoveSelectedButtonStatus();
1340          },
1341  
1342          /**
1343           * Set status of menu items removal button.
1344           *
1345           * @since 5.8.0
1346           */
1347          setRemoveSelectedButtonStatus : function() {
1348              var button = $( '.menu-items-delete' );
1349  
1350              if ( $( '.menu-item-checkbox:checked' ).length > 0 ) {
1351                  button.removeClass( 'disabled' );
1352              } else {
1353                  button.addClass( 'disabled' );
1354              }
1355          },
1356  
1357          attachMenuSaveSubmitListeners : function() {
1358              /*
1359               * When a navigation menu is saved, store a JSON representation of all form data
1360               * in a single input to avoid PHP `max_input_vars` limitations. See #14134.
1361               */
1362              $( '#update-nav-menu' ).on( 'submit', function() {
1363                  var navMenuData = $( '#update-nav-menu' ).serializeArray();
1364                  $( '[name="nav-menu-data"]' ).val( JSON.stringify( navMenuData ) );
1365              });
1366          },
1367  
1368          attachThemeLocationsListeners : function() {
1369              var loc = $('#nav-menu-theme-locations'), params = {};
1370              params.action = 'menu-locations-save';
1371              params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
1372              loc.find('input[type="submit"]').on( 'click', function() {
1373                  loc.find('select').each(function() {
1374                      params[this.name] = $(this).val();
1375                  });
1376                  loc.find( '.spinner' ).addClass( 'is-active' );
1377                  $.post( ajaxurl, params, function() {
1378                      loc.find( '.spinner' ).removeClass( 'is-active' );
1379                  });
1380                  return false;
1381              });
1382          },
1383  
1384          attachQuickSearchListeners : function() {
1385              var searchTimer;
1386  
1387              // Prevent form submission.
1388              $( '#nav-menu-meta' ).on( 'submit', function( event ) {
1389                  event.preventDefault();
1390              });
1391  
1392              $( '#nav-menu-meta' ).on( 'input', '.quick-search', function() {
1393                  var $this = $( this );
1394  
1395                  $this.attr( 'autocomplete', 'off' );
1396  
1397                  if ( searchTimer ) {
1398                      clearTimeout( searchTimer );
1399                  }
1400  
1401                  searchTimer = setTimeout( function() {
1402                      api.updateQuickSearchResults( $this );
1403                  }, 500 );
1404              }).on( 'blur', '.quick-search', function() {
1405                  api.lastSearch = '';
1406              });
1407          },
1408  
1409          updateQuickSearchResults : function(input) {
1410              var panel, params,
1411                  minSearchLength = 1,
1412                  q = input.val(),
1413                  pageSearchChecklist = $( '#page-search-checklist' );
1414  
1415              /*
1416               * Avoid a new Ajax search when the pressed key (e.g. arrows)
1417               * doesn't change the searched term.
1418               */
1419              if ( api.lastSearch == q ) {
1420                  return;
1421              }
1422  
1423              /*
1424               * Reset results when search is less than or equal to
1425               * minimum characters for searched term.
1426               */
1427              if ( q.length <= minSearchLength ) {
1428                  pageSearchChecklist.empty();
1429                  wp.a11y.speak( wp.i18n.__( 'Search results cleared' ) );
1430                  return;
1431              }
1432  
1433              api.lastSearch = q;
1434  
1435              panel = input.parents('.tabs-panel');
1436              params = {
1437                  'action': 'menu-quick-search',
1438                  'response-format': 'markup',
1439                  'menu': $('#menu').val(),
1440                  'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
1441                  'q': q,
1442                  'type': input.attr('name')
1443              };
1444  
1445              $( '.spinner', panel ).addClass( 'is-active' );
1446  
1447              $.post( ajaxurl, params, function(menuMarkup) {
1448                  api.processQuickSearchQueryResponse(menuMarkup, params, panel);
1449              });
1450          },
1451  
1452          addCustomLink : function( processMethod ) {
1453              var url = $('#custom-menu-item-url').val().toString(),
1454                  label = $('#custom-menu-item-name').val(),
1455                  urlRegex;
1456  
1457              if ( '' !== url ) {
1458                  url = url.trim();
1459              }
1460  
1461              processMethod = processMethod || api.addMenuItemToBottom;
1462  
1463              /*
1464               * Allow URLs including:
1465               * - http://example.com/
1466               * - //example.com
1467               * - /directory/
1468               * - ?query-param
1469               * - #target
1470               * - mailto:foo@example.com
1471               *
1472               * Any further validation will be handled on the server when the setting is attempted to be saved,
1473               * so this pattern does not need to be complete.
1474               */
1475              urlRegex = /^((\w+:)?\/\/\w.*|\w+:(?!\/\/$)|\/|\?|#)/;
1476              if ( ! urlRegex.test( url ) ) {
1477                  $('#customlinkdiv').addClass('form-invalid');
1478                  return false;
1479              }
1480  
1481              // Show the Ajax spinner.
1482              $( '.customlinkdiv .spinner' ).addClass( 'is-active' );
1483              this.addLinkToMenu( url, label, processMethod, function() {
1484                  // Remove the Ajax spinner.
1485                  $( '.customlinkdiv .spinner' ).removeClass( 'is-active' );
1486                  // Set custom link form back to defaults.
1487                  $('#custom-menu-item-name').val('').trigger( 'blur' );
1488                  $( '#custom-menu-item-url' ).val( '' ).attr( 'placeholder', 'https://' );
1489              });
1490          },
1491  
1492          addLinkToMenu : function(url, label, processMethod, callback) {
1493              processMethod = processMethod || api.addMenuItemToBottom;
1494              callback = callback || function(){};
1495  
1496              api.addItemToMenu({
1497                  '-1': {
1498                      'menu-item-type': 'custom',
1499                      'menu-item-url': url,
1500                      'menu-item-title': label
1501                  }
1502              }, processMethod, callback);
1503          },
1504  
1505          addItemToMenu : function(menuItem, processMethod, callback) {
1506              var menu = $('#menu').val(),
1507                  nonce = $('#menu-settings-column-nonce').val(),
1508                  params;
1509  
1510              processMethod = processMethod || function(){};
1511              callback = callback || function(){};
1512  
1513              params = {
1514                  'action': 'add-menu-item',
1515                  'menu': menu,
1516                  'menu-settings-column-nonce': nonce,
1517                  'menu-item': menuItem
1518              };
1519  
1520              $.post( ajaxurl, params, function(menuMarkup) {
1521                  var ins = $('#menu-instructions');
1522  
1523                  menuMarkup = menuMarkup || '';
1524                  menuMarkup = menuMarkup.toString().trim(); // Trim leading whitespaces.
1525                  processMethod(menuMarkup, params);
1526  
1527                  // Make it stand out a bit more visually, by adding a fadeIn.
1528                  $( 'li.pending' ).hide().fadeIn('slow');
1529                  $( '.drag-instructions' ).show();
1530                  if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
1531                      ins.addClass( 'menu-instructions-inactive' );
1532  
1533                  callback();
1534              });
1535          },
1536  
1537          /**
1538           * Process the add menu item request response into menu list item. Appends to menu.
1539           *
1540           * @param {string} menuMarkup The text server response of menu item markup.
1541           *
1542           * @fires document#menu-item-added Passes menuMarkup as a jQuery object.
1543           */
1544          addMenuItemToBottom : function( menuMarkup ) {
1545              var $menuMarkup = $( menuMarkup );
1546              $menuMarkup.hideAdvancedMenuItemFields().appendTo( api.targetList );
1547              api.refreshKeyboardAccessibility();
1548              api.refreshAdvancedAccessibility();
1549              wp.a11y.speak( menus.itemAdded );
1550              $( document ).trigger( 'menu-item-added', [ $menuMarkup ] );
1551          },
1552  
1553          /**
1554           * Process the add menu item request response into menu list item. Prepends to menu.
1555           *
1556           * @param {string} menuMarkup The text server response of menu item markup.
1557           *
1558           * @fires document#menu-item-added Passes menuMarkup as a jQuery object.
1559           */
1560          addMenuItemToTop : function( menuMarkup ) {
1561              var $menuMarkup = $( menuMarkup );
1562              $menuMarkup.hideAdvancedMenuItemFields().prependTo( api.targetList );
1563              api.refreshKeyboardAccessibility();
1564              api.refreshAdvancedAccessibility();
1565              wp.a11y.speak( menus.itemAdded );
1566              $( document ).trigger( 'menu-item-added', [ $menuMarkup ] );
1567          },
1568  
1569          attachUnsavedChangesListener : function() {
1570              $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').on( 'change', function(){
1571                  api.registerChange();
1572              });
1573  
1574              if ( 0 !== $('#menu-to-edit').length || 0 !== $('.menu-location-menus select').length ) {
1575                  window.onbeforeunload = function(){
1576                      if ( api.menusChanged )
1577                          return wp.i18n.__( 'The changes you made will be lost if you navigate away from this page.' );
1578                  };
1579              } else {
1580                  // Make the post boxes read-only, as they can't be used yet.
1581                  $( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).off( 'click' );
1582              }
1583          },
1584  
1585          registerChange : function() {
1586              api.menusChanged = true;
1587          },
1588  
1589          attachTabsPanelListeners : function() {
1590              $('#menu-settings-column').on('click', function(e) {
1591                  var selectAreaMatch, selectAll, panelId, wrapper, items,
1592                      target = $(e.target);
1593  
1594                  if ( target.hasClass('nav-tab-link') ) {
1595  
1596                      panelId = target.data( 'type' );
1597  
1598                      wrapper = target.parents('.accordion-section-content').first();
1599  
1600                      // Upon changing tabs, we want to uncheck all checkboxes.
1601                      $( 'input', wrapper ).prop( 'checked', false );
1602  
1603                      $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
1604                      $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
1605  
1606                      $('.tabs', wrapper).removeClass('tabs');
1607                      target.parent().addClass('tabs');
1608  
1609                      // Select the search bar.
1610                      $('.quick-search', wrapper).trigger( 'focus' );
1611  
1612                      // Hide controls in the search tab if no items found.
1613                      if ( ! wrapper.find( '.tabs-panel-active .menu-item-title' ).length ) {
1614                          wrapper.addClass( 'has-no-menu-item' );
1615                      } else {
1616                          wrapper.removeClass( 'has-no-menu-item' );
1617                      }
1618  
1619                      e.preventDefault();
1620                  } else if ( target.hasClass( 'select-all' ) ) {
1621                      selectAreaMatch = target.closest( '.button-controls' ).data( 'items-type' );
1622                      if ( selectAreaMatch ) {
1623                          items = $( '#' + selectAreaMatch + ' .tabs-panel-active .menu-item-title input' );
1624  
1625                          if ( items.length === items.filter( ':checked' ).length && ! target.is( ':checked' ) ) {
1626                              items.prop( 'checked', false );
1627                          } else if ( target.is( ':checked' ) ) {
1628                              items.prop( 'checked', true );
1629                          }
1630                      }
1631                  } else if ( target.hasClass( 'menu-item-checkbox' ) ) {
1632                      selectAreaMatch = target.closest( '.tabs-panel-active' ).parent().attr( 'id' );
1633                      if ( selectAreaMatch ) {
1634                          items     = $( '#' + selectAreaMatch + ' .tabs-panel-active .menu-item-title input' );
1635                          selectAll = $( '.button-controls[data-items-type="' + selectAreaMatch + '"] .select-all' );
1636  
1637                          if ( items.length === items.filter( ':checked' ).length && ! selectAll.is( ':checked' ) ) {
1638                              selectAll.prop( 'checked', true );
1639                          } else if ( selectAll.is( ':checked' ) ) {
1640                              selectAll.prop( 'checked', false );
1641                          }
1642                      }
1643                  } else if ( target.hasClass('submit-add-to-menu') ) {
1644                      api.registerChange();
1645  
1646                      if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
1647                          api.addCustomLink( api.addMenuItemToBottom );
1648                      else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
1649                          $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
1650                      return false;
1651                  }
1652              });
1653  
1654              /*
1655               * Delegate the `click` event and attach it just to the pagination
1656               * links thus excluding the current page `<span>`. See ticket #35577.
1657               */
1658              $( '#nav-menu-meta' ).on( 'click', 'a.page-numbers', function() {
1659                  var $container = $( this ).closest( '.inside' );
1660  
1661                  $.post( ajaxurl, this.href.replace( /.*\?/, '' ).replace( /action=([^&]*)/, '' ) + '&action=menu-get-metabox',
1662                      function( resp ) {
1663                          var metaBoxData = JSON.parse( resp ),
1664                              toReplace;
1665  
1666                          if ( -1 === resp.indexOf( 'replace-id' ) ) {
1667                              return;
1668                          }
1669  
1670                          // Get the post type menu meta box to update.
1671                          toReplace = document.getElementById( metaBoxData['replace-id'] );
1672  
1673                          if ( ! metaBoxData.markup || ! toReplace ) {
1674                              return;
1675                          }
1676  
1677                          // Update the post type menu meta box with new content from the response.
1678                          $container.html( metaBoxData.markup );
1679                      }
1680                  );
1681  
1682                  return false;
1683              });
1684          },
1685  
1686          eventOnClickEditLink : function(clickedEl) {
1687              var settings, item,
1688              matchedSection = /#(.*)$/.exec(clickedEl.href);
1689  
1690              if ( matchedSection && matchedSection[1] ) {
1691                  settings = $('#'+matchedSection[1]);
1692                  item = settings.parent();
1693                  if( 0 !== item.length ) {
1694                      if( item.hasClass('menu-item-edit-inactive') ) {
1695                          if( ! settings.data('menu-item-data') ) {
1696                              settings.data( 'menu-item-data', settings.getItemData() );
1697                          }
1698                          settings.slideDown('fast');
1699                          item.removeClass('menu-item-edit-inactive')
1700                              .addClass('menu-item-edit-active');
1701                      } else {
1702                          settings.slideUp('fast');
1703                          item.removeClass('menu-item-edit-active')
1704                              .addClass('menu-item-edit-inactive');
1705                      }
1706                      return false;
1707                  }
1708              }
1709          },
1710  
1711          eventOnClickCancelLink : function(clickedEl) {
1712              var settings = $( clickedEl ).closest( '.menu-item-settings' ),
1713                  thisMenuItem = $( clickedEl ).closest( '.menu-item' );
1714  
1715              thisMenuItem.removeClass( 'menu-item-edit-active' ).addClass( 'menu-item-edit-inactive' );
1716              settings.setItemData( settings.data( 'menu-item-data' ) ).hide();
1717              // Restore the title of the currently active/expanded menu item.
1718              thisMenuItem.find( '.menu-item-title' ).text( settings.data( 'menu-item-data' )['menu-item-title'] );
1719  
1720              return false;
1721          },
1722  
1723          eventOnClickMenuSave : function() {
1724              var menuName = $('#menu-name'),
1725                  menuNameVal = menuName.val();
1726  
1727              // Cancel and warn if invalid menu name.
1728              if ( ! menuNameVal || ! menuNameVal.replace( /\s+/, '' ) ) {
1729                  menuName.parent().addClass( 'form-invalid' );
1730                  return false;
1731              }
1732              // Copy menu theme locations.
1733              // Note: This appears to be dead code since #nav-menu-theme-locations no longer exists, perhaps removed in r32842.
1734              var $updateNavMenu = $('#update-nav-menu');
1735              $('#nav-menu-theme-locations select').each(function() {
1736                  $updateNavMenu.append(
1737                      $( '<input>', {
1738                          type: 'hidden',
1739                          name: this.name,
1740                          value: $( this ).val(),
1741                      } )
1742                  );
1743              });
1744              // Update menu item position data.
1745              api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
1746              window.onbeforeunload = null;
1747  
1748              return true;
1749          },
1750  
1751          eventOnClickMenuDelete : function() {
1752              // Delete warning AYS.
1753              if ( window.confirm( wp.i18n.__( 'You are about to permanently delete this menu.\n\'Cancel\' to stop, \'OK\' to delete.' ) ) ) {
1754                  window.onbeforeunload = null;
1755                  return true;
1756              }
1757              return false;
1758          },
1759  
1760          eventOnClickMenuItemDelete : function(clickedEl) {
1761              var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
1762  
1763              api.removeMenuItem( $('#menu-item-' + itemID) );
1764              api.registerChange();
1765              return false;
1766          },
1767  
1768          /**
1769           * Process the quick search response into a search result
1770           *
1771           * @param {string} resp  The server response to the query.
1772           * @param {Object} req   The request arguments.
1773           * @param {jQuery} panel The tabs panel we're searching in.
1774           */
1775          processQuickSearchQueryResponse : function(resp, req, panel) {
1776              var matched, newID,
1777              takenIDs = {},
1778              form = document.getElementById('nav-menu-meta'),
1779              pattern = /menu-item[(\[^]\]*/,
1780              $items = $('<div>').html(resp).find('li'),
1781              wrapper = panel.closest( '.accordion-section-content' ),
1782              selectAll = wrapper.find( '.button-controls .select-all' ),
1783              $item;
1784  
1785              if( ! $items.length ) {
1786                  let noResults = wp.i18n.__( 'No results found.' );
1787                  const li = $( '<li>' );
1788                  const p = $( '<p>', { text: noResults } );
1789                  li.append( p );
1790                  $('.categorychecklist', panel).empty().append( li );
1791                  $( '.spinner', panel ).removeClass( 'is-active' );
1792                  wrapper.addClass( 'has-no-menu-item' );
1793                  wp.a11y.speak( noResults, 'assertive' );
1794                  return;
1795              }
1796  
1797              $items.each(function(){
1798                  $item = $(this);
1799  
1800                  // Make a unique DB ID number.
1801                  matched = pattern.exec($item.html());
1802  
1803                  if ( matched && matched[1] ) {
1804                      newID = matched[1];
1805                      while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
1806                          newID--;
1807                      }
1808  
1809                      takenIDs[newID] = true;
1810                      if ( newID != matched[1] ) {
1811                          $item.html( $item.html().replace(new RegExp(
1812                              'menu-item\\[' + matched[1] + '\\]', 'g'),
1813                              'menu-item[' + newID + ']'
1814                          ) );
1815                      }
1816                  }
1817              });
1818  
1819              $('.categorychecklist', panel).html( $items );
1820              wp.a11y.speak( wp.i18n.sprintf( wp.i18n.__( '%d Search Results Found' ), $items.length ), 'assertive' );
1821              $( '.spinner', panel ).removeClass( 'is-active' );
1822              wrapper.removeClass( 'has-no-menu-item' );
1823  
1824              if ( selectAll.is( ':checked' ) ) {
1825                  selectAll.prop( 'checked', false );
1826              }
1827          },
1828  
1829          /**
1830           * Remove a menu item.
1831           *
1832           * @param {Object} el The element to be removed as a jQuery object.
1833           *
1834           * @fires document#menu-removing-item Passes the element to be removed.
1835           */
1836          removeMenuItem : function(el) {
1837              var children = el.childMenuItems();
1838  
1839              $( document ).trigger( 'menu-removing-item', [ el ] );
1840              el.addClass('deleting').animate({
1841                      opacity : 0,
1842                      height: 0
1843                  }, 350, function() {
1844                      var ins = $('#menu-instructions');
1845                      el.remove();
1846                      children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
1847                      if ( 0 === $( '#menu-to-edit li' ).length ) {
1848                          $( '.drag-instructions' ).hide();
1849                          ins.removeClass( 'menu-instructions-inactive' );
1850                      }
1851                      api.refreshAdvancedAccessibility();
1852                      wp.a11y.speak( menus.itemRemoved );
1853                      $( '#menu-to-edit' ).updateParentDropdown();
1854                      $( '#menu-to-edit' ).updateOrderDropdown();
1855                  });
1856          },
1857  
1858          depthToPx : function(depth) {
1859              return depth * api.options.menuItemDepthPerLevel;
1860          },
1861  
1862          pxToDepth : function(px) {
1863              return Math.floor(px / api.options.menuItemDepthPerLevel);
1864          }
1865  
1866      };
1867  
1868      $( function() {
1869  
1870          wpNavMenu.init();
1871  
1872          // Prevent focused element from being hidden by the sticky footer.
1873          $( '.menu-edit a, .menu-edit button, .menu-edit input, .menu-edit textarea, .menu-edit select' ).on('focus', function() {
1874              if ( window.innerWidth >= 783 ) {
1875                  var navMenuHeight = $( '#nav-menu-footer' ).height() + 20;
1876                  var bottomOffset = $(this).offset().top - ( $(window).scrollTop() + $(window).height() - $(this).height() );
1877  
1878                  if ( bottomOffset > 0 ) {
1879                      bottomOffset = 0;
1880                  }
1881                  bottomOffset = bottomOffset * -1;
1882  
1883                  if( bottomOffset < navMenuHeight ) {
1884                      var scrollTop = $(document).scrollTop();
1885                      $(document).scrollTop( scrollTop + ( navMenuHeight - bottomOffset ) );
1886                  }
1887              }
1888          });
1889      });
1890  
1891      // Show bulk action.
1892      $( document ).on( 'menu-item-added', function() {
1893          if ( ! $( '.bulk-actions' ).is( ':visible' ) ) {
1894              $( '.bulk-actions' ).show();
1895          }
1896      } );
1897  
1898      // Hide bulk action.
1899      $( document ).on( 'menu-removing-item', function( e, el ) {
1900          var menuElement = $( el ).parents( '#menu-to-edit' );
1901          if ( menuElement.find( 'li' ).length === 1 && $( '.bulk-actions' ).is( ':visible' ) ) {
1902              $( '.bulk-actions' ).hide();
1903          }
1904      } );
1905  
1906  })(jQuery);


Generated : Wed Sep 2 08:20:30 2026 Cross-referenced by PHPXref