[ Index ]

PHP Cross Reference of WordPress

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


Generated: Sat Nov 23 01:00:02 2024 Cross-referenced by PHPXref 0.7.1