PageRenderTime 66ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

http://github.com/wordpress/wordpress
JavaScript | 3428 lines | 2250 code | 437 blank | 741 comment | 338 complexity | a6ffef157a167b4fdf103bbd0418711e MD5 | raw file
Possible License(s): 0BSD
  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 a `keyup` event to fire a new search.
  188. this.$clearResults.on( 'click', function() {
  189. self.$search.val( '' ).focus().trigger( 'keyup' );
  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.bind( 'expanded', function() {
  196. if ( ! self.rendered ) {
  197. self.initList();
  198. self.rendered = true;
  199. }
  200. });
  201. // Load more items.
  202. this.sectionContent.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' ).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 ( '' === $.trim( itemName.val() ) ) {
  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.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( 'keyup' );
  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' ).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/down/left-right on the reorder nav.
  1453. $reorderNav = control.container.find( '.menu-item-reorder-nav' );
  1454. $reorderNav.find( '.menus-move-up, .menus-move-down, .menus-move-left, .menus-move-right' ).on( 'click', function() {
  1455. var moveBtn = $( this );
  1456. moveBtn.focus();
  1457. var isMoveUp = moveBtn.is( '.menus-move-up' ),
  1458. isMoveDown = moveBtn.is( '.menus-move-down' ),
  1459. isMoveLeft = moveBtn.is( '.menus-move-left' ),
  1460. isMoveRight = moveBtn.is( '.menus-move-right' );
  1461. if ( isMoveUp ) {
  1462. control.moveUp();
  1463. } else if ( isMoveDown ) {
  1464. control.moveDown();
  1465. } else if ( isMoveLeft ) {
  1466. control.moveLeft();
  1467. } else if ( isMoveRight ) {
  1468. control.moveRight();
  1469. }
  1470. moveBtn.focus(); // Re-focus after the container was moved.
  1471. } );
  1472. },
  1473. /**
  1474. * Set up event handlers for menu item updating.
  1475. */
  1476. _setupUpdateUI: function() {
  1477. var control = this,
  1478. settingValue = control.setting(),
  1479. updateNotifications;
  1480. control.elements = {};
  1481. control.elements.url = new api.Element( control.container.find( '.edit-menu-item-url' ) );
  1482. control.elements.title = new api.Element( control.container.find( '.edit-menu-item-title' ) );
  1483. control.elements.attr_title = new api.Element( control.container.find( '.edit-menu-item-attr-title' ) );
  1484. control.elements.target = new api.Element( control.container.find( '.edit-menu-item-target' ) );
  1485. control.elements.classes = new api.Element( control.container.find( '.edit-menu-item-classes' ) );
  1486. control.elements.xfn = new api.Element( control.container.find( '.edit-menu-item-xfn' ) );
  1487. control.elements.description = new api.Element( control.container.find( '.edit-menu-item-description' ) );
  1488. // @todo Allow other elements, added by plugins, to be automatically picked up here;
  1489. // allow additional values to be added to setting array.
  1490. _.each( control.elements, function( element, property ) {
  1491. element.bind(function( value ) {
  1492. if ( element.element.is( 'input[type=checkbox]' ) ) {
  1493. value = ( value ) ? element.element.val() : '';
  1494. }
  1495. var settingValue = control.setting();
  1496. if ( settingValue && settingValue[ property ] !== value ) {
  1497. settingValue = _.clone( settingValue );
  1498. settingValue[ property ] = value;
  1499. control.setting.set( settingValue );
  1500. }
  1501. });
  1502. if ( settingValue ) {
  1503. if ( ( property === 'classes' || property === 'xfn' ) && _.isArray( settingValue[ property ] ) ) {
  1504. element.set( settingValue[ property ].join( ' ' ) );
  1505. } else {
  1506. element.set( settingValue[ property ] );
  1507. }
  1508. }
  1509. });
  1510. control.setting.bind(function( to, from ) {
  1511. var itemId = control.params.menu_item_id,
  1512. followingSiblingItemControls = [],
  1513. childrenItemControls = [],
  1514. menuControl;
  1515. if ( false === to ) {
  1516. menuControl = api.control( 'nav_menu[' + String( from.nav_menu_term_id ) + ']' );
  1517. control.container.remove();
  1518. _.each( menuControl.getMenuItemControls(), function( otherControl ) {
  1519. if ( from.menu_item_parent === otherControl.setting().menu_item_parent && otherControl.setting().position > from.position ) {
  1520. followingSiblingItemControls.push( otherControl );
  1521. } else if ( otherControl.setting().menu_item_parent === itemId ) {
  1522. childrenItemControls.push( otherControl );
  1523. }
  1524. });
  1525. // Shift all following siblings by the number of children this item has.
  1526. _.each( followingSiblingItemControls, function( followingSiblingItemControl ) {
  1527. var value = _.clone( followingSiblingItemControl.setting() );
  1528. value.position += childrenItemControls.length;
  1529. followingSiblingItemControl.setting.set( value );
  1530. });
  1531. // Now move the children up to be the new subsequent siblings.
  1532. _.each( childrenItemControls, function( childrenItemControl, i ) {
  1533. var value = _.clone( childrenItemControl.setting() );
  1534. value.position = from.position + i;
  1535. value.menu_item_parent = from.menu_item_parent;
  1536. childrenItemControl.setting.set( value );
  1537. });
  1538. menuControl.debouncedReflowMenuItems();
  1539. } else {
  1540. // Update the elements' values to match the new setting properties.
  1541. _.each( to, function( value, key ) {
  1542. if ( control.elements[ key] ) {
  1543. control.elements[ key ].set( to[ key ] );
  1544. }
  1545. } );
  1546. control.container.find( '.menu-item-data-parent-id' ).val( to.menu_item_parent );
  1547. // Handle UI updates when the position or depth (parent) change.
  1548. if ( to.position !== from.position || to.menu_item_parent !== from.menu_item_parent ) {
  1549. control.getMenuControl().debouncedReflowMenuItems();
  1550. }
  1551. }
  1552. });
  1553. // Style the URL field as invalid when there is an invalid_url notification.
  1554. updateNotifications = function() {
  1555. control.elements.url.element.toggleClass( 'invalid', control.setting.notifications.has( 'invalid_url' ) );
  1556. };
  1557. control.setting.notifications.bind( 'add', updateNotifications );
  1558. control.setting.notifications.bind( 'removed', updateNotifications );
  1559. },
  1560. /**
  1561. * Set up event handlers for menu item deletion.
  1562. */
  1563. _setupRemoveUI: function() {
  1564. var control = this, $removeBtn;
  1565. // Configure delete button.
  1566. $removeBtn = control.container.find( '.item-delete' );
  1567. $removeBtn.on( 'click', function() {
  1568. // Find an adjacent element to add focus to when this menu item goes away.
  1569. var addingItems = true, $adjacentFocusTarget, $next, $prev,
  1570. instanceCounter = 0, // Instance count of the menu item deleted.
  1571. deleteItemOriginalItemId = control.params.original_item_id,
  1572. addedItems = control.getMenuControl().$sectionContent.find( '.menu-item' ),
  1573. availableMenuItem;
  1574. if ( ! $( 'body' ).hasClass( 'adding-menu-items' ) ) {
  1575. addingItems = false;
  1576. }
  1577. $next = control.container.nextAll( '.customize-control-nav_menu_item:visible' ).first();
  1578. $prev = control.container.prevAll( '.customize-control-nav_menu_item:visible' ).first();
  1579. if ( $next.length ) {
  1580. $adjacentFocusTarget = $next.find( false === addingItems ? '.item-edit' : '.item-delete' ).first();
  1581. } else if ( $prev.length ) {
  1582. $adjacentFocusTarget = $prev.find( false === addingItems ? '.item-edit' : '.item-delete' ).first();
  1583. } else {
  1584. $adjacentFocusTarget = control.container.nextAll( '.customize-control-nav_menu' ).find( '.add-new-menu-item' ).first();
  1585. }
  1586. /*
  1587. * If the menu item deleted is the only of its instance left,
  1588. * remove the check icon of this menu item in the right panel.
  1589. */
  1590. _.each( addedItems, function( addedItem ) {
  1591. var menuItemId, menuItemControl, matches;
  1592. // This is because menu item that's deleted is just hidden.
  1593. if ( ! $( addedItem ).is( ':visible' ) ) {
  1594. return;
  1595. }
  1596. matches = addedItem.getAttribute( 'id' ).match( /^customize-control-nav_menu_item-(-?\d+)$/, '' );
  1597. if ( ! matches ) {
  1598. return;
  1599. }
  1600. menuItemId = parseInt( matches[1], 10 );
  1601. menuItemControl = api.control( 'nav_menu_item[' + String( menuItemId ) + ']' );
  1602. // Check for duplicate menu items.
  1603. if ( menuItemControl && deleteItemOriginalItemId == menuItemControl.params.original_item_id ) {
  1604. instanceCounter++;
  1605. }
  1606. } );
  1607. if ( instanceCounter <= 1 ) {
  1608. // Revert the check icon to add icon.
  1609. availableMenuItem = $( '#menu-item-tpl-' + control.params.original_item_id );
  1610. availableMenuItem.removeClass( 'selected' );
  1611. availableMenuItem.find( '.menu-item-handle' ).removeClass( 'item-added' );
  1612. }
  1613. control.container.slideUp( function() {
  1614. control.setting.set( false );
  1615. wp.a11y.speak( api.Menus.data.l10n.itemDeleted );
  1616. $adjacentFocusTarget.focus(); // Keyboard accessibility.
  1617. } );
  1618. control.setting.set( false );
  1619. } );
  1620. },
  1621. _setupLinksUI: function() {
  1622. var $origBtn;
  1623. // Configure original link.
  1624. $origBtn = this.container.find( 'a.original-link' );
  1625. $origBtn.on( 'click', function( e ) {
  1626. e.preventDefault();
  1627. api.previewer.previewUrl( e.target.toString() );
  1628. } );
  1629. },
  1630. /**
  1631. * Update item handle title when changed.
  1632. */
  1633. _setupTitleUI: function() {
  1634. var control = this, titleEl;
  1635. // Ensure that whitespace is trimmed on blur so placeholder can be shown.
  1636. control.container.find( '.edit-menu-item-title' ).on( 'blur', function() {
  1637. $( this ).val( $.trim( $( this ).val() ) );
  1638. } );
  1639. titleEl = control.container.find( '.menu-item-title' );
  1640. control.setting.bind( function( item ) {
  1641. var trimmedTitle, titleText;
  1642. if ( ! item ) {
  1643. return;
  1644. }
  1645. trimmedTitle = $.trim( item.title );
  1646. titleText = trimmedTitle || item.original_title || api.Menus.data.l10n.untitled;
  1647. if ( item._invalid ) {
  1648. titleText = api.Menus.data.l10n.invalidTitleTpl.replace( '%s', titleText );
  1649. }
  1650. // Don't update to an empty title.
  1651. if ( trimmedTitle || item.original_title ) {
  1652. titleEl
  1653. .text( titleText )
  1654. .removeClass( 'no-title' );
  1655. } else {
  1656. titleEl
  1657. .text( titleText )
  1658. .addClass( 'no-title' );
  1659. }
  1660. } );
  1661. },
  1662. /**
  1663. *
  1664. * @return {number}
  1665. */
  1666. getDepth: function() {
  1667. var control = this, setting = control.setting(), depth = 0;
  1668. if ( ! setting ) {
  1669. return 0;
  1670. }
  1671. while ( setting && setting.menu_item_parent ) {
  1672. depth += 1;
  1673. control = api.control( 'nav_menu_item[' + setting.menu_item_parent + ']' );
  1674. if ( ! control ) {
  1675. break;
  1676. }
  1677. setting = control.setting();
  1678. }
  1679. return depth;
  1680. },
  1681. /**
  1682. * Amend the control's params with the data necessary for the JS template just in time.
  1683. */
  1684. renderContent: function() {
  1685. var control = this,
  1686. settingValue = control.setting(),
  1687. containerClasses;
  1688. control.params.title = settingValue.title || '';
  1689. control.params.depth = control.getDepth();
  1690. control.container.data( 'item-depth', control.params.depth );
  1691. containerClasses = [
  1692. 'menu-item',
  1693. 'menu-item-depth-' + String( control.params.depth ),
  1694. 'menu-item-' + settingValue.object,
  1695. 'menu-item-edit-inactive'
  1696. ];
  1697. if ( settingValue._invalid ) {
  1698. containerClasses.push( 'menu-item-invalid' );
  1699. control.params.title = api.Menus.data.l10n.invalidTitleTpl.replace( '%s', control.params.title );
  1700. } else if ( 'draft' === settingValue.status ) {
  1701. containerClasses.push( 'pending' );
  1702. control.params.title = api.Menus.data.pendingTitleTpl.replace( '%s', control.params.title );
  1703. }
  1704. control.params.el_classes = containerClasses.join( ' ' );
  1705. control.params.item_type_label = settingValue.type_label;
  1706. control.params.item_type = settingValue.type;
  1707. control.params.url = settingValue.url;
  1708. control.params.target = settingValue.target;
  1709. control.params.attr_title = settingValue.attr_title;
  1710. control.params.classes = _.isArray( settingValue.classes ) ? settingValue.classes.join( ' ' ) : settingValue.classes;
  1711. control.params.xfn = settingValue.xfn;
  1712. control.params.description = settingValue.description;
  1713. control.params.parent = settingValue.menu_item_parent;
  1714. control.params.original_title = settingValue.original_title || '';
  1715. control.container.addClass( control.params.el_classes );
  1716. api.Control.prototype.renderContent.call( control );
  1717. },
  1718. /***********************************************************************
  1719. * Begin public API methods
  1720. **********************************************************************/
  1721. /**
  1722. * @return {wp.customize.controlConstructor.nav_menu|null}
  1723. */
  1724. getMenuControl: function() {
  1725. var control = this, settingValue = control.setting();
  1726. if ( settingValue && settingValue.nav_menu_term_id ) {
  1727. return api.control( 'nav_menu[' + settingValue.nav_menu_term_id + ']' );
  1728. } else {
  1729. return null;
  1730. }
  1731. },
  1732. /**
  1733. * Expand the accordion section containing a control
  1734. */
  1735. expandControlSection: function() {
  1736. var $section = this.container.closest( '.accordion-section' );
  1737. if ( ! $section.hasClass( 'open' ) ) {
  1738. $section.find( '.accordion-section-title:first' ).trigger( 'click' );
  1739. }
  1740. },
  1741. /**
  1742. * @since 4.6.0
  1743. *
  1744. * @param {Boolean} expanded
  1745. * @param {Object} [params]
  1746. * @return {Boolean} False if state already applied.
  1747. */
  1748. _toggleExpanded: api.Section.prototype._toggleExpanded,
  1749. /**
  1750. * @since 4.6.0
  1751. *
  1752. * @param {Object} [params]
  1753. * @return {Boolean} False if already expanded.
  1754. */
  1755. expand: api.Section.prototype.expand,
  1756. /**
  1757. * Expand the menu item form control.
  1758. *
  1759. * @since 4.5.0 Added params.completeCallback.
  1760. *
  1761. * @param {Object} [params] - Optional params.
  1762. * @param {Function} [params.completeCallback] - Function to call when the form toggle has finished animating.
  1763. */
  1764. expandForm: function( params ) {
  1765. this.expand( params );
  1766. },
  1767. /**
  1768. * @since 4.6.0
  1769. *
  1770. * @param {Object} [params]
  1771. * @return {Boolean} False if already collapsed.
  1772. */
  1773. collapse: api.Section.prototype.collapse,
  1774. /**
  1775. * Collapse the menu item form control.
  1776. *
  1777. * @since 4.5.0 Added params.completeCallback.
  1778. *
  1779. * @param {Object} [params] - Optional params.
  1780. * @param {Function} [params.completeCallback] - Function to call when the form toggle has finished animating.
  1781. */
  1782. collapseForm: function( params ) {
  1783. this.collapse( params );
  1784. },
  1785. /**
  1786. * Expand or collapse the menu item control.
  1787. *
  1788. * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
  1789. * @since 4.5.0 Added params.completeCallback.
  1790. *
  1791. * @param {boolean} [showOrHide] - If not supplied, will be inverse of current visibility
  1792. * @param {Object} [params] - Optional params.
  1793. * @param {Function} [params.completeCallback] - Function to call when the form toggle has finished animating.
  1794. */
  1795. toggleForm: function( showOrHide, params ) {
  1796. if ( typeof showOrHide === 'undefined' ) {
  1797. showOrHide = ! this.expanded();
  1798. }
  1799. if ( showOrHide ) {
  1800. this.expand( params );
  1801. } else {
  1802. this.collapse( params );
  1803. }
  1804. },
  1805. /**
  1806. * Expand or collapse the menu item control.
  1807. *
  1808. * @since 4.6.0
  1809. * @param {boolean} [showOrHide] - If not supplied, will be inverse of current visibility
  1810. * @param {Object} [params] - Optional params.
  1811. * @param {Function} [params.completeCallback] - Function to call when the form toggle has finished animating.
  1812. */
  1813. onChangeExpanded: function( showOrHide, params ) {
  1814. var self = this, $menuitem, $inside, complete;
  1815. $menuitem = this.container;
  1816. $inside = $menuitem.find( '.menu-item-settings:first' );
  1817. if ( 'undefined' === typeof showOrHide ) {
  1818. showOrHide = ! $inside.is( ':visible' );
  1819. }
  1820. // Already expanded or collapsed.
  1821. if ( $inside.is( ':visible' ) === showOrHide ) {
  1822. if ( params && params.completeCallback ) {
  1823. params.completeCallback();
  1824. }
  1825. return;
  1826. }
  1827. if ( showOrHide ) {
  1828. // Close all other menu item controls before expanding this one.
  1829. api.control.each( function( otherControl ) {
  1830. if ( self.params.type === otherControl.params.type && self !== otherControl ) {
  1831. otherControl.collapseForm();
  1832. }
  1833. } );
  1834. complete = function() {
  1835. $menuitem
  1836. .removeClass( 'menu-item-edit-inactive' )
  1837. .addClass( 'menu-item-edit-active' );
  1838. self.container.trigger( 'expanded' );
  1839. if ( params && params.completeCallback ) {
  1840. params.completeCallback();
  1841. }
  1842. };
  1843. $menuitem.find( '.item-edit' ).attr( 'aria-expanded', 'true' );
  1844. $inside.slideDown( 'fast', complete );
  1845. self.container.trigger( 'expand' );
  1846. } else {
  1847. complete = function() {
  1848. $menuitem
  1849. .addClass( 'menu-item-edit-inactive' )
  1850. .removeClass( 'menu-item-edit-active' );
  1851. self.container.trigger( 'collapsed' );
  1852. if ( params && params.completeCallback ) {
  1853. params.completeCallback();
  1854. }
  1855. };
  1856. self.container.trigger( 'collapse' );
  1857. $menuitem.find( '.item-edit' ).attr( 'aria-expanded', 'false' );
  1858. $inside.slideUp( 'fast', complete );
  1859. }
  1860. },
  1861. /**
  1862. * Expand the containing menu section, expand the form, and focus on
  1863. * the first input in the control.
  1864. *
  1865. * @since 4.5.0 Added params.completeCallback.
  1866. *
  1867. * @param {Object} [params] - Params object.
  1868. * @param {Function} [params.completeCallback] - Optional callback function when focus has completed.
  1869. */
  1870. focus: function( params ) {
  1871. params = params || {};
  1872. var control = this, originalCompleteCallback = params.completeCallback, focusControl;
  1873. focusControl = function() {
  1874. control.expandControlSection();
  1875. params.completeCallback = function() {
  1876. var focusable;
  1877. // Note that we can't use :focusable due to a jQuery UI issue. See: https://github.com/jquery/jquery-ui/pull/1583
  1878. focusable = control.container.find( '.menu-item-settings' ).find( 'input, select, textarea, button, object, a[href], [tabindex]' ).filter( ':visible' );
  1879. focusable.first().focus();
  1880. if ( originalCompleteCallback ) {
  1881. originalCompleteCallback();
  1882. }
  1883. };
  1884. control.expandForm( params );
  1885. };
  1886. if ( api.section.has( control.section() ) ) {
  1887. api.section( control.section() ).expand( {
  1888. completeCallback: focusControl
  1889. } );
  1890. } else {
  1891. focusControl();
  1892. }
  1893. },
  1894. /**
  1895. * Move menu item up one in the menu.
  1896. */
  1897. moveUp: function() {
  1898. this._changePosition( -1 );
  1899. wp.a11y.speak( api.Menus.data.l10n.movedUp );
  1900. },
  1901. /**
  1902. * Move menu item up one in the menu.
  1903. */
  1904. moveDown: function() {
  1905. this._changePosition( 1 );
  1906. wp.a11y.speak( api.Menus.data.l10n.movedDown );
  1907. },
  1908. /**
  1909. * Move menu item and all children up one level of depth.
  1910. */
  1911. moveLeft: function() {
  1912. this._changeDepth( -1 );
  1913. wp.a11y.speak( api.Menus.data.l10n.movedLeft );
  1914. },
  1915. /**
  1916. * Move menu item and children one level deeper, as a submenu of the previous item.
  1917. */
  1918. moveRight: function() {
  1919. this._changeDepth( 1 );
  1920. wp.a11y.speak( api.Menus.data.l10n.movedRight );
  1921. },
  1922. /**
  1923. * Note that this will trigger a UI update, causing child items to
  1924. * move as well and cardinal order class names to be updated.
  1925. *
  1926. * @private
  1927. *
  1928. * @param {Number} offset 1|-1
  1929. */
  1930. _changePosition: function( offset ) {
  1931. var control = this,
  1932. adjacentSetting,
  1933. settingValue = _.clone( control.setting() ),
  1934. siblingSettings = [],
  1935. realPosition;
  1936. if ( 1 !== offset && -1 !== offset ) {
  1937. throw new Error( 'Offset changes by 1 are only supported.' );
  1938. }
  1939. // Skip moving deleted items.
  1940. if ( ! control.setting() ) {
  1941. return;
  1942. }
  1943. // Locate the other items under the same parent (siblings).
  1944. _( control.getMenuControl().getMenuItemControls() ).each(function( otherControl ) {
  1945. if ( otherControl.setting().menu_item_parent === settingValue.menu_item_parent ) {
  1946. siblingSettings.push( otherControl.setting );
  1947. }
  1948. });
  1949. siblingSettings.sort(function( a, b ) {
  1950. return a().position - b().position;
  1951. });
  1952. realPosition = _.indexOf( siblingSettings, control.setting );
  1953. if ( -1 === realPosition ) {
  1954. throw new Error( 'Expected setting to be among siblings.' );
  1955. }
  1956. // Skip doing anything if the item is already at the edge in the desired direction.
  1957. if ( ( realPosition === 0 && offset < 0 ) || ( realPosition === siblingSettings.length - 1 && offset > 0 ) ) {
  1958. // @todo Should we allow a menu item to be moved up to break it out of a parent? Adopt with previous or following parent?
  1959. return;
  1960. }
  1961. // Update any adjacent menu item setting to take on this item's position.
  1962. adjacentSetting = siblingSettings[ realPosition + offset ];
  1963. if ( adjacentSetting ) {
  1964. adjacentSetting.set( $.extend(
  1965. _.clone( adjacentSetting() ),
  1966. {
  1967. position: settingValue.position
  1968. }
  1969. ) );
  1970. }
  1971. settingValue.position += offset;
  1972. control.setting.set( settingValue );
  1973. },
  1974. /**
  1975. * Note that this will trigger a UI update, causing child items to
  1976. * move as well and cardinal order class names to be updated.
  1977. *
  1978. * @private
  1979. *
  1980. * @param {Number} offset 1|-1
  1981. */
  1982. _changeDepth: function( offset ) {
  1983. if ( 1 !== offset && -1 !== offset ) {
  1984. throw new Error( 'Offset changes by 1 are only supported.' );
  1985. }
  1986. var control = this,
  1987. settingValue = _.clone( control.setting() ),
  1988. siblingControls = [],
  1989. realPosition,
  1990. siblingControl,
  1991. parentControl;
  1992. // Locate the other items under the same parent (siblings).
  1993. _( control.getMenuControl().getMenuItemControls() ).each(function( otherControl ) {
  1994. if ( otherControl.setting().menu_item_parent === settingValue.menu_item_parent ) {
  1995. siblingControls.push( otherControl );
  1996. }
  1997. });
  1998. siblingControls.sort(function( a, b ) {
  1999. return a.setting().position - b.setting().position;
  2000. });
  2001. realPosition = _.indexOf( siblingControls, control );
  2002. if ( -1 === realPosition ) {
  2003. throw new Error( 'Expected control to be among siblings.' );
  2004. }
  2005. if ( -1 === offset ) {
  2006. // Skip moving left an item that is already at the top level.
  2007. if ( ! settingValue.menu_item_parent ) {
  2008. return;
  2009. }
  2010. parentControl = api.control( 'nav_menu_item[' + settingValue.menu_item_parent + ']' );
  2011. // Make this control the parent of all the following siblings.
  2012. _( siblingControls ).chain().slice( realPosition ).each(function( siblingControl, i ) {
  2013. siblingControl.setting.set(
  2014. $.extend(
  2015. {},
  2016. siblingControl.setting(),
  2017. {
  2018. menu_item_parent: control.params.menu_item_id,
  2019. position: i
  2020. }
  2021. )
  2022. );
  2023. });
  2024. // Increase the positions of the parent item's subsequent children to make room for this one.
  2025. _( control.getMenuControl().getMenuItemControls() ).each(function( otherControl ) {
  2026. var otherControlSettingValue, isControlToBeShifted;
  2027. isControlToBeShifted = (
  2028. otherControl.setting().menu_item_parent === parentControl.setting().menu_item_parent &&
  2029. otherControl.setting().position > parentControl.setting().position
  2030. );
  2031. if ( isControlToBeShifted ) {
  2032. otherControlSettingValue = _.clone( otherControl.setting() );
  2033. otherControl.setting.set(
  2034. $.extend(
  2035. otherControlSettingValue,
  2036. { position: otherControlSettingValue.position + 1 }
  2037. )
  2038. );
  2039. }
  2040. });
  2041. // Make this control the following sibling of its parent item.
  2042. settingValue.position = parentControl.setting().position + 1;
  2043. settingValue.menu_item_parent = parentControl.setting().menu_item_parent;
  2044. control.setting.set( settingValue );
  2045. } else if ( 1 === offset ) {
  2046. // Skip moving right an item that doesn't have a previous sibling.
  2047. if ( realPosition === 0 ) {
  2048. return;
  2049. }
  2050. // Make the control the last child of the previous sibling.
  2051. siblingControl = siblingControls[ realPosition - 1 ];
  2052. settingValue.menu_item_parent = siblingControl.params.menu_item_id;
  2053. settingValue.position = 0;
  2054. _( control.getMenuControl().getMenuItemControls() ).each(function( otherControl ) {
  2055. if ( otherControl.setting().menu_item_parent === settingValue.menu_item_parent ) {
  2056. settingValue.position = Math.max( settingValue.position, otherControl.setting().position );
  2057. }
  2058. });
  2059. settingValue.position += 1;
  2060. control.setting.set( settingValue );
  2061. }
  2062. }
  2063. } );
  2064. /**
  2065. * wp.customize.Menus.MenuNameControl
  2066. *
  2067. * Customizer control for a nav menu's name.
  2068. *
  2069. * @class wp.customize.Menus.MenuNameControl
  2070. * @augments wp.customize.Control
  2071. */
  2072. api.Menus.MenuNameControl = api.Control.extend(/** @lends wp.customize.Menus.MenuNameControl.prototype */{
  2073. ready: function() {
  2074. var control = this;
  2075. if ( control.setting ) {
  2076. var settingValue = control.setting();
  2077. control.nameElement = new api.Element( control.container.find( '.menu-name-field' ) );
  2078. control.nameElement.bind(function( value ) {
  2079. var settingValue = control.setting();
  2080. if ( settingValue && settingValue.name !== value ) {
  2081. settingValue = _.clone( settingValue );
  2082. settingValue.name = value;
  2083. control.setting.set( settingValue );
  2084. }
  2085. });
  2086. if ( settingValue ) {
  2087. control.nameElement.set( settingValue.name );
  2088. }
  2089. control.setting.bind(function( object ) {
  2090. if ( object ) {
  2091. control.nameElement.set( object.name );
  2092. }
  2093. });
  2094. }
  2095. }
  2096. });
  2097. /**
  2098. * wp.customize.Menus.MenuLocationsControl
  2099. *
  2100. * Customizer control for a nav menu's locations.
  2101. *
  2102. * @since 4.9.0
  2103. * @class wp.customize.Menus.MenuLocationsControl
  2104. * @augments wp.customize.Control
  2105. */
  2106. api.Menus.MenuLocationsControl = api.Control.extend(/** @lends wp.customize.Menus.MenuLocationsControl.prototype */{
  2107. /**
  2108. * Set up the control.
  2109. *
  2110. * @since 4.9.0
  2111. */
  2112. ready: function () {
  2113. var control = this;
  2114. control.container.find( '.assigned-menu-location' ).each(function() {
  2115. var container = $( this ),
  2116. checkbox = container.find( 'input[type=checkbox]' ),
  2117. element = new api.Element( checkbox ),
  2118. navMenuLocationSetting = api( 'nav_menu_locations[' + checkbox.data( 'location-id' ) + ']' ),
  2119. isNewMenu = control.params.menu_id === '',
  2120. updateCheckbox = isNewMenu ? _.noop : function( checked ) {
  2121. element.set( checked );
  2122. },
  2123. updateSetting = isNewMenu ? _.noop : function( checked ) {
  2124. navMenuLocationSetting.set( checked ? control.params.menu_id : 0 );
  2125. },
  2126. updateSelectedMenuLabel = function( selectedMenuId ) {
  2127. var menuSetting = api( 'nav_menu[' + String( selectedMenuId ) + ']' );
  2128. if ( ! selectedMenuId || ! menuSetting || ! menuSetting() ) {
  2129. container.find( '.theme-location-set' ).hide();
  2130. } else {
  2131. container.find( '.theme-location-set' ).show().find( 'span' ).text( displayNavMenuName( menuSetting().name ) );
  2132. }
  2133. };
  2134. updateCheckbox( navMenuLocationSetting.get() === control.params.menu_id );
  2135. checkbox.on( 'change', function() {
  2136. // Note: We can't use element.bind( function( checked ){ ... } ) here because it will trigger a change as well.
  2137. updateSetting( this.checked );
  2138. } );
  2139. navMenuLocationSetting.bind( function( selectedMenuId ) {
  2140. updateCheckbox( selectedMenuId === control.params.menu_id );
  2141. updateSelectedMenuLabel( selectedMenuId );
  2142. } );
  2143. updateSelectedMenuLabel( navMenuLocationSetting.get() );
  2144. });
  2145. },
  2146. /**
  2147. * Set the selected locations.
  2148. *
  2149. * This method sets the selected locations and allows us to do things like
  2150. * set the default location for a new menu.
  2151. *
  2152. * @since 4.9.0
  2153. *
  2154. * @param {Object.<string,boolean>} selections - A map of location selections.
  2155. * @return {void}
  2156. */
  2157. setSelections: function( selections ) {
  2158. this.container.find( '.menu-location' ).each( function( i, checkboxNode ) {
  2159. var locationId = checkboxNode.dataset.locationId;
  2160. checkboxNode.checked = locationId in selections ? selections[ locationId ] : false;
  2161. } );
  2162. }
  2163. });
  2164. /**
  2165. * wp.customize.Menus.MenuAutoAddControl
  2166. *
  2167. * Customizer control for a nav menu's auto add.
  2168. *
  2169. * @class wp.customize.Menus.MenuAutoAddControl
  2170. * @augments wp.customize.Control
  2171. */
  2172. api.Menus.MenuAutoAddControl = api.Control.extend(/** @lends wp.customize.Menus.MenuAutoAddControl.prototype */{
  2173. ready: function() {
  2174. var control = this,
  2175. settingValue = control.setting();
  2176. /*
  2177. * Since the control is not registered in PHP, we need to prevent the
  2178. * preview's sending of the activeControls to result in this control
  2179. * being deactivated.
  2180. */
  2181. control.active.validate = function() {
  2182. var value, section = api.section( control.section() );
  2183. if ( section ) {
  2184. value = section.active();
  2185. } else {
  2186. value = false;
  2187. }
  2188. return value;
  2189. };
  2190. control.autoAddElement = new api.Element( control.container.find( 'input[type=checkbox].auto_add' ) );
  2191. control.autoAddElement.bind(function( value ) {
  2192. var settingValue = control.setting();
  2193. if ( settingValue && settingValue.name !== value ) {
  2194. settingValue = _.clone( settingValue );
  2195. settingValue.auto_add = value;
  2196. control.setting.set( settingValue );
  2197. }
  2198. });
  2199. if ( settingValue ) {
  2200. control.autoAddElement.set( settingValue.auto_add );
  2201. }
  2202. control.setting.bind(function( object ) {
  2203. if ( object ) {
  2204. control.autoAddElement.set( object.auto_add );
  2205. }
  2206. });
  2207. }
  2208. });
  2209. /**
  2210. * wp.customize.Menus.MenuControl
  2211. *
  2212. * Customizer control for menus.
  2213. * Note that 'nav_menu' must match the WP_Menu_Customize_Control::$type
  2214. *
  2215. * @class wp.customize.Menus.MenuControl
  2216. * @augments wp.customize.Control
  2217. */
  2218. api.Menus.MenuControl = api.Control.extend(/** @lends wp.customize.Menus.MenuControl.prototype */{
  2219. /**
  2220. * Set up the control.
  2221. */
  2222. ready: function() {
  2223. var control = this,
  2224. section = api.section( control.section() ),
  2225. menuId = control.params.menu_id,
  2226. menu = control.setting(),
  2227. name,
  2228. widgetTemplate,
  2229. select;
  2230. if ( 'undefined' === typeof this.params.menu_id ) {
  2231. throw new Error( 'params.menu_id was not defined' );
  2232. }
  2233. /*
  2234. * Since the control is not registered in PHP, we need to prevent the
  2235. * preview's sending of the activeControls to result in this control
  2236. * being deactivated.
  2237. */
  2238. control.active.validate = function() {
  2239. var value;
  2240. if ( section ) {
  2241. value = section.active();
  2242. } else {
  2243. value = false;
  2244. }
  2245. return value;
  2246. };
  2247. control.$controlSection = section.headContainer;
  2248. control.$sectionContent = control.container.closest( '.accordion-section-content' );
  2249. this._setupModel();
  2250. api.section( control.section(), function( section ) {
  2251. section.deferred.initSortables.done(function( menuList ) {
  2252. control._setupSortable( menuList );
  2253. });
  2254. } );
  2255. this._setupAddition();
  2256. this._setupTitle();
  2257. // Add menu to Navigation Menu widgets.
  2258. if ( menu ) {
  2259. name = displayNavMenuName( menu.name );
  2260. // Add the menu to the existing controls.
  2261. api.control.each( function( widgetControl ) {
  2262. if ( ! widgetControl.extended( api.controlConstructor.widget_form ) || 'nav_menu' !== widgetControl.params.widget_id_base ) {
  2263. return;
  2264. }
  2265. widgetControl.container.find( '.nav-menu-widget-form-controls:first' ).show();
  2266. widgetControl.container.find( '.nav-menu-widget-no-menus-message:first' ).hide();
  2267. select = widgetControl.container.find( 'select' );
  2268. if ( 0 === select.find( 'option[value=' + String( menuId ) + ']' ).length ) {
  2269. select.append( new Option( name, menuId ) );
  2270. }
  2271. } );
  2272. // Add the menu to the widget template.
  2273. widgetTemplate = $( '#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )' );
  2274. widgetTemplate.find( '.nav-menu-widget-form-controls:first' ).show();
  2275. widgetTemplate.find( '.nav-menu-widget-no-menus-message:first' ).hide();
  2276. select = widgetTemplate.find( '.widget-inside select:first' );
  2277. if ( 0 === select.find( 'option[value=' + String( menuId ) + ']' ).length ) {
  2278. select.append( new Option( name, menuId ) );
  2279. }
  2280. }
  2281. /*
  2282. * Wait for menu items to be added.
  2283. * Ideally, we'd bind to an event indicating construction is complete,
  2284. * but deferring appears to be the best option today.
  2285. */
  2286. _.defer( function () {
  2287. control.updateInvitationVisibility();
  2288. } );
  2289. },
  2290. /**
  2291. * Update ordering of menu item controls when the setting is updated.
  2292. */
  2293. _setupModel: function() {
  2294. var control = this,
  2295. menuId = control.params.menu_id;
  2296. control.setting.bind( function( to ) {
  2297. var name;
  2298. if ( false === to ) {
  2299. control._handleDeletion();
  2300. } else {
  2301. // Update names in the Navigation Menu widgets.
  2302. name = displayNavMenuName( to.name );
  2303. api.control.each( function( widgetControl ) {
  2304. if ( ! widgetControl.extended( api.controlConstructor.widget_form ) || 'nav_menu' !== widgetControl.params.widget_id_base ) {
  2305. return;
  2306. }
  2307. var select = widgetControl.container.find( 'select' );
  2308. select.find( 'option[value=' + String( menuId ) + ']' ).text( name );
  2309. });
  2310. }
  2311. } );
  2312. },
  2313. /**
  2314. * Allow items in each menu to be re-ordered, and for the order to be previewed.
  2315. *
  2316. * Notice that the UI aspects here are handled by wpNavMenu.initSortables()
  2317. * which is called in MenuSection.onChangeExpanded()
  2318. *
  2319. * @param {object} menuList - The element that has sortable().
  2320. */
  2321. _setupSortable: function( menuList ) {
  2322. var control = this;
  2323. if ( ! menuList.is( control.$sectionContent ) ) {
  2324. throw new Error( 'Unexpected menuList.' );
  2325. }
  2326. menuList.on( 'sortstart', function() {
  2327. control.isSorting = true;
  2328. });
  2329. menuList.on( 'sortstop', function() {
  2330. setTimeout( function() { // Next tick.
  2331. var menuItemContainerIds = control.$sectionContent.sortable( 'toArray' ),
  2332. menuItemControls = [],
  2333. position = 0,
  2334. priority = 10;
  2335. control.isSorting = false;
  2336. // Reset horizontal scroll position when done dragging.
  2337. control.$sectionContent.scrollLeft( 0 );
  2338. _.each( menuItemContainerIds, function( menuItemContainerId ) {
  2339. var menuItemId, menuItemControl, matches;
  2340. matches = menuItemContainerId.match( /^customize-control-nav_menu_item-(-?\d+)$/, '' );
  2341. if ( ! matches ) {
  2342. return;
  2343. }
  2344. menuItemId = parseInt( matches[1], 10 );
  2345. menuItemControl = api.control( 'nav_menu_item[' + String( menuItemId ) + ']' );
  2346. if ( menuItemControl ) {
  2347. menuItemControls.push( menuItemControl );
  2348. }
  2349. } );
  2350. _.each( menuItemControls, function( menuItemControl ) {
  2351. if ( false === menuItemControl.setting() ) {
  2352. // Skip deleted items.
  2353. return;
  2354. }
  2355. var setting = _.clone( menuItemControl.setting() );
  2356. position += 1;
  2357. priority += 1;
  2358. setting.position = position;
  2359. menuItemControl.priority( priority );
  2360. // Note that wpNavMenu will be setting this .menu-item-data-parent-id input's value.
  2361. setting.menu_item_parent = parseInt( menuItemControl.container.find( '.menu-item-data-parent-id' ).val(), 10 );
  2362. if ( ! setting.menu_item_parent ) {
  2363. setting.menu_item_parent = 0;
  2364. }
  2365. menuItemControl.setting.set( setting );
  2366. });
  2367. });
  2368. });
  2369. control.isReordering = false;
  2370. /**
  2371. * Keyboard-accessible reordering.
  2372. */
  2373. this.container.find( '.reorder-toggle' ).on( 'click', function() {
  2374. control.toggleReordering( ! control.isReordering );
  2375. } );
  2376. },
  2377. /**
  2378. * Set up UI for adding a new menu item.
  2379. */
  2380. _setupAddition: function() {
  2381. var self = this;
  2382. this.container.find( '.add-new-menu-item' ).on( 'click', function( event ) {
  2383. if ( self.$sectionContent.hasClass( 'reordering' ) ) {
  2384. return;
  2385. }
  2386. if ( ! $( 'body' ).hasClass( 'adding-menu-items' ) ) {
  2387. $( this ).attr( 'aria-expanded', 'true' );
  2388. api.Menus.availableMenuItemsPanel.open( self );
  2389. } else {
  2390. $( this ).attr( 'aria-expanded', 'false' );
  2391. api.Menus.availableMenuItemsPanel.close();
  2392. event.stopPropagation();
  2393. }
  2394. } );
  2395. },
  2396. _handleDeletion: function() {
  2397. var control = this,
  2398. section,
  2399. menuId = control.params.menu_id,
  2400. removeSection,
  2401. widgetTemplate,
  2402. navMenuCount = 0;
  2403. section = api.section( control.section() );
  2404. removeSection = function() {
  2405. section.container.remove();
  2406. api.section.remove( section.id );
  2407. };
  2408. if ( section && section.expanded() ) {
  2409. section.collapse({
  2410. completeCallback: function() {
  2411. removeSection();
  2412. wp.a11y.speak( api.Menus.data.l10n.menuDeleted );
  2413. api.panel( 'nav_menus' ).focus();
  2414. }
  2415. });
  2416. } else {
  2417. removeSection();
  2418. }
  2419. api.each(function( setting ) {
  2420. if ( /^nav_menu\[/.test( setting.id ) && false !== setting() ) {
  2421. navMenuCount += 1;
  2422. }
  2423. });
  2424. // Remove the menu from any Navigation Menu widgets.
  2425. api.control.each(function( widgetControl ) {
  2426. if ( ! widgetControl.extended( api.controlConstructor.widget_form ) || 'nav_menu' !== widgetControl.params.widget_id_base ) {
  2427. return;
  2428. }
  2429. var select = widgetControl.container.find( 'select' );
  2430. if ( select.val() === String( menuId ) ) {
  2431. select.prop( 'selectedIndex', 0 ).trigger( 'change' );
  2432. }
  2433. widgetControl.container.find( '.nav-menu-widget-form-controls:first' ).toggle( 0 !== navMenuCount );
  2434. widgetControl.container.find( '.nav-menu-widget-no-menus-message:first' ).toggle( 0 === navMenuCount );
  2435. widgetControl.container.find( 'option[value=' + String( menuId ) + ']' ).remove();
  2436. });
  2437. // Remove the menu to the nav menu widget template.
  2438. widgetTemplate = $( '#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )' );
  2439. widgetTemplate.find( '.nav-menu-widget-form-controls:first' ).toggle( 0 !== navMenuCount );
  2440. widgetTemplate.find( '.nav-menu-widget-no-menus-message:first' ).toggle( 0 === navMenuCount );
  2441. widgetTemplate.find( 'option[value=' + String( menuId ) + ']' ).remove();
  2442. },
  2443. /**
  2444. * Update Section Title as menu name is changed.
  2445. */
  2446. _setupTitle: function() {
  2447. var control = this;
  2448. control.setting.bind( function( menu ) {
  2449. if ( ! menu ) {
  2450. return;
  2451. }
  2452. var section = api.section( control.section() ),
  2453. menuId = control.params.menu_id,
  2454. controlTitle = section.headContainer.find( '.accordion-section-title' ),
  2455. sectionTitle = section.contentContainer.find( '.customize-section-title h3' ),
  2456. location = section.headContainer.find( '.menu-in-location' ),
  2457. action = sectionTitle.find( '.customize-action' ),
  2458. name = displayNavMenuName( menu.name );
  2459. // Update the control title.
  2460. controlTitle.text( name );
  2461. if ( location.length ) {
  2462. location.appendTo( controlTitle );
  2463. }
  2464. // Update the section title.
  2465. sectionTitle.text( name );
  2466. if ( action.length ) {
  2467. action.prependTo( sectionTitle );
  2468. }
  2469. // Update the nav menu name in location selects.
  2470. api.control.each( function( control ) {
  2471. if ( /^nav_menu_locations\[/.test( control.id ) ) {
  2472. control.container.find( 'option[value=' + menuId + ']' ).text( name );
  2473. }
  2474. } );
  2475. // Update the nav menu name in all location checkboxes.
  2476. section.contentContainer.find( '.customize-control-checkbox input' ).each( function() {
  2477. if ( $( this ).prop( 'checked' ) ) {
  2478. $( '.current-menu-location-name-' + $( this ).data( 'location-id' ) ).text( name );
  2479. }
  2480. } );
  2481. } );
  2482. },
  2483. /***********************************************************************
  2484. * Begin public API methods
  2485. **********************************************************************/
  2486. /**
  2487. * Enable/disable the reordering UI
  2488. *
  2489. * @param {Boolean} showOrHide to enable/disable reordering
  2490. */
  2491. toggleReordering: function( showOrHide ) {
  2492. var addNewItemBtn = this.container.find( '.add-new-menu-item' ),
  2493. reorderBtn = this.container.find( '.reorder-toggle' ),
  2494. itemsTitle = this.$sectionContent.find( '.item-title' );
  2495. showOrHide = Boolean( showOrHide );
  2496. if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
  2497. return;
  2498. }
  2499. this.isReordering = showOrHide;
  2500. this.$sectionContent.toggleClass( 'reordering', showOrHide );
  2501. this.$sectionContent.sortable( this.isReordering ? 'disable' : 'enable' );
  2502. if ( this.isReordering ) {
  2503. addNewItemBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
  2504. reorderBtn.attr( 'aria-label', api.Menus.data.l10n.reorderLabelOff );
  2505. wp.a11y.speak( api.Menus.data.l10n.reorderModeOn );
  2506. itemsTitle.attr( 'aria-hidden', 'false' );
  2507. } else {
  2508. addNewItemBtn.removeAttr( 'tabindex aria-hidden' );
  2509. reorderBtn.attr( 'aria-label', api.Menus.data.l10n.reorderLabelOn );
  2510. wp.a11y.speak( api.Menus.data.l10n.reorderModeOff );
  2511. itemsTitle.attr( 'aria-hidden', 'true' );
  2512. }
  2513. if ( showOrHide ) {
  2514. _( this.getMenuItemControls() ).each( function( formControl ) {
  2515. formControl.collapseForm();
  2516. } );
  2517. }
  2518. },
  2519. /**
  2520. * @return {wp.customize.controlConstructor.nav_menu_item[]}
  2521. */
  2522. getMenuItemControls: function() {
  2523. var menuControl = this,
  2524. menuItemControls = [],
  2525. menuTermId = menuControl.params.menu_id;
  2526. api.control.each(function( control ) {
  2527. if ( 'nav_menu_item' === control.params.type && control.setting() && menuTermId === control.setting().nav_menu_term_id ) {
  2528. menuItemControls.push( control );
  2529. }
  2530. });
  2531. return menuItemControls;
  2532. },
  2533. /**
  2534. * Make sure that each menu item control has the proper depth.
  2535. */
  2536. reflowMenuItems: function() {
  2537. var menuControl = this,
  2538. menuItemControls = menuControl.getMenuItemControls(),
  2539. reflowRecursively;
  2540. reflowRecursively = function( context ) {
  2541. var currentMenuItemControls = [],
  2542. thisParent = context.currentParent;
  2543. _.each( context.menuItemControls, function( menuItemControl ) {
  2544. if ( thisParent === menuItemControl.setting().menu_item_parent ) {
  2545. currentMenuItemControls.push( menuItemControl );
  2546. // @todo We could remove this item from menuItemControls now, for efficiency.
  2547. }
  2548. });
  2549. currentMenuItemControls.sort( function( a, b ) {
  2550. return a.setting().position - b.setting().position;
  2551. });
  2552. _.each( currentMenuItemControls, function( menuItemControl ) {
  2553. // Update position.
  2554. context.currentAbsolutePosition += 1;
  2555. menuItemControl.priority.set( context.currentAbsolutePosition ); // This will change the sort order.
  2556. // Update depth.
  2557. if ( ! menuItemControl.container.hasClass( 'menu-item-depth-' + String( context.currentDepth ) ) ) {
  2558. _.each( menuItemControl.container.prop( 'className' ).match( /menu-item-depth-\d+/g ), function( className ) {
  2559. menuItemControl.container.removeClass( className );
  2560. });
  2561. menuItemControl.container.addClass( 'menu-item-depth-' + String( context.currentDepth ) );
  2562. }
  2563. menuItemControl.container.data( 'item-depth', context.currentDepth );
  2564. // Process any children items.
  2565. context.currentDepth += 1;
  2566. context.currentParent = menuItemControl.params.menu_item_id;
  2567. reflowRecursively( context );
  2568. context.currentDepth -= 1;
  2569. context.currentParent = thisParent;
  2570. });
  2571. // Update class names for reordering controls.
  2572. if ( currentMenuItemControls.length ) {
  2573. _( currentMenuItemControls ).each(function( menuItemControl ) {
  2574. menuItemControl.container.removeClass( 'move-up-disabled move-down-disabled move-left-disabled move-right-disabled' );
  2575. if ( 0 === context.currentDepth ) {
  2576. menuItemControl.container.addClass( 'move-left-disabled' );
  2577. } else if ( 10 === context.currentDepth ) {
  2578. menuItemControl.container.addClass( 'move-right-disabled' );
  2579. }
  2580. });
  2581. currentMenuItemControls[0].container
  2582. .addClass( 'move-up-disabled' )
  2583. .addClass( 'move-right-disabled' )
  2584. .toggleClass( 'move-down-disabled', 1 === currentMenuItemControls.length );
  2585. currentMenuItemControls[ currentMenuItemControls.length - 1 ].container
  2586. .addClass( 'move-down-disabled' )
  2587. .toggleClass( 'move-up-disabled', 1 === currentMenuItemControls.length );
  2588. }
  2589. };
  2590. reflowRecursively( {
  2591. menuItemControls: menuItemControls,
  2592. currentParent: 0,
  2593. currentDepth: 0,
  2594. currentAbsolutePosition: 0
  2595. } );
  2596. menuControl.updateInvitationVisibility( menuItemControls );
  2597. menuControl.container.find( '.reorder-toggle' ).toggle( menuItemControls.length > 1 );
  2598. },
  2599. /**
  2600. * Note that this function gets debounced so that when a lot of setting
  2601. * changes are made at once, for instance when moving a menu item that
  2602. * has child items, this function will only be called once all of the
  2603. * settings have been updated.
  2604. */
  2605. debouncedReflowMenuItems: _.debounce( function() {
  2606. this.reflowMenuItems.apply( this, arguments );
  2607. }, 0 ),
  2608. /**
  2609. * Add a new item to this menu.
  2610. *
  2611. * @param {object} item - Value for the nav_menu_item setting to be created.
  2612. * @return {wp.customize.Menus.controlConstructor.nav_menu_item} The newly-created nav_menu_item control instance.
  2613. */
  2614. addItemToMenu: function( item ) {
  2615. var menuControl = this, customizeId, settingArgs, setting, menuItemControl, placeholderId, position = 0, priority = 10,
  2616. originalItemId = item.id || '';
  2617. _.each( menuControl.getMenuItemControls(), function( control ) {
  2618. if ( false === control.setting() ) {
  2619. return;
  2620. }
  2621. priority = Math.max( priority, control.priority() );
  2622. if ( 0 === control.setting().menu_item_parent ) {
  2623. position = Math.max( position, control.setting().position );
  2624. }
  2625. });
  2626. position += 1;
  2627. priority += 1;
  2628. item = $.extend(
  2629. {},
  2630. api.Menus.data.defaultSettingValues.nav_menu_item,
  2631. item,
  2632. {
  2633. nav_menu_term_id: menuControl.params.menu_id,
  2634. original_title: item.title,
  2635. position: position
  2636. }
  2637. );
  2638. delete item.id; // Only used by Backbone.
  2639. placeholderId = api.Menus.generatePlaceholderAutoIncrementId();
  2640. customizeId = 'nav_menu_item[' + String( placeholderId ) + ']';
  2641. settingArgs = {
  2642. type: 'nav_menu_item',
  2643. transport: api.Menus.data.settingTransport,
  2644. previewer: api.previewer
  2645. };
  2646. setting = api.create( customizeId, customizeId, {}, settingArgs );
  2647. setting.set( item ); // Change from initial empty object to actual item to mark as dirty.
  2648. // Add the menu item control.
  2649. menuItemControl = new api.controlConstructor.nav_menu_item( customizeId, {
  2650. type: 'nav_menu_item',
  2651. section: menuControl.id,
  2652. priority: priority,
  2653. settings: {
  2654. 'default': customizeId
  2655. },
  2656. menu_item_id: placeholderId,
  2657. original_item_id: originalItemId
  2658. } );
  2659. api.control.add( menuItemControl );
  2660. setting.preview();
  2661. menuControl.debouncedReflowMenuItems();
  2662. wp.a11y.speak( api.Menus.data.l10n.itemAdded );
  2663. return menuItemControl;
  2664. },
  2665. /**
  2666. * Show an invitation to add new menu items when there are no menu items.
  2667. *
  2668. * @since 4.9.0
  2669. *
  2670. * @param {wp.customize.controlConstructor.nav_menu_item[]} optionalMenuItemControls
  2671. */
  2672. updateInvitationVisibility: function ( optionalMenuItemControls ) {
  2673. var menuItemControls = optionalMenuItemControls || this.getMenuItemControls();
  2674. this.container.find( '.new-menu-item-invitation' ).toggle( menuItemControls.length === 0 );
  2675. }
  2676. } );
  2677. /**
  2678. * Extends wp.customize.controlConstructor with control constructor for
  2679. * menu_location, menu_item, nav_menu, and new_menu.
  2680. */
  2681. $.extend( api.controlConstructor, {
  2682. nav_menu_location: api.Menus.MenuLocationControl,
  2683. nav_menu_item: api.Menus.MenuItemControl,
  2684. nav_menu: api.Menus.MenuControl,
  2685. nav_menu_name: api.Menus.MenuNameControl,
  2686. nav_menu_locations: api.Menus.MenuLocationsControl,
  2687. nav_menu_auto_add: api.Menus.MenuAutoAddControl
  2688. });
  2689. /**
  2690. * Extends wp.customize.panelConstructor with section constructor for menus.
  2691. */
  2692. $.extend( api.panelConstructor, {
  2693. nav_menus: api.Menus.MenusPanel
  2694. });
  2695. /**
  2696. * Extends wp.customize.sectionConstructor with section constructor for menu.
  2697. */
  2698. $.extend( api.sectionConstructor, {
  2699. nav_menu: api.Menus.MenuSection,
  2700. new_menu: api.Menus.NewMenuSection
  2701. });
  2702. /**
  2703. * Init Customizer for menus.
  2704. */
  2705. api.bind( 'ready', function() {
  2706. // Set up the menu items panel.
  2707. api.Menus.availableMenuItemsPanel = new api.Menus.AvailableMenuItemsPanelView({
  2708. collection: api.Menus.availableMenuItems
  2709. });
  2710. api.bind( 'saved', function( data ) {
  2711. if ( data.nav_menu_updates || data.nav_menu_item_updates ) {
  2712. api.Menus.applySavedData( data );
  2713. }
  2714. } );
  2715. /*
  2716. * Reset the list of posts created in the customizer once published.
  2717. * The setting is updated quietly (bypassing events being triggered)
  2718. * so that the customized state doesn't become immediately dirty.
  2719. */
  2720. api.state( 'changesetStatus' ).bind( function( status ) {
  2721. if ( 'publish' === status ) {
  2722. api( 'nav_menus_created_posts' )._value = [];
  2723. }
  2724. } );
  2725. // Open and focus menu control.
  2726. api.previewer.bind( 'focus-nav-menu-item-control', api.Menus.focusMenuItemControl );
  2727. } );
  2728. /**
  2729. * When customize_save comes back with a success, make sure any inserted
  2730. * nav menus and items are properly re-added with their newly-assigned IDs.
  2731. *
  2732. * @alias wp.customize.Menus.applySavedData
  2733. *
  2734. * @param {object} data
  2735. * @param {array} data.nav_menu_updates
  2736. * @param {array} data.nav_menu_item_updates
  2737. */
  2738. api.Menus.applySavedData = function( data ) {
  2739. var insertedMenuIdMapping = {}, insertedMenuItemIdMapping = {};
  2740. _( data.nav_menu_updates ).each(function( update ) {
  2741. var oldCustomizeId, newCustomizeId, customizeId, oldSetting, newSetting, setting, settingValue, oldSection, newSection, wasSaved, widgetTemplate, navMenuCount, shouldExpandNewSection;
  2742. if ( 'inserted' === update.status ) {
  2743. if ( ! update.previous_term_id ) {
  2744. throw new Error( 'Expected previous_term_id' );
  2745. }
  2746. if ( ! update.term_id ) {
  2747. throw new Error( 'Expected term_id' );
  2748. }
  2749. oldCustomizeId = 'nav_menu[' + String( update.previous_term_id ) + ']';
  2750. if ( ! api.has( oldCustomizeId ) ) {
  2751. throw new Error( 'Expected setting to exist: ' + oldCustomizeId );
  2752. }
  2753. oldSetting = api( oldCustomizeId );
  2754. if ( ! api.section.has( oldCustomizeId ) ) {
  2755. throw new Error( 'Expected control to exist: ' + oldCustomizeId );
  2756. }
  2757. oldSection = api.section( oldCustomizeId );
  2758. settingValue = oldSetting.get();
  2759. if ( ! settingValue ) {
  2760. throw new Error( 'Did not expect setting to be empty (deleted).' );
  2761. }
  2762. settingValue = $.extend( _.clone( settingValue ), update.saved_value );
  2763. insertedMenuIdMapping[ update.previous_term_id ] = update.term_id;
  2764. newCustomizeId = 'nav_menu[' + String( update.term_id ) + ']';
  2765. newSetting = api.create( newCustomizeId, newCustomizeId, settingValue, {
  2766. type: 'nav_menu',
  2767. transport: api.Menus.data.settingTransport,
  2768. previewer: api.previewer
  2769. } );
  2770. shouldExpandNewSection = oldSection.expanded();
  2771. if ( shouldExpandNewSection ) {
  2772. oldSection.collapse();
  2773. }
  2774. // Add the menu section.
  2775. newSection = new api.Menus.MenuSection( newCustomizeId, {
  2776. panel: 'nav_menus',
  2777. title: settingValue.name,
  2778. customizeAction: api.Menus.data.l10n.customizingMenus,
  2779. type: 'nav_menu',
  2780. priority: oldSection.priority.get(),
  2781. menu_id: update.term_id
  2782. } );
  2783. // Add new control for the new menu.
  2784. api.section.add( newSection );
  2785. // Update the values for nav menus in Navigation Menu controls.
  2786. api.control.each( function( setting ) {
  2787. if ( ! setting.extended( api.controlConstructor.widget_form ) || 'nav_menu' !== setting.params.widget_id_base ) {
  2788. return;
  2789. }
  2790. var select, oldMenuOption, newMenuOption;
  2791. select = setting.container.find( 'select' );
  2792. oldMenuOption = select.find( 'option[value=' + String( update.previous_term_id ) + ']' );
  2793. newMenuOption = select.find( 'option[value=' + String( update.term_id ) + ']' );
  2794. newMenuOption.prop( 'selected', oldMenuOption.prop( 'selected' ) );
  2795. oldMenuOption.remove();
  2796. } );
  2797. // Delete the old placeholder nav_menu.
  2798. oldSetting.callbacks.disable(); // Prevent setting triggering Customizer dirty state when set.
  2799. oldSetting.set( false );
  2800. oldSetting.preview();
  2801. newSetting.preview();
  2802. oldSetting._dirty = false;
  2803. // Remove nav_menu section.
  2804. oldSection.container.remove();
  2805. api.section.remove( oldCustomizeId );
  2806. // Update the nav_menu widget to reflect removed placeholder menu.
  2807. navMenuCount = 0;
  2808. api.each(function( setting ) {
  2809. if ( /^nav_menu\[/.test( setting.id ) && false !== setting() ) {
  2810. navMenuCount += 1;
  2811. }
  2812. });
  2813. widgetTemplate = $( '#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )' );
  2814. widgetTemplate.find( '.nav-menu-widget-form-controls:first' ).toggle( 0 !== navMenuCount );
  2815. widgetTemplate.find( '.nav-menu-widget-no-menus-message:first' ).toggle( 0 === navMenuCount );
  2816. widgetTemplate.find( 'option[value=' + String( update.previous_term_id ) + ']' ).remove();
  2817. // Update the nav_menu_locations[...] controls to remove the placeholder menus from the dropdown options.
  2818. wp.customize.control.each(function( control ){
  2819. if ( /^nav_menu_locations\[/.test( control.id ) ) {
  2820. control.container.find( 'option[value=' + String( update.previous_term_id ) + ']' ).remove();
  2821. }
  2822. });
  2823. // Update nav_menu_locations to reference the new ID.
  2824. api.each( function( setting ) {
  2825. var wasSaved = api.state( 'saved' ).get();
  2826. if ( /^nav_menu_locations\[/.test( setting.id ) && setting.get() === update.previous_term_id ) {
  2827. setting.set( update.term_id );
  2828. setting._dirty = false; // Not dirty because this is has also just been done on server in WP_Customize_Nav_Menu_Setting::update().
  2829. api.state( 'saved' ).set( wasSaved );
  2830. setting.preview();
  2831. }
  2832. } );
  2833. if ( shouldExpandNewSection ) {
  2834. newSection.expand();
  2835. }
  2836. } else if ( 'updated' === update.status ) {
  2837. customizeId = 'nav_menu[' + String( update.term_id ) + ']';
  2838. if ( ! api.has( customizeId ) ) {
  2839. throw new Error( 'Expected setting to exist: ' + customizeId );
  2840. }
  2841. // Make sure the setting gets updated with its sanitized server value (specifically the conflict-resolved name).
  2842. setting = api( customizeId );
  2843. if ( ! _.isEqual( update.saved_value, setting.get() ) ) {
  2844. wasSaved = api.state( 'saved' ).get();
  2845. setting.set( update.saved_value );
  2846. setting._dirty = false;
  2847. api.state( 'saved' ).set( wasSaved );
  2848. }
  2849. }
  2850. } );
  2851. // Build up mapping of nav_menu_item placeholder IDs to inserted IDs.
  2852. _( data.nav_menu_item_updates ).each(function( update ) {
  2853. if ( update.previous_post_id ) {
  2854. insertedMenuItemIdMapping[ update.previous_post_id ] = update.post_id;
  2855. }
  2856. });
  2857. _( data.nav_menu_item_updates ).each(function( update ) {
  2858. var oldCustomizeId, newCustomizeId, oldSetting, newSetting, settingValue, oldControl, newControl;
  2859. if ( 'inserted' === update.status ) {
  2860. if ( ! update.previous_post_id ) {
  2861. throw new Error( 'Expected previous_post_id' );
  2862. }
  2863. if ( ! update.post_id ) {
  2864. throw new Error( 'Expected post_id' );
  2865. }
  2866. oldCustomizeId = 'nav_menu_item[' + String( update.previous_post_id ) + ']';
  2867. if ( ! api.has( oldCustomizeId ) ) {
  2868. throw new Error( 'Expected setting to exist: ' + oldCustomizeId );
  2869. }
  2870. oldSetting = api( oldCustomizeId );
  2871. if ( ! api.control.has( oldCustomizeId ) ) {
  2872. throw new Error( 'Expected control to exist: ' + oldCustomizeId );
  2873. }
  2874. oldControl = api.control( oldCustomizeId );
  2875. settingValue = oldSetting.get();
  2876. if ( ! settingValue ) {
  2877. throw new Error( 'Did not expect setting to be empty (deleted).' );
  2878. }
  2879. settingValue = _.clone( settingValue );
  2880. // If the parent menu item was also inserted, update the menu_item_parent to the new ID.
  2881. if ( settingValue.menu_item_parent < 0 ) {
  2882. if ( ! insertedMenuItemIdMapping[ settingValue.menu_item_parent ] ) {
  2883. throw new Error( 'inserted ID for menu_item_parent not available' );
  2884. }
  2885. settingValue.menu_item_parent = insertedMenuItemIdMapping[ settingValue.menu_item_parent ];
  2886. }
  2887. // If the menu was also inserted, then make sure it uses the new menu ID for nav_menu_term_id.
  2888. if ( insertedMenuIdMapping[ settingValue.nav_menu_term_id ] ) {
  2889. settingValue.nav_menu_term_id = insertedMenuIdMapping[ settingValue.nav_menu_term_id ];
  2890. }
  2891. newCustomizeId = 'nav_menu_item[' + String( update.post_id ) + ']';
  2892. newSetting = api.create( newCustomizeId, newCustomizeId, settingValue, {
  2893. type: 'nav_menu_item',
  2894. transport: api.Menus.data.settingTransport,
  2895. previewer: api.previewer
  2896. } );
  2897. // Add the menu control.
  2898. newControl = new api.controlConstructor.nav_menu_item( newCustomizeId, {
  2899. type: 'nav_menu_item',
  2900. menu_id: update.post_id,
  2901. section: 'nav_menu[' + String( settingValue.nav_menu_term_id ) + ']',
  2902. priority: oldControl.priority.get(),
  2903. settings: {
  2904. 'default': newCustomizeId
  2905. },
  2906. menu_item_id: update.post_id
  2907. } );
  2908. // Remove old control.
  2909. oldControl.container.remove();
  2910. api.control.remove( oldCustomizeId );
  2911. // Add new control to take its place.
  2912. api.control.add( newControl );
  2913. // Delete the placeholder and preview the new setting.
  2914. oldSetting.callbacks.disable(); // Prevent setting triggering Customizer dirty state when set.
  2915. oldSetting.set( false );
  2916. oldSetting.preview();
  2917. newSetting.preview();
  2918. oldSetting._dirty = false;
  2919. newControl.container.toggleClass( 'menu-item-edit-inactive', oldControl.container.hasClass( 'menu-item-edit-inactive' ) );
  2920. }
  2921. });
  2922. /*
  2923. * Update the settings for any nav_menu widgets that had selected a placeholder ID.
  2924. */
  2925. _.each( data.widget_nav_menu_updates, function( widgetSettingValue, widgetSettingId ) {
  2926. var setting = api( widgetSettingId );
  2927. if ( setting ) {
  2928. setting._value = widgetSettingValue;
  2929. setting.preview(); // Send to the preview now so that menu refresh will use the inserted menu.
  2930. }
  2931. });
  2932. };
  2933. /**
  2934. * Focus a menu item control.
  2935. *
  2936. * @alias wp.customize.Menus.focusMenuItemControl
  2937. *
  2938. * @param {string} menuItemId
  2939. */
  2940. api.Menus.focusMenuItemControl = function( menuItemId ) {
  2941. var control = api.Menus.getMenuItemControl( menuItemId );
  2942. if ( control ) {
  2943. control.focus();
  2944. }
  2945. };
  2946. /**
  2947. * Get the control for a given menu.
  2948. *
  2949. * @alias wp.customize.Menus.getMenuControl
  2950. *
  2951. * @param menuId
  2952. * @return {wp.customize.controlConstructor.menus[]}
  2953. */
  2954. api.Menus.getMenuControl = function( menuId ) {
  2955. return api.control( 'nav_menu[' + menuId + ']' );
  2956. };
  2957. /**
  2958. * Given a menu item ID, get the control associated with it.
  2959. *
  2960. * @alias wp.customize.Menus.getMenuItemControl
  2961. *
  2962. * @param {string} menuItemId
  2963. * @return {object|null}
  2964. */
  2965. api.Menus.getMenuItemControl = function( menuItemId ) {
  2966. return api.control( menuItemIdToSettingId( menuItemId ) );
  2967. };
  2968. /**
  2969. * @alias wp.customize.Menus~menuItemIdToSettingId
  2970. *
  2971. * @param {String} menuItemId
  2972. */
  2973. function menuItemIdToSettingId( menuItemId ) {
  2974. return 'nav_menu_item[' + menuItemId + ']';
  2975. }
  2976. /**
  2977. * Apply sanitize_text_field()-like logic to the supplied name, returning a
  2978. * "unnammed" fallback string if the name is then empty.
  2979. *
  2980. * @alias wp.customize.Menus~displayNavMenuName
  2981. *
  2982. * @param {string} name
  2983. * @return {string}
  2984. */
  2985. function displayNavMenuName( name ) {
  2986. name = name || '';
  2987. name = wp.sanitize.stripTagsAndEncodeText( name ); // Remove any potential tags from name.
  2988. name = $.trim( name );
  2989. return name || api.Menus.data.l10n.unnamed;
  2990. }
  2991. })( wp.customize, wp, jQuery );