customize-selective-refresh.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. /**
  2. * @output wp-includes/js/customize-selective-refresh.js
  3. */
  4. /* global jQuery, JSON, _customizePartialRefreshExports, console */
  5. /** @namespace wp.customize.selectiveRefresh */
  6. wp.customize.selectiveRefresh = ( function( $, api ) {
  7. 'use strict';
  8. var self, Partial, Placement;
  9. self = {
  10. ready: $.Deferred(),
  11. editShortcutVisibility: new api.Value(),
  12. data: {
  13. partials: {},
  14. renderQueryVar: '',
  15. l10n: {
  16. shiftClickToEdit: ''
  17. }
  18. },
  19. currentRequest: null
  20. };
  21. _.extend( self, api.Events );
  22. /**
  23. * A Customizer Partial.
  24. *
  25. * A partial provides a rendering of one or more settings according to a template.
  26. *
  27. * @memberOf wp.customize.selectiveRefresh
  28. *
  29. * @see PHP class WP_Customize_Partial.
  30. *
  31. * @class
  32. * @augments wp.customize.Class
  33. * @since 4.5.0
  34. */
  35. Partial = self.Partial = api.Class.extend(/** @lends wp.customize.SelectiveRefresh.Partial.prototype */{
  36. id: null,
  37. /**
  38. * Default params.
  39. *
  40. * @since 4.9.0
  41. * @var {object}
  42. */
  43. defaults: {
  44. selector: null,
  45. primarySetting: null,
  46. containerInclusive: false,
  47. fallbackRefresh: true // Note this needs to be false in a front-end editing context.
  48. },
  49. /**
  50. * Constructor.
  51. *
  52. * @since 4.5.0
  53. *
  54. * @param {string} id - Unique identifier for the partial instance.
  55. * @param {Object} options - Options hash for the partial instance.
  56. * @param {string} options.type - Type of partial (e.g. nav_menu, widget, etc)
  57. * @param {string} options.selector - jQuery selector to find the container element in the page.
  58. * @param {Array} options.settings - The IDs for the settings the partial relates to.
  59. * @param {string} options.primarySetting - The ID for the primary setting the partial renders.
  60. * @param {boolean} options.fallbackRefresh - Whether to refresh the entire preview in case of a partial refresh failure.
  61. * @param {Object} [options.params] - Deprecated wrapper for the above properties.
  62. */
  63. initialize: function( id, options ) {
  64. var partial = this;
  65. options = options || {};
  66. partial.id = id;
  67. partial.params = _.extend(
  68. {
  69. settings: []
  70. },
  71. partial.defaults,
  72. options.params || options
  73. );
  74. partial.deferred = {};
  75. partial.deferred.ready = $.Deferred();
  76. partial.deferred.ready.done( function() {
  77. partial.ready();
  78. } );
  79. },
  80. /**
  81. * Set up the partial.
  82. *
  83. * @since 4.5.0
  84. */
  85. ready: function() {
  86. var partial = this;
  87. _.each( partial.placements(), function( placement ) {
  88. $( placement.container ).attr( 'title', self.data.l10n.shiftClickToEdit );
  89. partial.createEditShortcutForPlacement( placement );
  90. } );
  91. $( document ).on( 'click', partial.params.selector, function( e ) {
  92. if ( ! e.shiftKey ) {
  93. return;
  94. }
  95. e.preventDefault();
  96. _.each( partial.placements(), function( placement ) {
  97. if ( $( placement.container ).is( e.currentTarget ) ) {
  98. partial.showControl();
  99. }
  100. } );
  101. } );
  102. },
  103. /**
  104. * Create and show the edit shortcut for a given partial placement container.
  105. *
  106. * @since 4.7.0
  107. * @access public
  108. *
  109. * @param {Placement} placement The placement container element.
  110. * @return {void}
  111. */
  112. createEditShortcutForPlacement: function( placement ) {
  113. var partial = this, $shortcut, $placementContainer, illegalAncestorSelector, illegalContainerSelector;
  114. if ( ! placement.container ) {
  115. return;
  116. }
  117. $placementContainer = $( placement.container );
  118. illegalAncestorSelector = 'head';
  119. illegalContainerSelector = 'area, audio, base, bdi, bdo, br, button, canvas, col, colgroup, command, datalist, embed, head, hr, html, iframe, img, input, keygen, label, link, map, math, menu, meta, noscript, object, optgroup, option, param, progress, rp, rt, ruby, script, select, source, style, svg, table, tbody, textarea, tfoot, thead, title, tr, track, video, wbr';
  120. if ( ! $placementContainer.length || $placementContainer.is( illegalContainerSelector ) || $placementContainer.closest( illegalAncestorSelector ).length ) {
  121. return;
  122. }
  123. $shortcut = partial.createEditShortcut();
  124. $shortcut.on( 'click', function( event ) {
  125. event.preventDefault();
  126. event.stopPropagation();
  127. partial.showControl();
  128. } );
  129. partial.addEditShortcutToPlacement( placement, $shortcut );
  130. },
  131. /**
  132. * Add an edit shortcut to the placement container.
  133. *
  134. * @since 4.7.0
  135. * @access public
  136. *
  137. * @param {Placement} placement The placement for the partial.
  138. * @param {jQuery} $editShortcut The shortcut element as a jQuery object.
  139. * @return {void}
  140. */
  141. addEditShortcutToPlacement: function( placement, $editShortcut ) {
  142. var $placementContainer = $( placement.container );
  143. $placementContainer.prepend( $editShortcut );
  144. if ( ! $placementContainer.is( ':visible' ) || 'none' === $placementContainer.css( 'display' ) ) {
  145. $editShortcut.addClass( 'customize-partial-edit-shortcut-hidden' );
  146. }
  147. },
  148. /**
  149. * Return the unique class name for the edit shortcut button for this partial.
  150. *
  151. * @since 4.7.0
  152. * @access public
  153. *
  154. * @return {string} Partial ID converted into a class name for use in shortcut.
  155. */
  156. getEditShortcutClassName: function() {
  157. var partial = this, cleanId;
  158. cleanId = partial.id.replace( /]/g, '' ).replace( /\[/g, '-' );
  159. return 'customize-partial-edit-shortcut-' + cleanId;
  160. },
  161. /**
  162. * Return the appropriate translated string for the edit shortcut button.
  163. *
  164. * @since 4.7.0
  165. * @access public
  166. *
  167. * @return {string} Tooltip for edit shortcut.
  168. */
  169. getEditShortcutTitle: function() {
  170. var partial = this, l10n = self.data.l10n;
  171. switch ( partial.getType() ) {
  172. case 'widget':
  173. return l10n.clickEditWidget;
  174. case 'blogname':
  175. return l10n.clickEditTitle;
  176. case 'blogdescription':
  177. return l10n.clickEditTitle;
  178. case 'nav_menu':
  179. return l10n.clickEditMenu;
  180. default:
  181. return l10n.clickEditMisc;
  182. }
  183. },
  184. /**
  185. * Return the type of this partial
  186. *
  187. * Will use `params.type` if set, but otherwise will try to infer type from settingId.
  188. *
  189. * @since 4.7.0
  190. * @access public
  191. *
  192. * @return {string} Type of partial derived from type param or the related setting ID.
  193. */
  194. getType: function() {
  195. var partial = this, settingId;
  196. settingId = partial.params.primarySetting || _.first( partial.settings() ) || 'unknown';
  197. if ( partial.params.type ) {
  198. return partial.params.type;
  199. }
  200. if ( settingId.match( /^nav_menu_instance\[/ ) ) {
  201. return 'nav_menu';
  202. }
  203. if ( settingId.match( /^widget_.+\[\d+]$/ ) ) {
  204. return 'widget';
  205. }
  206. return settingId;
  207. },
  208. /**
  209. * Create an edit shortcut button for this partial.
  210. *
  211. * @since 4.7.0
  212. * @access public
  213. *
  214. * @return {jQuery} The edit shortcut button element.
  215. */
  216. createEditShortcut: function() {
  217. var partial = this, shortcutTitle, $buttonContainer, $button, $image;
  218. shortcutTitle = partial.getEditShortcutTitle();
  219. $buttonContainer = $( '<span>', {
  220. 'class': 'customize-partial-edit-shortcut ' + partial.getEditShortcutClassName()
  221. } );
  222. $button = $( '<button>', {
  223. 'aria-label': shortcutTitle,
  224. 'title': shortcutTitle,
  225. 'class': 'customize-partial-edit-shortcut-button'
  226. } );
  227. $image = $( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M13.89 3.39l2.71 2.72c.46.46.42 1.24.03 1.64l-8.01 8.02-5.56 1.16 1.16-5.58s7.6-7.63 7.99-8.03c.39-.39 1.22-.39 1.68.07zm-2.73 2.79l-5.59 5.61 1.11 1.11 5.54-5.65zm-2.97 8.23l5.58-5.6-1.07-1.08-5.59 5.6z"/></svg>' );
  228. $button.append( $image );
  229. $buttonContainer.append( $button );
  230. return $buttonContainer;
  231. },
  232. /**
  233. * Find all placements for this partial in the document.
  234. *
  235. * @since 4.5.0
  236. *
  237. * @return {Array.<Placement>}
  238. */
  239. placements: function() {
  240. var partial = this, selector;
  241. selector = partial.params.selector || '';
  242. if ( selector ) {
  243. selector += ', ';
  244. }
  245. selector += '[data-customize-partial-id="' + partial.id + '"]'; // @todo Consider injecting customize-partial-id-${id} classnames instead.
  246. return $( selector ).map( function() {
  247. var container = $( this ), context;
  248. context = container.data( 'customize-partial-placement-context' );
  249. if ( _.isString( context ) && '{' === context.substr( 0, 1 ) ) {
  250. throw new Error( 'context JSON parse error' );
  251. }
  252. return new Placement( {
  253. partial: partial,
  254. container: container,
  255. context: context
  256. } );
  257. } ).get();
  258. },
  259. /**
  260. * Get list of setting IDs related to this partial.
  261. *
  262. * @since 4.5.0
  263. *
  264. * @return {string[]}
  265. */
  266. settings: function() {
  267. var partial = this;
  268. if ( partial.params.settings && 0 !== partial.params.settings.length ) {
  269. return partial.params.settings;
  270. } else if ( partial.params.primarySetting ) {
  271. return [ partial.params.primarySetting ];
  272. } else {
  273. return [ partial.id ];
  274. }
  275. },
  276. /**
  277. * Return whether the setting is related to the partial.
  278. *
  279. * @since 4.5.0
  280. *
  281. * @param {wp.customize.Value|string} setting ID or object for setting.
  282. * @return {boolean} Whether the setting is related to the partial.
  283. */
  284. isRelatedSetting: function( setting /*... newValue, oldValue */ ) {
  285. var partial = this;
  286. if ( _.isString( setting ) ) {
  287. setting = api( setting );
  288. }
  289. if ( ! setting ) {
  290. return false;
  291. }
  292. return -1 !== _.indexOf( partial.settings(), setting.id );
  293. },
  294. /**
  295. * Show the control to modify this partial's setting(s).
  296. *
  297. * This may be overridden for inline editing.
  298. *
  299. * @since 4.5.0
  300. */
  301. showControl: function() {
  302. var partial = this, settingId = partial.params.primarySetting;
  303. if ( ! settingId ) {
  304. settingId = _.first( partial.settings() );
  305. }
  306. if ( partial.getType() === 'nav_menu' ) {
  307. if ( partial.params.navMenuArgs.theme_location ) {
  308. settingId = 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']';
  309. } else if ( partial.params.navMenuArgs.menu ) {
  310. settingId = 'nav_menu[' + String( partial.params.navMenuArgs.menu ) + ']';
  311. }
  312. }
  313. api.preview.send( 'focus-control-for-setting', settingId );
  314. },
  315. /**
  316. * Prepare container for selective refresh.
  317. *
  318. * @since 4.5.0
  319. *
  320. * @param {Placement} placement
  321. */
  322. preparePlacement: function( placement ) {
  323. $( placement.container ).addClass( 'customize-partial-refreshing' );
  324. },
  325. /**
  326. * Reference to the pending promise returned from self.requestPartial().
  327. *
  328. * @since 4.5.0
  329. * @private
  330. */
  331. _pendingRefreshPromise: null,
  332. /**
  333. * Request the new partial and render it into the placements.
  334. *
  335. * @since 4.5.0
  336. *
  337. * @this {wp.customize.selectiveRefresh.Partial}
  338. * @return {jQuery.Promise}
  339. */
  340. refresh: function() {
  341. var partial = this, refreshPromise;
  342. refreshPromise = self.requestPartial( partial );
  343. if ( ! partial._pendingRefreshPromise ) {
  344. _.each( partial.placements(), function( placement ) {
  345. partial.preparePlacement( placement );
  346. } );
  347. refreshPromise.done( function( placements ) {
  348. _.each( placements, function( placement ) {
  349. partial.renderContent( placement );
  350. } );
  351. } );
  352. refreshPromise.fail( function( data, placements ) {
  353. partial.fallback( data, placements );
  354. } );
  355. // Allow new request when this one finishes.
  356. partial._pendingRefreshPromise = refreshPromise;
  357. refreshPromise.always( function() {
  358. partial._pendingRefreshPromise = null;
  359. } );
  360. }
  361. return refreshPromise;
  362. },
  363. /**
  364. * Apply the addedContent in the placement to the document.
  365. *
  366. * Note the placement object will have its container and removedNodes
  367. * properties updated.
  368. *
  369. * @since 4.5.0
  370. *
  371. * @param {Placement} placement
  372. * @param {Element|jQuery} [placement.container] - This param will be empty if there was no element matching the selector.
  373. * @param {string|Object|boolean} placement.addedContent - Rendered HTML content, a data object for JS templates to render, or false if no render.
  374. * @param {Object} [placement.context] - Optional context information about the container.
  375. * @return {boolean} Whether the rendering was successful and the fallback was not invoked.
  376. */
  377. renderContent: function( placement ) {
  378. var partial = this, content, newContainerElement;
  379. if ( ! placement.container ) {
  380. partial.fallback( new Error( 'no_container' ), [ placement ] );
  381. return false;
  382. }
  383. placement.container = $( placement.container );
  384. if ( false === placement.addedContent ) {
  385. partial.fallback( new Error( 'missing_render' ), [ placement ] );
  386. return false;
  387. }
  388. // Currently a subclass needs to override renderContent to handle partials returning data object.
  389. if ( ! _.isString( placement.addedContent ) ) {
  390. partial.fallback( new Error( 'non_string_content' ), [ placement ] );
  391. return false;
  392. }
  393. /* jshint ignore:start */
  394. self.orginalDocumentWrite = document.write;
  395. document.write = function() {
  396. throw new Error( self.data.l10n.badDocumentWrite );
  397. };
  398. /* jshint ignore:end */
  399. try {
  400. content = placement.addedContent;
  401. if ( wp.emoji && wp.emoji.parse && ! $.contains( document.head, placement.container[0] ) ) {
  402. content = wp.emoji.parse( content );
  403. }
  404. if ( partial.params.containerInclusive ) {
  405. // Note that content may be an empty string, and in this case jQuery will just remove the oldContainer.
  406. newContainerElement = $( content );
  407. // Merge the new context on top of the old context.
  408. placement.context = _.extend(
  409. placement.context,
  410. newContainerElement.data( 'customize-partial-placement-context' ) || {}
  411. );
  412. newContainerElement.data( 'customize-partial-placement-context', placement.context );
  413. placement.removedNodes = placement.container;
  414. placement.container = newContainerElement;
  415. placement.removedNodes.replaceWith( placement.container );
  416. placement.container.attr( 'title', self.data.l10n.shiftClickToEdit );
  417. } else {
  418. placement.removedNodes = document.createDocumentFragment();
  419. while ( placement.container[0].firstChild ) {
  420. placement.removedNodes.appendChild( placement.container[0].firstChild );
  421. }
  422. placement.container.html( content );
  423. }
  424. placement.container.removeClass( 'customize-render-content-error' );
  425. } catch ( error ) {
  426. if ( 'undefined' !== typeof console && console.error ) {
  427. console.error( partial.id, error );
  428. }
  429. partial.fallback( error, [ placement ] );
  430. }
  431. /* jshint ignore:start */
  432. document.write = self.orginalDocumentWrite;
  433. self.orginalDocumentWrite = null;
  434. /* jshint ignore:end */
  435. partial.createEditShortcutForPlacement( placement );
  436. placement.container.removeClass( 'customize-partial-refreshing' );
  437. // Prevent placement container from being re-triggered as being rendered among nested partials.
  438. placement.container.data( 'customize-partial-content-rendered', true );
  439. /*
  440. * Note that the 'wp_audio_shortcode_library' and 'wp_video_shortcode_library' filters
  441. * will determine whether or not wp.mediaelement is loaded and whether it will
  442. * initialize audio and video respectively. See also https://core.trac.wordpress.org/ticket/40144
  443. */
  444. if ( wp.mediaelement ) {
  445. wp.mediaelement.initialize();
  446. }
  447. if ( wp.playlist ) {
  448. wp.playlist.initialize();
  449. }
  450. /**
  451. * Announce when a partial's placement has been rendered so that dynamic elements can be re-built.
  452. */
  453. self.trigger( 'partial-content-rendered', placement );
  454. return true;
  455. },
  456. /**
  457. * Handle fail to render partial.
  458. *
  459. * The first argument is either the failing jqXHR or an Error object, and the second argument is the array of containers.
  460. *
  461. * @since 4.5.0
  462. */
  463. fallback: function() {
  464. var partial = this;
  465. if ( partial.params.fallbackRefresh ) {
  466. self.requestFullRefresh();
  467. }
  468. }
  469. } );
  470. /**
  471. * A Placement for a Partial.
  472. *
  473. * A partial placement is the actual physical representation of a partial for a given context.
  474. * It also may have information in relation to how a placement may have just changed.
  475. * The placement is conceptually similar to a DOM Range or MutationRecord.
  476. *
  477. * @memberOf wp.customize.selectiveRefresh
  478. *
  479. * @class Placement
  480. * @augments wp.customize.Class
  481. * @since 4.5.0
  482. */
  483. self.Placement = Placement = api.Class.extend(/** @lends wp.customize.selectiveRefresh.prototype */{
  484. /**
  485. * The partial with which the container is associated.
  486. *
  487. * @param {wp.customize.selectiveRefresh.Partial}
  488. */
  489. partial: null,
  490. /**
  491. * DOM element which contains the placement's contents.
  492. *
  493. * This will be null if the startNode and endNode do not point to the same
  494. * DOM element, such as in the case of a sidebar partial.
  495. * This container element itself will be replaced for partials that
  496. * have containerInclusive param defined as true.
  497. */
  498. container: null,
  499. /**
  500. * DOM node for the initial boundary of the placement.
  501. *
  502. * This will normally be the same as endNode since most placements appear as elements.
  503. * This is primarily useful for widget sidebars which do not have intrinsic containers, but
  504. * for which an HTML comment is output before to mark the starting position.
  505. */
  506. startNode: null,
  507. /**
  508. * DOM node for the terminal boundary of the placement.
  509. *
  510. * This will normally be the same as startNode since most placements appear as elements.
  511. * This is primarily useful for widget sidebars which do not have intrinsic containers, but
  512. * for which an HTML comment is output before to mark the ending position.
  513. */
  514. endNode: null,
  515. /**
  516. * Context data.
  517. *
  518. * This provides information about the placement which is included in the request
  519. * in order to render the partial properly.
  520. *
  521. * @param {object}
  522. */
  523. context: null,
  524. /**
  525. * The content for the partial when refreshed.
  526. *
  527. * @param {string}
  528. */
  529. addedContent: null,
  530. /**
  531. * DOM node(s) removed when the partial is refreshed.
  532. *
  533. * If the partial is containerInclusive, then the removedNodes will be
  534. * the single Element that was the partial's former placement. If the
  535. * partial is not containerInclusive, then the removedNodes will be a
  536. * documentFragment containing the nodes removed.
  537. *
  538. * @param {Element|DocumentFragment}
  539. */
  540. removedNodes: null,
  541. /**
  542. * Constructor.
  543. *
  544. * @since 4.5.0
  545. *
  546. * @param {Object} args
  547. * @param {Partial} args.partial
  548. * @param {jQuery|Element} [args.container]
  549. * @param {Node} [args.startNode]
  550. * @param {Node} [args.endNode]
  551. * @param {Object} [args.context]
  552. * @param {string} [args.addedContent]
  553. * @param {jQuery|DocumentFragment} [args.removedNodes]
  554. */
  555. initialize: function( args ) {
  556. var placement = this;
  557. args = _.extend( {}, args || {} );
  558. if ( ! args.partial || ! args.partial.extended( Partial ) ) {
  559. throw new Error( 'Missing partial' );
  560. }
  561. args.context = args.context || {};
  562. if ( args.container ) {
  563. args.container = $( args.container );
  564. }
  565. _.extend( placement, args );
  566. }
  567. });
  568. /**
  569. * Mapping of type names to Partial constructor subclasses.
  570. *
  571. * @since 4.5.0
  572. *
  573. * @type {Object.<string, wp.customize.selectiveRefresh.Partial>}
  574. */
  575. self.partialConstructor = {};
  576. self.partial = new api.Values({ defaultConstructor: Partial });
  577. /**
  578. * Get the POST vars for a Customizer preview request.
  579. *
  580. * @since 4.5.0
  581. * @see wp.customize.previewer.query()
  582. *
  583. * @return {Object}
  584. */
  585. self.getCustomizeQuery = function() {
  586. var dirtyCustomized = {};
  587. api.each( function( value, key ) {
  588. if ( value._dirty ) {
  589. dirtyCustomized[ key ] = value();
  590. }
  591. } );
  592. return {
  593. wp_customize: 'on',
  594. nonce: api.settings.nonce.preview,
  595. customize_theme: api.settings.theme.stylesheet,
  596. customized: JSON.stringify( dirtyCustomized ),
  597. customize_changeset_uuid: api.settings.changeset.uuid
  598. };
  599. };
  600. /**
  601. * Currently-requested partials and their associated deferreds.
  602. *
  603. * @since 4.5.0
  604. * @type {Object<string, { deferred: jQuery.Promise, partial: wp.customize.selectiveRefresh.Partial }>}
  605. */
  606. self._pendingPartialRequests = {};
  607. /**
  608. * Timeout ID for the current requesr, or null if no request is current.
  609. *
  610. * @since 4.5.0
  611. * @type {number|null}
  612. * @private
  613. */
  614. self._debouncedTimeoutId = null;
  615. /**
  616. * Current jqXHR for the request to the partials.
  617. *
  618. * @since 4.5.0
  619. * @type {jQuery.jqXHR|null}
  620. * @private
  621. */
  622. self._currentRequest = null;
  623. /**
  624. * Request full page refresh.
  625. *
  626. * When selective refresh is embedded in the context of front-end editing, this request
  627. * must fail or else changes will be lost, unless transactions are implemented.
  628. *
  629. * @since 4.5.0
  630. */
  631. self.requestFullRefresh = function() {
  632. api.preview.send( 'refresh' );
  633. };
  634. /**
  635. * Request a re-rendering of a partial.
  636. *
  637. * @since 4.5.0
  638. *
  639. * @param {wp.customize.selectiveRefresh.Partial} partial
  640. * @return {jQuery.Promise}
  641. */
  642. self.requestPartial = function( partial ) {
  643. var partialRequest;
  644. if ( self._debouncedTimeoutId ) {
  645. clearTimeout( self._debouncedTimeoutId );
  646. self._debouncedTimeoutId = null;
  647. }
  648. if ( self._currentRequest ) {
  649. self._currentRequest.abort();
  650. self._currentRequest = null;
  651. }
  652. partialRequest = self._pendingPartialRequests[ partial.id ];
  653. if ( ! partialRequest || 'pending' !== partialRequest.deferred.state() ) {
  654. partialRequest = {
  655. deferred: $.Deferred(),
  656. partial: partial
  657. };
  658. self._pendingPartialRequests[ partial.id ] = partialRequest;
  659. }
  660. // Prevent leaking partial into debounced timeout callback.
  661. partial = null;
  662. self._debouncedTimeoutId = setTimeout(
  663. function() {
  664. var data, partialPlacementContexts, partialsPlacements, request;
  665. self._debouncedTimeoutId = null;
  666. data = self.getCustomizeQuery();
  667. /*
  668. * It is key that the containers be fetched exactly at the point of the request being
  669. * made, because the containers need to be mapped to responses by array indices.
  670. */
  671. partialsPlacements = {};
  672. partialPlacementContexts = {};
  673. _.each( self._pendingPartialRequests, function( pending, partialId ) {
  674. partialsPlacements[ partialId ] = pending.partial.placements();
  675. if ( ! self.partial.has( partialId ) ) {
  676. pending.deferred.rejectWith( pending.partial, [ new Error( 'partial_removed' ), partialsPlacements[ partialId ] ] );
  677. } else {
  678. /*
  679. * Note that this may in fact be an empty array. In that case, it is the responsibility
  680. * of the Partial subclass instance to know where to inject the response, or else to
  681. * just issue a refresh (default behavior). The data being returned with each container
  682. * is the context information that may be needed to render certain partials, such as
  683. * the contained sidebar for rendering widgets or what the nav menu args are for a menu.
  684. */
  685. partialPlacementContexts[ partialId ] = _.map( partialsPlacements[ partialId ], function( placement ) {
  686. return placement.context || {};
  687. } );
  688. }
  689. } );
  690. data.partials = JSON.stringify( partialPlacementContexts );
  691. data[ self.data.renderQueryVar ] = '1';
  692. request = self._currentRequest = wp.ajax.send( null, {
  693. data: data,
  694. url: api.settings.url.self
  695. } );
  696. request.done( function( data ) {
  697. /**
  698. * Announce the data returned from a request to render partials.
  699. *
  700. * The data is filtered on the server via customize_render_partials_response
  701. * so plugins can inject data from the server to be utilized
  702. * on the client via this event. Plugins may use this filter
  703. * to communicate script and style dependencies that need to get
  704. * injected into the page to support the rendered partials.
  705. * This is similar to the 'saved' event.
  706. */
  707. self.trigger( 'render-partials-response', data );
  708. // Relay errors (warnings) captured during rendering and relay to console.
  709. if ( data.errors && 'undefined' !== typeof console && console.warn ) {
  710. _.each( data.errors, function( error ) {
  711. console.warn( error );
  712. } );
  713. }
  714. /*
  715. * Note that data is an array of items that correspond to the array of
  716. * containers that were submitted in the request. So we zip up the
  717. * array of containers with the array of contents for those containers,
  718. * and send them into .
  719. */
  720. _.each( self._pendingPartialRequests, function( pending, partialId ) {
  721. var placementsContents;
  722. if ( ! _.isArray( data.contents[ partialId ] ) ) {
  723. pending.deferred.rejectWith( pending.partial, [ new Error( 'unrecognized_partial' ), partialsPlacements[ partialId ] ] );
  724. } else {
  725. placementsContents = _.map( data.contents[ partialId ], function( content, i ) {
  726. var partialPlacement = partialsPlacements[ partialId ][ i ];
  727. if ( partialPlacement ) {
  728. partialPlacement.addedContent = content;
  729. } else {
  730. partialPlacement = new Placement( {
  731. partial: pending.partial,
  732. addedContent: content
  733. } );
  734. }
  735. return partialPlacement;
  736. } );
  737. pending.deferred.resolveWith( pending.partial, [ placementsContents ] );
  738. }
  739. } );
  740. self._pendingPartialRequests = {};
  741. } );
  742. request.fail( function( data, statusText ) {
  743. /*
  744. * Ignore failures caused by partial.currentRequest.abort()
  745. * The pending deferreds will remain in self._pendingPartialRequests
  746. * for re-use with the next request.
  747. */
  748. if ( 'abort' === statusText ) {
  749. return;
  750. }
  751. _.each( self._pendingPartialRequests, function( pending, partialId ) {
  752. pending.deferred.rejectWith( pending.partial, [ data, partialsPlacements[ partialId ] ] );
  753. } );
  754. self._pendingPartialRequests = {};
  755. } );
  756. },
  757. api.settings.timeouts.selectiveRefresh
  758. );
  759. return partialRequest.deferred.promise();
  760. };
  761. /**
  762. * Add partials for any nav menu container elements in the document.
  763. *
  764. * This method may be called multiple times. Containers that already have been
  765. * seen will be skipped.
  766. *
  767. * @since 4.5.0
  768. *
  769. * @param {jQuery|HTMLElement} [rootElement]
  770. * @param {object} [options]
  771. * @param {boolean=true} [options.triggerRendered]
  772. */
  773. self.addPartials = function( rootElement, options ) {
  774. var containerElements;
  775. if ( ! rootElement ) {
  776. rootElement = document.documentElement;
  777. }
  778. rootElement = $( rootElement );
  779. options = _.extend(
  780. {
  781. triggerRendered: true
  782. },
  783. options || {}
  784. );
  785. containerElements = rootElement.find( '[data-customize-partial-id]' );
  786. if ( rootElement.is( '[data-customize-partial-id]' ) ) {
  787. containerElements = containerElements.add( rootElement );
  788. }
  789. containerElements.each( function() {
  790. var containerElement = $( this ), partial, placement, id, Constructor, partialOptions, containerContext;
  791. id = containerElement.data( 'customize-partial-id' );
  792. if ( ! id ) {
  793. return;
  794. }
  795. containerContext = containerElement.data( 'customize-partial-placement-context' ) || {};
  796. partial = self.partial( id );
  797. if ( ! partial ) {
  798. partialOptions = containerElement.data( 'customize-partial-options' ) || {};
  799. partialOptions.constructingContainerContext = containerElement.data( 'customize-partial-placement-context' ) || {};
  800. Constructor = self.partialConstructor[ containerElement.data( 'customize-partial-type' ) ] || self.Partial;
  801. partial = new Constructor( id, partialOptions );
  802. self.partial.add( partial );
  803. }
  804. /*
  805. * Only trigger renders on (nested) partials that have been not been
  806. * handled yet. An example where this would apply is a nav menu
  807. * embedded inside of a navigation menu widget. When the widget's title
  808. * is updated, the entire widget will re-render and then the event
  809. * will be triggered for the nested nav menu to do any initialization.
  810. */
  811. if ( options.triggerRendered && ! containerElement.data( 'customize-partial-content-rendered' ) ) {
  812. placement = new Placement( {
  813. partial: partial,
  814. context: containerContext,
  815. container: containerElement
  816. } );
  817. $( placement.container ).attr( 'title', self.data.l10n.shiftClickToEdit );
  818. partial.createEditShortcutForPlacement( placement );
  819. /**
  820. * Announce when a partial's nested placement has been re-rendered.
  821. */
  822. self.trigger( 'partial-content-rendered', placement );
  823. }
  824. containerElement.data( 'customize-partial-content-rendered', true );
  825. } );
  826. };
  827. api.bind( 'preview-ready', function() {
  828. var handleSettingChange, watchSettingChange, unwatchSettingChange;
  829. _.extend( self.data, _customizePartialRefreshExports );
  830. // Create the partial JS models.
  831. _.each( self.data.partials, function( data, id ) {
  832. var Constructor, partial = self.partial( id );
  833. if ( ! partial ) {
  834. Constructor = self.partialConstructor[ data.type ] || self.Partial;
  835. partial = new Constructor(
  836. id,
  837. _.extend( { params: data }, data ) // Inclusion of params alias is for back-compat for custom partials that expect to augment this property.
  838. );
  839. self.partial.add( partial );
  840. } else {
  841. _.extend( partial.params, data );
  842. }
  843. } );
  844. /**
  845. * Handle change to a setting.
  846. *
  847. * Note this is largely needed because adding a 'change' event handler to wp.customize
  848. * will only include the changed setting object as an argument, not including the
  849. * new value or the old value.
  850. *
  851. * @since 4.5.0
  852. * @this {wp.customize.Setting}
  853. *
  854. * @param {*|null} newValue New value, or null if the setting was just removed.
  855. * @param {*|null} oldValue Old value, or null if the setting was just added.
  856. */
  857. handleSettingChange = function( newValue, oldValue ) {
  858. var setting = this;
  859. self.partial.each( function( partial ) {
  860. if ( partial.isRelatedSetting( setting, newValue, oldValue ) ) {
  861. partial.refresh();
  862. }
  863. } );
  864. };
  865. /**
  866. * Trigger the initial change for the added setting, and watch for changes.
  867. *
  868. * @since 4.5.0
  869. * @this {wp.customize.Values}
  870. *
  871. * @param {wp.customize.Setting} setting
  872. */
  873. watchSettingChange = function( setting ) {
  874. handleSettingChange.call( setting, setting(), null );
  875. setting.bind( handleSettingChange );
  876. };
  877. /**
  878. * Trigger the final change for the removed setting, and unwatch for changes.
  879. *
  880. * @since 4.5.0
  881. * @this {wp.customize.Values}
  882. *
  883. * @param {wp.customize.Setting} setting
  884. */
  885. unwatchSettingChange = function( setting ) {
  886. handleSettingChange.call( setting, null, setting() );
  887. setting.unbind( handleSettingChange );
  888. };
  889. api.bind( 'add', watchSettingChange );
  890. api.bind( 'remove', unwatchSettingChange );
  891. api.each( function( setting ) {
  892. setting.bind( handleSettingChange );
  893. } );
  894. // Add (dynamic) initial partials that are declared via data-* attributes.
  895. self.addPartials( document.documentElement, {
  896. triggerRendered: false
  897. } );
  898. // Add new dynamic partials when the document changes.
  899. if ( 'undefined' !== typeof MutationObserver ) {
  900. self.mutationObserver = new MutationObserver( function( mutations ) {
  901. _.each( mutations, function( mutation ) {
  902. self.addPartials( $( mutation.target ) );
  903. } );
  904. } );
  905. self.mutationObserver.observe( document.documentElement, {
  906. childList: true,
  907. subtree: true
  908. } );
  909. }
  910. /**
  911. * Handle rendering of partials.
  912. *
  913. * @param {api.selectiveRefresh.Placement} placement
  914. */
  915. api.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {
  916. if ( placement.container ) {
  917. self.addPartials( placement.container );
  918. }
  919. } );
  920. /**
  921. * Handle setting validities in partial refresh response.
  922. *
  923. * @param {object} data Response data.
  924. * @param {object} data.setting_validities Setting validities.
  925. */
  926. api.selectiveRefresh.bind( 'render-partials-response', function handleSettingValiditiesResponse( data ) {
  927. if ( data.setting_validities ) {
  928. api.preview.send( 'selective-refresh-setting-validities', data.setting_validities );
  929. }
  930. } );
  931. api.preview.bind( 'edit-shortcut-visibility', function( visibility ) {
  932. api.selectiveRefresh.editShortcutVisibility.set( visibility );
  933. } );
  934. api.selectiveRefresh.editShortcutVisibility.bind( function( visibility ) {
  935. var body = $( document.body ), shouldAnimateHide;
  936. shouldAnimateHide = ( 'hidden' === visibility && body.hasClass( 'customize-partial-edit-shortcuts-shown' ) && ! body.hasClass( 'customize-partial-edit-shortcuts-hidden' ) );
  937. body.toggleClass( 'customize-partial-edit-shortcuts-hidden', shouldAnimateHide );
  938. body.toggleClass( 'customize-partial-edit-shortcuts-shown', 'visible' === visibility );
  939. } );
  940. api.preview.bind( 'active', function() {
  941. // Make all partials ready.
  942. self.partial.each( function( partial ) {
  943. partial.deferred.ready.resolve();
  944. } );
  945. // Make all partials added henceforth as ready upon add.
  946. self.partial.bind( 'add', function( partial ) {
  947. partial.deferred.ready.resolve();
  948. } );
  949. } );
  950. } );
  951. return self;
  952. }( jQuery, wp.customize ) );