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