nav-menu.js 50 KB

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