You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1277 lines
41 KiB

  1. /**
  2. * WordPress Administration Navigation Menu
  3. * Interface JS functions
  4. *
  5. * @version 2.0.0
  6. *
  7. * @package WordPress
  8. * @subpackage Administration
  9. */
  10. /* global menus, postboxes, columns, isRtl, navMenuL10n, ajaxurl */
  11. var wpNavMenu;
  12. (function($) {
  13. var api;
  14. api = wpNavMenu = {
  15. options : {
  16. menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
  17. globalMaxDepth: 11,
  18. sortableItems: '> *',
  19. targetTolerance: 0
  20. },
  21. menuList : undefined, // Set in init.
  22. targetList : undefined, // Set in init.
  23. menusChanged : false,
  24. isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
  25. negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
  26. lastSearch: '',
  27. // Functions that run on init.
  28. init : function() {
  29. api.menuList = $('#menu-to-edit');
  30. api.targetList = api.menuList;
  31. this.jQueryExtensions();
  32. this.attachMenuEditListeners();
  33. this.attachQuickSearchListeners();
  34. this.attachThemeLocationsListeners();
  35. this.attachMenuSaveSubmitListeners();
  36. this.attachTabsPanelListeners();
  37. this.attachUnsavedChangesListener();
  38. if ( api.menuList.length )
  39. this.initSortables();
  40. if ( menus.oneThemeLocationNoMenus )
  41. $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom );
  42. this.initManageLocations();
  43. this.initAccessibility();
  44. this.initToggles();
  45. this.initPreviewing();
  46. },
  47. jQueryExtensions : function() {
  48. // jQuery extensions
  49. $.fn.extend({
  50. menuItemDepth : function() {
  51. var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
  52. return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
  53. },
  54. updateDepthClass : function(current, prev) {
  55. return this.each(function(){
  56. var t = $(this);
  57. prev = prev || t.menuItemDepth();
  58. $(this).removeClass('menu-item-depth-'+ prev )
  59. .addClass('menu-item-depth-'+ current );
  60. });
  61. },
  62. shiftDepthClass : function(change) {
  63. return this.each(function(){
  64. var t = $(this),
  65. depth = t.menuItemDepth(),
  66. newDepth = depth + change;
  67. t.removeClass( 'menu-item-depth-'+ depth )
  68. .addClass( 'menu-item-depth-'+ ( newDepth ) );
  69. if ( 0 === newDepth ) {
  70. t.find( '.is-submenu' ).hide();
  71. }
  72. });
  73. },
  74. childMenuItems : function() {
  75. var result = $();
  76. this.each(function(){
  77. var t = $(this), depth = t.menuItemDepth(), next = t.next( '.menu-item' );
  78. while( next.length && next.menuItemDepth() > depth ) {
  79. result = result.add( next );
  80. next = next.next( '.menu-item' );
  81. }
  82. });
  83. return result;
  84. },
  85. shiftHorizontally : function( dir ) {
  86. return this.each(function(){
  87. var t = $(this),
  88. depth = t.menuItemDepth(),
  89. newDepth = depth + dir;
  90. // Change .menu-item-depth-n class
  91. t.moveHorizontally( newDepth, depth );
  92. });
  93. },
  94. moveHorizontally : function( newDepth, depth ) {
  95. return this.each(function(){
  96. var t = $(this),
  97. children = t.childMenuItems(),
  98. diff = newDepth - depth,
  99. subItemText = t.find('.is-submenu');
  100. // Change .menu-item-depth-n class
  101. t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId();
  102. // If it has children, move those too
  103. if ( children ) {
  104. children.each(function() {
  105. var t = $(this),
  106. thisDepth = t.menuItemDepth(),
  107. newDepth = thisDepth + diff;
  108. t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId();
  109. });
  110. }
  111. // Show "Sub item" helper text
  112. if (0 === newDepth)
  113. subItemText.hide();
  114. else
  115. subItemText.show();
  116. });
  117. },
  118. updateParentMenuItemDBId : function() {
  119. return this.each(function(){
  120. var item = $(this),
  121. input = item.find( '.menu-item-data-parent-id' ),
  122. depth = parseInt( item.menuItemDepth(), 10 ),
  123. parentDepth = depth - 1,
  124. parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first();
  125. if ( 0 === depth ) { // Item is on the top level, has no parent
  126. input.val(0);
  127. } else { // Find the parent item, and retrieve its object id.
  128. input.val( parent.find( '.menu-item-data-db-id' ).val() );
  129. }
  130. });
  131. },
  132. hideAdvancedMenuItemFields : function() {
  133. return this.each(function(){
  134. var that = $(this);
  135. $('.hide-column-tog').not(':checked').each(function(){
  136. that.find('.field-' + $(this).val() ).addClass('hidden-field');
  137. });
  138. });
  139. },
  140. /**
  141. * Adds selected menu items to the menu.
  142. *
  143. * @param jQuery metabox The metabox jQuery object.
  144. */
  145. addSelectedToMenu : function(processMethod) {
  146. if ( 0 === $('#menu-to-edit').length ) {
  147. return false;
  148. }
  149. return this.each(function() {
  150. var t = $(this), menuItems = {},
  151. 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' ),
  152. re = /menu-item\[([^\]]*)/;
  153. processMethod = processMethod || api.addMenuItemToBottom;
  154. // If no items are checked, bail.
  155. if ( !checkboxes.length )
  156. return false;
  157. // Show the ajax spinner
  158. t.find( '.button-controls .spinner' ).addClass( 'is-active' );
  159. // Retrieve menu item data
  160. $(checkboxes).each(function(){
  161. var t = $(this),
  162. listItemDBIDMatch = re.exec( t.attr('name') ),
  163. listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
  164. if ( this.className && -1 != this.className.indexOf('add-to-top') )
  165. processMethod = api.addMenuItemToTop;
  166. menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
  167. });
  168. // Add the items
  169. api.addItemToMenu(menuItems, processMethod, function(){
  170. // Deselect the items and hide the ajax spinner
  171. checkboxes.removeAttr('checked');
  172. t.find( '.button-controls .spinner' ).removeClass( 'is-active' );
  173. });
  174. });
  175. },
  176. getItemData : function( itemType, id ) {
  177. itemType = itemType || 'menu-item';
  178. var itemData = {}, i,
  179. fields = [
  180. 'menu-item-db-id',
  181. 'menu-item-object-id',
  182. 'menu-item-object',
  183. 'menu-item-parent-id',
  184. 'menu-item-position',
  185. 'menu-item-type',
  186. 'menu-item-title',
  187. 'menu-item-url',
  188. 'menu-item-description',
  189. 'menu-item-attr-title',
  190. 'menu-item-target',
  191. 'menu-item-classes',
  192. 'menu-item-xfn'
  193. ];
  194. if( !id && itemType == 'menu-item' ) {
  195. id = this.find('.menu-item-data-db-id').val();
  196. }
  197. if( !id ) return itemData;
  198. this.find('input').each(function() {
  199. var field;
  200. i = fields.length;
  201. while ( i-- ) {
  202. if( itemType == 'menu-item' )
  203. field = fields[i] + '[' + id + ']';
  204. else if( itemType == 'add-menu-item' )
  205. field = 'menu-item[' + id + '][' + fields[i] + ']';
  206. if (
  207. this.name &&
  208. field == this.name
  209. ) {
  210. itemData[fields[i]] = this.value;
  211. }
  212. }
  213. });
  214. return itemData;
  215. },
  216. setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
  217. itemType = itemType || 'menu-item';
  218. if( !id && itemType == 'menu-item' ) {
  219. id = $('.menu-item-data-db-id', this).val();
  220. }
  221. if( !id ) return this;
  222. this.find('input').each(function() {
  223. var t = $(this), field;
  224. $.each( itemData, function( attr, val ) {
  225. if( itemType == 'menu-item' )
  226. field = attr + '[' + id + ']';
  227. else if( itemType == 'add-menu-item' )
  228. field = 'menu-item[' + id + '][' + attr + ']';
  229. if ( field == t.attr('name') ) {
  230. t.val( val );
  231. }
  232. });
  233. });
  234. return this;
  235. }
  236. });
  237. },
  238. countMenuItems : function( depth ) {
  239. return $( '.menu-item-depth-' + depth ).length;
  240. },
  241. moveMenuItem : function( $this, dir ) {
  242. var items, newItemPosition, newDepth,
  243. menuItems = $( '#menu-to-edit li' ),
  244. menuItemsCount = menuItems.length,
  245. thisItem = $this.parents( 'li.menu-item' ),
  246. thisItemChildren = thisItem.childMenuItems(),
  247. thisItemData = thisItem.getItemData(),
  248. thisItemDepth = parseInt( thisItem.menuItemDepth(), 10 ),
  249. thisItemPosition = parseInt( thisItem.index(), 10 ),
  250. nextItem = thisItem.next(),
  251. nextItemChildren = nextItem.childMenuItems(),
  252. nextItemDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1,
  253. prevItem = thisItem.prev(),
  254. prevItemDepth = parseInt( prevItem.menuItemDepth(), 10 ),
  255. prevItemId = prevItem.getItemData()['menu-item-db-id'];
  256. switch ( dir ) {
  257. case 'up':
  258. newItemPosition = thisItemPosition - 1;
  259. // Already at top
  260. if ( 0 === thisItemPosition )
  261. break;
  262. // If a sub item is moved to top, shift it to 0 depth
  263. if ( 0 === newItemPosition && 0 !== thisItemDepth )
  264. thisItem.moveHorizontally( 0, thisItemDepth );
  265. // If prev item is sub item, shift to match depth
  266. if ( 0 !== prevItemDepth )
  267. thisItem.moveHorizontally( prevItemDepth, thisItemDepth );
  268. // Does this item have sub items?
  269. if ( thisItemChildren ) {
  270. items = thisItem.add( thisItemChildren );
  271. // Move the entire block
  272. items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
  273. } else {
  274. thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
  275. }
  276. break;
  277. case 'down':
  278. // Does this item have sub items?
  279. if ( thisItemChildren ) {
  280. items = thisItem.add( thisItemChildren ),
  281. nextItem = menuItems.eq( items.length + thisItemPosition ),
  282. nextItemChildren = 0 !== nextItem.childMenuItems().length;
  283. if ( nextItemChildren ) {
  284. newDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1;
  285. thisItem.moveHorizontally( newDepth, thisItemDepth );
  286. }
  287. // Have we reached the bottom?
  288. if ( menuItemsCount === thisItemPosition + items.length )
  289. break;
  290. items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId();
  291. } else {
  292. // If next item has sub items, shift depth
  293. if ( 0 !== nextItemChildren.length )
  294. thisItem.moveHorizontally( nextItemDepth, thisItemDepth );
  295. // Have we reached the bottom
  296. if ( menuItemsCount === thisItemPosition + 1 )
  297. break;
  298. thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId();
  299. }
  300. break;
  301. case 'top':
  302. // Already at top
  303. if ( 0 === thisItemPosition )
  304. break;
  305. // Does this item have sub items?
  306. if ( thisItemChildren ) {
  307. items = thisItem.add( thisItemChildren );
  308. // Move the entire block
  309. items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
  310. } else {
  311. thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
  312. }
  313. break;
  314. case 'left':
  315. // As far left as possible
  316. if ( 0 === thisItemDepth )
  317. break;
  318. thisItem.shiftHorizontally( -1 );
  319. break;
  320. case 'right':
  321. // Can't be sub item at top
  322. if ( 0 === thisItemPosition )
  323. break;
  324. // Already sub item of prevItem
  325. if ( thisItemData['menu-item-parent-id'] === prevItemId )
  326. break;
  327. thisItem.shiftHorizontally( 1 );
  328. break;
  329. }
  330. $this.focus();
  331. api.registerChange();
  332. api.refreshKeyboardAccessibility();
  333. api.refreshAdvancedAccessibility();
  334. },
  335. initAccessibility : function() {
  336. var menu = $( '#menu-to-edit' );
  337. api.refreshKeyboardAccessibility();
  338. api.refreshAdvancedAccessibility();
  339. // Refresh the accessibility when the user comes close to the item in any way
  340. menu.on( 'mouseenter.refreshAccessibility focus.refreshAccessibility touchstart.refreshAccessibility' , '.menu-item' , function(){
  341. api.refreshAdvancedAccessibilityOfItem( $( this ).find( 'a.item-edit' ) );
  342. } );
  343. // We have to update on click as well because we might hover first, change the item, and then click.
  344. menu.on( 'click', 'a.item-edit', function() {
  345. api.refreshAdvancedAccessibilityOfItem( $( this ) );
  346. } );
  347. // Links for moving items
  348. menu.on( 'click', '.menus-move', function () {
  349. var $this = $( this ),
  350. dir = $this.data( 'dir' );
  351. if ( 'undefined' !== typeof dir ) {
  352. api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), dir );
  353. }
  354. });
  355. },
  356. /**
  357. * refreshAdvancedAccessibilityOfItem( [itemToRefresh] )
  358. *
  359. * Refreshes advanced accessibility buttons for one menu item.
  360. * Shows or hides buttons based on the location of the menu item.
  361. *
  362. * @param {object} itemToRefresh The menu item that might need its advanced accessibility buttons refreshed
  363. */
  364. refreshAdvancedAccessibilityOfItem : function( itemToRefresh ) {
  365. // Only refresh accessibility when necessary
  366. if ( true !== $( itemToRefresh ).data( 'needs_accessibility_refresh' ) ) {
  367. return;
  368. }
  369. var thisLink, thisLinkText, primaryItems, itemPosition, title,
  370. parentItem, parentItemId, parentItemName, subItems,
  371. $this = $( itemToRefresh ),
  372. menuItem = $this.closest( 'li.menu-item' ).first(),
  373. depth = menuItem.menuItemDepth(),
  374. isPrimaryMenuItem = ( 0 === depth ),
  375. itemName = $this.closest( '.menu-item-handle' ).find( '.menu-item-title' ).text(),
  376. position = parseInt( menuItem.index(), 10 ),
  377. prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1, 10 ),
  378. prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(),
  379. prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(),
  380. totalMenuItems = $('#menu-to-edit li').length,
  381. hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length;
  382. menuItem.find( '.field-move' ).toggle( totalMenuItems > 1 );
  383. // Where can they move this menu item?
  384. if ( 0 !== position ) {
  385. thisLink = menuItem.find( '.menus-move-up' );
  386. thisLink.attr( 'aria-label', menus.moveUp ).css( 'display', 'inline' );
  387. }
  388. if ( 0 !== position && isPrimaryMenuItem ) {
  389. thisLink = menuItem.find( '.menus-move-top' );
  390. thisLink.attr( 'aria-label', menus.moveToTop ).css( 'display', 'inline' );
  391. }
  392. if ( position + 1 !== totalMenuItems && 0 !== position ) {
  393. thisLink = menuItem.find( '.menus-move-down' );
  394. thisLink.attr( 'aria-label', menus.moveDown ).css( 'display', 'inline' );
  395. }
  396. if ( 0 === position && 0 !== hasSameDepthSibling ) {
  397. thisLink = menuItem.find( '.menus-move-down' );
  398. thisLink.attr( 'aria-label', menus.moveDown ).css( 'display', 'inline' );
  399. }
  400. if ( ! isPrimaryMenuItem ) {
  401. thisLink = menuItem.find( '.menus-move-left' ),
  402. thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft );
  403. thisLink.attr( 'aria-label', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).text( thisLinkText ).css( 'display', 'inline' );
  404. }
  405. if ( 0 !== position ) {
  406. if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) {
  407. thisLink = menuItem.find( '.menus-move-right' ),
  408. thisLinkText = menus.under.replace( '%s', prevItemNameRight );
  409. thisLink.attr( 'aria-label', menus.moveUnder.replace( '%s', prevItemNameRight ) ).text( thisLinkText ).css( 'display', 'inline' );
  410. }
  411. }
  412. if ( isPrimaryMenuItem ) {
  413. primaryItems = $( '.menu-item-depth-0' ),
  414. itemPosition = primaryItems.index( menuItem ) + 1,
  415. totalMenuItems = primaryItems.length,
  416. // String together help text for primary menu items
  417. title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems );
  418. } else {
  419. parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).first(),
  420. parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
  421. parentItemName = parentItem.find( '.menu-item-title' ).text(),
  422. subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
  423. itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
  424. // String together help text for sub menu items
  425. title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName );
  426. }
  427. // @todo Consider to update just the `aria-label` attribute.
  428. $this.attr( 'aria-label', title ).text( title );
  429. // Mark this item's accessibility as refreshed
  430. $this.data( 'needs_accessibility_refresh', false );
  431. },
  432. /**
  433. * refreshAdvancedAccessibility
  434. *
  435. * Hides all advanced accessibility buttons and marks them for refreshing.
  436. */
  437. refreshAdvancedAccessibility : function() {
  438. // Hide all the move buttons by default.
  439. $( '.menu-item-settings .field-move .menus-move' ).hide();
  440. // Mark all menu items as unprocessed
  441. $( 'a.item-edit' ).data( 'needs_accessibility_refresh', true );
  442. // All open items have to be refreshed or they will show no links
  443. $( '.menu-item-edit-active a.item-edit' ).each( function() {
  444. api.refreshAdvancedAccessibilityOfItem( this );
  445. } );
  446. },
  447. refreshKeyboardAccessibility : function() {
  448. $( 'a.item-edit' ).off( 'focus' ).on( 'focus', function(){
  449. $(this).off( 'keydown' ).on( 'keydown', function(e){
  450. var arrows,
  451. $this = $( this ),
  452. thisItem = $this.parents( 'li.menu-item' ),
  453. thisItemData = thisItem.getItemData();
  454. // Bail if it's not an arrow key
  455. if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
  456. return;
  457. // Avoid multiple keydown events
  458. $this.off('keydown');
  459. // Bail if there is only one menu item
  460. if ( 1 === $('#menu-to-edit li').length )
  461. return;
  462. // If RTL, swap left/right arrows
  463. arrows = { '38': 'up', '40': 'down', '37': 'left', '39': 'right' };
  464. if ( $('body').hasClass('rtl') )
  465. arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
  466. switch ( arrows[e.which] ) {
  467. case 'up':
  468. api.moveMenuItem( $this, 'up' );
  469. break;
  470. case 'down':
  471. api.moveMenuItem( $this, 'down' );
  472. break;
  473. case 'left':
  474. api.moveMenuItem( $this, 'left' );
  475. break;
  476. case 'right':
  477. api.moveMenuItem( $this, 'right' );
  478. break;
  479. }
  480. // Put focus back on same menu item
  481. $( '#edit-' + thisItemData['menu-item-db-id'] ).focus();
  482. return false;
  483. });
  484. });
  485. },
  486. initPreviewing : function() {
  487. // Update the item handle title when the navigation label is changed.
  488. $( '#menu-to-edit' ).on( 'change input', '.edit-menu-item-title', function(e) {
  489. var input = $( e.currentTarget ), title, titleEl;
  490. title = input.val();
  491. titleEl = input.closest( '.menu-item' ).find( '.menu-item-title' );
  492. // Don't update to empty title.
  493. if ( title ) {
  494. titleEl.text( title ).removeClass( 'no-title' );
  495. } else {
  496. titleEl.text( navMenuL10n.untitled ).addClass( 'no-title' );
  497. }
  498. } );
  499. },
  500. initToggles : function() {
  501. // init postboxes
  502. postboxes.add_postbox_toggles('nav-menus');
  503. // adjust columns functions for menus UI
  504. columns.useCheckboxesForHidden();
  505. columns.checked = function(field) {
  506. $('.field-' + field).removeClass('hidden-field');
  507. };
  508. columns.unchecked = function(field) {
  509. $('.field-' + field).addClass('hidden-field');
  510. };
  511. // hide fields
  512. api.menuList.hideAdvancedMenuItemFields();
  513. $('.hide-postbox-tog').click(function () {
  514. var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
  515. $.post(ajaxurl, {
  516. action: 'closed-postboxes',
  517. hidden: hidden,
  518. closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
  519. page: 'nav-menus'
  520. });
  521. });
  522. },
  523. initSortables : function() {
  524. var currentDepth = 0, originalDepth, minDepth, maxDepth,
  525. prev, next, prevBottom, nextThreshold, helperHeight, transport,
  526. menuEdge = api.menuList.offset().left,
  527. body = $('body'), maxChildDepth,
  528. menuMaxDepth = initialMenuMaxDepth();
  529. if( 0 !== $( '#menu-to-edit li' ).length )
  530. $( '.drag-instructions' ).show();
  531. // Use the right edge if RTL.
  532. menuEdge += api.isRTL ? api.menuList.width() : 0;
  533. api.menuList.sortable({
  534. handle: '.menu-item-handle',
  535. placeholder: 'sortable-placeholder',
  536. items: api.options.sortableItems,
  537. start: function(e, ui) {
  538. var height, width, parent, children, tempHolder;
  539. // handle placement for rtl orientation
  540. if ( api.isRTL )
  541. ui.item[0].style.right = 'auto';
  542. transport = ui.item.children('.menu-item-transport');
  543. // Set depths. currentDepth must be set before children are located.
  544. originalDepth = ui.item.menuItemDepth();
  545. updateCurrentDepth(ui, originalDepth);
  546. // Attach child elements to parent
  547. // Skip the placeholder
  548. parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
  549. children = parent.childMenuItems();
  550. transport.append( children );
  551. // Update the height of the placeholder to match the moving item.
  552. height = transport.outerHeight();
  553. // If there are children, account for distance between top of children and parent
  554. height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
  555. height += ui.helper.outerHeight();
  556. helperHeight = height;
  557. height -= 2; // Subtract 2 for borders
  558. ui.placeholder.height(height);
  559. // Update the width of the placeholder to match the moving item.
  560. maxChildDepth = originalDepth;
  561. children.each(function(){
  562. var depth = $(this).menuItemDepth();
  563. maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
  564. });
  565. width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
  566. width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
  567. width -= 2; // Subtract 2 for borders
  568. ui.placeholder.width(width);
  569. // Update the list of menu items.
  570. tempHolder = ui.placeholder.next( '.menu-item' );
  571. tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
  572. ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
  573. $(this).sortable( 'refresh' ); // The children aren't sortable. We should let jQ UI know.
  574. ui.item.after( ui.placeholder ); // reattach the placeholder.
  575. tempHolder.css('margin-top', 0); // reset the margin
  576. // Now that the element is complete, we can update...
  577. updateSharedVars(ui);
  578. },
  579. stop: function(e, ui) {
  580. var children, subMenuTitle,
  581. depthChange = currentDepth - originalDepth;
  582. // Return child elements to the list
  583. children = transport.children().insertAfter(ui.item);
  584. // Add "sub menu" description
  585. subMenuTitle = ui.item.find( '.item-title .is-submenu' );
  586. if ( 0 < currentDepth )
  587. subMenuTitle.show();
  588. else
  589. subMenuTitle.hide();
  590. // Update depth classes
  591. if ( 0 !== depthChange ) {
  592. ui.item.updateDepthClass( currentDepth );
  593. children.shiftDepthClass( depthChange );
  594. updateMenuMaxDepth( depthChange );
  595. }
  596. // Register a change
  597. api.registerChange();
  598. // Update the item data.
  599. ui.item.updateParentMenuItemDBId();
  600. // address sortable's incorrectly-calculated top in opera
  601. ui.item[0].style.top = 0;
  602. // handle drop placement for rtl orientation
  603. if ( api.isRTL ) {
  604. ui.item[0].style.left = 'auto';
  605. ui.item[0].style.right = 0;
  606. }
  607. api.refreshKeyboardAccessibility();
  608. api.refreshAdvancedAccessibility();
  609. },
  610. change: function(e, ui) {
  611. // Make sure the placeholder is inside the menu.
  612. // Otherwise fix it, or we're in trouble.
  613. if( ! ui.placeholder.parent().hasClass('menu') )
  614. (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
  615. updateSharedVars(ui);
  616. },
  617. sort: function(e, ui) {
  618. var offset = ui.helper.offset(),
  619. edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
  620. depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
  621. // Check and correct if depth is not within range.
  622. // Also, if the dragged element is dragged upwards over
  623. // an item, shift the placeholder to a child position.
  624. if ( depth > maxDepth || offset.top < ( prevBottom - api.options.targetTolerance ) ) {
  625. depth = maxDepth;
  626. } else if ( depth < minDepth ) {
  627. depth = minDepth;
  628. }
  629. if( depth != currentDepth )
  630. updateCurrentDepth(ui, depth);
  631. // If we overlap the next element, manually shift downwards
  632. if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
  633. next.after( ui.placeholder );
  634. updateSharedVars( ui );
  635. $( this ).sortable( 'refreshPositions' );
  636. }
  637. }
  638. });
  639. function updateSharedVars(ui) {
  640. var depth;
  641. prev = ui.placeholder.prev( '.menu-item' );
  642. next = ui.placeholder.next( '.menu-item' );
  643. // Make sure we don't select the moving item.
  644. if( prev[0] == ui.item[0] ) prev = prev.prev( '.menu-item' );
  645. if( next[0] == ui.item[0] ) next = next.next( '.menu-item' );
  646. prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
  647. nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
  648. minDepth = (next.length) ? next.menuItemDepth() : 0;
  649. if( prev.length )
  650. maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
  651. else
  652. maxDepth = 0;
  653. }
  654. function updateCurrentDepth(ui, depth) {
  655. ui.placeholder.updateDepthClass( depth, currentDepth );
  656. currentDepth = depth;
  657. }
  658. function initialMenuMaxDepth() {
  659. if( ! body[0].className ) return 0;
  660. var match = body[0].className.match(/menu-max-depth-(\d+)/);
  661. return match && match[1] ? parseInt( match[1], 10 ) : 0;
  662. }
  663. function updateMenuMaxDepth( depthChange ) {
  664. var depth, newDepth = menuMaxDepth;
  665. if ( depthChange === 0 ) {
  666. return;
  667. } else if ( depthChange > 0 ) {
  668. depth = maxChildDepth + depthChange;
  669. if( depth > menuMaxDepth )
  670. newDepth = depth;
  671. } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
  672. while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
  673. newDepth--;
  674. }
  675. // Update the depth class.
  676. body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
  677. menuMaxDepth = newDepth;
  678. }
  679. },
  680. initManageLocations : function () {
  681. $('#menu-locations-wrap form').submit(function(){
  682. window.onbeforeunload = null;
  683. });
  684. $('.menu-location-menus select').on('change', function () {
  685. var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
  686. if ($(this).find('option:selected').data('orig'))
  687. editLink.show();
  688. else
  689. editLink.hide();
  690. });
  691. },
  692. attachMenuEditListeners : function() {
  693. var that = this;
  694. $('#update-nav-menu').bind('click', function(e) {
  695. if ( e.target && e.target.className ) {
  696. if ( -1 != e.target.className.indexOf('item-edit') ) {
  697. return that.eventOnClickEditLink(e.target);
  698. } else if ( -1 != e.target.className.indexOf('menu-save') ) {
  699. return that.eventOnClickMenuSave(e.target);
  700. } else if ( -1 != e.target.className.indexOf('menu-delete') ) {
  701. return that.eventOnClickMenuDelete(e.target);
  702. } else if ( -1 != e.target.className.indexOf('item-delete') ) {
  703. return that.eventOnClickMenuItemDelete(e.target);
  704. } else if ( -1 != e.target.className.indexOf('item-cancel') ) {
  705. return that.eventOnClickCancelLink(e.target);
  706. }
  707. }
  708. });
  709. $('#add-custom-links input[type="text"]').keypress(function(e){
  710. $('#customlinkdiv').removeClass('form-invalid');
  711. if ( e.keyCode === 13 ) {
  712. e.preventDefault();
  713. $( '#submit-customlinkdiv' ).click();
  714. }
  715. });
  716. },
  717. attachMenuSaveSubmitListeners : function() {
  718. /*
  719. * When a navigation menu is saved, store a JSON representation of all form data
  720. * in a single input to avoid PHP `max_input_vars` limitations. See #14134.
  721. */
  722. $( '#update-nav-menu' ).submit( function() {
  723. var navMenuData = $( '#update-nav-menu' ).serializeArray();
  724. $( '[name="nav-menu-data"]' ).val( JSON.stringify( navMenuData ) );
  725. });
  726. },
  727. attachThemeLocationsListeners : function() {
  728. var loc = $('#nav-menu-theme-locations'), params = {};
  729. params.action = 'menu-locations-save';
  730. params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
  731. loc.find('input[type="submit"]').click(function() {
  732. loc.find('select').each(function() {
  733. params[this.name] = $(this).val();
  734. });
  735. loc.find( '.spinner' ).addClass( 'is-active' );
  736. $.post( ajaxurl, params, function() {
  737. loc.find( '.spinner' ).removeClass( 'is-active' );
  738. });
  739. return false;
  740. });
  741. },
  742. attachQuickSearchListeners : function() {
  743. var searchTimer,
  744. inputEvent;
  745. // Prevent form submission.
  746. $( '#nav-menu-meta' ).on( 'submit', function( event ) {
  747. event.preventDefault();
  748. });
  749. /*
  750. * Use feature detection to determine whether inputs should use
  751. * the `keyup` or `input` event. Input is preferred but lacks support
  752. * in legacy browsers. See changeset 34078, see also ticket #26600#comment:59
  753. */
  754. if ( 'oninput' in document.createElement( 'input' ) ) {
  755. inputEvent = 'input';
  756. } else {
  757. inputEvent = 'keyup';
  758. }
  759. $( '#nav-menu-meta' ).on( inputEvent, '.quick-search', function() {
  760. var $this = $( this );
  761. $this.attr( 'autocomplete', 'off' );
  762. if ( searchTimer ) {
  763. clearTimeout( searchTimer );
  764. }
  765. searchTimer = setTimeout( function() {
  766. api.updateQuickSearchResults( $this );
  767. }, 500 );
  768. }).on( 'blur', '.quick-search', function() {
  769. api.lastSearch = '';
  770. });
  771. },
  772. updateQuickSearchResults : function(input) {
  773. var panel, params,
  774. minSearchLength = 2,
  775. q = input.val();
  776. /*
  777. * Minimum characters for a search. Also avoid a new AJAX search when
  778. * the pressed key (e.g. arrows) doesn't change the searched term.
  779. */
  780. if ( q.length < minSearchLength || api.lastSearch == q ) {
  781. return;
  782. }
  783. api.lastSearch = q;
  784. panel = input.parents('.tabs-panel');
  785. params = {
  786. 'action': 'menu-quick-search',
  787. 'response-format': 'markup',
  788. 'menu': $('#menu').val(),
  789. 'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
  790. 'q': q,
  791. 'type': input.attr('name')
  792. };
  793. $( '.spinner', panel ).addClass( 'is-active' );
  794. $.post( ajaxurl, params, function(menuMarkup) {
  795. api.processQuickSearchQueryResponse(menuMarkup, params, panel);
  796. });
  797. },
  798. addCustomLink : function( processMethod ) {
  799. var url = $('#custom-menu-item-url').val(),
  800. label = $('#custom-menu-item-name').val();
  801. processMethod = processMethod || api.addMenuItemToBottom;
  802. if ( '' === url || 'http://' == url ) {
  803. $('#customlinkdiv').addClass('form-invalid');
  804. return false;
  805. }
  806. // Show the ajax spinner
  807. $( '.customlinkdiv .spinner' ).addClass( 'is-active' );
  808. this.addLinkToMenu( url, label, processMethod, function() {
  809. // Remove the ajax spinner
  810. $( '.customlinkdiv .spinner' ).removeClass( 'is-active' );
  811. // Set custom link form back to defaults
  812. $('#custom-menu-item-name').val('').blur();
  813. $('#custom-menu-item-url').val('http://');
  814. });
  815. },
  816. addLinkToMenu : function(url, label, processMethod, callback) {
  817. processMethod = processMethod || api.addMenuItemToBottom;
  818. callback = callback || function(){};
  819. api.addItemToMenu({
  820. '-1': {
  821. 'menu-item-type': 'custom',
  822. 'menu-item-url': url,
  823. 'menu-item-title': label
  824. }
  825. }, processMethod, callback);
  826. },
  827. addItemToMenu : function(menuItem, processMethod, callback) {
  828. var menu = $('#menu').val(),
  829. nonce = $('#menu-settings-column-nonce').val(),
  830. params;
  831. processMethod = processMethod || function(){};
  832. callback = callback || function(){};
  833. params = {
  834. 'action': 'add-menu-item',
  835. 'menu': menu,
  836. 'menu-settings-column-nonce': nonce,
  837. 'menu-item': menuItem
  838. };
  839. $.post( ajaxurl, params, function(menuMarkup) {
  840. var ins = $('#menu-instructions');
  841. menuMarkup = $.trim( menuMarkup ); // Trim leading whitespaces
  842. processMethod(menuMarkup, params);
  843. // Make it stand out a bit more visually, by adding a fadeIn
  844. $( 'li.pending' ).hide().fadeIn('slow');
  845. $( '.drag-instructions' ).show();
  846. if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
  847. ins.addClass( 'menu-instructions-inactive' );
  848. callback();
  849. });
  850. },
  851. /**
  852. * Process the add menu item request response into menu list item.
  853. *
  854. * @param string menuMarkup The text server response of menu item markup.
  855. * @param object req The request arguments.
  856. */
  857. addMenuItemToBottom : function( menuMarkup ) {
  858. $(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
  859. api.refreshKeyboardAccessibility();
  860. api.refreshAdvancedAccessibility();
  861. },
  862. addMenuItemToTop : function( menuMarkup ) {
  863. $(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
  864. api.refreshKeyboardAccessibility();
  865. api.refreshAdvancedAccessibility();
  866. },
  867. attachUnsavedChangesListener : function() {
  868. $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){
  869. api.registerChange();
  870. });
  871. if ( 0 !== $('#menu-to-edit').length || 0 !== $('.menu-location-menus select').length ) {
  872. window.onbeforeunload = function(){
  873. if ( api.menusChanged )
  874. return navMenuL10n.saveAlert;
  875. };
  876. } else {
  877. // Make the post boxes read-only, as they can't be used yet
  878. $( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' );
  879. }
  880. },
  881. registerChange : function() {
  882. api.menusChanged = true;
  883. },
  884. attachTabsPanelListeners : function() {
  885. $('#menu-settings-column').bind('click', function(e) {
  886. var selectAreaMatch, panelId, wrapper, items,
  887. target = $(e.target);
  888. if ( target.hasClass('nav-tab-link') ) {
  889. panelId = target.data( 'type' );
  890. wrapper = target.parents('.accordion-section-content').first();
  891. // upon changing tabs, we want to uncheck all checkboxes
  892. $('input', wrapper).removeAttr('checked');
  893. $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
  894. $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
  895. $('.tabs', wrapper).removeClass('tabs');
  896. target.parent().addClass('tabs');
  897. // select the search bar
  898. $('.quick-search', wrapper).focus();
  899. // Hide controls in the search tab if no items found.
  900. if ( ! wrapper.find( '.tabs-panel-active .menu-item-title' ).length ) {
  901. wrapper.addClass( 'has-no-menu-item' );
  902. } else {
  903. wrapper.removeClass( 'has-no-menu-item' );
  904. }
  905. e.preventDefault();
  906. } else if ( target.hasClass('select-all') ) {
  907. selectAreaMatch = /#(.*)$/.exec(e.target.href);
  908. if ( selectAreaMatch && selectAreaMatch[1] ) {
  909. items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
  910. if( items.length === items.filter(':checked').length )
  911. items.removeAttr('checked');
  912. else
  913. items.prop('checked', true);
  914. return false;
  915. }
  916. } else if ( target.hasClass('submit-add-to-menu') ) {
  917. api.registerChange();
  918. if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
  919. api.addCustomLink( api.addMenuItemToBottom );
  920. else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
  921. $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
  922. return false;
  923. }
  924. });
  925. /*
  926. * Delegate the `click` event and attach it just to the pagination
  927. * links thus excluding the current page `<span>`. See ticket #35577.
  928. */
  929. $( '#nav-menu-meta' ).on( 'click', 'a.page-numbers', function() {
  930. var $container = $( this ).closest( '.inside' );
  931. $.post( ajaxurl, this.href.replace( /.*\?/, '' ).replace( /action=([^&]*)/, '' ) + '&action=menu-get-metabox',
  932. function( resp ) {
  933. var metaBoxData = $.parseJSON( resp ),
  934. toReplace;
  935. if ( -1 === resp.indexOf( 'replace-id' ) ) {
  936. return;
  937. }
  938. // Get the post type menu meta box to update.
  939. toReplace = document.getElementById( metaBoxData['replace-id'] );
  940. if ( ! metaBoxData.markup || ! toReplace ) {
  941. return;
  942. }
  943. // Update the post type menu meta box with new content from the response.
  944. $container.html( metaBoxData.markup );
  945. }
  946. );
  947. return false;
  948. });
  949. },
  950. eventOnClickEditLink : function(clickedEl) {
  951. var settings, item,
  952. matchedSection = /#(.*)$/.exec(clickedEl.href);
  953. if ( matchedSection && matchedSection[1] ) {
  954. settings = $('#'+matchedSection[1]);
  955. item = settings.parent();
  956. if( 0 !== item.length ) {
  957. if( item.hasClass('menu-item-edit-inactive') ) {
  958. if( ! settings.data('menu-item-data') ) {
  959. settings.data( 'menu-item-data', settings.getItemData() );
  960. }
  961. settings.slideDown('fast');
  962. item.removeClass('menu-item-edit-inactive')
  963. .addClass('menu-item-edit-active');
  964. } else {
  965. settings.slideUp('fast');
  966. item.removeClass('menu-item-edit-active')
  967. .addClass('menu-item-edit-inactive');
  968. }
  969. return false;
  970. }
  971. }
  972. },
  973. eventOnClickCancelLink : function(clickedEl) {
  974. var settings = $( clickedEl ).closest( '.menu-item-settings' ),
  975. thisMenuItem = $( clickedEl ).closest( '.menu-item' );
  976. thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive');
  977. settings.setItemData( settings.data('menu-item-data') ).hide();
  978. return false;
  979. },
  980. eventOnClickMenuSave : function() {
  981. var locs = '',
  982. menuName = $('#menu-name'),
  983. menuNameVal = menuName.val();
  984. // Cancel and warn if invalid menu name
  985. if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
  986. menuName.parent().addClass('form-invalid');
  987. return false;
  988. }
  989. // Copy menu theme locations
  990. $('#nav-menu-theme-locations select').each(function() {
  991. locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
  992. });
  993. $('#update-nav-menu').append( locs );
  994. // Update menu item position data
  995. api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
  996. window.onbeforeunload = null;
  997. return true;
  998. },
  999. eventOnClickMenuDelete : function() {
  1000. // Delete warning AYS
  1001. if ( window.confirm( navMenuL10n.warnDeleteMenu ) ) {
  1002. window.onbeforeunload = null;
  1003. return true;
  1004. }
  1005. return false;
  1006. },
  1007. eventOnClickMenuItemDelete : function(clickedEl) {
  1008. var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
  1009. api.removeMenuItem( $('#menu-item-' + itemID) );
  1010. api.registerChange();
  1011. return false;
  1012. },
  1013. /**
  1014. * Process the quick search response into a search result
  1015. *
  1016. * @param string resp The server response to the query.
  1017. * @param object req The request arguments.
  1018. * @param jQuery panel The tabs panel we're searching in.
  1019. */
  1020. processQuickSearchQueryResponse : function(resp, req, panel) {
  1021. var matched, newID,
  1022. takenIDs = {},
  1023. form = document.getElementById('nav-menu-meta'),
  1024. pattern = /menu-item[(\[^]\]*/,
  1025. $items = $('<div>').html(resp).find('li'),
  1026. wrapper = panel.closest( '.accordion-section-content' ),
  1027. $item;
  1028. if( ! $items.length ) {
  1029. $('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
  1030. $( '.spinner', panel ).removeClass( 'is-active' );
  1031. wrapper.addClass( 'has-no-menu-item' );
  1032. return;
  1033. }
  1034. $items.each(function(){
  1035. $item = $(this);
  1036. // make a unique DB ID number
  1037. matched = pattern.exec($item.html());
  1038. if ( matched && matched[1] ) {
  1039. newID = matched[1];
  1040. while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
  1041. newID--;
  1042. }
  1043. takenIDs[newID] = true;
  1044. if ( newID != matched[1] ) {
  1045. $item.html( $item.html().replace(new RegExp(
  1046. 'menu-item\\[' + matched[1] + '\\]', 'g'),
  1047. 'menu-item[' + newID + ']'
  1048. ) );
  1049. }
  1050. }
  1051. });
  1052. $('.categorychecklist', panel).html( $items );
  1053. $( '.spinner', panel ).removeClass( 'is-active' );
  1054. wrapper.removeClass( 'has-no-menu-item' );
  1055. },
  1056. removeMenuItem : function(el) {
  1057. var children = el.childMenuItems();
  1058. el.addClass('deleting').animate({
  1059. opacity : 0,
  1060. height: 0
  1061. }, 350, function() {
  1062. var ins = $('#menu-instructions');
  1063. el.remove();
  1064. children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
  1065. if ( 0 === $( '#menu-to-edit li' ).length ) {
  1066. $( '.drag-instructions' ).hide();
  1067. ins.removeClass( 'menu-instructions-inactive' );
  1068. }
  1069. api.refreshAdvancedAccessibility();
  1070. });
  1071. },
  1072. depthToPx : function(depth) {
  1073. return depth * api.options.menuItemDepthPerLevel;
  1074. },
  1075. pxToDepth : function(px) {
  1076. return Math.floor(px / api.options.menuItemDepthPerLevel);
  1077. }
  1078. };
  1079. $(document).ready(function(){ wpNavMenu.init(); });
  1080. })(jQuery);