Нет описания

nav-menu.js 49KB

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