1 /* global _wpCustomizeWidgetsSettings */
4 if ( ! wp || ! wp.customize ) { return; }
6 // Set up our namespace...
7 var api = wp.customize,
10 api.Widgets = api.Widgets || {};
13 api.Widgets.data = _wpCustomizeWidgetsSettings || {};
14 l10n = api.Widgets.data.l10n;
15 delete api.Widgets.data.l10n;
18 * wp.customize.Widgets.WidgetModel
20 * A single widget model.
23 * @augments Backbone.Model
25 api.Widgets.WidgetModel = Backbone.Model.extend({
44 * wp.customize.Widgets.WidgetCollection
46 * Collection for widget models.
49 * @augments Backbone.Model
51 api.Widgets.WidgetCollection = Backbone.Collection.extend({
52 model: api.Widgets.WidgetModel,
54 // Controls searching on the current widget collection
55 // and triggers an update event
56 doSearch: function( value ) {
58 // Don't do anything if we've already done this search
59 // Useful because the search handler fires multiple times per keystroke
60 if ( this.terms === value ) {
64 // Updates terms with the value passed
67 // If we have terms, run a search...
68 if ( this.terms.length > 0 ) {
69 this.search( this.terms );
72 // If search is blank, show all themes
73 // Useful for resetting the views when you clean the input
74 if ( this.terms === '' ) {
75 this.each( function ( widget ) {
76 widget.set( 'search_matched', true );
81 // Performs a search within the collection
83 search: function( term ) {
86 // Escape the term string for RegExp meta characters
87 term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
89 // Consider spaces as word delimiters and match the whole string
90 // so matching terms can be combined
91 term = term.replace( / /g, ')(?=.*' );
92 match = new RegExp( '^(?=.*' + term + ').+', 'i' );
94 this.each( function ( data ) {
95 haystack = [ data.get( 'name' ), data.get( 'id' ), data.get( 'description' ) ].join( ' ' );
96 data.set( 'search_matched', match.test( haystack ) );
100 api.Widgets.availableWidgets = new api.Widgets.WidgetCollection( api.Widgets.data.availableWidgets );
103 * wp.customize.Widgets.SidebarModel
105 * A single sidebar model.
108 * @augments Backbone.Model
110 api.Widgets.SidebarModel = Backbone.Model.extend({
123 * wp.customize.Widgets.SidebarCollection
125 * Collection for sidebar models.
128 * @augments Backbone.Collection
130 api.Widgets.SidebarCollection = Backbone.Collection.extend({
131 model: api.Widgets.SidebarModel
133 api.Widgets.registeredSidebars = new api.Widgets.SidebarCollection( api.Widgets.data.registeredSidebars );
136 * wp.customize.Widgets.AvailableWidgetsPanelView
138 * View class for the available widgets panel.
141 * @augments wp.Backbone.View
142 * @augments Backbone.View
144 api.Widgets.AvailableWidgetsPanelView = wp.Backbone.View.extend({
146 el: '#available-widgets',
149 'input #widgets-search': 'search',
150 'keyup #widgets-search': 'search',
151 'change #widgets-search': 'search',
152 'search #widgets-search': 'search',
153 'focus .widget-tpl' : 'focus',
154 'click .widget-tpl' : '_submit',
155 'keypress .widget-tpl' : '_submit',
156 'keydown' : 'keyboardAccessible'
159 // Cache current selected widget
162 // Cache sidebar control which has opened panel
163 currentSidebarControl: null,
166 initialize: function() {
169 this.$search = $( '#widgets-search' );
171 _.bindAll( this, 'close' );
173 this.listenTo( this.collection, 'change', this.updateList );
177 // If the available widgets panel is open and the customize controls are
178 // interacted with (i.e. available widgets panel is blurred) then close the
179 // available widgets panel.
180 $( '#customize-controls' ).on( 'click keydown', function( e ) {
181 var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' );
182 if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) {
187 // Close the panel if the URL in the preview changes
188 api.previewer.bind( 'url', this.close );
191 // Performs a search and handles selected widget
192 search: function( event ) {
195 this.collection.doSearch( event.target.value );
197 // Remove a widget from being selected if it is no longer visible
198 if ( this.selected && ! this.selected.is( ':visible' ) ) {
199 this.selected.removeClass( 'selected' );
200 this.selected = null;
203 // If a widget was selected but the filter value has been cleared out, clear selection
204 if ( this.selected && ! event.target.value ) {
205 this.selected.removeClass( 'selected' );
206 this.selected = null;
209 // If a filter has been entered and a widget hasn't been selected, select the first one shown
210 if ( ! this.selected && event.target.value ) {
211 firstVisible = this.$el.find( '> .widget-tpl:visible:first' );
212 if ( firstVisible.length ) {
213 this.select( firstVisible );
218 // Changes visibility of available widgets
219 updateList: function() {
220 this.collection.each( function( widget ) {
221 var widgetTpl = $( '#widget-tpl-' + widget.id );
222 widgetTpl.toggle( widget.get( 'search_matched' ) && ! widget.get( 'is_disabled' ) );
223 if ( widget.get( 'is_disabled' ) && widgetTpl.is( this.selected ) ) {
224 this.selected = null;
229 // Highlights a widget
230 select: function( widgetTpl ) {
231 this.selected = $( widgetTpl );
232 this.selected.siblings( '.widget-tpl' ).removeClass( 'selected' );
233 this.selected.addClass( 'selected' );
236 // Highlights a widget on focus
237 focus: function( event ) {
238 this.select( $( event.currentTarget ) );
241 // Submit handler for keypress and click on widget
242 _submit: function( event ) {
243 // Only proceed with keypress if it is Enter or Spacebar
244 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
248 this.submit( $( event.currentTarget ) );
251 // Adds a selected widget to the sidebar
252 submit: function( widgetTpl ) {
253 var widgetId, widget;
256 widgetTpl = this.selected;
259 if ( ! widgetTpl || ! this.currentSidebarControl ) {
263 this.select( widgetTpl );
265 widgetId = $( this.selected ).data( 'widget-id' );
266 widget = this.collection.findWhere( { id: widgetId } );
271 this.currentSidebarControl.addWidget( widget.get( 'id_base' ) );
277 open: function( sidebarControl ) {
278 this.currentSidebarControl = sidebarControl;
280 // Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens
281 _( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) {
282 if ( control.params.is_wide ) {
283 control.collapseForm();
287 $( 'body' ).addClass( 'adding-widget' );
289 this.$el.find( '.selected' ).removeClass( 'selected' );
292 this.collection.doSearch( '' );
294 this.$search.focus();
298 close: function( options ) {
299 options = options || {};
301 if ( options.returnFocus && this.currentSidebarControl ) {
302 this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
305 this.currentSidebarControl = null;
306 this.selected = null;
308 $( 'body' ).removeClass( 'adding-widget' );
310 this.$search.val( '' );
313 // Add keyboard accessiblity to the panel
314 keyboardAccessible: function( event ) {
315 var isEnter = ( event.which === 13 ),
316 isEsc = ( event.which === 27 ),
317 isDown = ( event.which === 40 ),
318 isUp = ( event.which === 38 ),
319 isTab = ( event.which === 9 ),
320 isShift = ( event.shiftKey ),
322 firstVisible = this.$el.find( '> .widget-tpl:visible:first' ),
323 lastVisible = this.$el.find( '> .widget-tpl:visible:last' ),
324 isSearchFocused = $( event.target ).is( this.$search ),
325 isLastWidgetFocused = $( event.target ).is( '.widget-tpl:visible:last' );
327 if ( isDown || isUp ) {
329 if ( isSearchFocused ) {
330 selected = firstVisible;
331 } else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) {
332 selected = this.selected.nextAll( '.widget-tpl:visible:first' );
335 if ( isSearchFocused ) {
336 selected = lastVisible;
337 } else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) {
338 selected = this.selected.prevAll( '.widget-tpl:visible:first' );
342 this.select( selected );
347 this.$search.focus();
353 // If enter pressed but nothing entered, don't do anything
354 if ( isEnter && ! this.$search.val() ) {
360 } else if ( isEsc ) {
361 this.close( { returnFocus: true } );
364 if ( isTab && ( isShift && isSearchFocused || ! isShift && isLastWidgetFocused ) ) {
365 this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
366 event.preventDefault();
372 * Handlers for the widget-synced event, organized by widget ID base.
373 * Other widgets may provide their own update handlers by adding
374 * listeners for the widget-synced event.
376 api.Widgets.formSyncHandlers = {
379 * @param {jQuery.Event} e
380 * @param {jQuery} widget
381 * @param {String} newForm
383 rss: function( e, widget, newForm ) {
384 var oldWidgetError = widget.find( '.widget-error:first' ),
385 newWidgetError = $( '<div>' + newForm + '</div>' ).find( '.widget-error:first' );
387 if ( oldWidgetError.length && newWidgetError.length ) {
388 oldWidgetError.replaceWith( newWidgetError );
389 } else if ( oldWidgetError.length ) {
390 oldWidgetError.remove();
391 } else if ( newWidgetError.length ) {
392 widget.find( '.widget-content:first' ).prepend( newWidgetError );
398 * wp.customize.Widgets.WidgetControl
400 * Customizer control for widgets.
401 * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type
404 * @augments wp.customize.Control
406 api.Widgets.WidgetControl = api.Control.extend({
407 defaultExpandedArguments: {
409 completeCallback: $.noop
415 initialize: function ( id, options ) {
417 api.Control.prototype.initialize.call( control, id, options );
418 control.expanded = new api.Value();
419 control.expandedArgumentsQueue = [];
420 control.expanded.bind( function ( expanded ) {
421 var args = control.expandedArgumentsQueue.shift();
422 args = $.extend( {}, control.defaultExpandedArguments, args );
423 control.onChangeExpanded( expanded, args );
425 control.expanded.set( false );
433 this._setupWideWidget();
434 this._setupControlToggle();
435 this._setupWidgetTitle();
436 this._setupReorderUI();
437 this._setupHighlightEffects();
438 this._setupUpdateUI();
439 this._setupRemoveUI();
442 * Trigger widget-added event so that plugins can attach any event
443 * listeners and dynamic UI elements.
445 $( document ).trigger( 'widget-added', [ this.container.find( '.widget:first' ) ] );
449 * Handle changes to the setting
451 _setupModel: function() {
452 var self = this, rememberSavedWidgetId;
454 api.Widgets.savedWidgetIds = api.Widgets.savedWidgetIds || [];
456 // Remember saved widgets so we know which to trash (move to inactive widgets sidebar)
457 rememberSavedWidgetId = function() {
458 api.Widgets.savedWidgetIds[self.params.widget_id] = true;
460 api.bind( 'ready', rememberSavedWidgetId );
461 api.bind( 'saved', rememberSavedWidgetId );
463 this._updateCount = 0;
464 this.isWidgetUpdating = false;
465 this.liveUpdateMode = true;
467 // Update widget whenever model changes
468 this.setting.bind( function( to, from ) {
469 if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) {
470 self.updateWidget( { instance: to } );
476 * Add special behaviors for wide widget controls
478 _setupWideWidget: function() {
479 var self = this, $widgetInside, $widgetForm, $customizeSidebar,
480 $themeControlsContainer, positionWidget;
482 if ( ! this.params.is_wide ) {
486 $widgetInside = this.container.find( '.widget-inside' );
487 $widgetForm = $widgetInside.find( '> .form' );
488 $customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' );
489 this.container.addClass( 'wide-widget-control' );
491 this.container.find( '.widget-content:first' ).css( {
492 'max-width': this.params.width,
493 'min-height': this.params.height
497 * Keep the widget-inside positioned so the top of fixed-positioned
498 * element is at the same top position as the widget-top. When the
499 * widget-top is scrolled out of view, keep the widget-top in view;
500 * likewise, don't allow the widget to drop off the bottom of the window.
501 * If a widget is too tall to fit in the window, don't let the height
502 * exceed the window height so that the contents of the widget control
503 * will become scrollable (overflow:auto).
505 positionWidget = function() {
506 var offsetTop = self.container.offset().top,
507 windowHeight = $( window ).height(),
508 formHeight = $widgetForm.outerHeight(),
510 $widgetInside.css( 'max-height', windowHeight );
512 0, // prevent top from going off screen
514 Math.max( offsetTop, 0 ), // distance widget in panel is from top of screen
515 windowHeight - formHeight // flush up against bottom of screen
518 $widgetInside.css( 'top', top );
521 $themeControlsContainer = $( '#customize-theme-controls' );
522 this.container.on( 'expand', function() {
524 $customizeSidebar.on( 'scroll', positionWidget );
525 $( window ).on( 'resize', positionWidget );
526 $themeControlsContainer.on( 'expanded collapsed', positionWidget );
528 this.container.on( 'collapsed', function() {
529 $customizeSidebar.off( 'scroll', positionWidget );
530 $( window ).off( 'resize', positionWidget );
531 $themeControlsContainer.off( 'expanded collapsed', positionWidget );
534 // Reposition whenever a sidebar's widgets are changed
535 api.each( function( setting ) {
536 if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) {
537 setting.bind( function() {
538 if ( self.container.hasClass( 'expanded' ) ) {
547 * Show/hide the control when clicking on the form title, when clicking
550 _setupControlToggle: function() {
551 var self = this, $closeBtn;
553 this.container.find( '.widget-top' ).on( 'click', function( e ) {
555 var sidebarWidgetsControl = self.getSidebarWidgetsControl();
556 if ( sidebarWidgetsControl.isReordering ) {
559 self.expanded( ! self.expanded() );
562 $closeBtn = this.container.find( '.widget-control-close' );
563 $closeBtn.on( 'click', function( e ) {
566 self.container.find( '.widget-top .widget-action:first' ).focus(); // keyboard accessibility
571 * Update the title of the form if a title field is entered
573 _setupWidgetTitle: function() {
574 var self = this, updateTitle;
576 updateTitle = function() {
577 var title = self.setting().title,
578 inWidgetTitle = self.container.find( '.in-widget-title' );
581 inWidgetTitle.text( ': ' + title );
583 inWidgetTitle.text( '' );
586 this.setting.bind( updateTitle );
591 * Set up the widget-reorder-nav
593 _setupReorderUI: function() {
594 var self = this, selectSidebarItem, $moveWidgetArea,
595 $reorderNav, updateAvailableSidebars;
598 * select the provided sidebar list item in the move widget area
602 selectSidebarItem = function( li ) {
603 li.siblings( '.selected' ).removeClass( 'selected' );
604 li.addClass( 'selected' );
605 var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id );
606 self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar );
610 * Add the widget reordering elements to the widget control
612 this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) );
614 _.template( api.Widgets.data.tpl.moveWidgetArea, {
615 sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' )
618 this.container.find( '.widget-top' ).after( $moveWidgetArea );
621 * Update available sidebars when their rendered state changes
623 updateAvailableSidebars = function() {
624 var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem;
626 selfSidebarItem = $sidebarItems.filter( function(){
627 return $( this ).data( 'id' ) === self.params.sidebar_id;
630 $sidebarItems.each( function() {
635 sidebarId = li.data( 'id' );
636 sidebar = api.Widgets.registeredSidebars.get( sidebarId );
638 li.toggle( sidebar.get( 'is_rendered' ) );
640 if ( li.hasClass( 'selected' ) && ! sidebar.get( 'is_rendered' ) ) {
641 selectSidebarItem( selfSidebarItem );
646 updateAvailableSidebars();
647 api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars );
650 * Handle clicks for up/down/move on the reorder nav
652 $reorderNav = this.container.find( '.widget-reorder-nav' );
653 $reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() {
654 $( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' );
655 } ).on( 'click keypress', function( event ) {
656 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
661 if ( $( this ).is( '.move-widget' ) ) {
662 self.toggleWidgetMoveArea();
664 var isMoveDown = $( this ).is( '.move-widget-down' ),
665 isMoveUp = $( this ).is( '.move-widget-up' ),
666 i = self.getWidgetSidebarPosition();
668 if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) {
674 $( '#screen-reader-messages' ).text( l10n.widgetMovedUp );
677 $( '#screen-reader-messages' ).text( l10n.widgetMovedDown );
680 $( this ).focus(); // re-focus after the container was moved
685 * Handle selecting a sidebar to move to
687 this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( e ) {
688 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
692 selectSidebarItem( $( this ) );
696 * Move widget to another sidebar
698 this.container.find( '.move-widget-btn' ).click( function() {
699 self.getSidebarWidgetsControl().toggleReordering( false );
701 var oldSidebarId = self.params.sidebar_id,
702 newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ),
703 oldSidebarWidgetsSetting, newSidebarWidgetsSetting,
704 oldSidebarWidgetIds, newSidebarWidgetIds, i;
706 oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' );
707 newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' );
708 oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() );
709 newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() );
711 i = self.getWidgetSidebarPosition();
712 oldSidebarWidgetIds.splice( i, 1 );
713 newSidebarWidgetIds.push( self.params.widget_id );
715 oldSidebarWidgetsSetting( oldSidebarWidgetIds );
716 newSidebarWidgetsSetting( newSidebarWidgetIds );
723 * Highlight widgets in preview when interacted with in the Customizer
725 _setupHighlightEffects: function() {
728 // Highlight whenever hovering or clicking over the form
729 this.container.on( 'mouseenter click', function() {
730 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
733 // Highlight when the setting is updated
734 this.setting.bind( function() {
735 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
740 * Set up event handlers for widget updating
742 _setupUpdateUI: function() {
743 var self = this, $widgetRoot, $widgetContent,
744 $saveBtn, updateWidgetDebounced, formSyncHandler;
746 $widgetRoot = this.container.find( '.widget:first' );
747 $widgetContent = $widgetRoot.find( '.widget-content:first' );
749 // Configure update button
750 $saveBtn = this.container.find( '.widget-control-save' );
751 $saveBtn.val( l10n.saveBtnLabel );
752 $saveBtn.attr( 'title', l10n.saveBtnTooltip );
753 $saveBtn.removeClass( 'button-primary' ).addClass( 'button-secondary' );
754 $saveBtn.on( 'click', function( e ) {
756 self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
759 updateWidgetDebounced = _.debounce( function() {
763 // Trigger widget form update when hitting Enter within an input
764 $widgetContent.on( 'keydown', 'input', function( e ) {
765 if ( 13 === e.which ) { // Enter
767 self.updateWidget( { ignoreActiveElement: true } );
771 // Handle widgets that support live previews
772 $widgetContent.on( 'change input propertychange', ':input', function( e ) {
773 if ( self.liveUpdateMode ) {
774 if ( e.type === 'change' ) {
776 } else if ( this.checkValidity && this.checkValidity() ) {
777 updateWidgetDebounced();
782 // Remove loading indicators when the setting is saved and the preview updates
783 this.setting.previewer.channel.bind( 'synced', function() {
784 self.container.removeClass( 'previewer-loading' );
787 api.previewer.bind( 'widget-updated', function( updatedWidgetId ) {
788 if ( updatedWidgetId === self.params.widget_id ) {
789 self.container.removeClass( 'previewer-loading' );
793 formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
794 if ( formSyncHandler ) {
795 $( document ).on( 'widget-synced', function( e, widget ) {
796 if ( $widgetRoot.is( widget ) ) {
797 formSyncHandler.apply( document, arguments );
804 * Update widget control to indicate whether it is currently rendered.
806 * Overrides api.Control.toggle()
810 * @param {Boolean} active
811 * @param {Object} args
812 * @param {Callback} args.completeCallback
814 onChangeActive: function ( active, args ) {
815 // Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments
816 this.container.toggleClass( 'widget-rendered', active );
817 if ( args.completeCallback ) {
818 args.completeCallback();
823 * Set up event handlers for widget removal
825 _setupRemoveUI: function() {
826 var self = this, $removeBtn, replaceDeleteWithRemove;
828 // Configure remove button
829 $removeBtn = this.container.find( 'a.widget-control-remove' );
830 $removeBtn.on( 'click', function( e ) {
833 // Find an adjacent element to add focus to when this widget goes away
834 var $adjacentFocusTarget;
835 if ( self.container.next().is( '.customize-control-widget_form' ) ) {
836 $adjacentFocusTarget = self.container.next().find( '.widget-action:first' );
837 } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) {
838 $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' );
840 $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' );
843 self.container.slideUp( function() {
844 var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
847 if ( ! sidebarsWidgetsControl ) {
851 sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
852 i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
857 sidebarWidgetIds.splice( i, 1 );
858 sidebarsWidgetsControl.setting( sidebarWidgetIds );
860 $adjacentFocusTarget.focus(); // keyboard accessibility
864 replaceDeleteWithRemove = function() {
865 $removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the link as "Delete"
866 $removeBtn.attr( 'title', l10n.removeBtnTooltip );
869 if ( this.params.is_new ) {
870 api.bind( 'saved', replaceDeleteWithRemove );
872 replaceDeleteWithRemove();
877 * Find all inputs in a widget container that should be considered when
878 * comparing the loaded form with the sanitized form, whose fields will
879 * be aligned to copy the sanitized over. The elements returned by this
880 * are passed into this._getInputsSignature(), and they are iterated
881 * over when copying sanitized values over to the the form loaded.
883 * @param {jQuery} container element in which to look for inputs
884 * @returns {jQuery} inputs
887 _getInputs: function( container ) {
888 return $( container ).find( ':input[name]' );
892 * Iterate over supplied inputs and create a signature string for all of them together.
893 * This string can be used to compare whether or not the form has all of the same fields.
895 * @param {jQuery} inputs
899 _getInputsSignature: function( inputs ) {
900 var inputsSignatures = _( inputs ).map( function( input ) {
901 var $input = $( input ), signatureParts;
903 if ( $input.is( ':checkbox, :radio' ) ) {
904 signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ];
906 signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ];
909 return signatureParts.join( ',' );
912 return inputsSignatures.join( ';' );
916 * Get the property that represents the state of an input.
918 * @param {jQuery|DOMElement} input
922 _getInputStatePropertyName: function( input ) {
923 var $input = $( input );
925 if ( $input.is( ':radio, :checkbox' ) ) {
932 /***********************************************************************
933 * Begin public API methods
934 **********************************************************************/
937 * @return {wp.customize.controlConstructor.sidebar_widgets[]}
939 getSidebarWidgetsControl: function() {
940 var settingId, sidebarWidgetsControl;
942 settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']';
943 sidebarWidgetsControl = api.control( settingId );
945 if ( ! sidebarWidgetsControl ) {
949 return sidebarWidgetsControl;
953 * Submit the widget form via Ajax and get back the updated instance,
954 * along with the new widget control form to render.
956 * @param {object} [args]
957 * @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used
958 * @param {Function|null} [args.complete=null] Function which is called when the request finishes. Context is bound to the control. First argument is any error. Following arguments are for success.
959 * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
961 updateWidget: function( args ) {
962 var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
963 updateNumber, params, data, $inputs, processing, jqxhr, isChanged;
968 ignoreActiveElement: false
971 instanceOverride = args.instance;
972 completeCallback = args.complete;
974 this._updateCount += 1;
975 updateNumber = this._updateCount;
977 $widgetRoot = this.container.find( '.widget:first' );
978 $widgetContent = $widgetRoot.find( '.widget-content:first' );
980 // Remove a previous error message
981 $widgetContent.find( '.widget-error' ).remove();
983 this.container.addClass( 'widget-form-loading' );
984 this.container.addClass( 'previewer-loading' );
985 processing = api.state( 'processing' );
986 processing( processing() + 1 );
988 if ( ! this.liveUpdateMode ) {
989 this.container.addClass( 'widget-form-disabled' );
993 params.action = 'update-widget';
994 params.wp_customize = 'on';
995 params.nonce = api.Widgets.data.nonce;
996 params.theme = api.settings.theme.stylesheet;
998 data = $.param( params );
999 $inputs = this._getInputs( $widgetContent );
1001 // Store the value we're submitting in data so that when the response comes back,
1002 // we know if it got sanitized; if there is no difference in the sanitized value,
1003 // then we do not need to touch the UI and mess up the user's ongoing editing.
1004 $inputs.each( function() {
1005 var input = $( this ),
1006 property = self._getInputStatePropertyName( this );
1007 input.data( 'state' + updateNumber, input.prop( property ) );
1010 if ( instanceOverride ) {
1011 data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } );
1013 data += '&' + $inputs.serialize();
1015 data += '&' + $widgetContent.find( '~ :input' ).serialize();
1017 jqxhr = $.post( wp.ajax.settings.url, data );
1019 jqxhr.done( function( r ) {
1020 var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse,
1021 isLiveUpdateAborted = false;
1023 // Check if the user is logged out.
1025 api.previewer.preview.iframe.hide();
1026 api.previewer.login().done( function() {
1027 self.updateWidget( args );
1028 api.previewer.preview.iframe.show();
1033 // Check for cheaters.
1035 api.previewer.cheatin();
1040 sanitizedForm = $( '<div>' + r.data.form + '</div>' );
1041 $sanitizedInputs = self._getInputs( sanitizedForm );
1042 hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs );
1044 // Restore live update mode if sanitized fields are now aligned with the existing fields
1045 if ( hasSameInputsInResponse && ! self.liveUpdateMode ) {
1046 self.liveUpdateMode = true;
1047 self.container.removeClass( 'widget-form-disabled' );
1048 self.container.find( 'input[name="savewidget"]' ).hide();
1051 // Sync sanitized field states to existing fields if they are aligned
1052 if ( hasSameInputsInResponse && self.liveUpdateMode ) {
1053 $inputs.each( function( i ) {
1054 var $input = $( this ),
1055 $sanitizedInput = $( $sanitizedInputs[i] ),
1056 property = self._getInputStatePropertyName( this ),
1057 submittedState, sanitizedState, canUpdateState;
1059 submittedState = $input.data( 'state' + updateNumber );
1060 sanitizedState = $sanitizedInput.prop( property );
1061 $input.data( 'sanitized', sanitizedState );
1063 canUpdateState = ( submittedState !== sanitizedState && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
1064 if ( canUpdateState ) {
1065 $input.prop( property, sanitizedState );
1069 $( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] );
1071 // Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled
1072 } else if ( self.liveUpdateMode ) {
1073 self.liveUpdateMode = false;
1074 self.container.find( 'input[name="savewidget"]' ).show();
1075 isLiveUpdateAborted = true;
1077 // Otherwise, replace existing form with the sanitized form
1079 $widgetContent.html( r.data.form );
1081 self.container.removeClass( 'widget-form-disabled' );
1083 $( document ).trigger( 'widget-updated', [ $widgetRoot ] );
1087 * If the old instance is identical to the new one, there is nothing new
1088 * needing to be rendered, and so we can preempt the event for the
1089 * preview finishing loading.
1091 isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance );
1093 self.isWidgetUpdating = true; // suppress triggering another updateWidget
1094 self.setting( r.data.instance );
1095 self.isWidgetUpdating = false;
1097 // no change was made, so stop the spinner now instead of when the preview would updates
1098 self.container.removeClass( 'previewer-loading' );
1101 if ( completeCallback ) {
1102 completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
1105 // General error message
1106 message = l10n.error;
1108 if ( r.data && r.data.message ) {
1109 message = r.data.message;
1112 if ( completeCallback ) {
1113 completeCallback.call( self, message );
1115 $widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' );
1120 jqxhr.fail( function( jqXHR, textStatus ) {
1121 if ( completeCallback ) {
1122 completeCallback.call( self, textStatus );
1126 jqxhr.always( function() {
1127 self.container.removeClass( 'widget-form-loading' );
1129 $inputs.each( function() {
1130 $( this ).removeData( 'state' + updateNumber );
1133 processing( processing() - 1 );
1138 * Expand the accordion section containing a control
1140 expandControlSection: function() {
1141 api.Control.prototype.expand.call( this );
1147 * @param {Boolean} expanded
1148 * @param {Object} [params]
1149 * @returns {Boolean} false if state already applied
1151 _toggleExpanded: api.Section.prototype._toggleExpanded,
1156 * @param {Object} [params]
1157 * @returns {Boolean} false if already expanded
1159 expand: api.Section.prototype.expand,
1162 * Expand the widget form control
1164 * @deprecated 4.1.0 Use this.expand() instead.
1166 expandForm: function() {
1173 * @param {Object} [params]
1174 * @returns {Boolean} false if already collapsed
1176 collapse: api.Section.prototype.collapse,
1179 * Collapse the widget form control
1181 * @deprecated 4.1.0 Use this.collapse() instead.
1183 collapseForm: function() {
1188 * Expand or collapse the widget control
1190 * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
1192 * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility
1194 toggleForm: function( showOrHide ) {
1195 if ( typeof showOrHide === 'undefined' ) {
1196 showOrHide = ! this.expanded();
1198 this.expanded( showOrHide );
1202 * Respond to change in the expanded state.
1204 * @param {Boolean} expanded
1205 * @param {Object} args merged on top of this.defaultActiveArguments
1207 onChangeExpanded: function ( expanded, args ) {
1208 var self = this, $widget, $inside, complete, prevComplete;
1210 // If the expanded state is unchanged only manipulate container expanded states
1211 if ( args.unchanged ) {
1213 api.Control.prototype.expand.call( self, {
1214 completeCallback: args.completeCallback
1220 $widget = this.container.find( 'div.widget:first' );
1221 $inside = $widget.find( '.widget-inside:first' );
1225 self.expandControlSection();
1227 // Close all other widget controls before expanding this one
1228 api.control.each( function( otherControl ) {
1229 if ( self.params.type === otherControl.params.type && self !== otherControl ) {
1230 otherControl.collapse();
1234 complete = function() {
1235 self.container.removeClass( 'expanding' );
1236 self.container.addClass( 'expanded' );
1237 self.container.trigger( 'expanded' );
1239 if ( args.completeCallback ) {
1240 prevComplete = complete;
1241 complete = function () {
1243 args.completeCallback();
1247 if ( self.params.is_wide ) {
1248 $inside.fadeIn( args.duration, complete );
1250 $inside.slideDown( args.duration, complete );
1253 self.container.trigger( 'expand' );
1254 self.container.addClass( 'expanding' );
1257 complete = function() {
1258 self.container.removeClass( 'collapsing' );
1259 self.container.removeClass( 'expanded' );
1260 self.container.trigger( 'collapsed' );
1262 if ( args.completeCallback ) {
1263 prevComplete = complete;
1264 complete = function () {
1266 args.completeCallback();
1270 self.container.trigger( 'collapse' );
1271 self.container.addClass( 'collapsing' );
1273 if ( self.params.is_wide ) {
1274 $inside.fadeOut( args.duration, complete );
1276 $inside.slideUp( args.duration, function() {
1277 $widget.css( { width:'', margin:'' } );
1285 * Get the position (index) of the widget in the containing sidebar
1289 getWidgetSidebarPosition: function() {
1290 var sidebarWidgetIds, position;
1292 sidebarWidgetIds = this.getSidebarWidgetsControl().setting();
1293 position = _.indexOf( sidebarWidgetIds, this.params.widget_id );
1295 if ( position === -1 ) {
1303 * Move widget up one in the sidebar
1305 moveUp: function() {
1306 this._moveWidgetByOne( -1 );
1310 * Move widget up one in the sidebar
1312 moveDown: function() {
1313 this._moveWidgetByOne( 1 );
1319 * @param {Number} offset 1|-1
1321 _moveWidgetByOne: function( offset ) {
1322 var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId;
1324 i = this.getWidgetSidebarPosition();
1326 sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting;
1327 sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // clone
1328 adjacentWidgetId = sidebarWidgetIds[i + offset];
1329 sidebarWidgetIds[i + offset] = this.params.widget_id;
1330 sidebarWidgetIds[i] = adjacentWidgetId;
1332 sidebarWidgetsSetting( sidebarWidgetIds );
1336 * Toggle visibility of the widget move area
1338 * @param {Boolean} [showOrHide]
1340 toggleWidgetMoveArea: function( showOrHide ) {
1341 var self = this, $moveWidgetArea;
1343 $moveWidgetArea = this.container.find( '.move-widget-area' );
1345 if ( typeof showOrHide === 'undefined' ) {
1346 showOrHide = ! $moveWidgetArea.hasClass( 'active' );
1350 // reset the selected sidebar
1351 $moveWidgetArea.find( '.selected' ).removeClass( 'selected' );
1353 $moveWidgetArea.find( 'li' ).filter( function() {
1354 return $( this ).data( 'id' ) === self.params.sidebar_id;
1355 } ).addClass( 'selected' );
1357 this.container.find( '.move-widget-btn' ).prop( 'disabled', true );
1360 $moveWidgetArea.toggleClass( 'active', showOrHide );
1364 * Highlight the widget control and section
1366 highlightSectionAndControl: function() {
1369 if ( this.container.is( ':hidden' ) ) {
1370 $target = this.container.closest( '.control-section' );
1372 $target = this.container;
1375 $( '.highlighted' ).removeClass( 'highlighted' );
1376 $target.addClass( 'highlighted' );
1378 setTimeout( function() {
1379 $target.removeClass( 'highlighted' );
1385 * wp.customize.Widgets.SidebarSection
1387 * Customizer section representing a widget area widget
1391 api.Widgets.SidebarSection = api.Section.extend({
1394 * Sync the section's active state back to the Backbone model's is_rendered attribute
1398 ready: function () {
1399 var section = this, registeredSidebar;
1400 api.Section.prototype.ready.call( this );
1401 registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId );
1402 section.active.bind( function ( active ) {
1403 registeredSidebar.set( 'is_rendered', active );
1405 registeredSidebar.set( 'is_rendered', section.active() );
1410 * wp.customize.Widgets.SidebarControl
1412 * Customizer control for widgets.
1413 * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type
1418 * @augments wp.customize.Control
1420 api.Widgets.SidebarControl = api.Control.extend({
1423 * Set up the control
1426 this.$controlSection = this.container.closest( '.control-section' );
1427 this.$sectionContent = this.container.closest( '.accordion-section-content' );
1430 this._setupSortable();
1431 this._setupAddition();
1432 this._applyCardinalOrderClassNames();
1436 * Update ordering of widget control forms when the setting is updated
1438 _setupModel: function() {
1441 this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
1442 var widgetFormControls, removedWidgetIds, priority;
1444 removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );
1446 // Filter out any persistent widget IDs for widgets which have been deactivated
1447 newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
1448 var parsedWidgetId = parseWidgetId( newWidgetId );
1450 return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
1453 widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
1454 var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1456 if ( ! widgetFormControl ) {
1457 widgetFormControl = self.addWidget( widgetId );
1460 return widgetFormControl;
1463 // Sort widget controls to their new positions
1464 widgetFormControls.sort( function( a, b ) {
1465 var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
1466 bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
1467 return aIndex - bIndex;
1471 _( widgetFormControls ).each( function ( control ) {
1472 control.priority( priority );
1473 control.section( self.section() );
1476 self.priority( priority ); // Make sure sidebar control remains at end
1478 // Re-sort widget form controls (including widgets form other sidebars newly moved here)
1479 self._applyCardinalOrderClassNames();
1481 // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated
1482 _( widgetFormControls ).each( function( widgetFormControl ) {
1483 widgetFormControl.params.sidebar_id = self.params.sidebar_id;
1486 // Cleanup after widget removal
1487 _( removedWidgetIds ).each( function( removedWidgetId ) {
1489 // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update
1490 setTimeout( function() {
1491 var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
1492 widget, isPresentInAnotherSidebar = false;
1494 // Check if the widget is in another sidebar
1495 api.each( function( otherSetting ) {
1496 if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) {
1500 var otherSidebarWidgets = otherSetting(), i;
1502 i = _.indexOf( otherSidebarWidgets, removedWidgetId );
1504 isPresentInAnotherSidebar = true;
1508 // If the widget is present in another sidebar, abort!
1509 if ( isPresentInAnotherSidebar ) {
1513 removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );
1515 // Detect if widget control was dragged to another sidebar
1516 wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
1518 // Delete any widget form controls for removed widgets
1519 if ( removedControl && ! wasDraggedToAnotherSidebar ) {
1520 api.control.remove( removedControl.id );
1521 removedControl.container.remove();
1524 // Move widget to inactive widgets sidebar (move it to trash) if has been previously saved
1525 // This prevents the inactive widgets sidebar from overflowing with throwaway widgets
1526 if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
1527 inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice();
1528 inactiveWidgets.push( removedWidgetId );
1529 api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() );
1532 // Make old single widget available for adding again
1533 removedIdBase = parseWidgetId( removedWidgetId ).id_base;
1534 widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
1535 if ( widget && ! widget.get( 'is_multi' ) ) {
1536 widget.set( 'is_disabled', false );
1545 * Allow widgets in sidebar to be re-ordered, and for the order to be previewed
1547 _setupSortable: function() {
1550 this.isReordering = false;
1553 * Update widget order setting when controls are re-ordered
1555 this.$sectionContent.sortable( {
1556 items: '> .customize-control-widget_form',
1557 handle: '.widget-top',
1559 connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
1560 update: function() {
1561 var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
1563 widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
1564 return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
1567 self.setting( widgetIds );
1572 * Expand other Customizer sidebar section when dragging a control widget over it,
1573 * allowing the control to be dropped into another section
1575 this.$controlSection.find( '.accordion-section-title' ).droppable({
1576 accept: '.customize-control-widget_form',
1578 var section = api.section( self.section.get() );
1580 allowMultiple: true, // Prevent the section being dragged from to be collapsed
1581 completeCallback: function () {
1582 // @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed
1583 api.section.each( function ( otherSection ) {
1584 if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) {
1585 otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' );
1594 * Keyboard-accessible reordering
1596 this.container.find( '.reorder-toggle' ).on( 'click keydown', function( event ) {
1597 if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar
1601 self.toggleReordering( ! self.isReordering );
1606 * Set up UI for adding a new widget
1608 _setupAddition: function() {
1611 this.container.find( '.add-new-widget' ).on( 'click keydown', function( event ) {
1612 if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar
1616 if ( self.$sectionContent.hasClass( 'reordering' ) ) {
1620 if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
1621 api.Widgets.availableWidgetsPanel.open( self );
1623 api.Widgets.availableWidgetsPanel.close();
1629 * Add classes to the widget_form controls to assist with styling
1631 _applyCardinalOrderClassNames: function() {
1632 var widgetControls = [];
1633 _.each( this.setting(), function ( widgetId ) {
1634 var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1635 if ( widgetControl ) {
1636 widgetControls.push( widgetControl );
1640 if ( ! widgetControls.length ) {
1644 $( widgetControls ).each( function () {
1646 .removeClass( 'first-widget' )
1647 .removeClass( 'last-widget' )
1648 .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
1651 _.first( widgetControls ).container
1652 .addClass( 'first-widget' )
1653 .find( '.move-widget-up' ).prop( 'tabIndex', -1 );
1655 _.last( widgetControls ).container
1656 .addClass( 'last-widget' )
1657 .find( '.move-widget-down' ).prop( 'tabIndex', -1 );
1661 /***********************************************************************
1662 * Begin public API methods
1663 **********************************************************************/
1666 * Enable/disable the reordering UI
1668 * @param {Boolean} showOrHide to enable/disable reordering
1670 * @todo We should have a reordering state instead and rename this to onChangeReordering
1672 toggleReordering: function( showOrHide ) {
1673 showOrHide = Boolean( showOrHide );
1675 if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
1679 this.isReordering = showOrHide;
1680 this.$sectionContent.toggleClass( 'reordering', showOrHide );
1683 _( this.getWidgetFormControls() ).each( function( formControl ) {
1684 formControl.collapse();
1687 this.$sectionContent.find( '.first-widget .move-widget' ).focus();
1688 this.$sectionContent.find( '.add-new-widget' ).prop( 'tabIndex', -1 );
1690 this.$sectionContent.find( '.add-new-widget' ).prop( 'tabIndex', 0 );
1695 * @return {wp.customize.controlConstructor.widget_form[]}
1697 getWidgetFormControls: function() {
1700 formControls = _( this.setting() ).map( function( widgetId ) {
1701 var settingId = widgetIdToSettingId( widgetId ),
1702 formControl = api.control( settingId );
1704 if ( ! formControl ) {
1711 return formControls;
1715 * @param {string} widgetId or an id_base for adding a previously non-existing widget
1716 * @returns {object|false} widget_form control instance, or false on error
1718 addWidget: function( widgetId ) {
1719 var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor,
1720 parsedWidgetId = parseWidgetId( widgetId ),
1721 widgetNumber = parsedWidgetId.number,
1722 widgetIdBase = parsedWidgetId.id_base,
1723 widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
1724 settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting;
1730 if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
1734 // Set up new multi widget
1735 if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
1736 widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
1737 widgetNumber = widget.get( 'multi_number' );
1740 controlHtml = $.trim( $( '#widget-tpl-' + widget.get( 'id' ) ).html() );
1741 if ( widget.get( 'is_multi' ) ) {
1742 controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
1743 return m.replace( /__i__|%i%/g, widgetNumber );
1746 widget.set( 'is_disabled', true ); // Prevent single widget from being added again now
1749 $widget = $( controlHtml );
1751 controlContainer = $( '<li/>' )
1752 .addClass( 'customize-control' )
1753 .addClass( 'customize-control-' + controlType )
1756 // Remove icon which is visible inside the panel
1757 controlContainer.find( '> .widget-icon' ).remove();
1759 if ( widget.get( 'is_multi' ) ) {
1760 controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber );
1761 controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber );
1764 widgetId = controlContainer.find( '[name="widget-id"]' ).val();
1766 controlContainer.hide(); // to be slid-down below
1768 settingId = 'widget_' + widget.get( 'id_base' );
1769 if ( widget.get( 'is_multi' ) ) {
1770 settingId += '[' + widgetNumber + ']';
1772 controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );
1774 // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget)
1775 isExistingWidget = api.has( settingId );
1776 if ( ! isExistingWidget ) {
1778 transport: 'refresh',
1779 previewer: this.setting.previewer
1781 setting = api.create( settingId, settingId, '', settingArgs );
1782 setting.set( {} ); // mark dirty, changing from '' to {}
1785 controlConstructor = api.controlConstructor[controlType];
1786 widgetFormControl = new controlConstructor( settingId, {
1789 'default': settingId
1791 content: controlContainer,
1792 sidebar_id: self.params.sidebar_id,
1793 widget_id: widgetId,
1794 widget_id_base: widget.get( 'id_base' ),
1796 is_new: ! isExistingWidget,
1797 width: widget.get( 'width' ),
1798 height: widget.get( 'height' ),
1799 is_wide: widget.get( 'is_wide' )
1801 previewer: self.setting.previewer
1803 api.control.add( settingId, widgetFormControl );
1805 // Make sure widget is removed from the other sidebars
1806 api.each( function( otherSetting ) {
1807 if ( otherSetting.id === self.setting.id ) {
1811 if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
1815 var otherSidebarWidgets = otherSetting().slice(),
1816 i = _.indexOf( otherSidebarWidgets, widgetId );
1819 otherSidebarWidgets.splice( i );
1820 otherSetting( otherSidebarWidgets );
1824 // Add widget to this sidebar
1825 sidebarWidgets = this.setting().slice();
1826 if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
1827 sidebarWidgets.push( widgetId );
1828 this.setting( sidebarWidgets );
1831 controlContainer.slideDown( function() {
1832 if ( isExistingWidget ) {
1833 widgetFormControl.expand();
1834 widgetFormControl.updateWidget( {
1835 instance: widgetFormControl.setting(),
1836 complete: function( error ) {
1840 widgetFormControl.focus();
1844 widgetFormControl.focus();
1848 return widgetFormControl;
1852 // Register models for custom section and control types
1853 $.extend( api.sectionConstructor, {
1854 sidebar: api.Widgets.SidebarSection
1856 $.extend( api.controlConstructor, {
1857 widget_form: api.Widgets.WidgetControl,
1858 sidebar_widgets: api.Widgets.SidebarControl
1862 * Init Customizer for widgets.
1864 api.bind( 'ready', function() {
1865 // Set up the widgets panel
1866 api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
1867 collection: api.Widgets.availableWidgets
1870 // Highlight widget control
1871 api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
1873 // Open and focus widget control
1874 api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
1878 * Highlight a widget control.
1880 * @param {string} widgetId
1882 api.Widgets.highlightWidgetFormControl = function( widgetId ) {
1883 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
1886 control.highlightSectionAndControl();
1891 * Focus a widget control.
1893 * @param {string} widgetId
1895 api.Widgets.focusWidgetFormControl = function( widgetId ) {
1896 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
1904 * Given a widget control, find the sidebar widgets control that contains it.
1905 * @param {string} widgetId
1906 * @return {object|null}
1908 api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
1909 var foundControl = null;
1911 // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl()
1912 api.control.each( function( control ) {
1913 if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
1914 foundControl = control;
1918 return foundControl;
1922 * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
1924 * @param {string} widgetId
1925 * @return {object|null}
1927 api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
1928 var foundControl = null;
1930 // @todo We can just use widgetIdToSettingId() here
1931 api.control.each( function( control ) {
1932 if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
1933 foundControl = control;
1937 return foundControl;
1941 * @param {String} widgetId
1944 function parseWidgetId( widgetId ) {
1945 var matches, parsed = {
1950 matches = widgetId.match( /^(.+)-(\d+)$/ );
1952 parsed.id_base = matches[1];
1953 parsed.number = parseInt( matches[2], 10 );
1955 // likely an old single widget
1956 parsed.id_base = widgetId;
1963 * @param {String} widgetId
1964 * @returns {String} settingId
1966 function widgetIdToSettingId( widgetId ) {
1967 var parsed = parseWidgetId( widgetId ), settingId;
1969 settingId = 'widget_' + parsed.id_base;
1970 if ( parsed.number ) {
1971 settingId += '[' + parsed.number + ']';
1977 })( window.wp, jQuery );