1 /* global _wpWidgetCustomizerPreviewSettings */
2 wp.customize.widgetsPreview = wp.customize.WidgetCustomizerPreview = (function( $, _, wp, api ) {
9 registeredSidebars: [],
10 registeredWidgets: {},
16 selectiveRefreshableWidgets: {}
20 * Init widgets preview.
24 self.init = function() {
27 self.preview = api.preview;
28 if ( ! _.isEmpty( self.selectiveRefreshableWidgets ) ) {
32 self.buildWidgetSelectors();
33 self.highlightControls();
35 self.preview.bind( 'highlight-widget', self.highlightWidget );
37 api.preview.bind( 'active', function() {
38 self.highlightControls();
43 * Partial representing a widget instance.
46 * @augments wp.customize.selectiveRefresh.Partial
49 self.WidgetPartial = api.selectiveRefresh.Partial.extend({
55 * @param {string} id - Partial ID.
56 * @param {Object} options
57 * @param {Object} options.params
59 initialize: function( id, options ) {
60 var partial = this, matches;
61 matches = id.match( /^widget\[(.+)]$/ );
63 throw new Error( 'Illegal id for widget partial.' );
66 partial.widgetId = matches[1];
67 partial.widgetIdParts = self.parseWidgetId( partial.widgetId );
68 options = options || {};
69 options.params = _.extend(
71 settings: [ self.getWidgetSettingId( partial.widgetId ) ],
72 containerInclusive: true
77 api.selectiveRefresh.Partial.prototype.initialize.call( partial, id, options );
81 * Refresh widget partial.
86 var partial = this, refreshDeferred;
87 if ( ! self.selectiveRefreshableWidgets[ partial.widgetIdParts.idBase ] ) {
88 refreshDeferred = $.Deferred();
89 refreshDeferred.reject();
91 return refreshDeferred.promise();
93 return api.selectiveRefresh.Partial.prototype.refresh.call( partial );
98 * Send widget-updated message to parent so spinner will get removed from widget control.
101 * @param {wp.customize.selectiveRefresh.Placement} placement
103 renderContent: function( placement ) {
105 if ( api.selectiveRefresh.Partial.prototype.renderContent.call( partial, placement ) ) {
106 api.preview.send( 'widget-updated', partial.widgetId );
107 api.selectiveRefresh.trigger( 'widget-updated', partial );
113 * Partial representing a widget area.
116 * @augments wp.customize.selectiveRefresh.Partial
119 self.SidebarPartial = api.selectiveRefresh.Partial.extend({
125 * @param {string} id - Partial ID.
126 * @param {Object} options
127 * @param {Object} options.params
129 initialize: function( id, options ) {
130 var partial = this, matches;
131 matches = id.match( /^sidebar\[(.+)]$/ );
133 throw new Error( 'Illegal id for sidebar partial.' );
135 partial.sidebarId = matches[1];
137 options = options || {};
138 options.params = _.extend(
140 settings: [ 'sidebars_widgets[' + partial.sidebarId + ']' ]
145 api.selectiveRefresh.Partial.prototype.initialize.call( partial, id, options );
147 if ( ! partial.params.sidebarArgs ) {
148 throw new Error( 'The sidebarArgs param was not provided.' );
150 if ( partial.params.settings.length > 1 ) {
151 throw new Error( 'Expected SidebarPartial to only have one associated setting' );
156 * Set up the partial.
161 var sidebarPartial = this;
163 // Watch for changes to the sidebar_widgets setting.
164 _.each( sidebarPartial.settings(), function( settingId ) {
165 api( settingId ).bind( _.bind( sidebarPartial.handleSettingChange, sidebarPartial ) );
168 // Trigger an event for this sidebar being updated whenever a widget inside is rendered.
169 api.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {
170 var isAssignedWidgetPartial = (
171 placement.partial.extended( self.WidgetPartial ) &&
172 ( -1 !== _.indexOf( sidebarPartial.getWidgetIds(), placement.partial.widgetId ) )
174 if ( isAssignedWidgetPartial ) {
175 api.selectiveRefresh.trigger( 'sidebar-updated', sidebarPartial );
179 // Make sure that a widget partial has a container in the DOM prior to a refresh.
180 api.bind( 'change', function( widgetSetting ) {
181 var widgetId, parsedId;
182 parsedId = self.parseWidgetSettingId( widgetSetting.id );
186 widgetId = parsedId.idBase;
187 if ( parsedId.number ) {
188 widgetId += '-' + String( parsedId.number );
190 if ( -1 !== _.indexOf( sidebarPartial.getWidgetIds(), widgetId ) ) {
191 sidebarPartial.ensureWidgetPlacementContainers( widgetId );
197 * Get the before/after boundary nodes for all instances of this sidebar (usually one).
199 * Note that TreeWalker is not implemented in IE8.
202 * @returns {Array.<{before: Comment, after: Comment, instanceNumber: number}>}
204 findDynamicSidebarBoundaryNodes: function() {
205 var partial = this, regExp, boundaryNodes = {}, recursiveCommentTraversal;
206 regExp = /^(dynamic_sidebar_before|dynamic_sidebar_after):(.+):(\d+)$/;
207 recursiveCommentTraversal = function( childNodes ) {
208 _.each( childNodes, function( node ) {
210 if ( 8 === node.nodeType ) {
211 matches = node.nodeValue.match( regExp );
212 if ( ! matches || matches[2] !== partial.sidebarId ) {
215 if ( _.isUndefined( boundaryNodes[ matches[3] ] ) ) {
216 boundaryNodes[ matches[3] ] = {
219 instanceNumber: parseInt( matches[3], 10 )
222 if ( 'dynamic_sidebar_before' === matches[1] ) {
223 boundaryNodes[ matches[3] ].before = node;
225 boundaryNodes[ matches[3] ].after = node;
227 } else if ( 1 === node.nodeType ) {
228 recursiveCommentTraversal( node.childNodes );
233 recursiveCommentTraversal( document.body.childNodes );
234 return _.values( boundaryNodes );
238 * Get the placements for this partial.
243 placements: function() {
245 return _.map( partial.findDynamicSidebarBoundaryNodes(), function( boundaryNodes ) {
246 return new api.selectiveRefresh.Placement( {
249 startNode: boundaryNodes.before,
250 endNode: boundaryNodes.after,
252 instanceNumber: boundaryNodes.instanceNumber
259 * Get the list of widget IDs associated with this widget area.
265 getWidgetIds: function() {
266 var sidebarPartial = this, settingId, widgetIds;
267 settingId = sidebarPartial.settings()[0];
269 throw new Error( 'Missing associated setting.' );
271 if ( ! api.has( settingId ) ) {
272 throw new Error( 'Setting does not exist.' );
274 widgetIds = api( settingId ).get();
275 if ( ! _.isArray( widgetIds ) ) {
276 throw new Error( 'Expected setting to be array of widget IDs' );
278 return widgetIds.slice( 0 );
282 * Reflow widgets in the sidebar, ensuring they have the proper position in the DOM.
286 * @return {Array.<wp.customize.selectiveRefresh.Placement>} List of placements that were reflowed.
288 reflowWidgets: function() {
289 var sidebarPartial = this, sidebarPlacements, widgetIds, widgetPartials, sortedSidebarContainers = [];
290 widgetIds = sidebarPartial.getWidgetIds();
291 sidebarPlacements = sidebarPartial.placements();
294 _.each( widgetIds, function( widgetId ) {
295 var widgetPartial = api.selectiveRefresh.partial( 'widget[' + widgetId + ']' );
296 if ( widgetPartial ) {
297 widgetPartials[ widgetId ] = widgetPartial;
301 _.each( sidebarPlacements, function( sidebarPlacement ) {
302 var sidebarWidgets = [], needsSort = false, thisPosition, lastPosition = -1;
304 // Gather list of widget partial containers in this sidebar, and determine if a sort is needed.
305 _.each( widgetPartials, function( widgetPartial ) {
306 _.each( widgetPartial.placements(), function( widgetPlacement ) {
308 if ( sidebarPlacement.context.instanceNumber === widgetPlacement.context.sidebar_instance_number ) {
309 thisPosition = widgetPlacement.container.index();
310 sidebarWidgets.push( {
311 partial: widgetPartial,
312 placement: widgetPlacement,
313 position: thisPosition
315 if ( thisPosition < lastPosition ) {
318 lastPosition = thisPosition;
324 _.each( sidebarWidgets, function( sidebarWidget ) {
325 sidebarPlacement.endNode.parentNode.insertBefore(
326 sidebarWidget.placement.container[0],
327 sidebarPlacement.endNode
330 // @todo Rename partial-placement-moved?
331 api.selectiveRefresh.trigger( 'partial-content-moved', sidebarWidget.placement );
334 sortedSidebarContainers.push( sidebarPlacement );
338 if ( sortedSidebarContainers.length > 0 ) {
339 api.selectiveRefresh.trigger( 'sidebar-updated', sidebarPartial );
342 return sortedSidebarContainers;
346 * Make sure there is a widget instance container in this sidebar for the given widget ID.
350 * @param {string} widgetId
351 * @returns {wp.customize.selectiveRefresh.Partial} Widget instance partial.
353 ensureWidgetPlacementContainers: function( widgetId ) {
354 var sidebarPartial = this, widgetPartial, wasInserted = false, partialId = 'widget[' + widgetId + ']';
355 widgetPartial = api.selectiveRefresh.partial( partialId );
356 if ( ! widgetPartial ) {
357 widgetPartial = new self.WidgetPartial( partialId, {
360 api.selectiveRefresh.partial.add( widgetPartial.id, widgetPartial );
363 // Make sure that there is a container element for the widget in the sidebar, if at least a placeholder.
364 _.each( sidebarPartial.placements(), function( sidebarPlacement ) {
365 var foundWidgetPlacement, widgetContainerElement;
367 foundWidgetPlacement = _.find( widgetPartial.placements(), function( widgetPlacement ) {
368 return ( widgetPlacement.context.sidebar_instance_number === sidebarPlacement.context.instanceNumber );
370 if ( foundWidgetPlacement ) {
374 widgetContainerElement = $(
375 sidebarPartial.params.sidebarArgs.before_widget.replace( '%1$s', widgetId ).replace( '%2$s', 'widget' ) +
376 sidebarPartial.params.sidebarArgs.after_widget
379 widgetContainerElement.attr( 'data-customize-partial-id', widgetPartial.id );
380 widgetContainerElement.attr( 'data-customize-partial-type', 'widget' );
381 widgetContainerElement.attr( 'data-customize-widget-id', widgetId );
384 * Make sure the widget container element has the customize-container context data.
385 * The sidebar_instance_number is used to disambiguate multiple instances of the
386 * same sidebar are rendered onto the template, and so the same widget is embedded
389 widgetContainerElement.data( 'customize-partial-placement-context', {
390 'sidebar_id': sidebarPartial.sidebarId,
391 'sidebar_instance_number': sidebarPlacement.context.instanceNumber
394 sidebarPlacement.endNode.parentNode.insertBefore( widgetContainerElement[0], sidebarPlacement.endNode );
399 sidebarPartial.reflowWidgets();
402 return widgetPartial;
406 * Handle change to the sidebars_widgets[] setting.
410 * @param {Array} newWidgetIds New widget ids.
411 * @param {Array} oldWidgetIds Old widget ids.
413 handleSettingChange: function( newWidgetIds, oldWidgetIds ) {
414 var sidebarPartial = this, needsRefresh, widgetsRemoved, widgetsAdded, addedWidgetPartials = [];
417 ( oldWidgetIds.length > 0 && 0 === newWidgetIds.length ) ||
418 ( newWidgetIds.length > 0 && 0 === oldWidgetIds.length )
420 if ( needsRefresh ) {
421 sidebarPartial.fallback();
425 // Handle removal of widgets.
426 widgetsRemoved = _.difference( oldWidgetIds, newWidgetIds );
427 _.each( widgetsRemoved, function( removedWidgetId ) {
428 var widgetPartial = api.selectiveRefresh.partial( 'widget[' + removedWidgetId + ']' );
429 if ( widgetPartial ) {
430 _.each( widgetPartial.placements(), function( placement ) {
432 placement.context.sidebar_id === sidebarPartial.sidebarId ||
433 ( placement.context.sidebar_args && placement.context.sidebar_args.id === sidebarPartial.sidebarId )
436 placement.container.remove();
442 // Handle insertion of widgets.
443 widgetsAdded = _.difference( newWidgetIds, oldWidgetIds );
444 _.each( widgetsAdded, function( addedWidgetId ) {
445 var widgetPartial = sidebarPartial.ensureWidgetPlacementContainers( addedWidgetId );
446 addedWidgetPartials.push( widgetPartial );
449 _.each( addedWidgetPartials, function( widgetPartial ) {
450 widgetPartial.refresh();
453 api.selectiveRefresh.trigger( 'sidebar-updated', sidebarPartial );
457 * Note that the meat is handled in handleSettingChange because it has the context of which widgets were removed.
461 refresh: function() {
462 var partial = this, deferred = $.Deferred();
464 deferred.fail( function() {
468 if ( 0 === partial.placements().length ) {
471 _.each( partial.reflowWidgets(), function( sidebarPlacement ) {
472 api.selectiveRefresh.trigger( 'partial-content-rendered', sidebarPlacement );
477 return deferred.promise();
481 api.selectiveRefresh.partialConstructor.sidebar = self.SidebarPartial;
482 api.selectiveRefresh.partialConstructor.widget = self.WidgetPartial;
485 * Add partials for the registered widget areas (sidebars).
489 self.addPartials = function() {
490 _.each( self.registeredSidebars, function( registeredSidebar ) {
491 var partial, partialId = 'sidebar[' + registeredSidebar.id + ']';
492 partial = api.selectiveRefresh.partial( partialId );
494 partial = new self.SidebarPartial( partialId, {
496 sidebarArgs: registeredSidebar
499 api.selectiveRefresh.partial.add( partial.id, partial );
505 * Calculate the selector for the sidebar's widgets based on the registered sidebar's info.
509 self.buildWidgetSelectors = function() {
512 $.each( self.registeredSidebars, function( i, sidebar ) {
514 sidebar.before_widget.replace( '%1$s', '' ).replace( '%2$s', '' ),
515 sidebar.before_title,
523 emptyWidget = $( widgetTpl );
524 widgetSelector = emptyWidget.prop( 'tagName' );
525 widgetClasses = emptyWidget.prop( 'className' );
527 // Prevent a rare case when before_widget, before_title, after_title and after_widget is empty.
528 if ( ! widgetClasses ) {
532 widgetClasses = widgetClasses.replace( /^\s+|\s+$/g, '' );
534 if ( widgetClasses ) {
535 widgetSelector += '.' + widgetClasses.split( /\s+/ ).join( '.' );
537 self.widgetSelectors.push( widgetSelector );
542 * Highlight the widget on widget updates or widget control mouse overs.
545 * @param {string} widgetId ID of the widget.
547 self.highlightWidget = function( widgetId ) {
548 var $body = $( document.body ),
549 $widget = $( '#' + widgetId );
551 $body.find( '.widget-customizer-highlighted-widget' ).removeClass( 'widget-customizer-highlighted-widget' );
553 $widget.addClass( 'widget-customizer-highlighted-widget' );
554 setTimeout( function() {
555 $widget.removeClass( 'widget-customizer-highlighted-widget' );
560 * Show a title and highlight widgets on hover. On shift+clicking
561 * focus the widget control.
565 self.highlightControls = function() {
567 selector = this.widgetSelectors.join( ',' );
569 $( selector ).attr( 'title', this.l10n.widgetTooltip );
571 $( document ).on( 'mouseenter', selector, function() {
572 self.preview.send( 'highlight-widget-control', $( this ).prop( 'id' ) );
575 // Open expand the widget control when shift+clicking the widget element
576 $( document ).on( 'click', selector, function( e ) {
577 if ( ! e.shiftKey ) {
582 self.preview.send( 'focus-widget-control', $( this ).prop( 'id' ) );
591 * @param {string} widgetId Widget ID.
592 * @returns {{idBase: string, number: number|null}}
594 self.parseWidgetId = function( widgetId ) {
595 var matches, parsed = {
600 matches = widgetId.match( /^(.+)-(\d+)$/ );
602 parsed.idBase = matches[1];
603 parsed.number = parseInt( matches[2], 10 );
605 parsed.idBase = widgetId; // Likely an old single widget.
612 * Parse a widget setting ID.
616 * @param {string} settingId Widget setting ID.
617 * @returns {{idBase: string, number: number|null}|null}
619 self.parseWidgetSettingId = function( settingId ) {
620 var matches, parsed = {
625 matches = settingId.match( /^widget_([^\[]+?)(?:\[(\d+)])?$/ );
629 parsed.idBase = matches[1];
631 parsed.number = parseInt( matches[2], 10 );
637 * Convert a widget ID into a Customizer setting ID.
641 * @param {string} widgetId Widget ID.
642 * @returns {string} settingId Setting ID.
644 self.getWidgetSettingId = function( widgetId ) {
645 var parsed = this.parseWidgetId( widgetId ), settingId;
647 settingId = 'widget_' + parsed.idBase;
648 if ( parsed.number ) {
649 settingId += '[' + String( parsed.number ) + ']';
655 api.bind( 'preview-ready', function() {
656 $.extend( self, _wpWidgetCustomizerPreviewSettings );
661 })( jQuery, _, wp, wp.customize );