nav-menu.js 42 KB

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