nav-menu.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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. $this.attr( 'aria-label', title );
  428. // Mark this item's accessibility as refreshed
  429. $this.data( 'needs_accessibility_refresh', false );
  430. },
  431. /**
  432. * refreshAdvancedAccessibility
  433. *
  434. * Hides all advanced accessibility buttons and marks them for refreshing.
  435. */
  436. refreshAdvancedAccessibility : function() {
  437. // Hide all the move buttons by default.
  438. $( '.menu-item-settings .field-move .menus-move' ).hide();
  439. // Mark all menu items as unprocessed
  440. $( 'a.item-edit' ).data( 'needs_accessibility_refresh', true );
  441. // All open items have to be refreshed or they will show no links
  442. $( '.menu-item-edit-active a.item-edit' ).each( function() {
  443. api.refreshAdvancedAccessibilityOfItem( this );
  444. } );
  445. },
  446. refreshKeyboardAccessibility : function() {
  447. $( 'a.item-edit' ).off( 'focus' ).on( 'focus', function(){
  448. $(this).off( 'keydown' ).on( 'keydown', function(e){
  449. var arrows,
  450. $this = $( this ),
  451. thisItem = $this.parents( 'li.menu-item' ),
  452. thisItemData = thisItem.getItemData();
  453. // Bail if it's not an arrow key
  454. if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
  455. return;
  456. // Avoid multiple keydown events
  457. $this.off('keydown');
  458. // Bail if there is only one menu item
  459. if ( 1 === $('#menu-to-edit li').length )
  460. return;
  461. // If RTL, swap left/right arrows
  462. arrows = { '38': 'up', '40': 'down', '37': 'left', '39': 'right' };
  463. if ( $('body').hasClass('rtl') )
  464. arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
  465. switch ( arrows[e.which] ) {
  466. case 'up':
  467. api.moveMenuItem( $this, 'up' );
  468. break;
  469. case 'down':
  470. api.moveMenuItem( $this, 'down' );
  471. break;
  472. case 'left':
  473. api.moveMenuItem( $this, 'left' );
  474. break;
  475. case 'right':
  476. api.moveMenuItem( $this, 'right' );
  477. break;
  478. }
  479. // Put focus back on same menu item
  480. $( '#edit-' + thisItemData['menu-item-db-id'] ).focus();
  481. return false;
  482. });
  483. });
  484. },
  485. initPreviewing : function() {
  486. // Update the item handle title when the navigation label is changed.
  487. $( '#menu-to-edit' ).on( 'change input', '.edit-menu-item-title', function(e) {
  488. var input = $( e.currentTarget ), title, titleEl;
  489. title = input.val();
  490. titleEl = input.closest( '.menu-item' ).find( '.menu-item-title' );
  491. // Don't update to empty title.
  492. if ( title ) {
  493. titleEl.text( title ).removeClass( 'no-title' );
  494. } else {
  495. titleEl.text( navMenuL10n.untitled ).addClass( 'no-title' );
  496. }
  497. } );
  498. },
  499. initToggles : function() {
  500. // init postboxes
  501. postboxes.add_postbox_toggles('nav-menus');
  502. // adjust columns functions for menus UI
  503. columns.useCheckboxesForHidden();
  504. columns.checked = function(field) {
  505. $('.field-' + field).removeClass('hidden-field');
  506. };
  507. columns.unchecked = function(field) {
  508. $('.field-' + field).addClass('hidden-field');
  509. };
  510. // hide fields
  511. api.menuList.hideAdvancedMenuItemFields();
  512. $('.hide-postbox-tog').click(function () {
  513. var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
  514. $.post(ajaxurl, {
  515. action: 'closed-postboxes',
  516. hidden: hidden,
  517. closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
  518. page: 'nav-menus'
  519. });
  520. });
  521. },
  522. initSortables : function() {
  523. var currentDepth = 0, originalDepth, minDepth, maxDepth,
  524. prev, next, prevBottom, nextThreshold, helperHeight, transport,
  525. menuEdge = api.menuList.offset().left,
  526. body = $('body'), maxChildDepth,
  527. menuMaxDepth = initialMenuMaxDepth();
  528. if( 0 !== $( '#menu-to-edit li' ).length )
  529. $( '.drag-instructions' ).show();
  530. // Use the right edge if RTL.
  531. menuEdge += api.isRTL ? api.menuList.width() : 0;
  532. api.menuList.sortable({
  533. handle: '.menu-item-handle',
  534. placeholder: 'sortable-placeholder',
  535. items: api.options.sortableItems,
  536. start: function(e, ui) {
  537. var height, width, parent, children, tempHolder;
  538. // handle placement for rtl orientation
  539. if ( api.isRTL )
  540. ui.item[0].style.right = 'auto';
  541. transport = ui.item.children('.menu-item-transport');
  542. // Set depths. currentDepth must be set before children are located.
  543. originalDepth = ui.item.menuItemDepth();
  544. updateCurrentDepth(ui, originalDepth);
  545. // Attach child elements to parent
  546. // Skip the placeholder
  547. parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
  548. children = parent.childMenuItems();
  549. transport.append( children );
  550. // Update the height of the placeholder to match the moving item.
  551. height = transport.outerHeight();
  552. // If there are children, account for distance between top of children and parent
  553. height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
  554. height += ui.helper.outerHeight();
  555. helperHeight = height;
  556. height -= 2; // Subtract 2 for borders
  557. ui.placeholder.height(height);
  558. // Update the width of the placeholder to match the moving item.
  559. maxChildDepth = originalDepth;
  560. children.each(function(){
  561. var depth = $(this).menuItemDepth();
  562. maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
  563. });
  564. width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
  565. width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
  566. width -= 2; // Subtract 2 for borders
  567. ui.placeholder.width(width);
  568. // Update the list of menu items.
  569. tempHolder = ui.placeholder.next( '.menu-item' );
  570. tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
  571. ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
  572. $(this).sortable( 'refresh' ); // The children aren't sortable. We should let jQ UI know.
  573. ui.item.after( ui.placeholder ); // reattach the placeholder.
  574. tempHolder.css('margin-top', 0); // reset the margin
  575. // Now that the element is complete, we can update...
  576. updateSharedVars(ui);
  577. },
  578. stop: function(e, ui) {
  579. var children, subMenuTitle,
  580. depthChange = currentDepth - originalDepth;
  581. // Return child elements to the list
  582. children = transport.children().insertAfter(ui.item);
  583. // Add "sub menu" description
  584. subMenuTitle = ui.item.find( '.item-title .is-submenu' );
  585. if ( 0 < currentDepth )
  586. subMenuTitle.show();
  587. else
  588. subMenuTitle.hide();
  589. // Update depth classes
  590. if ( 0 !== depthChange ) {
  591. ui.item.updateDepthClass( currentDepth );
  592. children.shiftDepthClass( depthChange );
  593. updateMenuMaxDepth( depthChange );
  594. }
  595. // Register a change
  596. api.registerChange();
  597. // Update the item data.
  598. ui.item.updateParentMenuItemDBId();
  599. // address sortable's incorrectly-calculated top in opera
  600. ui.item[0].style.top = 0;
  601. // handle drop placement for rtl orientation
  602. if ( api.isRTL ) {
  603. ui.item[0].style.left = 'auto';
  604. ui.item[0].style.right = 0;
  605. }
  606. api.refreshKeyboardAccessibility();
  607. api.refreshAdvancedAccessibility();
  608. },
  609. change: function(e, ui) {
  610. // Make sure the placeholder is inside the menu.
  611. // Otherwise fix it, or we're in trouble.
  612. if( ! ui.placeholder.parent().hasClass('menu') )
  613. (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
  614. updateSharedVars(ui);
  615. },
  616. sort: function(e, ui) {
  617. var offset = ui.helper.offset(),
  618. edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
  619. depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
  620. // Check and correct if depth is not within range.
  621. // Also, if the dragged element is dragged upwards over
  622. // an item, shift the placeholder to a child position.
  623. if ( depth > maxDepth || offset.top < ( prevBottom - api.options.targetTolerance ) ) {
  624. depth = maxDepth;
  625. } else if ( depth < minDepth ) {
  626. depth = minDepth;
  627. }
  628. if( depth != currentDepth )
  629. updateCurrentDepth(ui, depth);
  630. // If we overlap the next element, manually shift downwards
  631. if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
  632. next.after( ui.placeholder );
  633. updateSharedVars( ui );
  634. $( this ).sortable( 'refreshPositions' );
  635. }
  636. }
  637. });
  638. function updateSharedVars(ui) {
  639. var depth;
  640. prev = ui.placeholder.prev( '.menu-item' );
  641. next = ui.placeholder.next( '.menu-item' );
  642. // Make sure we don't select the moving item.
  643. if( prev[0] == ui.item[0] ) prev = prev.prev( '.menu-item' );
  644. if( next[0] == ui.item[0] ) next = next.next( '.menu-item' );
  645. prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
  646. nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
  647. minDepth = (next.length) ? next.menuItemDepth() : 0;
  648. if( prev.length )
  649. maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
  650. else
  651. maxDepth = 0;
  652. }
  653. function updateCurrentDepth(ui, depth) {
  654. ui.placeholder.updateDepthClass( depth, currentDepth );
  655. currentDepth = depth;
  656. }
  657. function initialMenuMaxDepth() {
  658. if( ! body[0].className ) return 0;
  659. var match = body[0].className.match(/menu-max-depth-(\d+)/);
  660. return match && match[1] ? parseInt( match[1], 10 ) : 0;
  661. }
  662. function updateMenuMaxDepth( depthChange ) {
  663. var depth, newDepth = menuMaxDepth;
  664. if ( depthChange === 0 ) {
  665. return;
  666. } else if ( depthChange > 0 ) {
  667. depth = maxChildDepth + depthChange;
  668. if( depth > menuMaxDepth )
  669. newDepth = depth;
  670. } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
  671. while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
  672. newDepth--;
  673. }
  674. // Update the depth class.
  675. body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
  676. menuMaxDepth = newDepth;
  677. }
  678. },
  679. initManageLocations : function () {
  680. $('#menu-locations-wrap form').submit(function(){
  681. window.onbeforeunload = null;
  682. });
  683. $('.menu-location-menus select').on('change', function () {
  684. var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
  685. if ($(this).find('option:selected').data('orig'))
  686. editLink.show();
  687. else
  688. editLink.hide();
  689. });
  690. },
  691. attachMenuEditListeners : function() {
  692. var that = this;
  693. $('#update-nav-menu').bind('click', function(e) {
  694. if ( e.target && e.target.className ) {
  695. if ( -1 != e.target.className.indexOf('item-edit') ) {
  696. return that.eventOnClickEditLink(e.target);
  697. } else if ( -1 != e.target.className.indexOf('menu-save') ) {
  698. return that.eventOnClickMenuSave(e.target);
  699. } else if ( -1 != e.target.className.indexOf('menu-delete') ) {
  700. return that.eventOnClickMenuDelete(e.target);
  701. } else if ( -1 != e.target.className.indexOf('item-delete') ) {
  702. return that.eventOnClickMenuItemDelete(e.target);
  703. } else if ( -1 != e.target.className.indexOf('item-cancel') ) {
  704. return that.eventOnClickCancelLink(e.target);
  705. }
  706. }
  707. });
  708. $('#add-custom-links input[type="text"]').keypress(function(e){
  709. $('#customlinkdiv').removeClass('form-invalid');
  710. if ( e.keyCode === 13 ) {
  711. e.preventDefault();
  712. $( '#submit-customlinkdiv' ).click();
  713. }
  714. });
  715. },
  716. attachMenuSaveSubmitListeners : function() {
  717. /*
  718. * When a navigation menu is saved, store a JSON representation of all form data
  719. * in a single input to avoid PHP `max_input_vars` limitations. See #14134.
  720. */
  721. $( '#update-nav-menu' ).submit( function() {
  722. var navMenuData = $( '#update-nav-menu' ).serializeArray();
  723. $( '[name="nav-menu-data"]' ).val( JSON.stringify( navMenuData ) );
  724. });
  725. },
  726. attachThemeLocationsListeners : function() {
  727. var loc = $('#nav-menu-theme-locations'), params = {};
  728. params.action = 'menu-locations-save';
  729. params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
  730. loc.find('input[type="submit"]').click(function() {
  731. loc.find('select').each(function() {
  732. params[this.name] = $(this).val();
  733. });
  734. loc.find( '.spinner' ).addClass( 'is-active' );
  735. $.post( ajaxurl, params, function() {
  736. loc.find( '.spinner' ).removeClass( 'is-active' );
  737. });
  738. return false;
  739. });
  740. },
  741. attachQuickSearchListeners : function() {
  742. var searchTimer,
  743. inputEvent;
  744. // Prevent form submission.
  745. $( '#nav-menu-meta' ).on( 'submit', function( event ) {
  746. event.preventDefault();
  747. });
  748. /*
  749. * Use feature detection to determine whether inputs should use
  750. * the `keyup` or `input` event. Input is preferred but lacks support
  751. * in legacy browsers. See changeset 34078, see also ticket #26600#comment:59
  752. */
  753. if ( 'oninput' in document.createElement( 'input' ) ) {
  754. inputEvent = 'input';
  755. } else {
  756. inputEvent = 'keyup';
  757. }
  758. $( '#nav-menu-meta' ).on( inputEvent, '.quick-search', function() {
  759. var $this = $( this );
  760. $this.attr( 'autocomplete', 'off' );
  761. if ( searchTimer ) {
  762. clearTimeout( searchTimer );
  763. }
  764. searchTimer = setTimeout( function() {
  765. api.updateQuickSearchResults( $this );
  766. }, 500 );
  767. }).on( 'blur', '.quick-search', function() {
  768. api.lastSearch = '';
  769. });
  770. },
  771. updateQuickSearchResults : function(input) {
  772. var panel, params,
  773. minSearchLength = 2,
  774. q = input.val();
  775. /*
  776. * Minimum characters for a search. Also avoid a new AJAX search when
  777. * the pressed key (e.g. arrows) doesn't change the searched term.
  778. */
  779. if ( q.length < minSearchLength || api.lastSearch == q ) {
  780. return;
  781. }
  782. api.lastSearch = q;
  783. panel = input.parents('.tabs-panel');
  784. params = {
  785. 'action': 'menu-quick-search',
  786. 'response-format': 'markup',
  787. 'menu': $('#menu').val(),
  788. 'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
  789. 'q': q,
  790. 'type': input.attr('name')
  791. };
  792. $( '.spinner', panel ).addClass( 'is-active' );
  793. $.post( ajaxurl, params, function(menuMarkup) {
  794. api.processQuickSearchQueryResponse(menuMarkup, params, panel);
  795. });
  796. },
  797. addCustomLink : function( processMethod ) {
  798. var url = $('#custom-menu-item-url').val(),
  799. label = $('#custom-menu-item-name').val();
  800. processMethod = processMethod || api.addMenuItemToBottom;
  801. if ( '' === url || 'http://' == url ) {
  802. $('#customlinkdiv').addClass('form-invalid');
  803. return false;
  804. }
  805. // Show the ajax spinner
  806. $( '.customlinkdiv .spinner' ).addClass( 'is-active' );
  807. this.addLinkToMenu( url, label, processMethod, function() {
  808. // Remove the ajax spinner
  809. $( '.customlinkdiv .spinner' ).removeClass( 'is-active' );
  810. // Set custom link form back to defaults
  811. $('#custom-menu-item-name').val('').blur();
  812. $('#custom-menu-item-url').val('http://');
  813. });
  814. },
  815. addLinkToMenu : function(url, label, processMethod, callback) {
  816. processMethod = processMethod || api.addMenuItemToBottom;
  817. callback = callback || function(){};
  818. api.addItemToMenu({
  819. '-1': {
  820. 'menu-item-type': 'custom',
  821. 'menu-item-url': url,
  822. 'menu-item-title': label
  823. }
  824. }, processMethod, callback);
  825. },
  826. addItemToMenu : function(menuItem, processMethod, callback) {
  827. var menu = $('#menu').val(),
  828. nonce = $('#menu-settings-column-nonce').val(),
  829. params;
  830. processMethod = processMethod || function(){};
  831. callback = callback || function(){};
  832. params = {
  833. 'action': 'add-menu-item',
  834. 'menu': menu,
  835. 'menu-settings-column-nonce': nonce,
  836. 'menu-item': menuItem
  837. };
  838. $.post( ajaxurl, params, function(menuMarkup) {
  839. var ins = $('#menu-instructions');
  840. menuMarkup = $.trim( menuMarkup ); // Trim leading whitespaces
  841. processMethod(menuMarkup, params);
  842. // Make it stand out a bit more visually, by adding a fadeIn
  843. $( 'li.pending' ).hide().fadeIn('slow');
  844. $( '.drag-instructions' ).show();
  845. if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
  846. ins.addClass( 'menu-instructions-inactive' );
  847. callback();
  848. });
  849. },
  850. /**
  851. * Process the add menu item request response into menu list item. Appends to menu.
  852. *
  853. * @param {string} menuMarkup The text server response of menu item markup.
  854. *
  855. * @fires document#menu-item-added Passes menuMarkup as a jQuery object.
  856. */
  857. addMenuItemToBottom : function( menuMarkup ) {
  858. var $menuMarkup = $( menuMarkup );
  859. $menuMarkup.hideAdvancedMenuItemFields().appendTo( api.targetList );
  860. api.refreshKeyboardAccessibility();
  861. api.refreshAdvancedAccessibility();
  862. $( document ).trigger( 'menu-item-added', [ $menuMarkup ] );
  863. },
  864. /**
  865. * Process the add menu item request response into menu list item. Prepends to menu.
  866. *
  867. * @param {string} menuMarkup The text server response of menu item markup.
  868. *
  869. * @fires document#menu-item-added Passes menuMarkup as a jQuery object.
  870. */
  871. addMenuItemToTop : function( menuMarkup ) {
  872. var $menuMarkup = $( menuMarkup );
  873. $menuMarkup.hideAdvancedMenuItemFields().prependTo( api.targetList );
  874. api.refreshKeyboardAccessibility();
  875. api.refreshAdvancedAccessibility();
  876. $( document ).trigger( 'menu-item-added', [ $menuMarkup ] );
  877. },
  878. attachUnsavedChangesListener : function() {
  879. $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){
  880. api.registerChange();
  881. });
  882. if ( 0 !== $('#menu-to-edit').length || 0 !== $('.menu-location-menus select').length ) {
  883. window.onbeforeunload = function(){
  884. if ( api.menusChanged )
  885. return navMenuL10n.saveAlert;
  886. };
  887. } else {
  888. // Make the post boxes read-only, as they can't be used yet
  889. $( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' );
  890. }
  891. },
  892. registerChange : function() {
  893. api.menusChanged = true;
  894. },
  895. attachTabsPanelListeners : function() {
  896. $('#menu-settings-column').bind('click', function(e) {
  897. var selectAreaMatch, panelId, wrapper, items,
  898. target = $(e.target);
  899. if ( target.hasClass('nav-tab-link') ) {
  900. panelId = target.data( 'type' );
  901. wrapper = target.parents('.accordion-section-content').first();
  902. // upon changing tabs, we want to uncheck all checkboxes
  903. $('input', wrapper).removeAttr('checked');
  904. $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
  905. $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
  906. $('.tabs', wrapper).removeClass('tabs');
  907. target.parent().addClass('tabs');
  908. // select the search bar
  909. $('.quick-search', wrapper).focus();
  910. // Hide controls in the search tab if no items found.
  911. if ( ! wrapper.find( '.tabs-panel-active .menu-item-title' ).length ) {
  912. wrapper.addClass( 'has-no-menu-item' );
  913. } else {
  914. wrapper.removeClass( 'has-no-menu-item' );
  915. }
  916. e.preventDefault();
  917. } else if ( target.hasClass('select-all') ) {
  918. selectAreaMatch = /#(.*)$/.exec(e.target.href);
  919. if ( selectAreaMatch && selectAreaMatch[1] ) {
  920. items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
  921. if( items.length === items.filter(':checked').length )
  922. items.removeAttr('checked');
  923. else
  924. items.prop('checked', true);
  925. return false;
  926. }
  927. } else if ( target.hasClass('submit-add-to-menu') ) {
  928. api.registerChange();
  929. if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
  930. api.addCustomLink( api.addMenuItemToBottom );
  931. else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
  932. $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
  933. return false;
  934. }
  935. });
  936. /*
  937. * Delegate the `click` event and attach it just to the pagination
  938. * links thus excluding the current page `<span>`. See ticket #35577.
  939. */
  940. $( '#nav-menu-meta' ).on( 'click', 'a.page-numbers', function() {
  941. var $container = $( this ).closest( '.inside' );
  942. $.post( ajaxurl, this.href.replace( /.*\?/, '' ).replace( /action=([^&]*)/, '' ) + '&action=menu-get-metabox',
  943. function( resp ) {
  944. var metaBoxData = $.parseJSON( resp ),
  945. toReplace;
  946. if ( -1 === resp.indexOf( 'replace-id' ) ) {
  947. return;
  948. }
  949. // Get the post type menu meta box to update.
  950. toReplace = document.getElementById( metaBoxData['replace-id'] );
  951. if ( ! metaBoxData.markup || ! toReplace ) {
  952. return;
  953. }
  954. // Update the post type menu meta box with new content from the response.
  955. $container.html( metaBoxData.markup );
  956. }
  957. );
  958. return false;
  959. });
  960. },
  961. eventOnClickEditLink : function(clickedEl) {
  962. var settings, item,
  963. matchedSection = /#(.*)$/.exec(clickedEl.href);
  964. if ( matchedSection && matchedSection[1] ) {
  965. settings = $('#'+matchedSection[1]);
  966. item = settings.parent();
  967. if( 0 !== item.length ) {
  968. if( item.hasClass('menu-item-edit-inactive') ) {
  969. if( ! settings.data('menu-item-data') ) {
  970. settings.data( 'menu-item-data', settings.getItemData() );
  971. }
  972. settings.slideDown('fast');
  973. item.removeClass('menu-item-edit-inactive')
  974. .addClass('menu-item-edit-active');
  975. } else {
  976. settings.slideUp('fast');
  977. item.removeClass('menu-item-edit-active')
  978. .addClass('menu-item-edit-inactive');
  979. }
  980. return false;
  981. }
  982. }
  983. },
  984. eventOnClickCancelLink : function(clickedEl) {
  985. var settings = $( clickedEl ).closest( '.menu-item-settings' ),
  986. thisMenuItem = $( clickedEl ).closest( '.menu-item' );
  987. thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive');
  988. settings.setItemData( settings.data('menu-item-data') ).hide();
  989. return false;
  990. },
  991. eventOnClickMenuSave : function() {
  992. var locs = '',
  993. menuName = $('#menu-name'),
  994. menuNameVal = menuName.val();
  995. // Cancel and warn if invalid menu name
  996. if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
  997. menuName.parent().addClass('form-invalid');
  998. return false;
  999. }
  1000. // Copy menu theme locations
  1001. $('#nav-menu-theme-locations select').each(function() {
  1002. locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
  1003. });
  1004. $('#update-nav-menu').append( locs );
  1005. // Update menu item position data
  1006. api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
  1007. window.onbeforeunload = null;
  1008. return true;
  1009. },
  1010. eventOnClickMenuDelete : function() {
  1011. // Delete warning AYS
  1012. if ( window.confirm( navMenuL10n.warnDeleteMenu ) ) {
  1013. window.onbeforeunload = null;
  1014. return true;
  1015. }
  1016. return false;
  1017. },
  1018. eventOnClickMenuItemDelete : function(clickedEl) {
  1019. var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
  1020. api.removeMenuItem( $('#menu-item-' + itemID) );
  1021. api.registerChange();
  1022. return false;
  1023. },
  1024. /**
  1025. * Process the quick search response into a search result
  1026. *
  1027. * @param string resp The server response to the query.
  1028. * @param object req The request arguments.
  1029. * @param jQuery panel The tabs panel we're searching in.
  1030. */
  1031. processQuickSearchQueryResponse : function(resp, req, panel) {
  1032. var matched, newID,
  1033. takenIDs = {},
  1034. form = document.getElementById('nav-menu-meta'),
  1035. pattern = /menu-item[(\[^]\]*/,
  1036. $items = $('<div>').html(resp).find('li'),
  1037. wrapper = panel.closest( '.accordion-section-content' ),
  1038. $item;
  1039. if( ! $items.length ) {
  1040. $('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
  1041. $( '.spinner', panel ).removeClass( 'is-active' );
  1042. wrapper.addClass( 'has-no-menu-item' );
  1043. return;
  1044. }
  1045. $items.each(function(){
  1046. $item = $(this);
  1047. // make a unique DB ID number
  1048. matched = pattern.exec($item.html());
  1049. if ( matched && matched[1] ) {
  1050. newID = matched[1];
  1051. while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
  1052. newID--;
  1053. }
  1054. takenIDs[newID] = true;
  1055. if ( newID != matched[1] ) {
  1056. $item.html( $item.html().replace(new RegExp(
  1057. 'menu-item\\[' + matched[1] + '\\]', 'g'),
  1058. 'menu-item[' + newID + ']'
  1059. ) );
  1060. }
  1061. }
  1062. });
  1063. $('.categorychecklist', panel).html( $items );
  1064. $( '.spinner', panel ).removeClass( 'is-active' );
  1065. wrapper.removeClass( 'has-no-menu-item' );
  1066. },
  1067. /**
  1068. * Remove a menu item.
  1069. * @param {object} el The element to be removed as a jQuery object.
  1070. *
  1071. * @fires document#menu-removing-item Passes the element to be removed.
  1072. */
  1073. removeMenuItem : function(el) {
  1074. var children = el.childMenuItems();
  1075. $( document ).trigger( 'menu-removing-item', [ el ] );
  1076. el.addClass('deleting').animate({
  1077. opacity : 0,
  1078. height: 0
  1079. }, 350, function() {
  1080. var ins = $('#menu-instructions');
  1081. el.remove();
  1082. children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
  1083. if ( 0 === $( '#menu-to-edit li' ).length ) {
  1084. $( '.drag-instructions' ).hide();
  1085. ins.removeClass( 'menu-instructions-inactive' );
  1086. }
  1087. api.refreshAdvancedAccessibility();
  1088. });
  1089. },
  1090. depthToPx : function(depth) {
  1091. return depth * api.options.menuItemDepthPerLevel;
  1092. },
  1093. pxToDepth : function(px) {
  1094. return Math.floor(px / api.options.menuItemDepthPerLevel);
  1095. }
  1096. };
  1097. $(document).ready(function(){ wpNavMenu.init(); });
  1098. })(jQuery);