customize-preview-nav-menus.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /**
  2. * @output wp-includes/js/customize-preview-nav-menus.js
  3. */
  4. /* global _wpCustomizePreviewNavMenusExports */
  5. /** @namespace wp.customize.navMenusPreview */
  6. wp.customize.navMenusPreview = wp.customize.MenusCustomizerPreview = ( function( $, _, wp, api ) {
  7. 'use strict';
  8. var self = {
  9. data: {
  10. navMenuInstanceArgs: {}
  11. }
  12. };
  13. if ( 'undefined' !== typeof _wpCustomizePreviewNavMenusExports ) {
  14. _.extend( self.data, _wpCustomizePreviewNavMenusExports );
  15. }
  16. /**
  17. * Initialize nav menus preview.
  18. */
  19. self.init = function() {
  20. var self = this, synced = false;
  21. /*
  22. * Keep track of whether we synced to determine whether or not bindSettingListener
  23. * should also initially fire the listener. This initial firing needs to wait until
  24. * after all of the settings have been synced from the pane in order to prevent
  25. * an infinite selective fallback-refresh. Note that this sync handler will be
  26. * added after the sync handler in customize-preview.js, so it will be triggered
  27. * after all of the settings are added.
  28. */
  29. api.preview.bind( 'sync', function() {
  30. synced = true;
  31. } );
  32. if ( api.selectiveRefresh ) {
  33. // Listen for changes to settings related to nav menus.
  34. api.each( function( setting ) {
  35. self.bindSettingListener( setting );
  36. } );
  37. api.bind( 'add', function( setting ) {
  38. /*
  39. * Handle case where an invalid nav menu item (one for which its associated object has been deleted)
  40. * is synced from the controls into the preview. Since invalid nav menu items are filtered out from
  41. * being exported to the frontend by the _is_valid_nav_menu_item filter in wp_get_nav_menu_items(),
  42. * the customizer controls will have a nav_menu_item setting where the preview will have none, and
  43. * this can trigger an infinite fallback refresh when the nav menu item lacks any valid items.
  44. */
  45. if ( setting.get() && ! setting.get()._invalid ) {
  46. self.bindSettingListener( setting, { fire: synced } );
  47. }
  48. } );
  49. api.bind( 'remove', function( setting ) {
  50. self.unbindSettingListener( setting );
  51. } );
  52. /*
  53. * Ensure that wp_nav_menu() instances nested inside of other partials
  54. * will be recognized as being present on the page.
  55. */
  56. api.selectiveRefresh.bind( 'render-partials-response', function( response ) {
  57. if ( response.nav_menu_instance_args ) {
  58. _.extend( self.data.navMenuInstanceArgs, response.nav_menu_instance_args );
  59. }
  60. } );
  61. }
  62. api.preview.bind( 'active', function() {
  63. self.highlightControls();
  64. } );
  65. };
  66. if ( api.selectiveRefresh ) {
  67. /**
  68. * Partial representing an invocation of wp_nav_menu().
  69. *
  70. * @memberOf wp.customize.navMenusPreview
  71. * @alias wp.customize.navMenusPreview.NavMenuInstancePartial
  72. *
  73. * @class
  74. * @augments wp.customize.selectiveRefresh.Partial
  75. * @since 4.5.0
  76. */
  77. self.NavMenuInstancePartial = api.selectiveRefresh.Partial.extend(/** @lends wp.customize.navMenusPreview.NavMenuInstancePartial.prototype */{
  78. /**
  79. * Constructor.
  80. *
  81. * @since 4.5.0
  82. * @param {string} id - Partial ID.
  83. * @param {Object} options
  84. * @param {Object} options.params
  85. * @param {Object} options.params.navMenuArgs
  86. * @param {string} options.params.navMenuArgs.args_hmac
  87. * @param {string} [options.params.navMenuArgs.theme_location]
  88. * @param {number} [options.params.navMenuArgs.menu]
  89. * @param {Object} [options.constructingContainerContext]
  90. */
  91. initialize: function( id, options ) {
  92. var partial = this, matches, argsHmac;
  93. matches = id.match( /^nav_menu_instance\[([0-9a-f]{32})]$/ );
  94. if ( ! matches ) {
  95. throw new Error( 'Illegal id for nav_menu_instance partial. The key corresponds with the args HMAC.' );
  96. }
  97. argsHmac = matches[1];
  98. options = options || {};
  99. options.params = _.extend(
  100. {
  101. selector: '[data-customize-partial-id="' + id + '"]',
  102. navMenuArgs: options.constructingContainerContext || {},
  103. containerInclusive: true
  104. },
  105. options.params || {}
  106. );
  107. api.selectiveRefresh.Partial.prototype.initialize.call( partial, id, options );
  108. if ( ! _.isObject( partial.params.navMenuArgs ) ) {
  109. throw new Error( 'Missing navMenuArgs' );
  110. }
  111. if ( partial.params.navMenuArgs.args_hmac !== argsHmac ) {
  112. throw new Error( 'args_hmac mismatch with id' );
  113. }
  114. },
  115. /**
  116. * Return whether the setting is related to this partial.
  117. *
  118. * @since 4.5.0
  119. * @param {wp.customize.Value|string} setting - Object or ID.
  120. * @param {number|Object|false|null} newValue - New value, or null if the setting was just removed.
  121. * @param {number|Object|false|null} oldValue - Old value, or null if the setting was just added.
  122. * @return {boolean}
  123. */
  124. isRelatedSetting: function( setting, newValue, oldValue ) {
  125. var partial = this, navMenuLocationSetting, navMenuId, isNavMenuItemSetting, _newValue, _oldValue, urlParser;
  126. if ( _.isString( setting ) ) {
  127. setting = api( setting );
  128. }
  129. /*
  130. * Prevent nav_menu_item changes only containing type_label differences triggering a refresh.
  131. * These settings in the preview do not include type_label property, and so if one of these
  132. * nav_menu_item settings is dirty, after a refresh the nav menu instance would do a selective
  133. * refresh immediately because the setting from the pane would have the type_label whereas
  134. * the setting in the preview would not, thus triggering a change event. The following
  135. * condition short-circuits this unnecessary selective refresh and also prevents an infinite
  136. * loop in the case where a nav_menu_instance partial had done a fallback refresh.
  137. * @todo Nav menu item settings should not include a type_label property to begin with.
  138. */
  139. isNavMenuItemSetting = /^nav_menu_item\[/.test( setting.id );
  140. if ( isNavMenuItemSetting && _.isObject( newValue ) && _.isObject( oldValue ) ) {
  141. _newValue = _.clone( newValue );
  142. _oldValue = _.clone( oldValue );
  143. delete _newValue.type_label;
  144. delete _oldValue.type_label;
  145. // Normalize URL scheme when parent frame is HTTPS to prevent selective refresh upon initial page load.
  146. if ( 'https' === api.preview.scheme.get() ) {
  147. urlParser = document.createElement( 'a' );
  148. urlParser.href = _newValue.url;
  149. urlParser.protocol = 'https:';
  150. _newValue.url = urlParser.href;
  151. urlParser.href = _oldValue.url;
  152. urlParser.protocol = 'https:';
  153. _oldValue.url = urlParser.href;
  154. }
  155. // Prevent original_title differences from causing refreshes if title is present.
  156. if ( newValue.title ) {
  157. delete _oldValue.original_title;
  158. delete _newValue.original_title;
  159. }
  160. if ( _.isEqual( _oldValue, _newValue ) ) {
  161. return false;
  162. }
  163. }
  164. if ( partial.params.navMenuArgs.theme_location ) {
  165. if ( 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']' === setting.id ) {
  166. return true;
  167. }
  168. navMenuLocationSetting = api( 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']' );
  169. }
  170. navMenuId = partial.params.navMenuArgs.menu;
  171. if ( ! navMenuId && navMenuLocationSetting ) {
  172. navMenuId = navMenuLocationSetting();
  173. }
  174. if ( ! navMenuId ) {
  175. return false;
  176. }
  177. return (
  178. ( 'nav_menu[' + navMenuId + ']' === setting.id ) ||
  179. ( isNavMenuItemSetting && (
  180. ( newValue && newValue.nav_menu_term_id === navMenuId ) ||
  181. ( oldValue && oldValue.nav_menu_term_id === navMenuId )
  182. ) )
  183. );
  184. },
  185. /**
  186. * Make sure that partial fallback behavior is invoked if there is no associated menu.
  187. *
  188. * @since 4.5.0
  189. *
  190. * @return {Promise}
  191. */
  192. refresh: function() {
  193. var partial = this, menuId, deferred = $.Deferred();
  194. // Make sure the fallback behavior is invoked when the partial is no longer associated with a menu.
  195. if ( _.isNumber( partial.params.navMenuArgs.menu ) ) {
  196. menuId = partial.params.navMenuArgs.menu;
  197. } else if ( partial.params.navMenuArgs.theme_location && api.has( 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']' ) ) {
  198. menuId = api( 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']' ).get();
  199. }
  200. if ( ! menuId ) {
  201. partial.fallback();
  202. deferred.reject();
  203. return deferred.promise();
  204. }
  205. return api.selectiveRefresh.Partial.prototype.refresh.call( partial );
  206. },
  207. /**
  208. * Render content.
  209. *
  210. * @inheritdoc
  211. * @param {wp.customize.selectiveRefresh.Placement} placement
  212. */
  213. renderContent: function( placement ) {
  214. var partial = this, previousContainer = placement.container;
  215. // Do fallback behavior to refresh preview if menu is now empty.
  216. if ( '' === placement.addedContent ) {
  217. placement.partial.fallback();
  218. }
  219. if ( api.selectiveRefresh.Partial.prototype.renderContent.call( partial, placement ) ) {
  220. // Trigger deprecated event.
  221. $( document ).trigger( 'customize-preview-menu-refreshed', [ {
  222. instanceNumber: null, // @deprecated
  223. wpNavArgs: placement.context, // @deprecated
  224. wpNavMenuArgs: placement.context,
  225. oldContainer: previousContainer,
  226. newContainer: placement.container
  227. } ] );
  228. }
  229. }
  230. });
  231. api.selectiveRefresh.partialConstructor.nav_menu_instance = self.NavMenuInstancePartial;
  232. /**
  233. * Request full refresh if there are nav menu instances that lack partials which also match the supplied args.
  234. *
  235. * @param {Object} navMenuInstanceArgs
  236. */
  237. self.handleUnplacedNavMenuInstances = function( navMenuInstanceArgs ) {
  238. var unplacedNavMenuInstances;
  239. unplacedNavMenuInstances = _.filter( _.values( self.data.navMenuInstanceArgs ), function( args ) {
  240. return ! api.selectiveRefresh.partial.has( 'nav_menu_instance[' + args.args_hmac + ']' );
  241. } );
  242. if ( _.findWhere( unplacedNavMenuInstances, navMenuInstanceArgs ) ) {
  243. api.selectiveRefresh.requestFullRefresh();
  244. return true;
  245. }
  246. return false;
  247. };
  248. /**
  249. * Add change listener for a nav_menu[], nav_menu_item[], or nav_menu_locations[] setting.
  250. *
  251. * @since 4.5.0
  252. *
  253. * @param {wp.customize.Value} setting
  254. * @param {Object} [options]
  255. * @param {boolean} options.fire Whether to invoke the callback after binding.
  256. * This is used when a dynamic setting is added.
  257. * @return {boolean} Whether the setting was bound.
  258. */
  259. self.bindSettingListener = function( setting, options ) {
  260. var matches;
  261. options = options || {};
  262. matches = setting.id.match( /^nav_menu\[(-?\d+)]$/ );
  263. if ( matches ) {
  264. setting._navMenuId = parseInt( matches[1], 10 );
  265. setting.bind( this.onChangeNavMenuSetting );
  266. if ( options.fire ) {
  267. this.onChangeNavMenuSetting.call( setting, setting(), false );
  268. }
  269. return true;
  270. }
  271. matches = setting.id.match( /^nav_menu_item\[(-?\d+)]$/ );
  272. if ( matches ) {
  273. setting._navMenuItemId = parseInt( matches[1], 10 );
  274. setting.bind( this.onChangeNavMenuItemSetting );
  275. if ( options.fire ) {
  276. this.onChangeNavMenuItemSetting.call( setting, setting(), false );
  277. }
  278. return true;
  279. }
  280. matches = setting.id.match( /^nav_menu_locations\[(.+?)]/ );
  281. if ( matches ) {
  282. setting._navMenuThemeLocation = matches[1];
  283. setting.bind( this.onChangeNavMenuLocationsSetting );
  284. if ( options.fire ) {
  285. this.onChangeNavMenuLocationsSetting.call( setting, setting(), false );
  286. }
  287. return true;
  288. }
  289. return false;
  290. };
  291. /**
  292. * Remove change listeners for nav_menu[], nav_menu_item[], or nav_menu_locations[] setting.
  293. *
  294. * @since 4.5.0
  295. *
  296. * @param {wp.customize.Value} setting
  297. */
  298. self.unbindSettingListener = function( setting ) {
  299. setting.unbind( this.onChangeNavMenuSetting );
  300. setting.unbind( this.onChangeNavMenuItemSetting );
  301. setting.unbind( this.onChangeNavMenuLocationsSetting );
  302. };
  303. /**
  304. * Handle change for nav_menu[] setting for nav menu instances lacking partials.
  305. *
  306. * @since 4.5.0
  307. *
  308. * @this {wp.customize.Value}
  309. */
  310. self.onChangeNavMenuSetting = function() {
  311. var setting = this;
  312. self.handleUnplacedNavMenuInstances( {
  313. menu: setting._navMenuId
  314. } );
  315. // Ensure all nav menu instances with a theme_location assigned to this menu are handled.
  316. api.each( function( otherSetting ) {
  317. if ( ! otherSetting._navMenuThemeLocation ) {
  318. return;
  319. }
  320. if ( setting._navMenuId === otherSetting() ) {
  321. self.handleUnplacedNavMenuInstances( {
  322. theme_location: otherSetting._navMenuThemeLocation
  323. } );
  324. }
  325. } );
  326. };
  327. /**
  328. * Handle change for nav_menu_item[] setting for nav menu instances lacking partials.
  329. *
  330. * @since 4.5.0
  331. *
  332. * @param {Object} newItem New value for nav_menu_item[] setting.
  333. * @param {Object} oldItem Old value for nav_menu_item[] setting.
  334. * @this {wp.customize.Value}
  335. */
  336. self.onChangeNavMenuItemSetting = function( newItem, oldItem ) {
  337. var item = newItem || oldItem, navMenuSetting;
  338. navMenuSetting = api( 'nav_menu[' + String( item.nav_menu_term_id ) + ']' );
  339. if ( navMenuSetting ) {
  340. self.onChangeNavMenuSetting.call( navMenuSetting );
  341. }
  342. };
  343. /**
  344. * Handle change for nav_menu_locations[] setting for nav menu instances lacking partials.
  345. *
  346. * @since 4.5.0
  347. *
  348. * @this {wp.customize.Value}
  349. */
  350. self.onChangeNavMenuLocationsSetting = function() {
  351. var setting = this, hasNavMenuInstance;
  352. self.handleUnplacedNavMenuInstances( {
  353. theme_location: setting._navMenuThemeLocation
  354. } );
  355. // If there are no wp_nav_menu() instances that refer to the theme location, do full refresh.
  356. hasNavMenuInstance = !! _.findWhere( _.values( self.data.navMenuInstanceArgs ), {
  357. theme_location: setting._navMenuThemeLocation
  358. } );
  359. if ( ! hasNavMenuInstance ) {
  360. api.selectiveRefresh.requestFullRefresh();
  361. }
  362. };
  363. }
  364. /**
  365. * Connect nav menu items with their corresponding controls in the pane.
  366. *
  367. * Setup shift-click on nav menu items which are more granular than the nav menu partial itself.
  368. * Also this applies even if a nav menu is not partial-refreshable.
  369. *
  370. * @since 4.5.0
  371. */
  372. self.highlightControls = function() {
  373. var selector = '.menu-item';
  374. // Skip adding highlights if not in the customizer preview iframe.
  375. if ( ! api.settings.channel ) {
  376. return;
  377. }
  378. // Focus on the menu item control when shift+clicking the menu item.
  379. $( document ).on( 'click', selector, function( e ) {
  380. var navMenuItemParts;
  381. if ( ! e.shiftKey ) {
  382. return;
  383. }
  384. navMenuItemParts = $( this ).attr( 'class' ).match( /(?:^|\s)menu-item-(-?\d+)(?:\s|$)/ );
  385. if ( navMenuItemParts ) {
  386. e.preventDefault();
  387. e.stopPropagation(); // Make sure a sub-nav menu item will get focused instead of parent items.
  388. api.preview.send( 'focus-nav-menu-item-control', parseInt( navMenuItemParts[1], 10 ) );
  389. }
  390. });
  391. };
  392. api.bind( 'preview-ready', function() {
  393. self.init();
  394. } );
  395. return self;
  396. }( jQuery, _, wp, wp.customize ) );