2 * WordPress Administration Navigation Menu
3 * Interface JS functions
8 * @subpackage Administration
11 /* global menus, postboxes, columns, isRtl, navMenuL10n, ajaxurl */
22 menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
28 menuList : undefined, // Set in init.
29 targetList : undefined, // Set in init.
31 isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
32 negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
35 // Functions that run on init.
37 api.menuList = $('#menu-to-edit');
38 api.targetList = api.menuList;
40 this.jQueryExtensions();
42 this.attachMenuEditListeners();
44 this.attachQuickSearchListeners();
45 this.attachThemeLocationsListeners();
46 this.attachMenuSaveSubmitListeners();
48 this.attachTabsPanelListeners();
50 this.attachUnsavedChangesListener();
52 if ( api.menuList.length )
55 if ( menus.oneThemeLocationNoMenus )
56 $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom );
58 this.initManageLocations();
60 this.initAccessibility();
64 this.initPreviewing();
67 jQueryExtensions : function() {
70 menuItemDepth : function() {
71 var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
72 return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
74 updateDepthClass : function(current, prev) {
75 return this.each(function(){
77 prev = prev || t.menuItemDepth();
78 $(this).removeClass('menu-item-depth-'+ prev )
79 .addClass('menu-item-depth-'+ current );
82 shiftDepthClass : function(change) {
83 return this.each(function(){
85 depth = t.menuItemDepth(),
86 newDepth = depth + change;
88 t.removeClass( 'menu-item-depth-'+ depth )
89 .addClass( 'menu-item-depth-'+ ( newDepth ) );
91 if ( 0 === newDepth ) {
92 t.find( '.is-submenu' ).hide();
96 childMenuItems : function() {
99 var t = $(this), depth = t.menuItemDepth(), next = t.next( '.menu-item' );
100 while( next.length && next.menuItemDepth() > depth ) {
101 result = result.add( next );
102 next = next.next( '.menu-item' );
107 shiftHorizontally : function( dir ) {
108 return this.each(function(){
110 depth = t.menuItemDepth(),
111 newDepth = depth + dir;
113 // Change .menu-item-depth-n class
114 t.moveHorizontally( newDepth, depth );
117 moveHorizontally : function( newDepth, depth ) {
118 return this.each(function(){
120 children = t.childMenuItems(),
121 diff = newDepth - depth,
122 subItemText = t.find('.is-submenu');
124 // Change .menu-item-depth-n class
125 t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId();
127 // If it has children, move those too
129 children.each(function() {
131 thisDepth = t.menuItemDepth(),
132 newDepth = thisDepth + diff;
133 t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId();
137 // Show "Sub item" helper text
144 updateParentMenuItemDBId : function() {
145 return this.each(function(){
147 input = item.find( '.menu-item-data-parent-id' ),
148 depth = parseInt( item.menuItemDepth(), 10 ),
149 parentDepth = depth - 1,
150 parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first();
152 if ( 0 === depth ) { // Item is on the top level, has no parent
154 } else { // Find the parent item, and retrieve its object id.
155 input.val( parent.find( '.menu-item-data-db-id' ).val() );
159 hideAdvancedMenuItemFields : function() {
160 return this.each(function(){
162 $('.hide-column-tog').not(':checked').each(function(){
163 that.find('.field-' + $(this).val() ).addClass('hidden-field');
168 * Adds selected menu items to the menu.
170 * @param jQuery metabox The metabox jQuery object.
172 addSelectedToMenu : function(processMethod) {
173 if ( 0 === $('#menu-to-edit').length ) {
177 return this.each(function() {
178 var t = $(this), menuItems = {},
179 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' ),
180 re = /menu-item\[([^\]]*)/;
182 processMethod = processMethod || api.addMenuItemToBottom;
184 // If no items are checked, bail.
185 if ( !checkboxes.length )
188 // Show the ajax spinner
189 t.find( '.button-controls .spinner' ).addClass( 'is-active' );
191 // Retrieve menu item data
192 $(checkboxes).each(function(){
194 listItemDBIDMatch = re.exec( t.attr('name') ),
195 listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
197 if ( this.className && -1 != this.className.indexOf('add-to-top') )
198 processMethod = api.addMenuItemToTop;
199 menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
203 api.addItemToMenu(menuItems, processMethod, function(){
204 // Deselect the items and hide the ajax spinner
205 checkboxes.removeAttr('checked');
206 t.find( '.button-controls .spinner' ).removeClass( 'is-active' );
210 getItemData : function( itemType, id ) {
211 itemType = itemType || 'menu-item';
213 var itemData = {}, i,
216 'menu-item-object-id',
218 'menu-item-parent-id',
219 'menu-item-position',
223 'menu-item-description',
224 'menu-item-attr-title',
230 if( !id && itemType == 'menu-item' ) {
231 id = this.find('.menu-item-data-db-id').val();
234 if( !id ) return itemData;
236 this.find('input').each(function() {
240 if( itemType == 'menu-item' )
241 field = fields[i] + '[' + id + ']';
242 else if( itemType == 'add-menu-item' )
243 field = 'menu-item[' + id + '][' + fields[i] + ']';
249 itemData[fields[i]] = this.value;
256 setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
257 itemType = itemType || 'menu-item';
259 if( !id && itemType == 'menu-item' ) {
260 id = $('.menu-item-data-db-id', this).val();
263 if( !id ) return this;
265 this.find('input').each(function() {
266 var t = $(this), field;
267 $.each( itemData, function( attr, val ) {
268 if( itemType == 'menu-item' )
269 field = attr + '[' + id + ']';
270 else if( itemType == 'add-menu-item' )
271 field = 'menu-item[' + id + '][' + attr + ']';
273 if ( field == t.attr('name') ) {
283 countMenuItems : function( depth ) {
284 return $( '.menu-item-depth-' + depth ).length;
287 moveMenuItem : function( $this, dir ) {
289 var items, newItemPosition, newDepth,
290 menuItems = $( '#menu-to-edit li' ),
291 menuItemsCount = menuItems.length,
292 thisItem = $this.parents( 'li.menu-item' ),
293 thisItemChildren = thisItem.childMenuItems(),
294 thisItemData = thisItem.getItemData(),
295 thisItemDepth = parseInt( thisItem.menuItemDepth(), 10 ),
296 thisItemPosition = parseInt( thisItem.index(), 10 ),
297 nextItem = thisItem.next(),
298 nextItemChildren = nextItem.childMenuItems(),
299 nextItemDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1,
300 prevItem = thisItem.prev(),
301 prevItemDepth = parseInt( prevItem.menuItemDepth(), 10 ),
302 prevItemId = prevItem.getItemData()['menu-item-db-id'];
306 newItemPosition = thisItemPosition - 1;
309 if ( 0 === thisItemPosition )
312 // If a sub item is moved to top, shift it to 0 depth
313 if ( 0 === newItemPosition && 0 !== thisItemDepth )
314 thisItem.moveHorizontally( 0, thisItemDepth );
316 // If prev item is sub item, shift to match depth
317 if ( 0 !== prevItemDepth )
318 thisItem.moveHorizontally( prevItemDepth, thisItemDepth );
320 // Does this item have sub items?
321 if ( thisItemChildren ) {
322 items = thisItem.add( thisItemChildren );
323 // Move the entire block
324 items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
326 thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
330 // Does this item have sub items?
331 if ( thisItemChildren ) {
332 items = thisItem.add( thisItemChildren ),
333 nextItem = menuItems.eq( items.length + thisItemPosition ),
334 nextItemChildren = 0 !== nextItem.childMenuItems().length;
336 if ( nextItemChildren ) {
337 newDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1;
338 thisItem.moveHorizontally( newDepth, thisItemDepth );
341 // Have we reached the bottom?
342 if ( menuItemsCount === thisItemPosition + items.length )
345 items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId();
347 // If next item has sub items, shift depth
348 if ( 0 !== nextItemChildren.length )
349 thisItem.moveHorizontally( nextItemDepth, thisItemDepth );
351 // Have we reached the bottom
352 if ( menuItemsCount === thisItemPosition + 1 )
354 thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId();
359 if ( 0 === thisItemPosition )
361 // Does this item have sub items?
362 if ( thisItemChildren ) {
363 items = thisItem.add( thisItemChildren );
364 // Move the entire block
365 items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
367 thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
371 // As far left as possible
372 if ( 0 === thisItemDepth )
374 thisItem.shiftHorizontally( -1 );
377 // Can't be sub item at top
378 if ( 0 === thisItemPosition )
380 // Already sub item of prevItem
381 if ( thisItemData['menu-item-parent-id'] === prevItemId )
383 thisItem.shiftHorizontally( 1 );
387 api.registerChange();
388 api.refreshKeyboardAccessibility();
389 api.refreshAdvancedAccessibility();
392 initAccessibility : function() {
393 var menu = $( '#menu-to-edit' );
395 api.refreshKeyboardAccessibility();
396 api.refreshAdvancedAccessibility();
398 // Refresh the accessibility when the user comes close to the item in any way
399 menu.on( 'mouseenter.refreshAccessibility focus.refreshAccessibility touchstart.refreshAccessibility' , '.menu-item' , function(){
400 api.refreshAdvancedAccessibilityOfItem( $( this ).find( 'a.item-edit' ) );
403 // We have to update on click as well because we might hover first, change the item, and then click.
404 menu.on( 'click', 'a.item-edit', function() {
405 api.refreshAdvancedAccessibilityOfItem( $( this ) );
408 // Links for moving items
409 menu.on( 'click', '.menus-move', function () {
410 var $this = $( this ),
411 dir = $this.data( 'dir' );
413 if ( 'undefined' !== typeof dir ) {
414 api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), dir );
420 * refreshAdvancedAccessibilityOfItem( [itemToRefresh] )
422 * Refreshes advanced accessibility buttons for one menu item.
423 * Shows or hides buttons based on the location of the menu item.
425 * @param {object} itemToRefresh The menu item that might need its advanced accessibility buttons refreshed
427 refreshAdvancedAccessibilityOfItem : function( itemToRefresh ) {
429 // Only refresh accessibility when necessary
430 if ( true !== $( itemToRefresh ).data( 'needs_accessibility_refresh' ) ) {
434 var thisLink, thisLinkText, primaryItems, itemPosition, title,
435 parentItem, parentItemId, parentItemName, subItems,
436 $this = $( itemToRefresh ),
437 menuItem = $this.closest( 'li.menu-item' ).first(),
438 depth = menuItem.menuItemDepth(),
439 isPrimaryMenuItem = ( 0 === depth ),
440 itemName = $this.closest( '.menu-item-handle' ).find( '.menu-item-title' ).text(),
441 position = parseInt( menuItem.index(), 10 ),
442 prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1, 10 ),
443 prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(),
444 prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(),
445 totalMenuItems = $('#menu-to-edit li').length,
446 hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length;
448 menuItem.find( '.field-move' ).toggle( totalMenuItems > 1 );
450 // Where can they move this menu item?
451 if ( 0 !== position ) {
452 thisLink = menuItem.find( '.menus-move-up' );
453 thisLink.attr( 'aria-label', menus.moveUp ).css( 'display', 'inline' );
456 if ( 0 !== position && isPrimaryMenuItem ) {
457 thisLink = menuItem.find( '.menus-move-top' );
458 thisLink.attr( 'aria-label', menus.moveToTop ).css( 'display', 'inline' );
461 if ( position + 1 !== totalMenuItems && 0 !== position ) {
462 thisLink = menuItem.find( '.menus-move-down' );
463 thisLink.attr( 'aria-label', menus.moveDown ).css( 'display', 'inline' );
466 if ( 0 === position && 0 !== hasSameDepthSibling ) {
467 thisLink = menuItem.find( '.menus-move-down' );
468 thisLink.attr( 'aria-label', menus.moveDown ).css( 'display', 'inline' );
471 if ( ! isPrimaryMenuItem ) {
472 thisLink = menuItem.find( '.menus-move-left' ),
473 thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft );
474 thisLink.attr( 'aria-label', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).text( thisLinkText ).css( 'display', 'inline' );
477 if ( 0 !== position ) {
478 if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) {
479 thisLink = menuItem.find( '.menus-move-right' ),
480 thisLinkText = menus.under.replace( '%s', prevItemNameRight );
481 thisLink.attr( 'aria-label', menus.moveUnder.replace( '%s', prevItemNameRight ) ).text( thisLinkText ).css( 'display', 'inline' );
485 if ( isPrimaryMenuItem ) {
486 primaryItems = $( '.menu-item-depth-0' ),
487 itemPosition = primaryItems.index( menuItem ) + 1,
488 totalMenuItems = primaryItems.length,
490 // String together help text for primary menu items
491 title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems );
493 parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).first(),
494 parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
495 parentItemName = parentItem.find( '.menu-item-title' ).text(),
496 subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
497 itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
499 // String together help text for sub menu items
500 title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName );
503 // @todo Consider to update just the `aria-label` attribute.
504 $this.attr( 'aria-label', title ).text( title );
506 // Mark this item's accessibility as refreshed
507 $this.data( 'needs_accessibility_refresh', false );
511 * refreshAdvancedAccessibility
513 * Hides all advanced accessibility buttons and marks them for refreshing.
515 refreshAdvancedAccessibility : function() {
517 // Hide all the move buttons by default.
518 $( '.menu-item-settings .field-move .menus-move' ).hide();
520 // Mark all menu items as unprocessed
521 $( 'a.item-edit' ).data( 'needs_accessibility_refresh', true );
523 // All open items have to be refreshed or they will show no links
524 $( '.menu-item-edit-active a.item-edit' ).each( function() {
525 api.refreshAdvancedAccessibilityOfItem( this );
529 refreshKeyboardAccessibility : function() {
530 $( 'a.item-edit' ).off( 'focus' ).on( 'focus', function(){
531 $(this).off( 'keydown' ).on( 'keydown', function(e){
535 thisItem = $this.parents( 'li.menu-item' ),
536 thisItemData = thisItem.getItemData();
538 // Bail if it's not an arrow key
539 if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
542 // Avoid multiple keydown events
543 $this.off('keydown');
545 // Bail if there is only one menu item
546 if ( 1 === $('#menu-to-edit li').length )
549 // If RTL, swap left/right arrows
550 arrows = { '38': 'up', '40': 'down', '37': 'left', '39': 'right' };
551 if ( $('body').hasClass('rtl') )
552 arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
554 switch ( arrows[e.which] ) {
556 api.moveMenuItem( $this, 'up' );
559 api.moveMenuItem( $this, 'down' );
562 api.moveMenuItem( $this, 'left' );
565 api.moveMenuItem( $this, 'right' );
568 // Put focus back on same menu item
569 $( '#edit-' + thisItemData['menu-item-db-id'] ).focus();
575 initPreviewing : function() {
576 // Update the item handle title when the navigation label is changed.
577 $( '#menu-to-edit' ).on( 'change input', '.edit-menu-item-title', function(e) {
578 var input = $( e.currentTarget ), title, titleEl;
580 titleEl = input.closest( '.menu-item' ).find( '.menu-item-title' );
581 // Don't update to empty title.
583 titleEl.text( title ).removeClass( 'no-title' );
585 titleEl.text( navMenuL10n.untitled ).addClass( 'no-title' );
590 initToggles : function() {
592 postboxes.add_postbox_toggles('nav-menus');
594 // adjust columns functions for menus UI
595 columns.useCheckboxesForHidden();
596 columns.checked = function(field) {
597 $('.field-' + field).removeClass('hidden-field');
599 columns.unchecked = function(field) {
600 $('.field-' + field).addClass('hidden-field');
603 api.menuList.hideAdvancedMenuItemFields();
605 $('.hide-postbox-tog').click(function () {
606 var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
608 action: 'closed-postboxes',
610 closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
616 initSortables : function() {
617 var currentDepth = 0, originalDepth, minDepth, maxDepth,
618 prev, next, prevBottom, nextThreshold, helperHeight, transport,
619 menuEdge = api.menuList.offset().left,
620 body = $('body'), maxChildDepth,
621 menuMaxDepth = initialMenuMaxDepth();
623 if( 0 !== $( '#menu-to-edit li' ).length )
624 $( '.drag-instructions' ).show();
626 // Use the right edge if RTL.
627 menuEdge += api.isRTL ? api.menuList.width() : 0;
629 api.menuList.sortable({
630 handle: '.menu-item-handle',
631 placeholder: 'sortable-placeholder',
632 items: api.options.sortableItems,
633 start: function(e, ui) {
634 var height, width, parent, children, tempHolder;
636 // handle placement for rtl orientation
638 ui.item[0].style.right = 'auto';
640 transport = ui.item.children('.menu-item-transport');
642 // Set depths. currentDepth must be set before children are located.
643 originalDepth = ui.item.menuItemDepth();
644 updateCurrentDepth(ui, originalDepth);
646 // Attach child elements to parent
647 // Skip the placeholder
648 parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
649 children = parent.childMenuItems();
650 transport.append( children );
652 // Update the height of the placeholder to match the moving item.
653 height = transport.outerHeight();
654 // If there are children, account for distance between top of children and parent
655 height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
656 height += ui.helper.outerHeight();
657 helperHeight = height;
658 height -= 2; // Subtract 2 for borders
659 ui.placeholder.height(height);
661 // Update the width of the placeholder to match the moving item.
662 maxChildDepth = originalDepth;
663 children.each(function(){
664 var depth = $(this).menuItemDepth();
665 maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
667 width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
668 width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
669 width -= 2; // Subtract 2 for borders
670 ui.placeholder.width(width);
672 // Update the list of menu items.
673 tempHolder = ui.placeholder.next( '.menu-item' );
674 tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
675 ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
676 $(this).sortable( 'refresh' ); // The children aren't sortable. We should let jQ UI know.
677 ui.item.after( ui.placeholder ); // reattach the placeholder.
678 tempHolder.css('margin-top', 0); // reset the margin
680 // Now that the element is complete, we can update...
681 updateSharedVars(ui);
683 stop: function(e, ui) {
684 var children, subMenuTitle,
685 depthChange = currentDepth - originalDepth;
687 // Return child elements to the list
688 children = transport.children().insertAfter(ui.item);
690 // Add "sub menu" description
691 subMenuTitle = ui.item.find( '.item-title .is-submenu' );
692 if ( 0 < currentDepth )
697 // Update depth classes
698 if ( 0 !== depthChange ) {
699 ui.item.updateDepthClass( currentDepth );
700 children.shiftDepthClass( depthChange );
701 updateMenuMaxDepth( depthChange );
704 api.registerChange();
705 // Update the item data.
706 ui.item.updateParentMenuItemDBId();
708 // address sortable's incorrectly-calculated top in opera
709 ui.item[0].style.top = 0;
711 // handle drop placement for rtl orientation
713 ui.item[0].style.left = 'auto';
714 ui.item[0].style.right = 0;
717 api.refreshKeyboardAccessibility();
718 api.refreshAdvancedAccessibility();
720 change: function(e, ui) {
721 // Make sure the placeholder is inside the menu.
722 // Otherwise fix it, or we're in trouble.
723 if( ! ui.placeholder.parent().hasClass('menu') )
724 (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
726 updateSharedVars(ui);
728 sort: function(e, ui) {
729 var offset = ui.helper.offset(),
730 edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
731 depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
733 // Check and correct if depth is not within range.
734 // Also, if the dragged element is dragged upwards over
735 // an item, shift the placeholder to a child position.
736 if ( depth > maxDepth || offset.top < ( prevBottom - api.options.targetTolerance ) ) {
738 } else if ( depth < minDepth ) {
742 if( depth != currentDepth )
743 updateCurrentDepth(ui, depth);
745 // If we overlap the next element, manually shift downwards
746 if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
747 next.after( ui.placeholder );
748 updateSharedVars( ui );
749 $( this ).sortable( 'refreshPositions' );
754 function updateSharedVars(ui) {
757 prev = ui.placeholder.prev( '.menu-item' );
758 next = ui.placeholder.next( '.menu-item' );
760 // Make sure we don't select the moving item.
761 if( prev[0] == ui.item[0] ) prev = prev.prev( '.menu-item' );
762 if( next[0] == ui.item[0] ) next = next.next( '.menu-item' );
764 prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
765 nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
766 minDepth = (next.length) ? next.menuItemDepth() : 0;
769 maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
774 function updateCurrentDepth(ui, depth) {
775 ui.placeholder.updateDepthClass( depth, currentDepth );
776 currentDepth = depth;
779 function initialMenuMaxDepth() {
780 if( ! body[0].className ) return 0;
781 var match = body[0].className.match(/menu-max-depth-(\d+)/);
782 return match && match[1] ? parseInt( match[1], 10 ) : 0;
785 function updateMenuMaxDepth( depthChange ) {
786 var depth, newDepth = menuMaxDepth;
787 if ( depthChange === 0 ) {
789 } else if ( depthChange > 0 ) {
790 depth = maxChildDepth + depthChange;
791 if( depth > menuMaxDepth )
793 } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
794 while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
797 // Update the depth class.
798 body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
799 menuMaxDepth = newDepth;
803 initManageLocations : function () {
804 $('#menu-locations-wrap form').submit(function(){
805 window.onbeforeunload = null;
807 $('.menu-location-menus select').on('change', function () {
808 var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
809 if ($(this).find('option:selected').data('orig'))
816 attachMenuEditListeners : function() {
818 $('#update-nav-menu').bind('click', function(e) {
819 if ( e.target && e.target.className ) {
820 if ( -1 != e.target.className.indexOf('item-edit') ) {
821 return that.eventOnClickEditLink(e.target);
822 } else if ( -1 != e.target.className.indexOf('menu-save') ) {
823 return that.eventOnClickMenuSave(e.target);
824 } else if ( -1 != e.target.className.indexOf('menu-delete') ) {
825 return that.eventOnClickMenuDelete(e.target);
826 } else if ( -1 != e.target.className.indexOf('item-delete') ) {
827 return that.eventOnClickMenuItemDelete(e.target);
828 } else if ( -1 != e.target.className.indexOf('item-cancel') ) {
829 return that.eventOnClickCancelLink(e.target);
833 $('#add-custom-links input[type="text"]').keypress(function(e){
834 $('#customlinkdiv').removeClass('form-invalid');
836 if ( e.keyCode === 13 ) {
838 $( '#submit-customlinkdiv' ).click();
843 attachMenuSaveSubmitListeners : function() {
845 * When a navigation menu is saved, store a JSON representation of all form data
846 * in a single input to avoid PHP `max_input_vars` limitations. See #14134.
848 $( '#update-nav-menu' ).submit( function() {
849 var navMenuData = $( '#update-nav-menu' ).serializeArray();
850 $( '[name="nav-menu-data"]' ).val( JSON.stringify( navMenuData ) );
854 attachThemeLocationsListeners : function() {
855 var loc = $('#nav-menu-theme-locations'), params = {};
856 params.action = 'menu-locations-save';
857 params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
858 loc.find('input[type="submit"]').click(function() {
859 loc.find('select').each(function() {
860 params[this.name] = $(this).val();
862 loc.find( '.spinner' ).addClass( 'is-active' );
863 $.post( ajaxurl, params, function() {
864 loc.find( '.spinner' ).removeClass( 'is-active' );
870 attachQuickSearchListeners : function() {
874 // Prevent form submission.
875 $( '#nav-menu-meta' ).on( 'submit', function( event ) {
876 event.preventDefault();
880 * Use feature detection to determine whether inputs should use
881 * the `keyup` or `input` event. Input is preferred but lacks support
882 * in legacy browsers. See changeset 34078, see also ticket #26600#comment:59
884 if ( 'oninput' in document.createElement( 'input' ) ) {
885 inputEvent = 'input';
887 inputEvent = 'keyup';
890 $( '#nav-menu-meta' ).on( inputEvent, '.quick-search', function() {
891 var $this = $( this );
893 $this.attr( 'autocomplete', 'off' );
896 clearTimeout( searchTimer );
899 searchTimer = setTimeout( function() {
900 api.updateQuickSearchResults( $this );
902 }).on( 'blur', '.quick-search', function() {
907 updateQuickSearchResults : function(input) {
913 * Minimum characters for a search. Also avoid a new AJAX search when
914 * the pressed key (e.g. arrows) doesn't change the searched term.
916 if ( q.length < minSearchLength || api.lastSearch == q ) {
922 panel = input.parents('.tabs-panel');
924 'action': 'menu-quick-search',
925 'response-format': 'markup',
926 'menu': $('#menu').val(),
927 'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
929 'type': input.attr('name')
932 $( '.spinner', panel ).addClass( 'is-active' );
934 $.post( ajaxurl, params, function(menuMarkup) {
935 api.processQuickSearchQueryResponse(menuMarkup, params, panel);
939 addCustomLink : function( processMethod ) {
940 var url = $('#custom-menu-item-url').val(),
941 label = $('#custom-menu-item-name').val();
943 processMethod = processMethod || api.addMenuItemToBottom;
945 if ( '' === url || 'http://' == url ) {
946 $('#customlinkdiv').addClass('form-invalid');
950 // Show the ajax spinner
951 $( '.customlinkdiv .spinner' ).addClass( 'is-active' );
952 this.addLinkToMenu( url, label, processMethod, function() {
953 // Remove the ajax spinner
954 $( '.customlinkdiv .spinner' ).removeClass( 'is-active' );
955 // Set custom link form back to defaults
956 $('#custom-menu-item-name').val('').blur();
957 $('#custom-menu-item-url').val('http://');
961 addLinkToMenu : function(url, label, processMethod, callback) {
962 processMethod = processMethod || api.addMenuItemToBottom;
963 callback = callback || function(){};
967 'menu-item-type': 'custom',
968 'menu-item-url': url,
969 'menu-item-title': label
971 }, processMethod, callback);
974 addItemToMenu : function(menuItem, processMethod, callback) {
975 var menu = $('#menu').val(),
976 nonce = $('#menu-settings-column-nonce').val(),
979 processMethod = processMethod || function(){};
980 callback = callback || function(){};
983 'action': 'add-menu-item',
985 'menu-settings-column-nonce': nonce,
986 'menu-item': menuItem
989 $.post( ajaxurl, params, function(menuMarkup) {
990 var ins = $('#menu-instructions');
992 menuMarkup = $.trim( menuMarkup ); // Trim leading whitespaces
993 processMethod(menuMarkup, params);
995 // Make it stand out a bit more visually, by adding a fadeIn
996 $( 'li.pending' ).hide().fadeIn('slow');
997 $( '.drag-instructions' ).show();
998 if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
999 ins.addClass( 'menu-instructions-inactive' );
1006 * Process the add menu item request response into menu list item.
1008 * @param string menuMarkup The text server response of menu item markup.
1009 * @param object req The request arguments.
1011 addMenuItemToBottom : function( menuMarkup ) {
1012 $(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
1013 api.refreshKeyboardAccessibility();
1014 api.refreshAdvancedAccessibility();
1017 addMenuItemToTop : function( menuMarkup ) {
1018 $(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
1019 api.refreshKeyboardAccessibility();
1020 api.refreshAdvancedAccessibility();
1023 attachUnsavedChangesListener : function() {
1024 $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){
1025 api.registerChange();
1028 if ( 0 !== $('#menu-to-edit').length || 0 !== $('.menu-location-menus select').length ) {
1029 window.onbeforeunload = function(){
1030 if ( api.menusChanged )
1031 return navMenuL10n.saveAlert;
1034 // Make the post boxes read-only, as they can't be used yet
1035 $( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' );
1039 registerChange : function() {
1040 api.menusChanged = true;
1043 attachTabsPanelListeners : function() {
1044 $('#menu-settings-column').bind('click', function(e) {
1045 var selectAreaMatch, panelId, wrapper, items,
1046 target = $(e.target);
1048 if ( target.hasClass('nav-tab-link') ) {
1050 panelId = target.data( 'type' );
1052 wrapper = target.parents('.accordion-section-content').first();
1054 // upon changing tabs, we want to uncheck all checkboxes
1055 $('input', wrapper).removeAttr('checked');
1057 $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
1058 $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
1060 $('.tabs', wrapper).removeClass('tabs');
1061 target.parent().addClass('tabs');
1063 // select the search bar
1064 $('.quick-search', wrapper).focus();
1066 // Hide controls in the search tab if no items found.
1067 if ( ! wrapper.find( '.tabs-panel-active .menu-item-title' ).length ) {
1068 wrapper.addClass( 'has-no-menu-item' );
1070 wrapper.removeClass( 'has-no-menu-item' );
1074 } else if ( target.hasClass('select-all') ) {
1075 selectAreaMatch = /#(.*)$/.exec(e.target.href);
1076 if ( selectAreaMatch && selectAreaMatch[1] ) {
1077 items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
1078 if( items.length === items.filter(':checked').length )
1079 items.removeAttr('checked');
1081 items.prop('checked', true);
1084 } else if ( target.hasClass('submit-add-to-menu') ) {
1085 api.registerChange();
1087 if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
1088 api.addCustomLink( api.addMenuItemToBottom );
1089 else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
1090 $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
1096 * Delegate the `click` event and attach it just to the pagination
1097 * links thus excluding the current page `<span>`. See ticket #35577.
1099 $( '#nav-menu-meta' ).on( 'click', 'a.page-numbers', function() {
1100 var $container = $( this ).closest( '.inside' );
1102 $.post( ajaxurl, this.href.replace( /.*\?/, '' ).replace( /action=([^&]*)/, '' ) + '&action=menu-get-metabox',
1104 var metaBoxData = $.parseJSON( resp ),
1107 if ( -1 === resp.indexOf( 'replace-id' ) ) {
1111 // Get the post type menu meta box to update.
1112 toReplace = document.getElementById( metaBoxData['replace-id'] );
1114 if ( ! metaBoxData.markup || ! toReplace ) {
1118 // Update the post type menu meta box with new content from the response.
1119 $container.html( metaBoxData.markup );
1127 eventOnClickEditLink : function(clickedEl) {
1129 matchedSection = /#(.*)$/.exec(clickedEl.href);
1130 if ( matchedSection && matchedSection[1] ) {
1131 settings = $('#'+matchedSection[1]);
1132 item = settings.parent();
1133 if( 0 !== item.length ) {
1134 if( item.hasClass('menu-item-edit-inactive') ) {
1135 if( ! settings.data('menu-item-data') ) {
1136 settings.data( 'menu-item-data', settings.getItemData() );
1138 settings.slideDown('fast');
1139 item.removeClass('menu-item-edit-inactive')
1140 .addClass('menu-item-edit-active');
1142 settings.slideUp('fast');
1143 item.removeClass('menu-item-edit-active')
1144 .addClass('menu-item-edit-inactive');
1151 eventOnClickCancelLink : function(clickedEl) {
1152 var settings = $( clickedEl ).closest( '.menu-item-settings' ),
1153 thisMenuItem = $( clickedEl ).closest( '.menu-item' );
1154 thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive');
1155 settings.setItemData( settings.data('menu-item-data') ).hide();
1159 eventOnClickMenuSave : function() {
1161 menuName = $('#menu-name'),
1162 menuNameVal = menuName.val();
1163 // Cancel and warn if invalid menu name
1164 if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
1165 menuName.parent().addClass('form-invalid');
1168 // Copy menu theme locations
1169 $('#nav-menu-theme-locations select').each(function() {
1170 locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
1172 $('#update-nav-menu').append( locs );
1173 // Update menu item position data
1174 api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
1175 window.onbeforeunload = null;
1180 eventOnClickMenuDelete : function() {
1181 // Delete warning AYS
1182 if ( window.confirm( navMenuL10n.warnDeleteMenu ) ) {
1183 window.onbeforeunload = null;
1189 eventOnClickMenuItemDelete : function(clickedEl) {
1190 var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
1191 api.removeMenuItem( $('#menu-item-' + itemID) );
1192 api.registerChange();
1197 * Process the quick search response into a search result
1199 * @param string resp The server response to the query.
1200 * @param object req The request arguments.
1201 * @param jQuery panel The tabs panel we're searching in.
1203 processQuickSearchQueryResponse : function(resp, req, panel) {
1206 form = document.getElementById('nav-menu-meta'),
1207 pattern = /menu-item[(\[^]\]*/,
1208 $items = $('<div>').html(resp).find('li'),
1209 wrapper = panel.closest( '.accordion-section-content' ),
1212 if( ! $items.length ) {
1213 $('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
1214 $( '.spinner', panel ).removeClass( 'is-active' );
1215 wrapper.addClass( 'has-no-menu-item' );
1219 $items.each(function(){
1222 // make a unique DB ID number
1223 matched = pattern.exec($item.html());
1225 if ( matched && matched[1] ) {
1227 while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
1231 takenIDs[newID] = true;
1232 if ( newID != matched[1] ) {
1233 $item.html( $item.html().replace(new RegExp(
1234 'menu-item\\[' + matched[1] + '\\]', 'g'),
1235 'menu-item[' + newID + ']'
1241 $('.categorychecklist', panel).html( $items );
1242 $( '.spinner', panel ).removeClass( 'is-active' );
1243 wrapper.removeClass( 'has-no-menu-item' );
1246 removeMenuItem : function(el) {
1247 var children = el.childMenuItems();
1249 el.addClass('deleting').animate({
1252 }, 350, function() {
1253 var ins = $('#menu-instructions');
1255 children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
1256 if ( 0 === $( '#menu-to-edit li' ).length ) {
1257 $( '.drag-instructions' ).hide();
1258 ins.removeClass( 'menu-instructions-inactive' );
1260 api.refreshAdvancedAccessibility();
1264 depthToPx : function(depth) {
1265 return depth * api.options.menuItemDepthPerLevel;
1268 pxToDepth : function(px) {
1269 return Math.floor(px / api.options.menuItemDepthPerLevel);
1274 $(document).ready(function(){ wpNavMenu.init(); });