PageRenderTime 58ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-admin/js/customize-nav-menus.js

https://gitlab.com/campus-academy/krowkaramel
JavaScript | 1663 lines | 1087 code | 211 blank | 365 comment | 141 complexity | 114060e265b788628899a3c3fb3c6648 MD5 | raw file
  1. /**
  2. * @output wp-admin/js/customize-nav-menus.js
  3. */
  4. /* global _wpCustomizeNavMenusSettings, wpNavMenu, console */
  5. ( function( api, wp, $ ) {
  6. 'use strict';
  7. /**
  8. * Set up wpNavMenu for drag and drop.
  9. */
  10. wpNavMenu.originalInit = wpNavMenu.init;
  11. wpNavMenu.options.menuItemDepthPerLevel = 20;
  12. wpNavMenu.options.sortableItems = '> .customize-control-nav_menu_item';
  13. wpNavMenu.options.targetTolerance = 10;
  14. wpNavMenu.init = function() {
  15. this.jQueryExtensions();
  16. };
  17. /**
  18. * @namespace wp.customize.Menus
  19. */
  20. api.Menus = api.Menus || {};
  21. // Link settings.
  22. api.Menus.data = {
  23. itemTypes: [],
  24. l10n: {},
  25. settingTransport: 'refresh',
  26. phpIntMax: 0,
  27. defaultSettingValues: {
  28. nav_menu: {},
  29. nav_menu_item: {}
  30. },
  31. locationSlugMappedToName: {}
  32. };
  33. if ( 'undefined' !== typeof _wpCustomizeNavMenusSettings ) {
  34. $.extend( api.Menus.data, _wpCustomizeNavMenusSettings );
  35. }
  36. /**
  37. * Newly-created Nav Menus and Nav Menu Items have negative integer IDs which
  38. * serve as placeholders until Save & Publish happens.
  39. *
  40. * @alias wp.customize.Menus.generatePlaceholderAutoIncrementId
  41. *
  42. * @return {number}
  43. */
  44. api.Menus.generatePlaceholderAutoIncrementId = function() {
  45. return -Math.ceil( api.Menus.data.phpIntMax * Math.random() );
  46. };
  47. /**
  48. * wp.customize.Menus.AvailableItemModel
  49. *
  50. * A single available menu item model. See PHP's WP_Customize_Nav_Menu_Item_Setting class.
  51. *
  52. * @class wp.customize.Menus.AvailableItemModel
  53. * @augments Backbone.Model
  54. */
  55. api.Menus.AvailableItemModel = Backbone.Model.extend( $.extend(
  56. {
  57. id: null // This is only used by Backbone.
  58. },
  59. api.Menus.data.defaultSettingValues.nav_menu_item
  60. ) );
  61. /**
  62. * wp.customize.Menus.AvailableItemCollection
  63. *
  64. * Collection for available menu item models.
  65. *
  66. * @class wp.customize.Menus.AvailableItemCollection
  67. * @augments Backbone.Collection
  68. */
  69. api.Menus.AvailableItemCollection = Backbone.Collection.extend(/** @lends wp.customize.Menus.AvailableItemCollection.prototype */{
  70. model: api.Menus.AvailableItemModel,
  71. sort_key: 'order',
  72. comparator: function( item ) {
  73. return -item.get( this.sort_key );
  74. },
  75. sortByField: function( fieldName ) {
  76. this.sort_key = fieldName;
  77. this.sort();
  78. }
  79. });
  80. api.Menus.availableMenuItems = new api.Menus.AvailableItemCollection( api.Menus.data.availableMenuItems );
  81. /**
  82. * Insert a new `auto-draft` post.
  83. *
  84. * @since 4.7.0
  85. * @alias wp.customize.Menus.insertAutoDraftPost
  86. *
  87. * @param {Object} params - Parameters for the draft post to create.
  88. * @param {string} params.post_type - Post type to add.
  89. * @param {string} params.post_title - Post title to use.
  90. * @return {jQuery.promise} Promise resolved with the added post.
  91. */
  92. api.Menus.insertAutoDraftPost = function insertAutoDraftPost( params ) {
  93. var request, deferred = $.Deferred();
  94. request = wp.ajax.post( 'customize-nav-menus-insert-auto-draft', {
  95. 'customize-menus-nonce': api.settings.nonce['customize-menus'],
  96. 'wp_customize': 'on',
  97. 'customize_changeset_uuid': api.settings.changeset.uuid,
  98. 'params': params
  99. } );
  100. request.done( function( response ) {
  101. if ( response.post_id ) {
  102. api( 'nav_menus_created_posts' ).set(
  103. api( 'nav_menus_created_posts' ).get().concat( [ response.post_id ] )
  104. );
  105. if ( 'page' === params.post_type ) {
  106. // Activate static front page controls as this could be the first page created.
  107. if ( api.section.has( 'static_front_page' ) ) {
  108. api.section( 'static_front_page' ).activate();
  109. }
  110. // Add new page to dropdown-pages controls.
  111. api.control.each( function( control ) {
  112. var select;
  113. if ( 'dropdown-pages' === control.params.type ) {
  114. select = control.container.find( 'select[name^="_customize-dropdown-pages-"]' );
  115. select.append( new Option( params.post_title, response.post_id ) );
  116. }
  117. } );
  118. }
  119. deferred.resolve( response );
  120. }
  121. } );
  122. request.fail( function( response ) {
  123. var error = response || '';
  124. if ( 'undefined' !== typeof response.message ) {
  125. error = response.message;
  126. }
  127. console.error( error );
  128. deferred.rejectWith( error );
  129. } );
  130. return deferred.promise();
  131. };
  132. api.Menus.AvailableMenuItemsPanelView = wp.Backbone.View.extend(/** @lends wp.customize.Menus.AvailableMenuItemsPanelView.prototype */{
  133. el: '#available-menu-items',
  134. events: {
  135. 'input #menu-items-search': 'debounceSearch',
  136. 'focus .menu-item-tpl': 'focus',
  137. 'click .menu-item-tpl': '_submit',
  138. 'click #custom-menu-item-submit': '_submitLink',
  139. 'keypress #custom-menu-item-name': '_submitLink',
  140. 'click .new-content-item .add-content': '_submitNew',
  141. 'keypress .create-item-input': '_submitNew',
  142. 'keydown': 'keyboardAccessible'
  143. },
  144. // Cache current selected menu item.
  145. selected: null,
  146. // Cache menu control that opened the panel.
  147. currentMenuControl: null,
  148. debounceSearch: null,
  149. $search: null,
  150. $clearResults: null,
  151. searchTerm: '',
  152. rendered: false,
  153. pages: {},
  154. sectionContent: '',
  155. loading: false,
  156. addingNew: false,
  157. /**
  158. * wp.customize.Menus.AvailableMenuItemsPanelView
  159. *
  160. * View class for the available menu items panel.
  161. *
  162. * @constructs wp.customize.Menus.AvailableMenuItemsPanelView
  163. * @augments wp.Backbone.View
  164. */
  165. initialize: function() {
  166. var self = this;
  167. if ( ! api.panel.has( 'nav_menus' ) ) {
  168. return;
  169. }
  170. this.$search = $( '#menu-items-search' );
  171. this.$clearResults = this.$el.find( '.clear-results' );
  172. this.sectionContent = this.$el.find( '.available-menu-items-list' );
  173. this.debounceSearch = _.debounce( self.search, 500 );
  174. _.bindAll( this, 'close' );
  175. /*
  176. * If the available menu items panel is open and the customize controls
  177. * are interacted with (other than an item being deleted), then close
  178. * the available menu items panel. Also close on back button click.
  179. */
  180. $( '#customize-controls, .customize-section-back' ).on( 'click keydown', function( e ) {
  181. var isDeleteBtn = $( e.target ).is( '.item-delete, .item-delete *' ),
  182. isAddNewBtn = $( e.target ).is( '.add-new-menu-item, .add-new-menu-item *' );
  183. if ( $( 'body' ).hasClass( 'adding-menu-items' ) && ! isDeleteBtn && ! isAddNewBtn ) {
  184. self.close();
  185. }
  186. } );
  187. // Clear the search results and trigger an `input` event to fire a new search.
  188. this.$clearResults.on( 'click', function() {
  189. self.$search.val( '' ).trigger( 'focus' ).trigger( 'input' );
  190. } );
  191. this.$el.on( 'input', '#custom-menu-item-name.invalid, #custom-menu-item-url.invalid', function() {
  192. $( this ).removeClass( 'invalid' );
  193. });
  194. // Load available items if it looks like we'll need them.
  195. api.panel( 'nav_menus' ).container.on( 'expanded', function() {
  196. if ( ! self.rendered ) {
  197. self.initList();
  198. self.rendered = true;
  199. }
  200. });
  201. // Load more items.
  202. this.sectionContent.on( 'scroll', function() {
  203. var totalHeight = self.$el.find( '.accordion-section.open .available-menu-items-list' ).prop( 'scrollHeight' ),
  204. visibleHeight = self.$el.find( '.accordion-section.open' ).height();
  205. if ( ! self.loading && $( this ).scrollTop() > 3 / 4 * totalHeight - visibleHeight ) {
  206. var type = $( this ).data( 'type' ),
  207. object = $( this ).data( 'object' );
  208. if ( 'search' === type ) {
  209. if ( self.searchTerm ) {
  210. self.doSearch( self.pages.search );
  211. }
  212. } else {
  213. self.loadItems( [
  214. { type: type, object: object }
  215. ] );
  216. }
  217. }
  218. });
  219. // Close the panel if the URL in the preview changes.
  220. api.previewer.bind( 'url', this.close );
  221. self.delegateEvents();
  222. },
  223. // Search input change handler.
  224. search: function( event ) {
  225. var $searchSection = $( '#available-menu-items-search' ),
  226. $otherSections = $( '#available-menu-items .accordion-section' ).not( $searchSection );
  227. if ( ! event ) {
  228. return;
  229. }
  230. if ( this.searchTerm === event.target.value ) {
  231. return;
  232. }
  233. if ( '' !== event.target.value && ! $searchSection.hasClass( 'open' ) ) {
  234. $otherSections.fadeOut( 100 );
  235. $searchSection.find( '.accordion-section-content' ).slideDown( 'fast' );
  236. $searchSection.addClass( 'open' );
  237. this.$clearResults.addClass( 'is-visible' );
  238. } else if ( '' === event.target.value ) {
  239. $searchSection.removeClass( 'open' );
  240. $otherSections.show();
  241. this.$clearResults.removeClass( 'is-visible' );
  242. }
  243. this.searchTerm = event.target.value;
  244. this.pages.search = 1;
  245. this.doSearch( 1 );
  246. },
  247. // Get search results.
  248. doSearch: function( page ) {
  249. var self = this, params,
  250. $section = $( '#available-menu-items-search' ),
  251. $content = $section.find( '.accordion-section-content' ),
  252. itemTemplate = wp.template( 'available-menu-item' );
  253. if ( self.currentRequest ) {
  254. self.currentRequest.abort();
  255. }
  256. if ( page < 0 ) {
  257. return;
  258. } else if ( page > 1 ) {
  259. $section.addClass( 'loading-more' );
  260. $content.attr( 'aria-busy', 'true' );
  261. wp.a11y.speak( api.Menus.data.l10n.itemsLoadingMore );
  262. } else if ( '' === self.searchTerm ) {
  263. $content.html( '' );
  264. wp.a11y.speak( '' );
  265. return;
  266. }
  267. $section.addClass( 'loading' );
  268. self.loading = true;
  269. params = api.previewer.query( { excludeCustomizedSaved: true } );
  270. _.extend( params, {
  271. 'customize-menus-nonce': api.settings.nonce['customize-menus'],
  272. 'wp_customize': 'on',
  273. 'search': self.searchTerm,
  274. 'page': page
  275. } );
  276. self.currentRequest = wp.ajax.post( 'search-available-menu-items-customizer', params );
  277. self.currentRequest.done(function( data ) {
  278. var items;
  279. if ( 1 === page ) {
  280. // Clear previous results as it's a new search.
  281. $content.empty();
  282. }
  283. $section.removeClass( 'loading loading-more' );
  284. $content.attr( 'aria-busy', 'false' );
  285. $section.addClass( 'open' );
  286. self.loading = false;
  287. items = new api.Menus.AvailableItemCollection( data.items );
  288. self.collection.add( items.models );
  289. items.each( function( menuItem ) {
  290. $content.append( itemTemplate( menuItem.attributes ) );
  291. } );
  292. if ( 20 > items.length ) {
  293. self.pages.search = -1; // Up to 20 posts and 20 terms in results, if <20, no more results for either.
  294. } else {
  295. self.pages.search = self.pages.search + 1;
  296. }
  297. if ( items && page > 1 ) {
  298. wp.a11y.speak( api.Menus.data.l10n.itemsFoundMore.replace( '%d', items.length ) );
  299. } else if ( items && page === 1 ) {
  300. wp.a11y.speak( api.Menus.data.l10n.itemsFound.replace( '%d', items.length ) );
  301. }
  302. });
  303. self.currentRequest.fail(function( data ) {
  304. // data.message may be undefined, for example when typing slow and the request is aborted.
  305. if ( data.message ) {
  306. $content.empty().append( $( '<li class="nothing-found"></li>' ).text( data.message ) );
  307. wp.a11y.speak( data.message );
  308. }
  309. self.pages.search = -1;
  310. });
  311. self.currentRequest.always(function() {
  312. $section.removeClass( 'loading loading-more' );
  313. $content.attr( 'aria-busy', 'false' );
  314. self.loading = false;
  315. self.currentRequest = null;
  316. });
  317. },
  318. // Render the individual items.
  319. initList: function() {
  320. var self = this;
  321. // Render the template for each item by type.
  322. _.each( api.Menus.data.itemTypes, function( itemType ) {
  323. self.pages[ itemType.type + ':' + itemType.object ] = 0;
  324. } );
  325. self.loadItems( api.Menus.data.itemTypes );
  326. },
  327. /**
  328. * Load available nav menu items.
  329. *
  330. * @since 4.3.0
  331. * @since 4.7.0 Changed function signature to take list of item types instead of single type/object.
  332. * @access private
  333. *
  334. * @param {Array.<Object>} itemTypes List of objects containing type and key.
  335. * @param {string} deprecated Formerly the object parameter.
  336. * @return {void}
  337. */
  338. loadItems: function( itemTypes, deprecated ) {
  339. var self = this, _itemTypes, requestItemTypes = [], params, request, itemTemplate, availableMenuItemContainers = {};
  340. itemTemplate = wp.template( 'available-menu-item' );
  341. if ( _.isString( itemTypes ) && _.isString( deprecated ) ) {
  342. _itemTypes = [ { type: itemTypes, object: deprecated } ];
  343. } else {
  344. _itemTypes = itemTypes;
  345. }
  346. _.each( _itemTypes, function( itemType ) {
  347. var container, name = itemType.type + ':' + itemType.object;
  348. if ( -1 === self.pages[ name ] ) {
  349. return; // Skip types for which there are no more results.
  350. }
  351. container = $( '#available-menu-items-' + itemType.type + '-' + itemType.object );
  352. container.find( '.accordion-section-title' ).addClass( 'loading' );
  353. availableMenuItemContainers[ name ] = container;
  354. requestItemTypes.push( {
  355. object: itemType.object,
  356. type: itemType.type,
  357. page: self.pages[ name ]
  358. } );
  359. } );
  360. if ( 0 === requestItemTypes.length ) {
  361. return;
  362. }
  363. self.loading = true;
  364. params = api.previewer.query( { excludeCustomizedSaved: true } );
  365. _.extend( params, {
  366. 'customize-menus-nonce': api.settings.nonce['customize-menus'],
  367. 'wp_customize': 'on',
  368. 'item_types': requestItemTypes
  369. } );
  370. request = wp.ajax.post( 'load-available-menu-items-customizer', params );
  371. request.done(function( data ) {
  372. var typeInner;
  373. _.each( data.items, function( typeItems, name ) {
  374. if ( 0 === typeItems.length ) {
  375. if ( 0 === self.pages[ name ] ) {
  376. availableMenuItemContainers[ name ].find( '.accordion-section-title' )
  377. .addClass( 'cannot-expand' )
  378. .removeClass( 'loading' )
  379. .find( '.accordion-section-title > button' )
  380. .prop( 'tabIndex', -1 );
  381. }
  382. self.pages[ name ] = -1;
  383. return;
  384. } else if ( ( 'post_type:page' === name ) && ( ! availableMenuItemContainers[ name ].hasClass( 'open' ) ) ) {
  385. availableMenuItemContainers[ name ].find( '.accordion-section-title > button' ).trigger( 'click' );
  386. }
  387. typeItems = new api.Menus.AvailableItemCollection( typeItems ); // @todo Why is this collection created and then thrown away?
  388. self.collection.add( typeItems.models );
  389. typeInner = availableMenuItemContainers[ name ].find( '.available-menu-items-list' );
  390. typeItems.each( function( menuItem ) {
  391. typeInner.append( itemTemplate( menuItem.attributes ) );
  392. } );
  393. self.pages[ name ] += 1;
  394. });
  395. });
  396. request.fail(function( data ) {
  397. if ( typeof console !== 'undefined' && console.error ) {
  398. console.error( data );
  399. }
  400. });
  401. request.always(function() {
  402. _.each( availableMenuItemContainers, function( container ) {
  403. container.find( '.accordion-section-title' ).removeClass( 'loading' );
  404. } );
  405. self.loading = false;
  406. });
  407. },
  408. // Adjust the height of each section of items to fit the screen.
  409. itemSectionHeight: function() {
  410. var sections, lists, totalHeight, accordionHeight, diff;
  411. totalHeight = window.innerHeight;
  412. sections = this.$el.find( '.accordion-section:not( #available-menu-items-search ) .accordion-section-content' );
  413. lists = this.$el.find( '.accordion-section:not( #available-menu-items-search ) .available-menu-items-list:not(":only-child")' );
  414. accordionHeight = 46 * ( 1 + sections.length ) + 14; // Magic numbers.
  415. diff = totalHeight - accordionHeight;
  416. if ( 120 < diff && 290 > diff ) {
  417. sections.css( 'max-height', diff );
  418. lists.css( 'max-height', ( diff - 60 ) );
  419. }
  420. },
  421. // Highlights a menu item.
  422. select: function( menuitemTpl ) {
  423. this.selected = $( menuitemTpl );
  424. this.selected.siblings( '.menu-item-tpl' ).removeClass( 'selected' );
  425. this.selected.addClass( 'selected' );
  426. },
  427. // Highlights a menu item on focus.
  428. focus: function( event ) {
  429. this.select( $( event.currentTarget ) );
  430. },
  431. // Submit handler for keypress and click on menu item.
  432. _submit: function( event ) {
  433. // Only proceed with keypress if it is Enter or Spacebar.
  434. if ( 'keypress' === event.type && ( 13 !== event.which && 32 !== event.which ) ) {
  435. return;
  436. }
  437. this.submit( $( event.currentTarget ) );
  438. },
  439. // Adds a selected menu item to the menu.
  440. submit: function( menuitemTpl ) {
  441. var menuitemId, menu_item;
  442. if ( ! menuitemTpl ) {
  443. menuitemTpl = this.selected;
  444. }
  445. if ( ! menuitemTpl || ! this.currentMenuControl ) {
  446. return;
  447. }
  448. this.select( menuitemTpl );
  449. menuitemId = $( this.selected ).data( 'menu-item-id' );
  450. menu_item = this.collection.findWhere( { id: menuitemId } );
  451. if ( ! menu_item ) {
  452. return;
  453. }
  454. this.currentMenuControl.addItemToMenu( menu_item.attributes );
  455. $( menuitemTpl ).find( '.menu-item-handle' ).addClass( 'item-added' );
  456. },
  457. // Submit handler for keypress and click on custom menu item.
  458. _submitLink: function( event ) {
  459. // Only proceed with keypress if it is Enter.
  460. if ( 'keypress' === event.type && 13 !== event.which ) {
  461. return;
  462. }
  463. this.submitLink();
  464. },
  465. // Adds the custom menu item to the menu.
  466. submitLink: function() {
  467. var menuItem,
  468. itemName = $( '#custom-menu-item-name' ),
  469. itemUrl = $( '#custom-menu-item-url' ),
  470. url = itemUrl.val().trim(),
  471. urlRegex;
  472. if ( ! this.currentMenuControl ) {
  473. return;
  474. }
  475. /*
  476. * Allow URLs including:
  477. * - http://example.com/
  478. * - //example.com
  479. * - /directory/
  480. * - ?query-param
  481. * - #target
  482. * - mailto:foo@example.com
  483. *
  484. * Any further validation will be handled on the server when the setting is attempted to be saved,
  485. * so this pattern does not need to be complete.
  486. */
  487. urlRegex = /^((\w+:)?\/\/\w.*|\w+:(?!\/\/$)|\/|\?|#)/;
  488. if ( '' === itemName.val() ) {
  489. itemName.addClass( 'invalid' );
  490. return;
  491. } else if ( ! urlRegex.test( url ) ) {
  492. itemUrl.addClass( 'invalid' );
  493. return;
  494. }
  495. menuItem = {
  496. 'title': itemName.val(),
  497. 'url': url,
  498. 'type': 'custom',
  499. 'type_label': api.Menus.data.l10n.custom_label,
  500. 'object': 'custom'
  501. };
  502. this.currentMenuControl.addItemToMenu( menuItem );
  503. // Reset the custom link form.
  504. itemUrl.val( '' ).attr( 'placeholder', 'https://' );
  505. itemName.val( '' );
  506. },
  507. /**
  508. * Submit handler for keypress (enter) on field and click on button.
  509. *
  510. * @since 4.7.0
  511. * @private
  512. *
  513. * @param {jQuery.Event} event Event.
  514. * @return {void}
  515. */
  516. _submitNew: function( event ) {
  517. var container;
  518. // Only proceed with keypress if it is Enter.
  519. if ( 'keypress' === event.type && 13 !== event.which ) {
  520. return;
  521. }
  522. if ( this.addingNew ) {
  523. return;
  524. }
  525. container = $( event.target ).closest( '.accordion-section' );
  526. this.submitNew( container );
  527. },
  528. /**
  529. * Creates a new object and adds an associated menu item to the menu.
  530. *
  531. * @since 4.7.0
  532. * @private
  533. *
  534. * @param {jQuery} container
  535. * @return {void}
  536. */
  537. submitNew: function( container ) {
  538. var panel = this,
  539. itemName = container.find( '.create-item-input' ),
  540. title = itemName.val(),
  541. dataContainer = container.find( '.available-menu-items-list' ),
  542. itemType = dataContainer.data( 'type' ),
  543. itemObject = dataContainer.data( 'object' ),
  544. itemTypeLabel = dataContainer.data( 'type_label' ),
  545. promise;
  546. if ( ! this.currentMenuControl ) {
  547. return;
  548. }
  549. // Only posts are supported currently.
  550. if ( 'post_type' !== itemType ) {
  551. return;
  552. }
  553. if ( '' === itemName.val().trim() ) {
  554. itemName.addClass( 'invalid' );
  555. itemName.focus();
  556. return;
  557. } else {
  558. itemName.removeClass( 'invalid' );
  559. container.find( '.accordion-section-title' ).addClass( 'loading' );
  560. }
  561. panel.addingNew = true;
  562. itemName.attr( 'disabled', 'disabled' );
  563. promise = api.Menus.insertAutoDraftPost( {
  564. post_title: title,
  565. post_type: itemObject
  566. } );
  567. promise.done( function( data ) {
  568. var availableItem, $content, itemElement;
  569. availableItem = new api.Menus.AvailableItemModel( {
  570. 'id': 'post-' + data.post_id, // Used for available menu item Backbone models.
  571. 'title': itemName.val(),
  572. 'type': itemType,
  573. 'type_label': itemTypeLabel,
  574. 'object': itemObject,
  575. 'object_id': data.post_id,
  576. 'url': data.url
  577. } );
  578. // Add new item to menu.
  579. panel.currentMenuControl.addItemToMenu( availableItem.attributes );
  580. // Add the new item to the list of available items.
  581. api.Menus.availableMenuItemsPanel.collection.add( availableItem );
  582. $content = container.find( '.available-menu-items-list' );
  583. itemElement = $( wp.template( 'available-menu-item' )( availableItem.attributes ) );
  584. itemElement.find( '.menu-item-handle:first' ).addClass( 'item-added' );
  585. $content.prepend( itemElement );
  586. $content.scrollTop();
  587. // Reset the create content form.
  588. itemName.val( '' ).removeAttr( 'disabled' );
  589. panel.addingNew = false;
  590. container.find( '.accordion-section-title' ).removeClass( 'loading' );
  591. } );
  592. },
  593. // Opens the panel.
  594. open: function( menuControl ) {
  595. var panel = this, close;
  596. this.currentMenuControl = menuControl;
  597. this.itemSectionHeight();
  598. if ( api.section.has( 'publish_settings' ) ) {
  599. api.section( 'publish_settings' ).collapse();
  600. }
  601. $( 'body' ).addClass( 'adding-menu-items' );
  602. close = function() {
  603. panel.close();
  604. $( this ).off( 'click', close );
  605. };
  606. $( '#customize-preview' ).on( 'click', close );
  607. // Collapse all controls.
  608. _( this.currentMenuControl.getMenuItemControls() ).each( function( control ) {
  609. control.collapseForm();
  610. } );
  611. this.$el.find( '.selected' ).removeClass( 'selected' );
  612. this.$search.trigger( 'focus' );
  613. },
  614. // Closes the panel.
  615. close: function( options ) {
  616. options = options || {};
  617. if ( options.returnFocus && this.currentMenuControl ) {
  618. this.currentMenuControl.container.find( '.add-new-menu-item' ).focus();
  619. }
  620. this.currentMenuControl = null;
  621. this.selected = null;
  622. $( 'body' ).removeClass( 'adding-menu-items' );
  623. $( '#available-menu-items .menu-item-handle.item-added' ).removeClass( 'item-added' );
  624. this.$search.val( '' ).trigger( 'input' );
  625. },
  626. // Add a few keyboard enhancements to the panel.
  627. keyboardAccessible: function( event ) {
  628. var isEnter = ( 13 === event.which ),
  629. isEsc = ( 27 === event.which ),
  630. isBackTab = ( 9 === event.which && event.shiftKey ),
  631. isSearchFocused = $( event.target ).is( this.$search );
  632. // If enter pressed but nothing entered, don't do anything.
  633. if ( isEnter && ! this.$search.val() ) {
  634. return;
  635. }
  636. if ( isSearchFocused && isBackTab ) {
  637. this.currentMenuControl.container.find( '.add-new-menu-item' ).focus();
  638. event.preventDefault(); // Avoid additional back-tab.
  639. } else if ( isEsc ) {
  640. this.close( { returnFocus: true } );
  641. }
  642. }
  643. });
  644. /**
  645. * wp.customize.Menus.MenusPanel
  646. *
  647. * Customizer panel for menus. This is used only for screen options management.
  648. * Note that 'menus' must match the WP_Customize_Menu_Panel::$type.
  649. *
  650. * @class wp.customize.Menus.MenusPanel
  651. * @augments wp.customize.Panel
  652. */
  653. api.Menus.MenusPanel = api.Panel.extend(/** @lends wp.customize.Menus.MenusPanel.prototype */{
  654. attachEvents: function() {
  655. api.Panel.prototype.attachEvents.call( this );
  656. var panel = this,
  657. panelMeta = panel.container.find( '.panel-meta' ),
  658. help = panelMeta.find( '.customize-help-toggle' ),
  659. content = panelMeta.find( '.customize-panel-description' ),
  660. options = $( '#screen-options-wrap' ),
  661. button = panelMeta.find( '.customize-screen-options-toggle' );
  662. button.on( 'click keydown', function( event ) {
  663. if ( api.utils.isKeydownButNotEnterEvent( event ) ) {
  664. return;
  665. }
  666. event.preventDefault();
  667. // Hide description.
  668. if ( content.not( ':hidden' ) ) {
  669. content.slideUp( 'fast' );
  670. help.attr( 'aria-expanded', 'false' );
  671. }
  672. if ( 'true' === button.attr( 'aria-expanded' ) ) {
  673. button.attr( 'aria-expanded', 'false' );
  674. panelMeta.removeClass( 'open' );
  675. panelMeta.removeClass( 'active-menu-screen-options' );
  676. options.slideUp( 'fast' );
  677. } else {
  678. button.attr( 'aria-expanded', 'true' );
  679. panelMeta.addClass( 'open' );
  680. panelMeta.addClass( 'active-menu-screen-options' );
  681. options.slideDown( 'fast' );
  682. }
  683. return false;
  684. } );
  685. // Help toggle.
  686. help.on( 'click keydown', function( event ) {
  687. if ( api.utils.isKeydownButNotEnterEvent( event ) ) {
  688. return;
  689. }
  690. event.preventDefault();
  691. if ( 'true' === button.attr( 'aria-expanded' ) ) {
  692. button.attr( 'aria-expanded', 'false' );
  693. help.attr( 'aria-expanded', 'true' );
  694. panelMeta.addClass( 'open' );
  695. panelMeta.removeClass( 'active-menu-screen-options' );
  696. options.slideUp( 'fast' );
  697. content.slideDown( 'fast' );
  698. }
  699. } );
  700. },
  701. /**
  702. * Update field visibility when clicking on the field toggles.
  703. */
  704. ready: function() {
  705. var panel = this;
  706. panel.container.find( '.hide-column-tog' ).on( 'click', function() {
  707. panel.saveManageColumnsState();
  708. });
  709. // Inject additional heading into the menu locations section's head container.
  710. api.section( 'menu_locations', function( section ) {
  711. section.headContainer.prepend(
  712. wp.template( 'nav-menu-locations-header' )( api.Menus.data )
  713. );
  714. } );
  715. },
  716. /**
  717. * Save hidden column states.
  718. *
  719. * @since 4.3.0
  720. * @private
  721. *
  722. * @return {void}
  723. */
  724. saveManageColumnsState: _.debounce( function() {
  725. var panel = this;
  726. if ( panel._updateHiddenColumnsRequest ) {
  727. panel._updateHiddenColumnsRequest.abort();
  728. }
  729. panel._updateHiddenColumnsRequest = wp.ajax.post( 'hidden-columns', {
  730. hidden: panel.hidden(),
  731. screenoptionnonce: $( '#screenoptionnonce' ).val(),
  732. page: 'nav-menus'
  733. } );
  734. panel._updateHiddenColumnsRequest.always( function() {
  735. panel._updateHiddenColumnsRequest = null;
  736. } );
  737. }, 2000 ),
  738. /**
  739. * @deprecated Since 4.7.0 now that the nav_menu sections are responsible for toggling the classes on their own containers.
  740. */
  741. checked: function() {},
  742. /**
  743. * @deprecated Since 4.7.0 now that the nav_menu sections are responsible for toggling the classes on their own containers.
  744. */
  745. unchecked: function() {},
  746. /**
  747. * Get hidden fields.
  748. *
  749. * @since 4.3.0
  750. * @private
  751. *
  752. * @return {Array} Fields (columns) that are hidden.
  753. */
  754. hidden: function() {
  755. return $( '.hide-column-tog' ).not( ':checked' ).map( function() {
  756. var id = this.id;
  757. return id.substring( 0, id.length - 5 );
  758. }).get().join( ',' );
  759. }
  760. } );
  761. /**
  762. * wp.customize.Menus.MenuSection
  763. *
  764. * Customizer section for menus. This is used only for lazy-loading child controls.
  765. * Note that 'nav_menu' must match the WP_Customize_Menu_Section::$type.
  766. *
  767. * @class wp.customize.Menus.MenuSection
  768. * @augments wp.customize.Section
  769. */
  770. api.Menus.MenuSection = api.Section.extend(/** @lends wp.customize.Menus.MenuSection.prototype */{
  771. /**
  772. * Initialize.
  773. *
  774. * @since 4.3.0
  775. *
  776. * @param {string} id
  777. * @param {Object} options
  778. */
  779. initialize: function( id, options ) {
  780. var section = this;
  781. api.Section.prototype.initialize.call( section, id, options );
  782. section.deferred.initSortables = $.Deferred();
  783. },
  784. /**
  785. * Ready.
  786. */
  787. ready: function() {
  788. var section = this, fieldActiveToggles, handleFieldActiveToggle;
  789. if ( 'undefined' === typeof section.params.menu_id ) {
  790. throw new Error( 'params.menu_id was not defined' );
  791. }
  792. /*
  793. * Since newly created sections won't be registered in PHP, we need to prevent the
  794. * preview's sending of the activeSections to result in this control
  795. * being deactivated when the preview refreshes. So we can hook onto
  796. * the setting that has the same ID and its presence can dictate
  797. * whether the section is active.
  798. */
  799. section.active.validate = function() {
  800. if ( ! api.has( section.id ) ) {
  801. return false;
  802. }
  803. return !! api( section.id ).get();
  804. };
  805. section.populateControls();
  806. section.navMenuLocationSettings = {};
  807. section.assignedLocations = new api.Value( [] );
  808. api.each(function( setting, id ) {
  809. var matches = id.match( /^nav_menu_locations\[(.+?)]/ );
  810. if ( matches ) {
  811. section.navMenuLocationSettings[ matches[1] ] = setting;
  812. setting.bind( function() {
  813. section.refreshAssignedLocations();
  814. });
  815. }
  816. });
  817. section.assignedLocations.bind(function( to ) {
  818. section.updateAssignedLocationsInSectionTitle( to );
  819. });
  820. section.refreshAssignedLocations();
  821. api.bind( 'pane-contents-reflowed', function() {
  822. // Skip menus that have been removed.
  823. if ( ! section.contentContainer.parent().length ) {
  824. return;
  825. }
  826. section.container.find( '.menu-item .menu-item-reorder-nav button' ).attr({ 'tabindex': '0', 'aria-hidden': 'false' });
  827. section.container.find( '.menu-item.move-up-disabled .menus-move-up' ).attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
  828. section.container.find( '.menu-item.move-down-disabled .menus-move-down' ).attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
  829. section.container.find( '.menu-item.move-left-disabled .menus-move-left' ).attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
  830. section.container.find( '.menu-item.move-right-disabled .menus-move-right' ).attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
  831. } );
  832. /**
  833. * Update the active field class for the content container for a given checkbox toggle.
  834. *
  835. * @this {jQuery}
  836. * @return {void}
  837. */
  838. handleFieldActiveToggle = function() {
  839. var className = 'field-' + $( this ).val() + '-active';
  840. section.contentContainer.toggleClass( className, $( this ).prop( 'checked' ) );
  841. };
  842. fieldActiveToggles = api.panel( 'nav_menus' ).contentContainer.find( '.metabox-prefs:first' ).find( '.hide-column-tog' );
  843. fieldActiveToggles.each( handleFieldActiveToggle );
  844. fieldActiveToggles.on( 'click', handleFieldActiveToggle );
  845. },
  846. populateControls: function() {
  847. var section = this,
  848. menuNameControlId,
  849. menuLocationsControlId,
  850. menuAutoAddControlId,
  851. menuDeleteControlId,
  852. menuControl,
  853. menuNameControl,
  854. menuLocationsControl,
  855. menuAutoAddControl,
  856. menuDeleteControl;
  857. // Add the control for managing the menu name.
  858. menuNameControlId = section.id + '[name]';
  859. menuNameControl = api.control( menuNameControlId );
  860. if ( ! menuNameControl ) {
  861. menuNameControl = new api.controlConstructor.nav_menu_name( menuNameControlId, {
  862. type: 'nav_menu_name',
  863. label: api.Menus.data.l10n.menuNameLabel,
  864. section: section.id,
  865. priority: 0,
  866. settings: {
  867. 'default': section.id
  868. }
  869. } );
  870. api.control.add( menuNameControl );
  871. menuNameControl.active.set( true );
  872. }
  873. // Add the menu control.
  874. menuControl = api.control( section.id );
  875. if ( ! menuControl ) {
  876. menuControl = new api.controlConstructor.nav_menu( section.id, {
  877. type: 'nav_menu',
  878. section: section.id,
  879. priority: 998,
  880. settings: {
  881. 'default': section.id
  882. },
  883. menu_id: section.params.menu_id
  884. } );
  885. api.control.add( menuControl );
  886. menuControl.active.set( true );
  887. }
  888. // Add the menu locations control.
  889. menuLocationsControlId = section.id + '[locations]';
  890. menuLocationsControl = api.control( menuLocationsControlId );
  891. if ( ! menuLocationsControl ) {
  892. menuLocationsControl = new api.controlConstructor.nav_menu_locations( menuLocationsControlId, {
  893. section: section.id,
  894. priority: 999,
  895. settings: {
  896. 'default': section.id
  897. },
  898. menu_id: section.params.menu_id
  899. } );
  900. api.control.add( menuLocationsControl.id, menuLocationsControl );
  901. menuControl.active.set( true );
  902. }
  903. // Add the control for managing the menu auto_add.
  904. menuAutoAddControlId = section.id + '[auto_add]';
  905. menuAutoAddControl = api.control( menuAutoAddControlId );
  906. if ( ! menuAutoAddControl ) {
  907. menuAutoAddControl = new api.controlConstructor.nav_menu_auto_add( menuAutoAddControlId, {
  908. type: 'nav_menu_auto_add',
  909. label: '',
  910. section: section.id,
  911. priority: 1000,
  912. settings: {
  913. 'default': section.id
  914. }
  915. } );
  916. api.control.add( menuAutoAddControl );
  917. menuAutoAddControl.active.set( true );
  918. }
  919. // Add the control for deleting the menu.
  920. menuDeleteControlId = section.id + '[delete]';
  921. menuDeleteControl = api.control( menuDeleteControlId );
  922. if ( ! menuDeleteControl ) {
  923. menuDeleteControl = new api.Control( menuDeleteControlId, {
  924. section: section.id,
  925. priority: 1001,
  926. templateId: 'nav-menu-delete-button'
  927. } );
  928. api.control.add( menuDeleteControl.id, menuDeleteControl );
  929. menuDeleteControl.active.set( true );
  930. menuDeleteControl.deferred.embedded.done( function () {
  931. menuDeleteControl.container.find( 'button' ).on( 'click', function() {
  932. var menuId = section.params.menu_id;
  933. var menuControl = api.Menus.getMenuControl( menuId );
  934. menuControl.setting.set( false );
  935. });
  936. } );
  937. }
  938. },
  939. /**
  940. *
  941. */
  942. refreshAssignedLocations: function() {
  943. var section = this,
  944. menuTermId = section.params.menu_id,
  945. currentAssignedLocations = [];
  946. _.each( section.navMenuLocationSettings, function( setting, themeLocation ) {
  947. if ( setting() === menuTermId ) {
  948. currentAssignedLocations.push( themeLocation );
  949. }
  950. });
  951. section.assignedLocations.set( currentAssignedLocations );
  952. },
  953. /**
  954. * @param {Array} themeLocationSlugs Theme location slugs.
  955. */
  956. updateAssignedLocationsInSectionTitle: function( themeLocationSlugs ) {
  957. var section = this,
  958. $title;
  959. $title = section.container.find( '.accordion-section-title:first' );
  960. $title.find( '.menu-in-location' ).remove();
  961. _.each( themeLocationSlugs, function( themeLocationSlug ) {
  962. var $label, locationName;
  963. $label = $( '<span class="menu-in-location"></span>' );
  964. locationName = api.Menus.data.locationSlugMappedToName[ themeLocationSlug ];
  965. $label.text( api.Menus.data.l10n.menuLocation.replace( '%s', locationName ) );
  966. $title.append( $label );
  967. });
  968. section.container.toggleClass( 'assigned-to-menu-location', 0 !== themeLocationSlugs.length );
  969. },
  970. onChangeExpanded: function( expanded, args ) {
  971. var section = this, completeCallback;
  972. if ( expanded ) {
  973. wpNavMenu.menuList = section.contentContainer;
  974. wpNavMenu.targetList = wpNavMenu.menuList;
  975. // Add attributes needed by wpNavMenu.
  976. $( '#menu-to-edit' ).removeAttr( 'id' );
  977. wpNavMenu.menuList.attr( 'id', 'menu-to-edit' ).addClass( 'menu' );
  978. _.each( api.section( section.id ).controls(), function( control ) {
  979. if ( 'nav_menu_item' === control.params.type ) {
  980. control.actuallyEmbed();
  981. }
  982. } );
  983. // Make sure Sortables is initialized after the section has been expanded to prevent `offset` issues.
  984. if ( args.completeCallback ) {
  985. completeCallback = args.completeCallback;
  986. }
  987. args.completeCallback = function() {
  988. if ( 'resolved' !== section.deferred.initSortables.state() ) {
  989. wpNavMenu.initSortables(); // Depends on menu-to-edit ID being set above.
  990. section.deferred.initSortables.resolve( wpNavMenu.menuList ); // Now MenuControl can extend the sortable.
  991. // @todo Note that wp.customize.reflowPaneContents() is debounced,
  992. // so this immediate change will show a slight flicker while priorities get updated.
  993. api.control( 'nav_menu[' + String( section.params.menu_id ) + ']' ).reflowMenuItems();
  994. }
  995. if ( _.isFunction( completeCallback ) ) {
  996. completeCallback();
  997. }
  998. };
  999. }
  1000. api.Section.prototype.onChangeExpanded.call( section, expanded, args );
  1001. },
  1002. /**
  1003. * Highlight how a user may create new menu items.
  1004. *
  1005. * This method reminds the user to create new menu items and how.
  1006. * It's exposed this way because this class knows best which UI needs
  1007. * highlighted but those expanding this section know more about why and
  1008. * when the affordance should be highlighted.
  1009. *
  1010. * @since 4.9.0
  1011. *
  1012. * @return {void}
  1013. */
  1014. highlightNewItemButton: function() {
  1015. api.utils.highlightButton( this.contentContainer.find( '.add-new-menu-item' ), { delay: 2000 } );
  1016. }
  1017. });
  1018. /**
  1019. * Create a nav menu setting and section.
  1020. *
  1021. * @since 4.9.0
  1022. *
  1023. * @param {string} [name=''] Nav menu name.
  1024. * @return {wp.customize.Menus.MenuSection} Added nav menu.
  1025. */
  1026. api.Menus.createNavMenu = function createNavMenu( name ) {
  1027. var customizeId, placeholderId, setting;
  1028. placeholderId = api.Menus.generatePlaceholderAutoIncrementId();
  1029. customizeId = 'nav_menu[' + String( placeholderId ) + ']';
  1030. // Register the menu control setting.
  1031. setting = api.create( customizeId, customizeId, {}, {
  1032. type: 'nav_menu',
  1033. transport: api.Menus.data.settingTransport,
  1034. previewer: api.previewer
  1035. } );
  1036. setting.set( $.extend(
  1037. {},
  1038. api.Menus.data.defaultSettingValues.nav_menu,
  1039. {
  1040. name: name || ''
  1041. }
  1042. ) );
  1043. /*
  1044. * Add the menu section (and its controls).
  1045. * Note that this will automatically create the required controls
  1046. * inside via the Section's ready method.
  1047. */
  1048. return api.section.add( new api.Menus.MenuSection( customizeId, {
  1049. panel: 'nav_menus',
  1050. title: displayNavMenuName( name ),
  1051. customizeAction: api.Menus.data.l10n.customizingMenus,
  1052. priority: 10,
  1053. menu_id: placeholderId
  1054. } ) );
  1055. };
  1056. /**
  1057. * wp.customize.Menus.NewMenuSection
  1058. *
  1059. * Customizer section for new menus.
  1060. *
  1061. * @class wp.customize.Menus.NewMenuSection
  1062. * @augments wp.customize.Section
  1063. */
  1064. api.Menus.NewMenuSection = api.Section.extend(/** @lends wp.customize.Menus.NewMenuSection.prototype */{
  1065. /**
  1066. * Add behaviors for the accordion section.
  1067. *
  1068. * @since 4.3.0
  1069. */
  1070. attachEvents: function() {
  1071. var section = this,
  1072. container = section.container,
  1073. contentContainer = section.contentContainer,
  1074. navMenuSettingPattern = /^nav_menu\[/;
  1075. section.headContainer.find( '.accordion-section-title' ).replaceWith(
  1076. wp.template( 'nav-menu-create-menu-section-title' )
  1077. );
  1078. /*
  1079. * We have to manually handle section expanded because we do not
  1080. * apply the `accordion-section-title` class to this button-driven section.
  1081. */
  1082. container.on( 'click', '.customize-add-menu-button', function() {
  1083. section.expand();
  1084. });
  1085. contentContainer.on( 'keydown', '.menu-name-field', function( event ) {
  1086. if ( 13 === event.which ) { // Enter.
  1087. section.submit();
  1088. }
  1089. } );
  1090. contentContainer.on( 'click', '#customize-new-menu-submit', function( event ) {
  1091. section.submit();
  1092. event.stopPropagation();
  1093. event.preventDefault();
  1094. } );
  1095. /**
  1096. * Get number of non-deleted nav menus.
  1097. *
  1098. * @since 4.9.0
  1099. * @return {number} Count.
  1100. */
  1101. function getNavMenuCount() {
  1102. var count = 0;
  1103. api.each( function( setting ) {
  1104. if ( navMenuSettingPattern.test( setting.id ) && false !== setting.get() ) {
  1105. count += 1;
  1106. }
  1107. } );
  1108. return count;
  1109. }
  1110. /**
  1111. * Update visibility of notice to prompt users to create menus.
  1112. *
  1113. * @since 4.9.0
  1114. * @return {void}
  1115. */
  1116. function updateNoticeVisibility() {
  1117. container.find( '.add-new-menu-notice' ).prop( 'hidden', getNavMenuCount() > 0 );
  1118. }
  1119. /**
  1120. * Handle setting addition.
  1121. *
  1122. * @since 4.9.0
  1123. * @param {wp.customize.Setting} setting - Added setting.
  1124. * @return {void}
  1125. */
  1126. function addChangeEventListener( setting ) {
  1127. if ( navMenuSettingPattern.test( setting.id ) ) {
  1128. setting.bind( updateNoticeVisibility );
  1129. updateNoticeVisibility();
  1130. }
  1131. }
  1132. /**
  1133. * Handle setting removal.
  1134. *
  1135. * @since 4.9.0
  1136. * @param {wp.customize.Setting} setting - Removed setting.
  1137. * @return {void}
  1138. */
  1139. function removeChangeEventListener( setting ) {
  1140. if ( navMenuSettingPattern.test( setting.id ) ) {
  1141. setting.unbind( updateNoticeVisibility );
  1142. updateNoticeVisibility();
  1143. }
  1144. }
  1145. api.each( addChangeEventListener );
  1146. api.bind( 'add', addChangeEventListener );
  1147. api.bind( 'removed', removeChangeEventListener );
  1148. updateNoticeVisibility();
  1149. api.Section.prototype.attachEvents.apply( section, arguments );
  1150. },
  1151. /**
  1152. * Set up the control.
  1153. *
  1154. * @since 4.9.0
  1155. */
  1156. ready: function() {
  1157. this.populateControls();
  1158. },
  1159. /**
  1160. * Create the controls for this section.
  1161. *
  1162. * @since 4.9.0
  1163. */
  1164. populateControls: function() {
  1165. var section = this,
  1166. menuNameControlId,
  1167. menuLocationsControlId,
  1168. newMenuSubmitControlId,
  1169. menuNameControl,
  1170. menuLocationsControl,
  1171. newMenuSubmitControl;
  1172. menuNameControlId = section.id + '[name]';
  1173. menuNameControl = api.control( menuNameControlId );
  1174. if ( ! menuNameControl ) {
  1175. menuNameControl = new api.controlConstructor.nav_menu_name( menuNameControlId, {
  1176. label: api.Menus.data.l10n.menuNameLabel,
  1177. description: api.Menus.data.l10n.newMenuNameDescription,
  1178. section: section.id,
  1179. priority: 0
  1180. } );
  1181. api.control.add( menuNameControl.id, menuNameControl );
  1182. menuNameControl.active.set( true );
  1183. }
  1184. menuLocationsControlId = section.id + '[locations]';
  1185. menuLocationsControl = api.control( menuLocationsControlId );
  1186. if ( ! menuLocationsControl ) {
  1187. menuLocationsControl = new api.controlConstructor.nav_menu_locations( menuLocationsControlId, {
  1188. section: section.id,
  1189. priority: 1,
  1190. menu_id: '',
  1191. isCreating: true
  1192. } );
  1193. api.control.add( menuLocationsControlId, menuLocationsControl );
  1194. menuLocationsControl.active.set( true );
  1195. }
  1196. newMenuSubmitControlId = section.id + '[submit]';
  1197. newMenuSubmitControl = api.control( newMenuSubmitControlId );
  1198. if ( !newMenuSubmitControl ) {
  1199. newMenuSubmitControl = new api.Control( newMenuSubmitControlId, {
  1200. section: section.id,
  1201. priority: 1,
  1202. templateId: 'nav-menu-submit-new-button'
  1203. } );
  1204. api.control.add( newMenuSubmitControlId, newMenuSubmitControl );
  1205. newMenuSubmitControl.active.set( true );
  1206. }
  1207. },
  1208. /**
  1209. * Create the new menu with name and location supplied by the user.
  1210. *
  1211. * @since 4.9.0
  1212. */
  1213. submit: function() {
  1214. var section = this,
  1215. contentContainer = section.contentContainer,
  1216. nameInput = contentContainer.find( '.menu-name-field' ).first(),
  1217. name = nameInput.val(),
  1218. menuSection;
  1219. if ( ! name ) {
  1220. nameInput.addClass( 'invalid' );
  1221. nameInput.focus();
  1222. return;
  1223. }
  1224. menuSection = api.Menus.createNavMenu( name );
  1225. // Clear name field.
  1226. nameInput.val( '' );
  1227. nameInput.removeClass( 'invalid' );
  1228. contentContainer.find( '.assigned-menu-location input[type=checkbox]' ).each( function() {
  1229. var checkbox = $( this ),
  1230. navMenuLocationSetting;
  1231. if ( checkbox.prop( 'checked' ) ) {
  1232. navMenuLocationSetting = api( 'nav_menu_locations[' + checkbox.data( 'location-id' ) + ']' );
  1233. navMenuLocationSetting.set( menuSection.params.menu_id );
  1234. // Reset state for next new menu.
  1235. checkbox.prop( 'checked', false );
  1236. }
  1237. } );
  1238. wp.a11y.speak( api.Menus.data.l10n.menuAdded );
  1239. // Focus on the new menu section.
  1240. menuSection.focus( {
  1241. completeCallback: function() {
  1242. menuSection.highlightNewItemButton();
  1243. }
  1244. } );
  1245. },
  1246. /**
  1247. * Select a default location.
  1248. *
  1249. * This method selects a single location by default so we can support
  1250. * creating a menu for a specific menu location.
  1251. *
  1252. * @since 4.9.0
  1253. *
  1254. * @param {string|null} locationId - The ID of the location to select. `null` clears all selections.
  1255. * @return {void}
  1256. */
  1257. selectDefaultLocation: function( locationId ) {
  1258. var locationControl = api.control( this.id + '[locations]' ),
  1259. locationSelections = {};
  1260. if ( locationId !== null ) {
  1261. locationSelections[ locationId ] = true;
  1262. }
  1263. locationControl.setSelections( locationSelections );
  1264. }
  1265. });
  1266. /**
  1267. * wp.customize.Menus.MenuLocationControl
  1268. *
  1269. * Customizer control for menu locations (rendered as a <select>).
  1270. * Note that 'nav_menu_location' must match the WP_Customize_Nav_Menu_Location_Control::$type.
  1271. *
  1272. * @class wp.customize.Menus.MenuLocationControl
  1273. * @augments wp.customize.Control
  1274. */
  1275. api.Menus.MenuLocationControl = api.Control.extend(/** @lends wp.customize.Menus.MenuLocationControl.prototype */{
  1276. initialize: function( id, options ) {
  1277. var control = this,
  1278. matches = id.match( /^nav_menu_locations\[(.+?)]/ );
  1279. control.themeLocation = matches[1];
  1280. api.Control.prototype.initialize.call( control, id, options );
  1281. },
  1282. ready: function() {
  1283. var control = this, navMenuIdRegex = /^nav_menu\[(-?\d+)]/;
  1284. // @todo It would be better if this was added directly on the setting itself, as opposed to the control.
  1285. control.setting.validate = function( value ) {
  1286. if ( '' === value ) {
  1287. return 0;
  1288. } else {
  1289. return parseInt( value, 10 );
  1290. }
  1291. };
  1292. // Create and Edit menu buttons.
  1293. control.container.find( '.create-menu' ).on( 'click', function() {
  1294. var addMenuSection = api.section( 'add_menu' );
  1295. addMenuSection.selectDefaultLocation( this.dataset.locationId );
  1296. addMenuSection.focus();
  1297. } );
  1298. control.container.find( '.edit-menu' ).on( 'click', function() {
  1299. var menuId = control.setting();
  1300. api.section( 'nav_menu[' + menuId + ']' ).focus();
  1301. });
  1302. control.setting.bind( 'change', function() {
  1303. var menuIsSelected = 0 !== control.setting();
  1304. control.container.find( '.create-menu' ).toggleClass( 'hidden', menuIsSelected );
  1305. control.container.find( '.edit-menu' ).toggleClass( 'hidden', ! menuIsSelected );
  1306. });
  1307. // Add/remove menus from the available options when they are added and removed.
  1308. api.bind( 'add', function( setting ) {
  1309. var option, menuId, matches = setting.id.match( navMenuIdRegex );
  1310. if ( ! matches || false === setting() ) {
  1311. return;
  1312. }
  1313. menuId = matches[1];
  1314. option = new Option( displayNavMenuName( setting().name ), menuId );
  1315. control.container.find( 'select' ).append( option );
  1316. });
  1317. api.bind( 'remove', function( setting ) {
  1318. var menuId, matches = setting.id.match( navMenuIdRegex );
  1319. if ( ! matches ) {
  1320. return;
  1321. }
  1322. menuId = parseInt( matches[1], 10 );
  1323. if ( control.setting() === menuId ) {
  1324. control.setting.set( '' );
  1325. }
  1326. control.container.find( 'option[value=' + menuId + ']' ).remove();
  1327. });
  1328. api.bind( 'change', function( setting ) {
  1329. var menuId, matches = setting.id.match( navMenuIdRegex );
  1330. if ( ! matches ) {
  1331. return;
  1332. }
  1333. menuId = parseInt( matches[1], 10 );
  1334. if ( false === setting() ) {
  1335. if ( control.setting() === menuId ) {
  1336. control.setting.set( '' );
  1337. }
  1338. control.container.find( 'option[value=' + menuId + ']' ).remove();
  1339. } else {
  1340. control.container.find( 'option[value=' + menuId + ']' ).text( displayNavMenuName( setting().name ) );
  1341. }
  1342. });
  1343. }
  1344. });
  1345. api.Menus.MenuItemControl = api.Control.extend(/** @lends wp.customize.Menus.MenuItemControl.prototype */{
  1346. /**
  1347. * wp.customize.Menus.MenuItemControl
  1348. *
  1349. * Customizer control for menu items.
  1350. * Note that 'menu_item' must match the WP_Customize_Menu_Item_Control::$type.
  1351. *
  1352. * @constructs wp.customize.Menus.MenuItemControl
  1353. * @augments wp.customize.Control
  1354. *
  1355. * @inheritDoc
  1356. */
  1357. initialize: function( id, options ) {
  1358. var control = this;
  1359. control.expanded = new api.Value( false );
  1360. control.expandedArgumentsQueue = [];
  1361. control.expanded.bind( function( expanded ) {
  1362. var args = control.expandedArgumentsQueue.shift();
  1363. args = $.extend( {}, control.defaultExpandedArguments, args );
  1364. control.onChangeExpanded( expanded, args );
  1365. });
  1366. api.Control.prototype.initialize.call( control, id, options );
  1367. control.active.validate = function() {
  1368. var value, section = api.section( control.section() );
  1369. if ( section ) {
  1370. value = section.active();
  1371. } else {
  1372. value = false;
  1373. }
  1374. return value;
  1375. };
  1376. },
  1377. /**
  1378. * Override the embed() method to do nothing,
  1379. * so that the control isn't embedded on load,
  1380. * unless the containing section is already expanded.
  1381. *
  1382. * @since 4.3.0
  1383. */
  1384. embed: function() {
  1385. var control = this,
  1386. sectionId = control.section(),
  1387. section;
  1388. if ( ! sectionId ) {
  1389. return;
  1390. }
  1391. section = api.section( sectionId );
  1392. if ( ( section && section.expanded() ) || api.settings.autofocus.control === control.id ) {
  1393. control.actuallyEmbed();
  1394. }
  1395. },
  1396. /**
  1397. * This function is called in Section.onChangeExpanded() so the control
  1398. * will only get embedded when the Section is first expanded.
  1399. *
  1400. * @since 4.3.0
  1401. */
  1402. actuallyEmbed: function() {
  1403. var control = this;
  1404. if ( 'resolved' === control.deferred.embedded.state() ) {
  1405. return;
  1406. }
  1407. control.renderContent();
  1408. control.deferred.embedded.resolve(); // This triggers control.ready().
  1409. },
  1410. /**
  1411. * Set up the control.
  1412. */
  1413. ready: function() {
  1414. if ( 'undefined' === typeof this.params.menu_item_id ) {
  1415. throw new Error( 'params.menu_item_id was not defined' );
  1416. }
  1417. this._setupControlToggle();
  1418. this._setupReorderUI();
  1419. this._setupUpdateUI();
  1420. this._setupRemoveUI();
  1421. this._setupLinksUI();
  1422. this._setupTitleUI();
  1423. },
  1424. /**
  1425. * Show/hide the settings when clicking on the menu item handle.
  1426. */
  1427. _setupControlToggle: function() {
  1428. var control = this;
  1429. this.container.find( '.menu-item-handle' ).on( 'click', function( e ) {
  1430. e.preventDefault();
  1431. e.stopPropagation();
  1432. var menuControl = control.getMenuControl(),
  1433. isDeleteBtn = $( e.target ).is( '.item-delete, .item-delete *' ),
  1434. isAddNewBtn = $( e.target ).is( '.add-new-menu-item, .add-new-menu-item *' );
  1435. if ( $( 'body' ).hasClass( 'adding-menu-items' ) && ! isDeleteBtn && ! isAddNewBtn ) {
  1436. api.Menus.availableMenuItemsPanel.close();
  1437. }
  1438. if ( menuControl.isReordering || menuControl.isSorting ) {
  1439. return;
  1440. }
  1441. control.toggleForm();
  1442. } );
  1443. },
  1444. /**
  1445. * Set up the menu-item-reorder-nav
  1446. */
  1447. _setupReorderUI: function() {
  1448. var control = this, template, $reorderNav;
  1449. template = wp.template( 'menu-item-reorder-nav' );
  1450. // Add the menu item reordering elements to the menu item control.
  1451. control.container.find( '.item-controls' ).after( template );
  1452. // Handle clicks for up/do