customize-preview-nav-menus.js 15 KB

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