1 /* global jQuery, JSON, _customizePartialRefreshExports, console */
3 wp.customize.selectiveRefresh = ( function( $, api ) {
5 var self, Partial, Placement;
20 _.extend( self, api.Events );
23 * A Customizer Partial.
25 * A partial provides a rendering of one or more settings according to a template.
27 * @see PHP class WP_Customize_Partial.
30 * @augments wp.customize.Class
33 * @param {string} id Unique identifier for the control instance.
34 * @param {object} options Options hash for the control instance.
35 * @param {object} options.params
36 * @param {string} options.params.type Type of partial (e.g. nav_menu, widget, etc)
37 * @param {string} options.params.selector jQuery selector to find the container element in the page.
38 * @param {array} options.params.settings The IDs for the settings the partial relates to.
39 * @param {string} options.params.primarySetting The ID for the primary setting the partial renders.
40 * @param {bool} options.params.fallbackRefresh Whether to refresh the entire preview in case of a partial refresh failure.
42 Partial = self.Partial = api.Class.extend({
51 * @param {string} id - Partial ID.
52 * @param {Object} options
53 * @param {Object} options.params
55 initialize: function( id, options ) {
57 options = options || {};
60 partial.params = _.extend(
65 containerInclusive: false,
66 fallbackRefresh: true // Note this needs to be false in a front-end editing context.
71 partial.deferred = {};
72 partial.deferred.ready = $.Deferred();
74 partial.deferred.ready.done( function() {
86 _.each( _.pluck( partial.placements(), 'container' ), function( container ) {
87 $( container ).attr( 'title', self.data.l10n.shiftClickToEdit );
89 $( document ).on( 'click', partial.params.selector, function( e ) {
94 _.each( partial.placements(), function( placement ) {
95 if ( $( placement.container ).is( e.currentTarget ) ) {
96 partial.showControl();
103 * Find all placements for this partial int he document.
107 * @return {Array.<Placement>}
109 placements: function() {
110 var partial = this, selector;
112 selector = partial.params.selector || '';
116 selector += '[data-customize-partial-id="' + partial.id + '"]'; // @todo Consider injecting customize-partial-id-${id} classnames instead.
118 return $( selector ).map( function() {
119 var container = $( this ), context;
121 context = container.data( 'customize-partial-placement-context' );
122 if ( _.isString( context ) && '{' === context.substr( 0, 1 ) ) {
123 throw new Error( 'context JSON parse error' );
126 return new Placement( {
128 container: container,
135 * Get list of setting IDs related to this partial.
141 settings: function() {
143 if ( partial.params.settings && 0 !== partial.params.settings.length ) {
144 return partial.params.settings;
145 } else if ( partial.params.primarySetting ) {
146 return [ partial.params.primarySetting ];
148 return [ partial.id ];
153 * Return whether the setting is related to the partial.
157 * @param {wp.customize.Value|string} setting ID or object for setting.
158 * @return {boolean} Whether the setting is related to the partial.
160 isRelatedSetting: function( setting /*... newValue, oldValue */ ) {
162 if ( _.isString( setting ) ) {
163 setting = api( setting );
168 return -1 !== _.indexOf( partial.settings(), setting.id );
172 * Show the control to modify this partial's setting(s).
174 * This may be overridden for inline editing.
178 showControl: function() {
179 var partial = this, settingId = partial.params.primarySetting;
181 settingId = _.first( partial.settings() );
183 api.preview.send( 'focus-control-for-setting', settingId );
187 * Prepare container for selective refresh.
191 * @param {Placement} placement
193 preparePlacement: function( placement ) {
194 $( placement.container ).addClass( 'customize-partial-refreshing' );
198 * Reference to the pending promise returned from self.requestPartial().
203 _pendingRefreshPromise: null,
206 * Request the new partial and render it into the placements.
210 * @this {wp.customize.selectiveRefresh.Partial}
211 * @return {jQuery.Promise}
213 refresh: function() {
214 var partial = this, refreshPromise;
216 refreshPromise = self.requestPartial( partial );
218 if ( ! partial._pendingRefreshPromise ) {
219 _.each( partial.placements(), function( placement ) {
220 partial.preparePlacement( placement );
223 refreshPromise.done( function( placements ) {
224 _.each( placements, function( placement ) {
225 partial.renderContent( placement );
229 refreshPromise.fail( function( data, placements ) {
230 partial.fallback( data, placements );
233 // Allow new request when this one finishes.
234 partial._pendingRefreshPromise = refreshPromise;
235 refreshPromise.always( function() {
236 partial._pendingRefreshPromise = null;
240 return refreshPromise;
244 * Apply the addedContent in the placement to the document.
246 * Note the placement object will have its container and removedNodes
247 * properties updated.
251 * @param {Placement} placement
252 * @param {Element|jQuery} [placement.container] - This param will be empty if there was no element matching the selector.
253 * @param {string|object|boolean} placement.addedContent - Rendered HTML content, a data object for JS templates to render, or false if no render.
254 * @param {object} [placement.context] - Optional context information about the container.
255 * @returns {boolean} Whether the rendering was successful and the fallback was not invoked.
257 renderContent: function( placement ) {
258 var partial = this, content, newContainerElement;
259 if ( ! placement.container ) {
260 partial.fallback( new Error( 'no_container' ), [ placement ] );
263 placement.container = $( placement.container );
264 if ( false === placement.addedContent ) {
265 partial.fallback( new Error( 'missing_render' ), [ placement ] );
269 // Currently a subclass needs to override renderContent to handle partials returning data object.
270 if ( ! _.isString( placement.addedContent ) ) {
271 partial.fallback( new Error( 'non_string_content' ), [ placement ] );
275 /* jshint ignore:start */
276 self.orginalDocumentWrite = document.write;
277 document.write = function() {
278 throw new Error( self.data.l10n.badDocumentWrite );
280 /* jshint ignore:end */
282 content = placement.addedContent;
283 if ( wp.emoji && wp.emoji.parse && ! $.contains( document.head, placement.container[0] ) ) {
284 content = wp.emoji.parse( content );
287 if ( partial.params.containerInclusive ) {
289 // Note that content may be an empty string, and in this case jQuery will just remove the oldContainer
290 newContainerElement = $( content );
292 // Merge the new context on top of the old context.
293 placement.context = _.extend(
295 newContainerElement.data( 'customize-partial-placement-context' ) || {}
297 newContainerElement.data( 'customize-partial-placement-context', placement.context );
299 placement.removedNodes = placement.container;
300 placement.container = newContainerElement;
301 placement.removedNodes.replaceWith( placement.container );
302 placement.container.attr( 'title', self.data.l10n.shiftClickToEdit );
304 placement.removedNodes = document.createDocumentFragment();
305 while ( placement.container[0].firstChild ) {
306 placement.removedNodes.appendChild( placement.container[0].firstChild );
309 placement.container.html( content );
312 placement.container.removeClass( 'customize-render-content-error' );
314 if ( 'undefined' !== typeof console && console.error ) {
315 console.error( partial.id, error );
318 /* jshint ignore:start */
319 document.write = self.orginalDocumentWrite;
320 self.orginalDocumentWrite = null;
321 /* jshint ignore:end */
323 placement.container.removeClass( 'customize-partial-refreshing' );
325 // Prevent placement container from being being re-triggered as being rendered among nested partials.
326 placement.container.data( 'customize-partial-content-rendered', true );
329 * Announce when a partial's placement has been rendered so that dynamic elements can be re-built.
331 self.trigger( 'partial-content-rendered', placement );
336 * Handle fail to render partial.
338 * The first argument is either the failing jqXHR or an Error object, and the second argument is the array of containers.
342 fallback: function() {
344 if ( partial.params.fallbackRefresh ) {
345 self.requestFullRefresh();
351 * A Placement for a Partial.
353 * A partial placement is the actual physical representation of a partial for a given context.
354 * It also may have information in relation to how a placement may have just changed.
355 * The placement is conceptually similar to a DOM Range or MutationRecord.
358 * @augments wp.customize.Class
361 self.Placement = Placement = api.Class.extend({
364 * The partial with which the container is associated.
366 * @param {wp.customize.selectiveRefresh.Partial}
371 * DOM element which contains the placement's contents.
373 * This will be null if the startNode and endNode do not point to the same
374 * DOM element, such as in the case of a sidebar partial.
375 * This container element itself will be replaced for partials that
376 * have containerInclusive param defined as true.
381 * DOM node for the initial boundary of the placement.
383 * This will normally be the same as endNode since most placements appear as elements.
384 * This is primarily useful for widget sidebars which do not have intrinsic containers, but
385 * for which an HTML comment is output before to mark the starting position.
390 * DOM node for the terminal boundary of the placement.
392 * This will normally be the same as startNode since most placements appear as elements.
393 * This is primarily useful for widget sidebars which do not have intrinsic containers, but
394 * for which an HTML comment is output before to mark the ending position.
401 * This provides information about the placement which is included in the request
402 * in order to render the partial properly.
409 * The content for the partial when refreshed.
416 * DOM node(s) removed when the partial is refreshed.
418 * If the partial is containerInclusive, then the removedNodes will be
419 * the single Element that was the partial's former placement. If the
420 * partial is not containerInclusive, then the removedNodes will be a
421 * documentFragment containing the nodes removed.
423 * @param {Element|DocumentFragment}
432 * @param {object} args
433 * @param {Partial} args.partial
434 * @param {jQuery|Element} [args.container]
435 * @param {Node} [args.startNode]
436 * @param {Node} [args.endNode]
437 * @param {object} [args.context]
438 * @param {string} [args.addedContent]
439 * @param {jQuery|DocumentFragment} [args.removedNodes]
441 initialize: function( args ) {
442 var placement = this;
444 args = _.extend( {}, args || {} );
445 if ( ! args.partial || ! args.partial.extended( Partial ) ) {
446 throw new Error( 'Missing partial' );
448 args.context = args.context || {};
449 if ( args.container ) {
450 args.container = $( args.container );
453 _.extend( placement, args );
459 * Mapping of type names to Partial constructor subclasses.
463 * @type {Object.<string, wp.customize.selectiveRefresh.Partial>}
465 self.partialConstructor = {};
467 self.partial = new api.Values({ defaultConstructor: Partial });
470 * Get the POST vars for a Customizer preview request.
473 * @see wp.customize.previewer.query()
477 self.getCustomizeQuery = function() {
478 var dirtyCustomized = {};
479 api.each( function( value, key ) {
480 if ( value._dirty ) {
481 dirtyCustomized[ key ] = value();
487 nonce: api.settings.nonce.preview,
488 theme: api.settings.theme.stylesheet,
489 customized: JSON.stringify( dirtyCustomized )
494 * Currently-requested partials and their associated deferreds.
497 * @type {Object<string, { deferred: jQuery.Promise, partial: wp.customize.selectiveRefresh.Partial }>}
499 self._pendingPartialRequests = {};
502 * Timeout ID for the current requesr, or null if no request is current.
505 * @type {number|null}
508 self._debouncedTimeoutId = null;
511 * Current jqXHR for the request to the partials.
514 * @type {jQuery.jqXHR|null}
517 self._currentRequest = null;
520 * Request full page refresh.
522 * When selective refresh is embedded in the context of front-end editing, this request
523 * must fail or else changes will be lost, unless transactions are implemented.
527 self.requestFullRefresh = function() {
528 api.preview.send( 'refresh' );
532 * Request a re-rendering of a partial.
536 * @param {wp.customize.selectiveRefresh.Partial} partial
537 * @return {jQuery.Promise}
539 self.requestPartial = function( partial ) {
542 if ( self._debouncedTimeoutId ) {
543 clearTimeout( self._debouncedTimeoutId );
544 self._debouncedTimeoutId = null;
546 if ( self._currentRequest ) {
547 self._currentRequest.abort();
548 self._currentRequest = null;
551 partialRequest = self._pendingPartialRequests[ partial.id ];
552 if ( ! partialRequest || 'pending' !== partialRequest.deferred.state() ) {
554 deferred: $.Deferred(),
557 self._pendingPartialRequests[ partial.id ] = partialRequest;
560 // Prevent leaking partial into debounced timeout callback.
563 self._debouncedTimeoutId = setTimeout(
565 var data, partialPlacementContexts, partialsPlacements, request;
567 self._debouncedTimeoutId = null;
568 data = self.getCustomizeQuery();
571 * It is key that the containers be fetched exactly at the point of the request being
572 * made, because the containers need to be mapped to responses by array indices.
574 partialsPlacements = {};
576 partialPlacementContexts = {};
578 _.each( self._pendingPartialRequests, function( pending, partialId ) {
579 partialsPlacements[ partialId ] = pending.partial.placements();
580 if ( ! self.partial.has( partialId ) ) {
581 pending.deferred.rejectWith( pending.partial, [ new Error( 'partial_removed' ), partialsPlacements[ partialId ] ] );
584 * Note that this may in fact be an empty array. In that case, it is the responsibility
585 * of the Partial subclass instance to know where to inject the response, or else to
586 * just issue a refresh (default behavior). The data being returned with each container
587 * is the context information that may be needed to render certain partials, such as
588 * the contained sidebar for rendering widgets or what the nav menu args are for a menu.
590 partialPlacementContexts[ partialId ] = _.map( partialsPlacements[ partialId ], function( placement ) {
591 return placement.context || {};
596 data.partials = JSON.stringify( partialPlacementContexts );
597 data[ self.data.renderQueryVar ] = '1';
599 request = self._currentRequest = wp.ajax.send( null, {
601 url: api.settings.url.self
604 request.done( function( data ) {
607 * Announce the data returned from a request to render partials.
609 * The data is filtered on the server via customize_render_partials_response
610 * so plugins can inject data from the server to be utilized
611 * on the client via this event. Plugins may use this filter
612 * to communicate script and style dependencies that need to get
613 * injected into the page to support the rendered partials.
614 * This is similar to the 'saved' event.
616 self.trigger( 'render-partials-response', data );
618 // Relay errors (warnings) captured during rendering and relay to console.
619 if ( data.errors && 'undefined' !== typeof console && console.warn ) {
620 _.each( data.errors, function( error ) {
621 console.warn( error );
626 * Note that data is an array of items that correspond to the array of
627 * containers that were submitted in the request. So we zip up the
628 * array of containers with the array of contents for those containers,
629 * and send them into .
631 _.each( self._pendingPartialRequests, function( pending, partialId ) {
632 var placementsContents;
633 if ( ! _.isArray( data.contents[ partialId ] ) ) {
634 pending.deferred.rejectWith( pending.partial, [ new Error( 'unrecognized_partial' ), partialsPlacements[ partialId ] ] );
636 placementsContents = _.map( data.contents[ partialId ], function( content, i ) {
637 var partialPlacement = partialsPlacements[ partialId ][ i ];
638 if ( partialPlacement ) {
639 partialPlacement.addedContent = content;
641 partialPlacement = new Placement( {
642 partial: pending.partial,
643 addedContent: content
646 return partialPlacement;
648 pending.deferred.resolveWith( pending.partial, [ placementsContents ] );
651 self._pendingPartialRequests = {};
654 request.fail( function( data, statusText ) {
657 * Ignore failures caused by partial.currentRequest.abort()
658 * The pending deferreds will remain in self._pendingPartialRequests
659 * for re-use with the next request.
661 if ( 'abort' === statusText ) {
665 _.each( self._pendingPartialRequests, function( pending, partialId ) {
666 pending.deferred.rejectWith( pending.partial, [ data, partialsPlacements[ partialId ] ] );
668 self._pendingPartialRequests = {};
671 self.data.refreshBuffer
674 return partialRequest.deferred.promise();
678 * Add partials for any nav menu container elements in the document.
680 * This method may be called multiple times. Containers that already have been
681 * seen will be skipped.
685 * @param {jQuery|HTMLElement} [rootElement]
686 * @param {object} [options]
687 * @param {boolean=true} [options.triggerRendered]
689 self.addPartials = function( rootElement, options ) {
690 var containerElements;
691 if ( ! rootElement ) {
692 rootElement = document.documentElement;
694 rootElement = $( rootElement );
697 triggerRendered: true
702 containerElements = rootElement.find( '[data-customize-partial-id]' );
703 if ( rootElement.is( '[data-customize-partial-id]' ) ) {
704 containerElements = containerElements.add( rootElement );
706 containerElements.each( function() {
707 var containerElement = $( this ), partial, id, Constructor, partialOptions, containerContext;
708 id = containerElement.data( 'customize-partial-id' );
712 containerContext = containerElement.data( 'customize-partial-placement-context' ) || {};
714 partial = self.partial( id );
716 partialOptions = containerElement.data( 'customize-partial-options' ) || {};
717 partialOptions.constructingContainerContext = containerElement.data( 'customize-partial-placement-context' ) || {};
718 Constructor = self.partialConstructor[ containerElement.data( 'customize-partial-type' ) ] || self.Partial;
719 partial = new Constructor( id, partialOptions );
720 self.partial.add( partial.id, partial );
724 * Only trigger renders on (nested) partials that have been not been
725 * handled yet. An example where this would apply is a nav menu
726 * embedded inside of a custom menu widget. When the widget's title
727 * is updated, the entire widget will re-render and then the event
728 * will be triggered for the nested nav menu to do any initialization.
730 if ( options.triggerRendered && ! containerElement.data( 'customize-partial-content-rendered' ) ) {
733 * Announce when a partial's nested placement has been re-rendered.
735 self.trigger( 'partial-content-rendered', new Placement( {
737 context: containerContext,
738 container: containerElement
741 containerElement.data( 'customize-partial-content-rendered', true );
745 api.bind( 'preview-ready', function() {
746 var handleSettingChange, watchSettingChange, unwatchSettingChange;
748 // Polyfill for IE8 to support the document.head attribute.
749 if ( ! document.head ) {
750 document.head = $( 'head:first' )[0];
753 _.extend( self.data, _customizePartialRefreshExports );
755 // Create the partial JS models.
756 _.each( self.data.partials, function( data, id ) {
757 var Constructor, partial = self.partial( id );
759 Constructor = self.partialConstructor[ data.type ] || self.Partial;
760 partial = new Constructor( id, { params: data } );
761 self.partial.add( id, partial );
763 _.extend( partial.params, data );
768 * Handle change to a setting.
770 * Note this is largely needed because adding a 'change' event handler to wp.customize
771 * will only include the changed setting object as an argument, not including the
772 * new value or the old value.
775 * @this {wp.customize.Setting}
777 * @param {*|null} newValue New value, or null if the setting was just removed.
778 * @param {*|null} oldValue Old value, or null if the setting was just added.
780 handleSettingChange = function( newValue, oldValue ) {
782 self.partial.each( function( partial ) {
783 if ( partial.isRelatedSetting( setting, newValue, oldValue ) ) {
790 * Trigger the initial change for the added setting, and watch for changes.
793 * @this {wp.customize.Values}
795 * @param {wp.customize.Setting} setting
797 watchSettingChange = function( setting ) {
798 handleSettingChange.call( setting, setting(), null );
799 setting.bind( handleSettingChange );
803 * Trigger the final change for the removed setting, and unwatch for changes.
806 * @this {wp.customize.Values}
808 * @param {wp.customize.Setting} setting
810 unwatchSettingChange = function( setting ) {
811 handleSettingChange.call( setting, null, setting() );
812 setting.unbind( handleSettingChange );
815 api.bind( 'add', watchSettingChange );
816 api.bind( 'remove', unwatchSettingChange );
817 api.each( function( setting ) {
818 setting.bind( handleSettingChange );
821 // Add (dynamic) initial partials that are declared via data-* attributes.
822 self.addPartials( document.documentElement, {
823 triggerRendered: false
826 // Add new dynamic partials when the document changes.
827 if ( 'undefined' !== typeof MutationObserver ) {
828 self.mutationObserver = new MutationObserver( function( mutations ) {
829 _.each( mutations, function( mutation ) {
830 self.addPartials( $( mutation.target ) );
833 self.mutationObserver.observe( document.documentElement, {
840 * Handle rendering of partials.
842 * @param {api.selectiveRefresh.Placement} placement
844 api.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {
845 if ( placement.container ) {
846 self.addPartials( placement.container );
851 * Handle setting validities in partial refresh response.
853 * @param {object} data Response data.
854 * @param {object} data.setting_validities Setting validities.
856 api.selectiveRefresh.bind( 'render-partials-response', function handleSettingValiditiesResponse( data ) {
857 if ( data.setting_validities ) {
858 api.preview.send( 'selective-refresh-setting-validities', data.setting_validities );
862 api.preview.bind( 'active', function() {
864 // Make all partials ready.
865 self.partial.each( function( partial ) {
866 partial.deferred.ready.resolve();
869 // Make all partials added henceforth as ready upon add.
870 self.partial.bind( 'add', function( partial ) {
871 partial.deferred.ready.resolve();
878 }( jQuery, wp.customize ) );