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.
26 menuList : undefined, // Set in init.
27 targetList : undefined, // Set in init.
29 isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
30 negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
32 // Functions that run on init.
34 api.menuList = $('#menu-to-edit');
35 api.targetList = api.menuList;
37 this.jQueryExtensions();
39 this.attachMenuEditListeners();
41 this.setupInputWithDefaultTitle();
42 this.attachQuickSearchListeners();
43 this.attachThemeLocationsListeners();
45 this.attachTabsPanelListeners();
47 this.attachUnsavedChangesListener();
49 if ( api.menuList.length )
52 if ( menus.oneThemeLocationNoMenus )
53 $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom );
55 this.initManageLocations();
57 this.initAccessibility();
61 this.initPreviewing();
64 jQueryExtensions : function() {
67 menuItemDepth : function() {
68 var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
69 return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
71 updateDepthClass : function(current, prev) {
72 return this.each(function(){
74 prev = prev || t.menuItemDepth();
75 $(this).removeClass('menu-item-depth-'+ prev )
76 .addClass('menu-item-depth-'+ current );
79 shiftDepthClass : function(change) {
80 return this.each(function(){
82 depth = t.menuItemDepth();
83 $(this).removeClass('menu-item-depth-'+ depth )
84 .addClass('menu-item-depth-'+ (depth + change) );
87 childMenuItems : function() {
90 var t = $(this), depth = t.menuItemDepth(), next = t.next();
91 while( next.length && next.menuItemDepth() > depth ) {
92 result = result.add( next );
98 shiftHorizontally : function( dir ) {
99 return this.each(function(){
101 depth = t.menuItemDepth(),
102 newDepth = depth + dir;
104 // Change .menu-item-depth-n class
105 t.moveHorizontally( newDepth, depth );
108 moveHorizontally : function( newDepth, depth ) {
109 return this.each(function(){
111 children = t.childMenuItems(),
112 diff = newDepth - depth,
113 subItemText = t.find('.is-submenu');
115 // Change .menu-item-depth-n class
116 t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId();
118 // If it has children, move those too
120 children.each(function() {
122 thisDepth = t.menuItemDepth(),
123 newDepth = thisDepth + diff;
124 t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId();
128 // Show "Sub item" helper text
135 updateParentMenuItemDBId : function() {
136 return this.each(function(){
138 input = item.find( '.menu-item-data-parent-id' ),
139 depth = parseInt( item.menuItemDepth(), 10 ),
140 parentDepth = depth - 1,
141 parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first();
143 if ( 0 === depth ) { // Item is on the top level, has no parent
145 } else { // Find the parent item, and retrieve its object id.
146 input.val( parent.find( '.menu-item-data-db-id' ).val() );
150 hideAdvancedMenuItemFields : function() {
151 return this.each(function(){
153 $('.hide-column-tog').not(':checked').each(function(){
154 that.find('.field-' + $(this).val() ).addClass('hidden-field');
159 * Adds selected menu items to the menu.
161 * @param jQuery metabox The metabox jQuery object.
163 addSelectedToMenu : function(processMethod) {
164 if ( 0 === $('#menu-to-edit').length ) {
168 return this.each(function() {
169 var t = $(this), menuItems = {},
170 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' ),
171 re = /menu-item\[([^\]]*)/;
173 processMethod = processMethod || api.addMenuItemToBottom;
175 // If no items are checked, bail.
176 if ( !checkboxes.length )
179 // Show the ajax spinner
180 t.find( '.spinner' ).addClass( 'is-active' );
182 // Retrieve menu item data
183 $(checkboxes).each(function(){
185 listItemDBIDMatch = re.exec( t.attr('name') ),
186 listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
188 if ( this.className && -1 != this.className.indexOf('add-to-top') )
189 processMethod = api.addMenuItemToTop;
190 menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
194 api.addItemToMenu(menuItems, processMethod, function(){
195 // Deselect the items and hide the ajax spinner
196 checkboxes.removeAttr('checked');
197 t.find( '.spinner' ).removeClass( 'is-active' );
201 getItemData : function( itemType, id ) {
202 itemType = itemType || 'menu-item';
204 var itemData = {}, i,
207 'menu-item-object-id',
209 'menu-item-parent-id',
210 'menu-item-position',
214 'menu-item-description',
215 'menu-item-attr-title',
221 if( !id && itemType == 'menu-item' ) {
222 id = this.find('.menu-item-data-db-id').val();
225 if( !id ) return itemData;
227 this.find('input').each(function() {
231 if( itemType == 'menu-item' )
232 field = fields[i] + '[' + id + ']';
233 else if( itemType == 'add-menu-item' )
234 field = 'menu-item[' + id + '][' + fields[i] + ']';
240 itemData[fields[i]] = this.value;
247 setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
248 itemType = itemType || 'menu-item';
250 if( !id && itemType == 'menu-item' ) {
251 id = $('.menu-item-data-db-id', this).val();
254 if( !id ) return this;
256 this.find('input').each(function() {
257 var t = $(this), field;
258 $.each( itemData, function( attr, val ) {
259 if( itemType == 'menu-item' )
260 field = attr + '[' + id + ']';
261 else if( itemType == 'add-menu-item' )
262 field = 'menu-item[' + id + '][' + attr + ']';
264 if ( field == t.attr('name') ) {
274 countMenuItems : function( depth ) {
275 return $( '.menu-item-depth-' + depth ).length;
278 moveMenuItem : function( $this, dir ) {
280 var items, newItemPosition, newDepth,
281 menuItems = $( '#menu-to-edit li' ),
282 menuItemsCount = menuItems.length,
283 thisItem = $this.parents( 'li.menu-item' ),
284 thisItemChildren = thisItem.childMenuItems(),
285 thisItemData = thisItem.getItemData(),
286 thisItemDepth = parseInt( thisItem.menuItemDepth(), 10 ),
287 thisItemPosition = parseInt( thisItem.index(), 10 ),
288 nextItem = thisItem.next(),
289 nextItemChildren = nextItem.childMenuItems(),
290 nextItemDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1,
291 prevItem = thisItem.prev(),
292 prevItemDepth = parseInt( prevItem.menuItemDepth(), 10 ),
293 prevItemId = prevItem.getItemData()['menu-item-db-id'];
297 newItemPosition = thisItemPosition - 1;
300 if ( 0 === thisItemPosition )
303 // If a sub item is moved to top, shift it to 0 depth
304 if ( 0 === newItemPosition && 0 !== thisItemDepth )
305 thisItem.moveHorizontally( 0, thisItemDepth );
307 // If prev item is sub item, shift to match depth
308 if ( 0 !== prevItemDepth )
309 thisItem.moveHorizontally( prevItemDepth, thisItemDepth );
311 // Does this item have sub items?
312 if ( thisItemChildren ) {
313 items = thisItem.add( thisItemChildren );
314 // Move the entire block
315 items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
317 thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
321 // Does this item have sub items?
322 if ( thisItemChildren ) {
323 items = thisItem.add( thisItemChildren ),
324 nextItem = menuItems.eq( items.length + thisItemPosition ),
325 nextItemChildren = 0 !== nextItem.childMenuItems().length;
327 if ( nextItemChildren ) {
328 newDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1;
329 thisItem.moveHorizontally( newDepth, thisItemDepth );
332 // Have we reached the bottom?
333 if ( menuItemsCount === thisItemPosition + items.length )
336 items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId();
338 // If next item has sub items, shift depth
339 if ( 0 !== nextItemChildren.length )
340 thisItem.moveHorizontally( nextItemDepth, thisItemDepth );
342 // Have we reached the bottom
343 if ( menuItemsCount === thisItemPosition + 1 )
345 thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId();
350 if ( 0 === thisItemPosition )
352 // Does this item have sub items?
353 if ( thisItemChildren ) {
354 items = thisItem.add( thisItemChildren );
355 // Move the entire block
356 items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
358 thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
362 // As far left as possible
363 if ( 0 === thisItemDepth )
365 thisItem.shiftHorizontally( -1 );
368 // Can't be sub item at top
369 if ( 0 === thisItemPosition )
371 // Already sub item of prevItem
372 if ( thisItemData['menu-item-parent-id'] === prevItemId )
374 thisItem.shiftHorizontally( 1 );
378 api.registerChange();
379 api.refreshKeyboardAccessibility();
380 api.refreshAdvancedAccessibility();
383 initAccessibility : function() {
384 var menu = $( '#menu-to-edit' );
386 api.refreshKeyboardAccessibility();
387 api.refreshAdvancedAccessibility();
389 // Refresh the accessibility when the user comes close to the item in any way
390 menu.on( 'mouseenter.refreshAccessibility focus.refreshAccessibility touchstart.refreshAccessibility' , '.menu-item' , function(){
391 api.refreshAdvancedAccessibilityOfItem( $( this ).find( '.item-edit' ) );
394 // We have to update on click as well because we might hover first, change the item, and then click.
395 menu.on( 'click', '.item-edit', function() {
396 api.refreshAdvancedAccessibilityOfItem( $( this ) );
399 // Links for moving items
400 menu.on( 'click', '.menus-move', function ( e ) {
401 var $this = $( this ),
402 dir = $this.data( 'dir' );
404 if ( 'undefined' !== typeof dir ) {
405 api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), dir );
412 * refreshAdvancedAccessibilityOfItem( [itemToRefresh] )
414 * Refreshes advanced accessibility buttons for one menu item.
415 * Shows or hides buttons based on the location of the menu item.
417 * @param {object} itemToRefresh The menu item that might need its advanced accessibility buttons refreshed
419 refreshAdvancedAccessibilityOfItem : function( itemToRefresh ) {
421 // Only refresh accessibility when necessary
422 if ( true !== $( itemToRefresh ).data( 'needs_accessibility_refresh' ) ) {
426 var thisLink, thisLinkText, primaryItems, itemPosition, title,
427 parentItem, parentItemId, parentItemName, subItems,
428 $this = $( itemToRefresh ),
429 menuItem = $this.closest( 'li.menu-item' ).first(),
430 depth = menuItem.menuItemDepth(),
431 isPrimaryMenuItem = ( 0 === depth ),
432 itemName = $this.closest( '.menu-item-handle' ).find( '.menu-item-title' ).text(),
433 position = parseInt( menuItem.index(), 10 ),
434 prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1, 10 ),
435 prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(),
436 prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(),
437 totalMenuItems = $('#menu-to-edit li').length,
438 hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length;
440 menuItem.find( '.field-move' ).toggle( totalMenuItems > 1 );
442 // Where can they move this menu item?
443 if ( 0 !== position ) {
444 thisLink = menuItem.find( '.menus-move-up' );
445 thisLink.prop( 'title', menus.moveUp ).css( 'display', 'inline' );
448 if ( 0 !== position && isPrimaryMenuItem ) {
449 thisLink = menuItem.find( '.menus-move-top' );
450 thisLink.prop( 'title', menus.moveToTop ).css( 'display', 'inline' );
453 if ( position + 1 !== totalMenuItems && 0 !== position ) {
454 thisLink = menuItem.find( '.menus-move-down' );
455 thisLink.prop( 'title', menus.moveDown ).css( 'display', 'inline' );
458 if ( 0 === position && 0 !== hasSameDepthSibling ) {
459 thisLink = menuItem.find( '.menus-move-down' );
460 thisLink.prop( 'title', menus.moveDown ).css( 'display', 'inline' );
463 if ( ! isPrimaryMenuItem ) {
464 thisLink = menuItem.find( '.menus-move-left' ),
465 thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft );
466 thisLink.prop( 'title', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).text( thisLinkText ).css( 'display', 'inline' );
469 if ( 0 !== position ) {
470 if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) {
471 thisLink = menuItem.find( '.menus-move-right' ),
472 thisLinkText = menus.under.replace( '%s', prevItemNameRight );
473 thisLink.prop( 'title', menus.moveUnder.replace( '%s', prevItemNameRight ) ).text( thisLinkText ).css( 'display', 'inline' );
477 if ( isPrimaryMenuItem ) {
478 primaryItems = $( '.menu-item-depth-0' ),
479 itemPosition = primaryItems.index( menuItem ) + 1,
480 totalMenuItems = primaryItems.length,
482 // String together help text for primary menu items
483 title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems );
485 parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).first(),
486 parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
487 parentItemName = parentItem.find( '.menu-item-title' ).text(),
488 subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
489 itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
491 // String together help text for sub menu items
492 title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName );
495 $this.prop('title', title).text( title );
497 // Mark this item's accessibility as refreshed
498 $this.data( 'needs_accessibility_refresh', false );
502 * refreshAdvancedAccessibility
504 * Hides all advanced accessibility buttons and marks them for refreshing.
506 refreshAdvancedAccessibility : function() {
508 // Hide all links by default
509 $( '.menu-item-settings .field-move a' ).hide();
511 // Mark all menu items as unprocessed
512 $( '.item-edit' ).data( 'needs_accessibility_refresh', true );
514 // All open items have to be refreshed or they will show no links
515 $( '.menu-item-edit-active .item-edit' ).each( function() {
516 api.refreshAdvancedAccessibilityOfItem( this );
520 refreshKeyboardAccessibility : function() {
521 $( '.item-edit' ).off( 'focus' ).on( 'focus', function(){
522 $(this).off( 'keydown' ).on( 'keydown', function(e){
526 thisItem = $this.parents( 'li.menu-item' ),
527 thisItemData = thisItem.getItemData();
529 // Bail if it's not an arrow key
530 if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
533 // Avoid multiple keydown events
534 $this.off('keydown');
536 // Bail if there is only one menu item
537 if ( 1 === $('#menu-to-edit li').length )
540 // If RTL, swap left/right arrows
541 arrows = { '38': 'up', '40': 'down', '37': 'left', '39': 'right' };
542 if ( $('body').hasClass('rtl') )
543 arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
545 switch ( arrows[e.which] ) {
547 api.moveMenuItem( $this, 'up' );
550 api.moveMenuItem( $this, 'down' );
553 api.moveMenuItem( $this, 'left' );
556 api.moveMenuItem( $this, 'right' );
559 // Put focus back on same menu item
560 $( '#edit-' + thisItemData['menu-item-db-id'] ).focus();
566 initPreviewing : function() {
567 // Update the item handle title when the navigation label is changed.
568 $( '#menu-to-edit' ).on( 'change input', '.edit-menu-item-title', function(e) {
569 var input = $( e.currentTarget ), title, titleEl;
571 titleEl = input.closest( '.menu-item' ).find( '.menu-item-title' );
572 // Don't update to empty title.
574 titleEl.text( title ).removeClass( 'no-title' );
576 titleEl.text( navMenuL10n.untitled ).addClass( 'no-title' );
581 initToggles : function() {
583 postboxes.add_postbox_toggles('nav-menus');
585 // adjust columns functions for menus UI
586 columns.useCheckboxesForHidden();
587 columns.checked = function(field) {
588 $('.field-' + field).removeClass('hidden-field');
590 columns.unchecked = function(field) {
591 $('.field-' + field).addClass('hidden-field');
594 api.menuList.hideAdvancedMenuItemFields();
596 $('.hide-postbox-tog').click(function () {
597 var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
599 action: 'closed-postboxes',
601 closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
607 initSortables : function() {
608 var currentDepth = 0, originalDepth, minDepth, maxDepth,
609 prev, next, prevBottom, nextThreshold, helperHeight, transport,
610 menuEdge = api.menuList.offset().left,
611 body = $('body'), maxChildDepth,
612 menuMaxDepth = initialMenuMaxDepth();
614 if( 0 !== $( '#menu-to-edit li' ).length )
615 $( '.drag-instructions' ).show();
617 // Use the right edge if RTL.
618 menuEdge += api.isRTL ? api.menuList.width() : 0;
620 api.menuList.sortable({
621 handle: '.menu-item-handle',
622 placeholder: 'sortable-placeholder',
623 start: function(e, ui) {
624 var height, width, parent, children, tempHolder;
626 // handle placement for rtl orientation
628 ui.item[0].style.right = 'auto';
630 transport = ui.item.children('.menu-item-transport');
632 // Set depths. currentDepth must be set before children are located.
633 originalDepth = ui.item.menuItemDepth();
634 updateCurrentDepth(ui, originalDepth);
636 // Attach child elements to parent
637 // Skip the placeholder
638 parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
639 children = parent.childMenuItems();
640 transport.append( children );
642 // Update the height of the placeholder to match the moving item.
643 height = transport.outerHeight();
644 // If there are children, account for distance between top of children and parent
645 height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
646 height += ui.helper.outerHeight();
647 helperHeight = height;
648 height -= 2; // Subtract 2 for borders
649 ui.placeholder.height(height);
651 // Update the width of the placeholder to match the moving item.
652 maxChildDepth = originalDepth;
653 children.each(function(){
654 var depth = $(this).menuItemDepth();
655 maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
657 width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
658 width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
659 width -= 2; // Subtract 2 for borders
660 ui.placeholder.width(width);
662 // Update the list of menu items.
663 tempHolder = ui.placeholder.next();
664 tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
665 ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
666 $(this).sortable( 'refresh' ); // The children aren't sortable. We should let jQ UI know.
667 ui.item.after( ui.placeholder ); // reattach the placeholder.
668 tempHolder.css('margin-top', 0); // reset the margin
670 // Now that the element is complete, we can update...
671 updateSharedVars(ui);
673 stop: function(e, ui) {
674 var children, subMenuTitle,
675 depthChange = currentDepth - originalDepth;
677 // Return child elements to the list
678 children = transport.children().insertAfter(ui.item);
680 // Add "sub menu" description
681 subMenuTitle = ui.item.find( '.item-title .is-submenu' );
682 if ( 0 < currentDepth )
687 // Update depth classes
688 if ( 0 !== depthChange ) {
689 ui.item.updateDepthClass( currentDepth );
690 children.shiftDepthClass( depthChange );
691 updateMenuMaxDepth( depthChange );
694 api.registerChange();
695 // Update the item data.
696 ui.item.updateParentMenuItemDBId();
698 // address sortable's incorrectly-calculated top in opera
699 ui.item[0].style.top = 0;
701 // handle drop placement for rtl orientation
703 ui.item[0].style.left = 'auto';
704 ui.item[0].style.right = 0;
707 api.refreshKeyboardAccessibility();
708 api.refreshAdvancedAccessibility();
710 change: function(e, ui) {
711 // Make sure the placeholder is inside the menu.
712 // Otherwise fix it, or we're in trouble.
713 if( ! ui.placeholder.parent().hasClass('menu') )
714 (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
716 updateSharedVars(ui);
718 sort: function(e, ui) {
719 var offset = ui.helper.offset(),
720 edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
721 depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
722 // Check and correct if depth is not within range.
723 // Also, if the dragged element is dragged upwards over
724 // an item, shift the placeholder to a child position.
725 if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth;
726 else if ( depth < minDepth ) depth = minDepth;
728 if( depth != currentDepth )
729 updateCurrentDepth(ui, depth);
731 // If we overlap the next element, manually shift downwards
732 if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
733 next.after( ui.placeholder );
734 updateSharedVars( ui );
735 $( this ).sortable( 'refreshPositions' );
740 function updateSharedVars(ui) {
743 prev = ui.placeholder.prev();
744 next = ui.placeholder.next();
746 // Make sure we don't select the moving item.
747 if( prev[0] == ui.item[0] ) prev = prev.prev();
748 if( next[0] == ui.item[0] ) next = next.next();
750 prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
751 nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
752 minDepth = (next.length) ? next.menuItemDepth() : 0;
755 maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
760 function updateCurrentDepth(ui, depth) {
761 ui.placeholder.updateDepthClass( depth, currentDepth );
762 currentDepth = depth;
765 function initialMenuMaxDepth() {
766 if( ! body[0].className ) return 0;
767 var match = body[0].className.match(/menu-max-depth-(\d+)/);
768 return match && match[1] ? parseInt( match[1], 10 ) : 0;
771 function updateMenuMaxDepth( depthChange ) {
772 var depth, newDepth = menuMaxDepth;
773 if ( depthChange === 0 ) {
775 } else if ( depthChange > 0 ) {
776 depth = maxChildDepth + depthChange;
777 if( depth > menuMaxDepth )
779 } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
780 while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
783 // Update the depth class.
784 body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
785 menuMaxDepth = newDepth;
789 initManageLocations : function () {
790 $('#menu-locations-wrap form').submit(function(){
791 window.onbeforeunload = null;
793 $('.menu-location-menus select').on('change', function () {
794 var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
795 if ($(this).find('option:selected').data('orig'))
802 attachMenuEditListeners : function() {
804 $('#update-nav-menu').bind('click', function(e) {
805 if ( e.target && e.target.className ) {
806 if ( -1 != e.target.className.indexOf('item-edit') ) {
807 return that.eventOnClickEditLink(e.target);
808 } else if ( -1 != e.target.className.indexOf('menu-save') ) {
809 return that.eventOnClickMenuSave(e.target);
810 } else if ( -1 != e.target.className.indexOf('menu-delete') ) {
811 return that.eventOnClickMenuDelete(e.target);
812 } else if ( -1 != e.target.className.indexOf('item-delete') ) {
813 return that.eventOnClickMenuItemDelete(e.target);
814 } else if ( -1 != e.target.className.indexOf('item-cancel') ) {
815 return that.eventOnClickCancelLink(e.target);
819 $('#add-custom-links input[type="text"]').keypress(function(e){
820 if ( e.keyCode === 13 ) {
822 $( '#submit-customlinkdiv' ).click();
828 * An interface for managing default values for input elements
829 * that is both JS and accessibility-friendly.
831 * Input elements that add the class 'input-with-default-title'
832 * will have their values set to the provided HTML title when empty.
834 setupInputWithDefaultTitle : function() {
835 var name = 'input-with-default-title';
837 $('.' + name).each( function(){
838 var $t = $(this), title = $t.attr('title'), val = $t.val();
839 $t.data( name, title );
841 if( '' === val ) $t.val( title );
842 else if ( title == val ) return;
843 else $t.removeClass( name );
844 }).focus( function(){
846 if( $t.val() == $t.data(name) )
847 $t.val('').removeClass( name );
850 if( '' === $t.val() )
851 $t.addClass( name ).val( $t.data(name) );
854 $( '.blank-slate .input-with-default-title' ).focus();
857 attachThemeLocationsListeners : function() {
858 var loc = $('#nav-menu-theme-locations'), params = {};
859 params.action = 'menu-locations-save';
860 params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
861 loc.find('input[type="submit"]').click(function() {
862 loc.find('select').each(function() {
863 params[this.name] = $(this).val();
865 loc.find( '.spinner' ).addClass( 'is-active' );
866 $.post( ajaxurl, params, function() {
867 loc.find( '.spinner' ).removeClass( 'is-active' );
873 attachQuickSearchListeners : function() {
876 $('.quick-search').keypress(function(e){
879 if( 13 == e.which ) {
880 api.updateQuickSearchResults( t );
884 if( searchTimer ) clearTimeout(searchTimer);
886 searchTimer = setTimeout(function(){
887 api.updateQuickSearchResults( t );
889 }).attr('autocomplete','off');
892 updateQuickSearchResults : function(input) {
897 if( q.length < minSearchLength ) return;
899 panel = input.parents('.tabs-panel');
901 'action': 'menu-quick-search',
902 'response-format': 'markup',
903 'menu': $('#menu').val(),
904 'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
906 'type': input.attr('name')
909 $( '.spinner', panel ).addClass( 'is-active' );
911 $.post( ajaxurl, params, function(menuMarkup) {
912 api.processQuickSearchQueryResponse(menuMarkup, params, panel);
916 addCustomLink : function( processMethod ) {
917 var url = $('#custom-menu-item-url').val(),
918 label = $('#custom-menu-item-name').val();
920 processMethod = processMethod || api.addMenuItemToBottom;
922 if ( '' === url || 'http://' == url )
925 // Show the ajax spinner
926 $( '.customlinkdiv .spinner' ).addClass( 'is-active' );
927 this.addLinkToMenu( url, label, processMethod, function() {
928 // Remove the ajax spinner
929 $( '.customlinkdiv .spinner' ).removeClass( 'is-active' );
930 // Set custom link form back to defaults
931 $('#custom-menu-item-name').val('').blur();
932 $('#custom-menu-item-url').val('http://');
936 addLinkToMenu : function(url, label, processMethod, callback) {
937 processMethod = processMethod || api.addMenuItemToBottom;
938 callback = callback || function(){};
942 'menu-item-type': 'custom',
943 'menu-item-url': url,
944 'menu-item-title': label
946 }, processMethod, callback);
949 addItemToMenu : function(menuItem, processMethod, callback) {
950 var menu = $('#menu').val(),
951 nonce = $('#menu-settings-column-nonce').val(),
954 processMethod = processMethod || function(){};
955 callback = callback || function(){};
958 'action': 'add-menu-item',
960 'menu-settings-column-nonce': nonce,
961 'menu-item': menuItem
964 $.post( ajaxurl, params, function(menuMarkup) {
965 var ins = $('#menu-instructions');
967 menuMarkup = $.trim( menuMarkup ); // Trim leading whitespaces
968 processMethod(menuMarkup, params);
970 // Make it stand out a bit more visually, by adding a fadeIn
971 $( 'li.pending' ).hide().fadeIn('slow');
972 $( '.drag-instructions' ).show();
973 if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
974 ins.addClass( 'menu-instructions-inactive' );
981 * Process the add menu item request response into menu list item.
983 * @param string menuMarkup The text server response of menu item markup.
984 * @param object req The request arguments.
986 addMenuItemToBottom : function( menuMarkup ) {
987 $(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
988 api.refreshKeyboardAccessibility();
989 api.refreshAdvancedAccessibility();
992 addMenuItemToTop : function( menuMarkup ) {
993 $(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
994 api.refreshKeyboardAccessibility();
995 api.refreshAdvancedAccessibility();
998 attachUnsavedChangesListener : function() {
999 $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){
1000 api.registerChange();
1003 if ( 0 !== $('#menu-to-edit').length || 0 !== $('.menu-location-menus select').length ) {
1004 window.onbeforeunload = function(){
1005 if ( api.menusChanged )
1006 return navMenuL10n.saveAlert;
1009 // Make the post boxes read-only, as they can't be used yet
1010 $( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' );
1014 registerChange : function() {
1015 api.menusChanged = true;
1018 attachTabsPanelListeners : function() {
1019 $('#menu-settings-column').bind('click', function(e) {
1020 var selectAreaMatch, panelId, wrapper, items,
1021 target = $(e.target);
1023 if ( target.hasClass('nav-tab-link') ) {
1025 panelId = target.data( 'type' );
1027 wrapper = target.parents('.accordion-section-content').first();
1029 // upon changing tabs, we want to uncheck all checkboxes
1030 $('input', wrapper).removeAttr('checked');
1032 $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
1033 $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
1035 $('.tabs', wrapper).removeClass('tabs');
1036 target.parent().addClass('tabs');
1038 // select the search bar
1039 $('.quick-search', wrapper).focus();
1042 } else if ( target.hasClass('select-all') ) {
1043 selectAreaMatch = /#(.*)$/.exec(e.target.href);
1044 if ( selectAreaMatch && selectAreaMatch[1] ) {
1045 items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
1046 if( items.length === items.filter(':checked').length )
1047 items.removeAttr('checked');
1049 items.prop('checked', true);
1052 } else if ( target.hasClass('submit-add-to-menu') ) {
1053 api.registerChange();
1055 if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
1056 api.addCustomLink( api.addMenuItemToBottom );
1057 else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
1058 $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
1060 } else if ( target.hasClass('page-numbers') ) {
1061 $.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
1063 if ( -1 == resp.indexOf('replace-id') )
1066 var metaBoxData = $.parseJSON(resp),
1067 toReplace = document.getElementById(metaBoxData['replace-id']),
1068 placeholder = document.createElement('div'),
1069 wrap = document.createElement('div');
1071 if ( ! metaBoxData.markup || ! toReplace )
1074 wrap.innerHTML = metaBoxData.markup ? metaBoxData.markup : '';
1076 toReplace.parentNode.insertBefore( placeholder, toReplace );
1077 placeholder.parentNode.removeChild( toReplace );
1079 placeholder.parentNode.insertBefore( wrap, placeholder );
1081 placeholder.parentNode.removeChild( placeholder );
1091 eventOnClickEditLink : function(clickedEl) {
1093 matchedSection = /#(.*)$/.exec(clickedEl.href);
1094 if ( matchedSection && matchedSection[1] ) {
1095 settings = $('#'+matchedSection[1]);
1096 item = settings.parent();
1097 if( 0 !== item.length ) {
1098 if( item.hasClass('menu-item-edit-inactive') ) {
1099 if( ! settings.data('menu-item-data') ) {
1100 settings.data( 'menu-item-data', settings.getItemData() );
1102 settings.slideDown('fast');
1103 item.removeClass('menu-item-edit-inactive')
1104 .addClass('menu-item-edit-active');
1106 settings.slideUp('fast');
1107 item.removeClass('menu-item-edit-active')
1108 .addClass('menu-item-edit-inactive');
1115 eventOnClickCancelLink : function(clickedEl) {
1116 var settings = $( clickedEl ).closest( '.menu-item-settings' ),
1117 thisMenuItem = $( clickedEl ).closest( '.menu-item' );
1118 thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive');
1119 settings.setItemData( settings.data('menu-item-data') ).hide();
1123 eventOnClickMenuSave : function() {
1125 menuName = $('#menu-name'),
1126 menuNameVal = menuName.val();
1127 // Cancel and warn if invalid menu name
1128 if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
1129 menuName.parent().addClass('form-invalid');
1132 // Copy menu theme locations
1133 $('#nav-menu-theme-locations select').each(function() {
1134 locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
1136 $('#update-nav-menu').append( locs );
1137 // Update menu item position data
1138 api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
1139 window.onbeforeunload = null;
1144 eventOnClickMenuDelete : function() {
1145 // Delete warning AYS
1146 if ( window.confirm( navMenuL10n.warnDeleteMenu ) ) {
1147 window.onbeforeunload = null;
1153 eventOnClickMenuItemDelete : function(clickedEl) {
1154 var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
1155 api.removeMenuItem( $('#menu-item-' + itemID) );
1156 api.registerChange();
1161 * Process the quick search response into a search result
1163 * @param string resp The server response to the query.
1164 * @param object req The request arguments.
1165 * @param jQuery panel The tabs panel we're searching in.
1167 processQuickSearchQueryResponse : function(resp, req, panel) {
1170 form = document.getElementById('nav-menu-meta'),
1171 pattern = /menu-item[(\[^]\]*/,
1172 $items = $('<div>').html(resp).find('li'),
1175 if( ! $items.length ) {
1176 $('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
1177 $( '.spinner', panel ).removeClass( 'is-active' );
1181 $items.each(function(){
1184 // make a unique DB ID number
1185 matched = pattern.exec($item.html());
1187 if ( matched && matched[1] ) {
1189 while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
1193 takenIDs[newID] = true;
1194 if ( newID != matched[1] ) {
1195 $item.html( $item.html().replace(new RegExp(
1196 'menu-item\\[' + matched[1] + '\\]', 'g'),
1197 'menu-item[' + newID + ']'
1203 $('.categorychecklist', panel).html( $items );
1204 $( '.spinner', panel ).removeClass( 'is-active' );
1207 removeMenuItem : function(el) {
1208 var children = el.childMenuItems();
1210 el.addClass('deleting').animate({
1213 }, 350, function() {
1214 var ins = $('#menu-instructions');
1216 children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
1217 if ( 0 === $( '#menu-to-edit li' ).length ) {
1218 $( '.drag-instructions' ).hide();
1219 ins.removeClass( 'menu-instructions-inactive' );
1221 api.refreshAdvancedAccessibility();
1225 depthToPx : function(depth) {
1226 return depth * api.options.menuItemDepthPerLevel;
1229 pxToDepth : function(px) {
1230 return Math.floor(px / api.options.menuItemDepthPerLevel);
1235 $(document).ready(function(){ wpNavMenu.init(); });