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,
34 // Functions that run on init.
36 api.menuList = $('#menu-to-edit');
37 api.targetList = api.menuList;
39 this.jQueryExtensions();
41 this.attachMenuEditListeners();
43 this.setupInputWithDefaultTitle();
44 this.attachQuickSearchListeners();
45 this.attachThemeLocationsListeners();
47 this.attachTabsPanelListeners();
49 this.attachUnsavedChangesListener();
51 if ( api.menuList.length )
54 if ( menus.oneThemeLocationNoMenus )
55 $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom );
57 this.initManageLocations();
59 this.initAccessibility();
63 this.initPreviewing();
66 jQueryExtensions : function() {
69 menuItemDepth : function() {
70 var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
71 return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
73 updateDepthClass : function(current, prev) {
74 return this.each(function(){
76 prev = prev || t.menuItemDepth();
77 $(this).removeClass('menu-item-depth-'+ prev )
78 .addClass('menu-item-depth-'+ current );
81 shiftDepthClass : function(change) {
82 return this.each(function(){
84 depth = t.menuItemDepth();
85 $(this).removeClass('menu-item-depth-'+ depth )
86 .addClass('menu-item-depth-'+ (depth + change) );
89 childMenuItems : function() {
92 var t = $(this), depth = t.menuItemDepth(), next = t.next( '.menu-item' );
93 while( next.length && next.menuItemDepth() > depth ) {
94 result = result.add( next );
95 next = next.next( '.menu-item' );
100 shiftHorizontally : function( dir ) {
101 return this.each(function(){
103 depth = t.menuItemDepth(),
104 newDepth = depth + dir;
106 // Change .menu-item-depth-n class
107 t.moveHorizontally( newDepth, depth );
110 moveHorizontally : function( newDepth, depth ) {
111 return this.each(function(){
113 children = t.childMenuItems(),
114 diff = newDepth - depth,
115 subItemText = t.find('.is-submenu');
117 // Change .menu-item-depth-n class
118 t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId();
120 // If it has children, move those too
122 children.each(function() {
124 thisDepth = t.menuItemDepth(),
125 newDepth = thisDepth + diff;
126 t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId();
130 // Show "Sub item" helper text
137 updateParentMenuItemDBId : function() {
138 return this.each(function(){
140 input = item.find( '.menu-item-data-parent-id' ),
141 depth = parseInt( item.menuItemDepth(), 10 ),
142 parentDepth = depth - 1,
143 parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first();
145 if ( 0 === depth ) { // Item is on the top level, has no parent
147 } else { // Find the parent item, and retrieve its object id.
148 input.val( parent.find( '.menu-item-data-db-id' ).val() );
152 hideAdvancedMenuItemFields : function() {
153 return this.each(function(){
155 $('.hide-column-tog').not(':checked').each(function(){
156 that.find('.field-' + $(this).val() ).addClass('hidden-field');
161 * Adds selected menu items to the menu.
163 * @param jQuery metabox The metabox jQuery object.
165 addSelectedToMenu : function(processMethod) {
166 if ( 0 === $('#menu-to-edit').length ) {
170 return this.each(function() {
171 var t = $(this), menuItems = {},
172 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' ),
173 re = /menu-item\[([^\]]*)/;
175 processMethod = processMethod || api.addMenuItemToBottom;
177 // If no items are checked, bail.
178 if ( !checkboxes.length )
181 // Show the ajax spinner
182 t.find( '.spinner' ).addClass( 'is-active' );
184 // Retrieve menu item data
185 $(checkboxes).each(function(){
187 listItemDBIDMatch = re.exec( t.attr('name') ),
188 listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
190 if ( this.className && -1 != this.className.indexOf('add-to-top') )
191 processMethod = api.addMenuItemToTop;
192 menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
196 api.addItemToMenu(menuItems, processMethod, function(){
197 // Deselect the items and hide the ajax spinner
198 checkboxes.removeAttr('checked');
199 t.find( '.spinner' ).removeClass( 'is-active' );
203 getItemData : function( itemType, id ) {
204 itemType = itemType || 'menu-item';
206 var itemData = {}, i,
209 'menu-item-object-id',
211 'menu-item-parent-id',
212 'menu-item-position',
216 'menu-item-description',
217 'menu-item-attr-title',
223 if( !id && itemType == 'menu-item' ) {
224 id = this.find('.menu-item-data-db-id').val();
227 if( !id ) return itemData;
229 this.find('input').each(function() {
233 if( itemType == 'menu-item' )
234 field = fields[i] + '[' + id + ']';
235 else if( itemType == 'add-menu-item' )
236 field = 'menu-item[' + id + '][' + fields[i] + ']';
242 itemData[fields[i]] = this.value;
249 setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
250 itemType = itemType || 'menu-item';
252 if( !id && itemType == 'menu-item' ) {
253 id = $('.menu-item-data-db-id', this).val();
256 if( !id ) return this;
258 this.find('input').each(function() {
259 var t = $(this), field;
260 $.each( itemData, function( attr, val ) {
261 if( itemType == 'menu-item' )
262 field = attr + '[' + id + ']';
263 else if( itemType == 'add-menu-item' )
264 field = 'menu-item[' + id + '][' + attr + ']';
266 if ( field == t.attr('name') ) {
276 countMenuItems : function( depth ) {
277 return $( '.menu-item-depth-' + depth ).length;
280 moveMenuItem : function( $this, dir ) {
282 var items, newItemPosition, newDepth,
283 menuItems = $( '#menu-to-edit li' ),
284 menuItemsCount = menuItems.length,
285 thisItem = $this.parents( 'li.menu-item' ),
286 thisItemChildren = thisItem.childMenuItems(),
287 thisItemData = thisItem.getItemData(),
288 thisItemDepth = parseInt( thisItem.menuItemDepth(), 10 ),
289 thisItemPosition = parseInt( thisItem.index(), 10 ),
290 nextItem = thisItem.next(),
291 nextItemChildren = nextItem.childMenuItems(),
292 nextItemDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1,
293 prevItem = thisItem.prev(),
294 prevItemDepth = parseInt( prevItem.menuItemDepth(), 10 ),
295 prevItemId = prevItem.getItemData()['menu-item-db-id'];
299 newItemPosition = thisItemPosition - 1;
302 if ( 0 === thisItemPosition )
305 // If a sub item is moved to top, shift it to 0 depth
306 if ( 0 === newItemPosition && 0 !== thisItemDepth )
307 thisItem.moveHorizontally( 0, thisItemDepth );
309 // If prev item is sub item, shift to match depth
310 if ( 0 !== prevItemDepth )
311 thisItem.moveHorizontally( prevItemDepth, thisItemDepth );
313 // Does this item have sub items?
314 if ( thisItemChildren ) {
315 items = thisItem.add( thisItemChildren );
316 // Move the entire block
317 items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
319 thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
323 // Does this item have sub items?
324 if ( thisItemChildren ) {
325 items = thisItem.add( thisItemChildren ),
326 nextItem = menuItems.eq( items.length + thisItemPosition ),
327 nextItemChildren = 0 !== nextItem.childMenuItems().length;
329 if ( nextItemChildren ) {
330 newDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1;
331 thisItem.moveHorizontally( newDepth, thisItemDepth );
334 // Have we reached the bottom?
335 if ( menuItemsCount === thisItemPosition + items.length )
338 items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId();
340 // If next item has sub items, shift depth
341 if ( 0 !== nextItemChildren.length )
342 thisItem.moveHorizontally( nextItemDepth, thisItemDepth );
344 // Have we reached the bottom
345 if ( menuItemsCount === thisItemPosition + 1 )
347 thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId();
352 if ( 0 === thisItemPosition )
354 // Does this item have sub items?
355 if ( thisItemChildren ) {
356 items = thisItem.add( thisItemChildren );
357 // Move the entire block
358 items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
360 thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
364 // As far left as possible
365 if ( 0 === thisItemDepth )
367 thisItem.shiftHorizontally( -1 );
370 // Can't be sub item at top
371 if ( 0 === thisItemPosition )
373 // Already sub item of prevItem
374 if ( thisItemData['menu-item-parent-id'] === prevItemId )
376 thisItem.shiftHorizontally( 1 );
380 api.registerChange();
381 api.refreshKeyboardAccessibility();
382 api.refreshAdvancedAccessibility();
385 initAccessibility : function() {
386 var menu = $( '#menu-to-edit' );
388 api.refreshKeyboardAccessibility();
389 api.refreshAdvancedAccessibility();
391 // Refresh the accessibility when the user comes close to the item in any way
392 menu.on( 'mouseenter.refreshAccessibility focus.refreshAccessibility touchstart.refreshAccessibility' , '.menu-item' , function(){
393 api.refreshAdvancedAccessibilityOfItem( $( this ).find( 'a.item-edit' ) );
396 // We have to update on click as well because we might hover first, change the item, and then click.
397 menu.on( 'click', 'a.item-edit', function() {
398 api.refreshAdvancedAccessibilityOfItem( $( this ) );
401 // Links for moving items
402 menu.on( 'click', '.menus-move', function ( e ) {
403 var $this = $( this ),
404 dir = $this.data( 'dir' );
406 if ( 'undefined' !== typeof dir ) {
407 api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), dir );
414 * refreshAdvancedAccessibilityOfItem( [itemToRefresh] )
416 * Refreshes advanced accessibility buttons for one menu item.
417 * Shows or hides buttons based on the location of the menu item.
419 * @param {object} itemToRefresh The menu item that might need its advanced accessibility buttons refreshed
421 refreshAdvancedAccessibilityOfItem : function( itemToRefresh ) {
423 // Only refresh accessibility when necessary
424 if ( true !== $( itemToRefresh ).data( 'needs_accessibility_refresh' ) ) {
428 var thisLink, thisLinkText, primaryItems, itemPosition, title,
429 parentItem, parentItemId, parentItemName, subItems,
430 $this = $( itemToRefresh ),
431 menuItem = $this.closest( 'li.menu-item' ).first(),
432 depth = menuItem.menuItemDepth(),
433 isPrimaryMenuItem = ( 0 === depth ),
434 itemName = $this.closest( '.menu-item-handle' ).find( '.menu-item-title' ).text(),
435 position = parseInt( menuItem.index(), 10 ),
436 prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1, 10 ),
437 prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(),
438 prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(),
439 totalMenuItems = $('#menu-to-edit li').length,
440 hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length;
442 menuItem.find( '.field-move' ).toggle( totalMenuItems > 1 );
444 // Where can they move this menu item?
445 if ( 0 !== position ) {
446 thisLink = menuItem.find( '.menus-move-up' );
447 thisLink.prop( 'title', menus.moveUp ).css( 'display', 'inline' );
450 if ( 0 !== position && isPrimaryMenuItem ) {
451 thisLink = menuItem.find( '.menus-move-top' );
452 thisLink.prop( 'title', menus.moveToTop ).css( 'display', 'inline' );
455 if ( position + 1 !== totalMenuItems && 0 !== position ) {
456 thisLink = menuItem.find( '.menus-move-down' );
457 thisLink.prop( 'title', menus.moveDown ).css( 'display', 'inline' );
460 if ( 0 === position && 0 !== hasSameDepthSibling ) {
461 thisLink = menuItem.find( '.menus-move-down' );
462 thisLink.prop( 'title', menus.moveDown ).css( 'display', 'inline' );
465 if ( ! isPrimaryMenuItem ) {
466 thisLink = menuItem.find( '.menus-move-left' ),
467 thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft );
468 thisLink.prop( 'title', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).text( thisLinkText ).css( 'display', 'inline' );
471 if ( 0 !== position ) {
472 if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) {
473 thisLink = menuItem.find( '.menus-move-right' ),
474 thisLinkText = menus.under.replace( '%s', prevItemNameRight );
475 thisLink.prop( 'title', menus.moveUnder.replace( '%s', prevItemNameRight ) ).text( thisLinkText ).css( 'display', 'inline' );
479 if ( isPrimaryMenuItem ) {
480 primaryItems = $( '.menu-item-depth-0' ),
481 itemPosition = primaryItems.index( menuItem ) + 1,
482 totalMenuItems = primaryItems.length,
484 // String together help text for primary menu items
485 title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems );
487 parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).first(),
488 parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
489 parentItemName = parentItem.find( '.menu-item-title' ).text(),
490 subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
491 itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
493 // String together help text for sub menu items
494 title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName );
497 $this.prop('title', title).text( title );
499 // Mark this item's accessibility as refreshed
500 $this.data( 'needs_accessibility_refresh', false );
504 * refreshAdvancedAccessibility
506 * Hides all advanced accessibility buttons and marks them for refreshing.
508 refreshAdvancedAccessibility : function() {
510 // Hide all links by default
511 $( '.menu-item-settings .field-move a' ).hide();
513 // Mark all menu items as unprocessed
514 $( 'a.item-edit' ).data( 'needs_accessibility_refresh', true );
516 // All open items have to be refreshed or they will show no links
517 $( '.menu-item-edit-active a.item-edit' ).each( function() {
518 api.refreshAdvancedAccessibilityOfItem( this );
522 refreshKeyboardAccessibility : function() {
523 $( 'a.item-edit' ).off( 'focus' ).on( 'focus', function(){
524 $(this).off( 'keydown' ).on( 'keydown', function(e){
528 thisItem = $this.parents( 'li.menu-item' ),
529 thisItemData = thisItem.getItemData();
531 // Bail if it's not an arrow key
532 if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
535 // Avoid multiple keydown events
536 $this.off('keydown');
538 // Bail if there is only one menu item
539 if ( 1 === $('#menu-to-edit li').length )
542 // If RTL, swap left/right arrows
543 arrows = { '38': 'up', '40': 'down', '37': 'left', '39': 'right' };
544 if ( $('body').hasClass('rtl') )
545 arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
547 switch ( arrows[e.which] ) {
549 api.moveMenuItem( $this, 'up' );
552 api.moveMenuItem( $this, 'down' );
555 api.moveMenuItem( $this, 'left' );
558 api.moveMenuItem( $this, 'right' );
561 // Put focus back on same menu item
562 $( '#edit-' + thisItemData['menu-item-db-id'] ).focus();
568 initPreviewing : function() {
569 // Update the item handle title when the navigation label is changed.
570 $( '#menu-to-edit' ).on( 'change input', '.edit-menu-item-title', function(e) {
571 var input = $( e.currentTarget ), title, titleEl;
573 titleEl = input.closest( '.menu-item' ).find( '.menu-item-title' );
574 // Don't update to empty title.
576 titleEl.text( title ).removeClass( 'no-title' );
578 titleEl.text( navMenuL10n.untitled ).addClass( 'no-title' );
583 initToggles : function() {
585 postboxes.add_postbox_toggles('nav-menus');
587 // adjust columns functions for menus UI
588 columns.useCheckboxesForHidden();
589 columns.checked = function(field) {
590 $('.field-' + field).removeClass('hidden-field');
592 columns.unchecked = function(field) {
593 $('.field-' + field).addClass('hidden-field');
596 api.menuList.hideAdvancedMenuItemFields();
598 $('.hide-postbox-tog').click(function () {
599 var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
601 action: 'closed-postboxes',
603 closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
609 initSortables : function() {
610 var currentDepth = 0, originalDepth, minDepth, maxDepth,
611 prev, next, prevBottom, nextThreshold, helperHeight, transport,
612 menuEdge = api.menuList.offset().left,
613 body = $('body'), maxChildDepth,
614 menuMaxDepth = initialMenuMaxDepth();
616 if( 0 !== $( '#menu-to-edit li' ).length )
617 $( '.drag-instructions' ).show();
619 // Use the right edge if RTL.
620 menuEdge += api.isRTL ? api.menuList.width() : 0;
622 api.menuList.sortable({
623 handle: '.menu-item-handle',
624 placeholder: 'sortable-placeholder',
625 items: api.options.sortableItems,
626 start: function(e, ui) {
627 var height, width, parent, children, tempHolder;
629 // handle placement for rtl orientation
631 ui.item[0].style.right = 'auto';
633 transport = ui.item.children('.menu-item-transport');
635 // Set depths. currentDepth must be set before children are located.
636 originalDepth = ui.item.menuItemDepth();
637 updateCurrentDepth(ui, originalDepth);
639 // Attach child elements to parent
640 // Skip the placeholder
641 parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
642 children = parent.childMenuItems();
643 transport.append( children );
645 // Update the height of the placeholder to match the moving item.
646 height = transport.outerHeight();
647 // If there are children, account for distance between top of children and parent
648 height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
649 height += ui.helper.outerHeight();
650 helperHeight = height;
651 height -= 2; // Subtract 2 for borders
652 ui.placeholder.height(height);
654 // Update the width of the placeholder to match the moving item.
655 maxChildDepth = originalDepth;
656 children.each(function(){
657 var depth = $(this).menuItemDepth();
658 maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
660 width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
661 width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
662 width -= 2; // Subtract 2 for borders
663 ui.placeholder.width(width);
665 // Update the list of menu items.
666 tempHolder = ui.placeholder.next( '.menu-item' );
667 tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
668 ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
669 $(this).sortable( 'refresh' ); // The children aren't sortable. We should let jQ UI know.
670 ui.item.after( ui.placeholder ); // reattach the placeholder.
671 tempHolder.css('margin-top', 0); // reset the margin
673 // Now that the element is complete, we can update...
674 updateSharedVars(ui);
676 stop: function(e, ui) {
677 var children, subMenuTitle,
678 depthChange = currentDepth - originalDepth;
680 // Return child elements to the list
681 children = transport.children().insertAfter(ui.item);
683 // Add "sub menu" description
684 subMenuTitle = ui.item.find( '.item-title .is-submenu' );
685 if ( 0 < currentDepth )
690 // Update depth classes
691 if ( 0 !== depthChange ) {
692 ui.item.updateDepthClass( currentDepth );
693 children.shiftDepthClass( depthChange );
694 updateMenuMaxDepth( depthChange );
697 api.registerChange();
698 // Update the item data.
699 ui.item.updateParentMenuItemDBId();
701 // address sortable's incorrectly-calculated top in opera
702 ui.item[0].style.top = 0;
704 // handle drop placement for rtl orientation
706 ui.item[0].style.left = 'auto';
707 ui.item[0].style.right = 0;
710 api.refreshKeyboardAccessibility();
711 api.refreshAdvancedAccessibility();
713 change: function(e, ui) {
714 // Make sure the placeholder is inside the menu.
715 // Otherwise fix it, or we're in trouble.
716 if( ! ui.placeholder.parent().hasClass('menu') )
717 (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
719 updateSharedVars(ui);
721 sort: function(e, ui) {
722 var offset = ui.helper.offset(),
723 edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
724 depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
726 // Check and correct if depth is not within range.
727 // Also, if the dragged element is dragged upwards over
728 // an item, shift the placeholder to a child position.
729 if ( depth > maxDepth || offset.top < ( prevBottom - api.options.targetTolerance ) ) {
731 } else if ( depth < minDepth ) {
735 if( depth != currentDepth )
736 updateCurrentDepth(ui, depth);
738 // If we overlap the next element, manually shift downwards
739 if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
740 next.after( ui.placeholder );
741 updateSharedVars( ui );
742 $( this ).sortable( 'refreshPositions' );
747 function updateSharedVars(ui) {
750 prev = ui.placeholder.prev( '.menu-item' );
751 next = ui.placeholder.next( '.menu-item' );
753 // Make sure we don't select the moving item.
754 if( prev[0] == ui.item[0] ) prev = prev.prev( '.menu-item' );
755 if( next[0] == ui.item[0] ) next = next.next( '.menu-item' );
757 prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
758 nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
759 minDepth = (next.length) ? next.menuItemDepth() : 0;
762 maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
767 function updateCurrentDepth(ui, depth) {
768 ui.placeholder.updateDepthClass( depth, currentDepth );
769 currentDepth = depth;
772 function initialMenuMaxDepth() {
773 if( ! body[0].className ) return 0;
774 var match = body[0].className.match(/menu-max-depth-(\d+)/);
775 return match && match[1] ? parseInt( match[1], 10 ) : 0;
778 function updateMenuMaxDepth( depthChange ) {
779 var depth, newDepth = menuMaxDepth;
780 if ( depthChange === 0 ) {
782 } else if ( depthChange > 0 ) {
783 depth = maxChildDepth + depthChange;
784 if( depth > menuMaxDepth )
786 } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
787 while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
790 // Update the depth class.
791 body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
792 menuMaxDepth = newDepth;
796 initManageLocations : function () {
797 $('#menu-locations-wrap form').submit(function(){
798 window.onbeforeunload = null;
800 $('.menu-location-menus select').on('change', function () {
801 var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
802 if ($(this).find('option:selected').data('orig'))
809 attachMenuEditListeners : function() {
811 $('#update-nav-menu').bind('click', function(e) {
812 if ( e.target && e.target.className ) {
813 if ( -1 != e.target.className.indexOf('item-edit') ) {
814 return that.eventOnClickEditLink(e.target);
815 } else if ( -1 != e.target.className.indexOf('menu-save') ) {
816 return that.eventOnClickMenuSave(e.target);
817 } else if ( -1 != e.target.className.indexOf('menu-delete') ) {
818 return that.eventOnClickMenuDelete(e.target);
819 } else if ( -1 != e.target.className.indexOf('item-delete') ) {
820 return that.eventOnClickMenuItemDelete(e.target);
821 } else if ( -1 != e.target.className.indexOf('item-cancel') ) {
822 return that.eventOnClickCancelLink(e.target);
826 $('#add-custom-links input[type="text"]').keypress(function(e){
827 $('#customlinkdiv').removeClass('form-invalid');
829 if ( e.keyCode === 13 ) {
831 $( '#submit-customlinkdiv' ).click();
837 * An interface for managing default values for input elements
838 * that is both JS and accessibility-friendly.
840 * Input elements that add the class 'input-with-default-title'
841 * will have their values set to the provided HTML title when empty.
843 setupInputWithDefaultTitle : function() {
844 var name = 'input-with-default-title';
846 $('.' + name).each( function(){
847 var $t = $(this), title = $t.attr('title'), val = $t.val();
848 $t.data( name, title );
850 if( '' === val ) $t.val( title );
851 else if ( title == val ) return;
852 else $t.removeClass( name );
853 }).focus( function(){
855 if( $t.val() == $t.data(name) )
856 $t.val('').removeClass( name );
859 if( '' === $t.val() )
860 $t.addClass( name ).val( $t.data(name) );
863 $( '.blank-slate .input-with-default-title' ).focus();
866 attachThemeLocationsListeners : function() {
867 var loc = $('#nav-menu-theme-locations'), params = {};
868 params.action = 'menu-locations-save';
869 params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
870 loc.find('input[type="submit"]').click(function() {
871 loc.find('select').each(function() {
872 params[this.name] = $(this).val();
874 loc.find( '.spinner' ).addClass( 'is-active' );
875 $.post( ajaxurl, params, function() {
876 loc.find( '.spinner' ).removeClass( 'is-active' );
882 attachQuickSearchListeners : function() {
885 $('.quick-search').keypress(function(e){
888 if( 13 == e.which ) {
889 api.updateQuickSearchResults( t );
893 if( searchTimer ) clearTimeout(searchTimer);
895 searchTimer = setTimeout(function(){
896 api.updateQuickSearchResults( t );
898 }).attr('autocomplete','off');
901 updateQuickSearchResults : function(input) {
906 if( q.length < minSearchLength ) return;
908 panel = input.parents('.tabs-panel');
910 'action': 'menu-quick-search',
911 'response-format': 'markup',
912 'menu': $('#menu').val(),
913 'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
915 'type': input.attr('name')
918 $( '.spinner', panel ).addClass( 'is-active' );
920 $.post( ajaxurl, params, function(menuMarkup) {
921 api.processQuickSearchQueryResponse(menuMarkup, params, panel);
925 addCustomLink : function( processMethod ) {
926 var url = $('#custom-menu-item-url').val(),
927 label = $('#custom-menu-item-name').val();
929 processMethod = processMethod || api.addMenuItemToBottom;
931 if ( '' === url || 'http://' == url ) {
932 $('#customlinkdiv').addClass('form-invalid');
936 // Show the ajax spinner
937 $( '.customlinkdiv .spinner' ).addClass( 'is-active' );
938 this.addLinkToMenu( url, label, processMethod, function() {
939 // Remove the ajax spinner
940 $( '.customlinkdiv .spinner' ).removeClass( 'is-active' );
941 // Set custom link form back to defaults
942 $('#custom-menu-item-name').val('').blur();
943 $('#custom-menu-item-url').val('http://');
947 addLinkToMenu : function(url, label, processMethod, callback) {
948 processMethod = processMethod || api.addMenuItemToBottom;
949 callback = callback || function(){};
953 'menu-item-type': 'custom',
954 'menu-item-url': url,
955 'menu-item-title': label
957 }, processMethod, callback);
960 addItemToMenu : function(menuItem, processMethod, callback) {
961 var menu = $('#menu').val(),
962 nonce = $('#menu-settings-column-nonce').val(),
965 processMethod = processMethod || function(){};
966 callback = callback || function(){};
969 'action': 'add-menu-item',
971 'menu-settings-column-nonce': nonce,
972 'menu-item': menuItem
975 $.post( ajaxurl, params, function(menuMarkup) {
976 var ins = $('#menu-instructions');
978 menuMarkup = $.trim( menuMarkup ); // Trim leading whitespaces
979 processMethod(menuMarkup, params);
981 // Make it stand out a bit more visually, by adding a fadeIn
982 $( 'li.pending' ).hide().fadeIn('slow');
983 $( '.drag-instructions' ).show();
984 if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
985 ins.addClass( 'menu-instructions-inactive' );
992 * Process the add menu item request response into menu list item.
994 * @param string menuMarkup The text server response of menu item markup.
995 * @param object req The request arguments.
997 addMenuItemToBottom : function( menuMarkup ) {
998 $(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
999 api.refreshKeyboardAccessibility();
1000 api.refreshAdvancedAccessibility();
1003 addMenuItemToTop : function( menuMarkup ) {
1004 $(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
1005 api.refreshKeyboardAccessibility();
1006 api.refreshAdvancedAccessibility();
1009 attachUnsavedChangesListener : function() {
1010 $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){
1011 api.registerChange();
1014 if ( 0 !== $('#menu-to-edit').length || 0 !== $('.menu-location-menus select').length ) {
1015 window.onbeforeunload = function(){
1016 if ( api.menusChanged )
1017 return navMenuL10n.saveAlert;
1020 // Make the post boxes read-only, as they can't be used yet
1021 $( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' );
1025 registerChange : function() {
1026 api.menusChanged = true;
1029 attachTabsPanelListeners : function() {
1030 $('#menu-settings-column').bind('click', function(e) {
1031 var selectAreaMatch, panelId, wrapper, items,
1032 target = $(e.target);
1034 if ( target.hasClass('nav-tab-link') ) {
1036 panelId = target.data( 'type' );
1038 wrapper = target.parents('.accordion-section-content').first();
1040 // upon changing tabs, we want to uncheck all checkboxes
1041 $('input', wrapper).removeAttr('checked');
1043 $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
1044 $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
1046 $('.tabs', wrapper).removeClass('tabs');
1047 target.parent().addClass('tabs');
1049 // select the search bar
1050 $('.quick-search', wrapper).focus();
1053 } else if ( target.hasClass('select-all') ) {
1054 selectAreaMatch = /#(.*)$/.exec(e.target.href);
1055 if ( selectAreaMatch && selectAreaMatch[1] ) {
1056 items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
1057 if( items.length === items.filter(':checked').length )
1058 items.removeAttr('checked');
1060 items.prop('checked', true);
1063 } else if ( target.hasClass('submit-add-to-menu') ) {
1064 api.registerChange();
1066 if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
1067 api.addCustomLink( api.addMenuItemToBottom );
1068 else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
1069 $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
1071 } else if ( target.hasClass('page-numbers') ) {
1072 $.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
1074 if ( -1 == resp.indexOf('replace-id') )
1077 var metaBoxData = $.parseJSON(resp),
1078 toReplace = document.getElementById(metaBoxData['replace-id']),
1079 placeholder = document.createElement('div'),
1080 wrap = document.createElement('div');
1082 if ( ! metaBoxData.markup || ! toReplace )
1085 wrap.innerHTML = metaBoxData.markup ? metaBoxData.markup : '';
1087 toReplace.parentNode.insertBefore( placeholder, toReplace );
1088 placeholder.parentNode.removeChild( toReplace );
1090 placeholder.parentNode.insertBefore( wrap, placeholder );
1092 placeholder.parentNode.removeChild( placeholder );
1102 eventOnClickEditLink : function(clickedEl) {
1104 matchedSection = /#(.*)$/.exec(clickedEl.href);
1105 if ( matchedSection && matchedSection[1] ) {
1106 settings = $('#'+matchedSection[1]);
1107 item = settings.parent();
1108 if( 0 !== item.length ) {
1109 if( item.hasClass('menu-item-edit-inactive') ) {
1110 if( ! settings.data('menu-item-data') ) {
1111 settings.data( 'menu-item-data', settings.getItemData() );
1113 settings.slideDown('fast');
1114 item.removeClass('menu-item-edit-inactive')
1115 .addClass('menu-item-edit-active');
1117 settings.slideUp('fast');
1118 item.removeClass('menu-item-edit-active')
1119 .addClass('menu-item-edit-inactive');
1126 eventOnClickCancelLink : function(clickedEl) {
1127 var settings = $( clickedEl ).closest( '.menu-item-settings' ),
1128 thisMenuItem = $( clickedEl ).closest( '.menu-item' );
1129 thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive');
1130 settings.setItemData( settings.data('menu-item-data') ).hide();
1134 eventOnClickMenuSave : function() {
1136 menuName = $('#menu-name'),
1137 menuNameVal = menuName.val();
1138 // Cancel and warn if invalid menu name
1139 if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
1140 menuName.parent().addClass('form-invalid');
1143 // Copy menu theme locations
1144 $('#nav-menu-theme-locations select').each(function() {
1145 locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
1147 $('#update-nav-menu').append( locs );
1148 // Update menu item position data
1149 api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
1150 window.onbeforeunload = null;
1155 eventOnClickMenuDelete : function() {
1156 // Delete warning AYS
1157 if ( window.confirm( navMenuL10n.warnDeleteMenu ) ) {
1158 window.onbeforeunload = null;
1164 eventOnClickMenuItemDelete : function(clickedEl) {
1165 var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
1166 api.removeMenuItem( $('#menu-item-' + itemID) );
1167 api.registerChange();
1172 * Process the quick search response into a search result
1174 * @param string resp The server response to the query.
1175 * @param object req The request arguments.
1176 * @param jQuery panel The tabs panel we're searching in.
1178 processQuickSearchQueryResponse : function(resp, req, panel) {
1181 form = document.getElementById('nav-menu-meta'),
1182 pattern = /menu-item[(\[^]\]*/,
1183 $items = $('<div>').html(resp).find('li'),
1186 if( ! $items.length ) {
1187 $('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
1188 $( '.spinner', panel ).removeClass( 'is-active' );
1192 $items.each(function(){
1195 // make a unique DB ID number
1196 matched = pattern.exec($item.html());
1198 if ( matched && matched[1] ) {
1200 while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
1204 takenIDs[newID] = true;
1205 if ( newID != matched[1] ) {
1206 $item.html( $item.html().replace(new RegExp(
1207 'menu-item\\[' + matched[1] + '\\]', 'g'),
1208 'menu-item[' + newID + ']'
1214 $('.categorychecklist', panel).html( $items );
1215 $( '.spinner', panel ).removeClass( 'is-active' );
1218 removeMenuItem : function(el) {
1219 var children = el.childMenuItems();
1221 el.addClass('deleting').animate({
1224 }, 350, function() {
1225 var ins = $('#menu-instructions');
1227 children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
1228 if ( 0 === $( '#menu-to-edit li' ).length ) {
1229 $( '.drag-instructions' ).hide();
1230 ins.removeClass( 'menu-instructions-inactive' );
1232 api.refreshAdvancedAccessibility();
1236 depthToPx : function(depth) {
1237 return depth * api.options.menuItemDepthPerLevel;
1240 pxToDepth : function(px) {
1241 return Math.floor(px / api.options.menuItemDepthPerLevel);
1246 $(document).ready(function(){ wpNavMenu.init(); });