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. Also close on back button click.
180 $( '#customize-controls, #available-widgets .customize-section-title' ).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, widgetFormControl;
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 widgetFormControl = this.currentSidebarControl.addWidget( widget.get( 'id_base' ) );
272 if ( widgetFormControl ) {
273 widgetFormControl.focus();
280 open: function( sidebarControl ) {
281 this.currentSidebarControl = sidebarControl;
283 // Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens
284 _( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) {
285 if ( control.params.is_wide ) {
286 control.collapseForm();
290 $( 'body' ).addClass( 'adding-widget' );
292 this.$el.find( '.selected' ).removeClass( 'selected' );
295 this.collection.doSearch( '' );
297 if ( ! api.settings.browser.mobile ) {
298 this.$search.focus();
303 close: function( options ) {
304 options = options || {};
306 if ( options.returnFocus && this.currentSidebarControl ) {
307 this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
310 this.currentSidebarControl = null;
311 this.selected = null;
313 $( 'body' ).removeClass( 'adding-widget' );
315 this.$search.val( '' );
318 // Add keyboard accessiblity to the panel
319 keyboardAccessible: function( event ) {
320 var isEnter = ( event.which === 13 ),
321 isEsc = ( event.which === 27 ),
322 isDown = ( event.which === 40 ),
323 isUp = ( event.which === 38 ),
324 isTab = ( event.which === 9 ),
325 isShift = ( event.shiftKey ),
327 firstVisible = this.$el.find( '> .widget-tpl:visible:first' ),
328 lastVisible = this.$el.find( '> .widget-tpl:visible:last' ),
329 isSearchFocused = $( event.target ).is( this.$search ),
330 isLastWidgetFocused = $( event.target ).is( '.widget-tpl:visible:last' );
332 if ( isDown || isUp ) {
334 if ( isSearchFocused ) {
335 selected = firstVisible;
336 } else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) {
337 selected = this.selected.nextAll( '.widget-tpl:visible:first' );
340 if ( isSearchFocused ) {
341 selected = lastVisible;
342 } else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) {
343 selected = this.selected.prevAll( '.widget-tpl:visible:first' );
347 this.select( selected );
352 this.$search.focus();
358 // If enter pressed but nothing entered, don't do anything
359 if ( isEnter && ! this.$search.val() ) {
365 } else if ( isEsc ) {
366 this.close( { returnFocus: true } );
369 if ( this.currentSidebarControl && isTab && ( isShift && isSearchFocused || ! isShift && isLastWidgetFocused ) ) {
370 this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
371 event.preventDefault();
377 * Handlers for the widget-synced event, organized by widget ID base.
378 * Other widgets may provide their own update handlers by adding
379 * listeners for the widget-synced event.
381 api.Widgets.formSyncHandlers = {
384 * @param {jQuery.Event} e
385 * @param {jQuery} widget
386 * @param {String} newForm
388 rss: function( e, widget, newForm ) {
389 var oldWidgetError = widget.find( '.widget-error:first' ),
390 newWidgetError = $( '<div>' + newForm + '</div>' ).find( '.widget-error:first' );
392 if ( oldWidgetError.length && newWidgetError.length ) {
393 oldWidgetError.replaceWith( newWidgetError );
394 } else if ( oldWidgetError.length ) {
395 oldWidgetError.remove();
396 } else if ( newWidgetError.length ) {
397 widget.find( '.widget-content:first' ).prepend( newWidgetError );
403 * wp.customize.Widgets.WidgetControl
405 * Customizer control for widgets.
406 * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type
409 * @augments wp.customize.Control
411 api.Widgets.WidgetControl = api.Control.extend({
412 defaultExpandedArguments: {
414 completeCallback: $.noop
420 initialize: function ( id, options ) {
422 api.Control.prototype.initialize.call( control, id, options );
423 control.expanded = new api.Value();
424 control.expandedArgumentsQueue = [];
425 control.expanded.bind( function ( expanded ) {
426 var args = control.expandedArgumentsQueue.shift();
427 args = $.extend( {}, control.defaultExpandedArguments, args );
428 control.onChangeExpanded( expanded, args );
430 control.expanded.set( false );
438 this._setupWideWidget();
439 this._setupControlToggle();
440 this._setupWidgetTitle();
441 this._setupReorderUI();
442 this._setupHighlightEffects();
443 this._setupUpdateUI();
444 this._setupRemoveUI();
447 * Trigger widget-added event so that plugins can attach any event
448 * listeners and dynamic UI elements.
450 $( document ).trigger( 'widget-added', [ this.container.find( '.widget:first' ) ] );
454 * Handle changes to the setting
456 _setupModel: function() {
457 var self = this, rememberSavedWidgetId;
459 api.Widgets.savedWidgetIds = api.Widgets.savedWidgetIds || [];
461 // Remember saved widgets so we know which to trash (move to inactive widgets sidebar)
462 rememberSavedWidgetId = function() {
463 api.Widgets.savedWidgetIds[self.params.widget_id] = true;
465 api.bind( 'ready', rememberSavedWidgetId );
466 api.bind( 'saved', rememberSavedWidgetId );
468 this._updateCount = 0;
469 this.isWidgetUpdating = false;
470 this.liveUpdateMode = true;
472 // Update widget whenever model changes
473 this.setting.bind( function( to, from ) {
474 if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) {
475 self.updateWidget( { instance: to } );
481 * Add special behaviors for wide widget controls
483 _setupWideWidget: function() {
484 var self = this, $widgetInside, $widgetForm, $customizeSidebar,
485 $themeControlsContainer, positionWidget;
487 if ( ! this.params.is_wide ) {
491 $widgetInside = this.container.find( '.widget-inside' );
492 $widgetForm = $widgetInside.find( '> .form' );
493 $customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' );
494 this.container.addClass( 'wide-widget-control' );
496 this.container.find( '.widget-content:first' ).css( {
497 'max-width': this.params.width,
498 'min-height': this.params.height
502 * Keep the widget-inside positioned so the top of fixed-positioned
503 * element is at the same top position as the widget-top. When the
504 * widget-top is scrolled out of view, keep the widget-top in view;
505 * likewise, don't allow the widget to drop off the bottom of the window.
506 * If a widget is too tall to fit in the window, don't let the height
507 * exceed the window height so that the contents of the widget control
508 * will become scrollable (overflow:auto).
510 positionWidget = function() {
511 var offsetTop = self.container.offset().top,
512 windowHeight = $( window ).height(),
513 formHeight = $widgetForm.outerHeight(),
515 $widgetInside.css( 'max-height', windowHeight );
517 0, // prevent top from going off screen
519 Math.max( offsetTop, 0 ), // distance widget in panel is from top of screen
520 windowHeight - formHeight // flush up against bottom of screen
523 $widgetInside.css( 'top', top );
526 $themeControlsContainer = $( '#customize-theme-controls' );
527 this.container.on( 'expand', function() {
529 $customizeSidebar.on( 'scroll', positionWidget );
530 $( window ).on( 'resize', positionWidget );
531 $themeControlsContainer.on( 'expanded collapsed', positionWidget );
533 this.container.on( 'collapsed', function() {
534 $customizeSidebar.off( 'scroll', positionWidget );
535 $( window ).off( 'resize', positionWidget );
536 $themeControlsContainer.off( 'expanded collapsed', positionWidget );
539 // Reposition whenever a sidebar's widgets are changed
540 api.each( function( setting ) {
541 if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) {
542 setting.bind( function() {
543 if ( self.container.hasClass( 'expanded' ) ) {
552 * Show/hide the control when clicking on the form title, when clicking
555 _setupControlToggle: function() {
556 var self = this, $closeBtn;
558 this.container.find( '.widget-top' ).on( 'click', function( e ) {
560 var sidebarWidgetsControl = self.getSidebarWidgetsControl();
561 if ( sidebarWidgetsControl.isReordering ) {
564 self.expanded( ! self.expanded() );
567 $closeBtn = this.container.find( '.widget-control-close' );
568 $closeBtn.on( 'click', function( e ) {
571 self.container.find( '.widget-top .widget-action:first' ).focus(); // keyboard accessibility
576 * Update the title of the form if a title field is entered
578 _setupWidgetTitle: function() {
579 var self = this, updateTitle;
581 updateTitle = function() {
582 var title = self.setting().title,
583 inWidgetTitle = self.container.find( '.in-widget-title' );
586 inWidgetTitle.text( ': ' + title );
588 inWidgetTitle.text( '' );
591 this.setting.bind( updateTitle );
596 * Set up the widget-reorder-nav
598 _setupReorderUI: function() {
599 var self = this, selectSidebarItem, $moveWidgetArea,
600 $reorderNav, updateAvailableSidebars;
603 * select the provided sidebar list item in the move widget area
607 selectSidebarItem = function( li ) {
608 li.siblings( '.selected' ).removeClass( 'selected' );
609 li.addClass( 'selected' );
610 var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id );
611 self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar );
615 * Add the widget reordering elements to the widget control
617 this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) );
619 _.template( api.Widgets.data.tpl.moveWidgetArea, {
620 sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' )
623 this.container.find( '.widget-top' ).after( $moveWidgetArea );
626 * Update available sidebars when their rendered state changes
628 updateAvailableSidebars = function() {
629 var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem,
630 renderedSidebarCount = 0;
632 selfSidebarItem = $sidebarItems.filter( function(){
633 return $( this ).data( 'id' ) === self.params.sidebar_id;
636 $sidebarItems.each( function() {
638 sidebarId, sidebar, sidebarIsRendered;
640 sidebarId = li.data( 'id' );
641 sidebar = api.Widgets.registeredSidebars.get( sidebarId );
642 sidebarIsRendered = sidebar.get( 'is_rendered' );
644 li.toggle( sidebarIsRendered );
646 if ( sidebarIsRendered ) {
647 renderedSidebarCount += 1;
650 if ( li.hasClass( 'selected' ) && ! sidebarIsRendered ) {
651 selectSidebarItem( selfSidebarItem );
655 if ( renderedSidebarCount > 1 ) {
656 self.container.find( '.move-widget' ).show();
658 self.container.find( '.move-widget' ).hide();
662 updateAvailableSidebars();
663 api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars );
666 * Handle clicks for up/down/move on the reorder nav
668 $reorderNav = this.container.find( '.widget-reorder-nav' );
669 $reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() {
670 $( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' );
671 } ).on( 'click keypress', function( event ) {
672 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
677 if ( $( this ).is( '.move-widget' ) ) {
678 self.toggleWidgetMoveArea();
680 var isMoveDown = $( this ).is( '.move-widget-down' ),
681 isMoveUp = $( this ).is( '.move-widget-up' ),
682 i = self.getWidgetSidebarPosition();
684 if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) {
690 wp.a11y.speak( l10n.widgetMovedUp );
693 wp.a11y.speak( l10n.widgetMovedDown );
696 $( this ).focus(); // re-focus after the container was moved
701 * Handle selecting a sidebar to move to
703 this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( event ) {
704 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
707 event.preventDefault();
708 selectSidebarItem( $( this ) );
712 * Move widget to another sidebar
714 this.container.find( '.move-widget-btn' ).click( function() {
715 self.getSidebarWidgetsControl().toggleReordering( false );
717 var oldSidebarId = self.params.sidebar_id,
718 newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ),
719 oldSidebarWidgetsSetting, newSidebarWidgetsSetting,
720 oldSidebarWidgetIds, newSidebarWidgetIds, i;
722 oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' );
723 newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' );
724 oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() );
725 newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() );
727 i = self.getWidgetSidebarPosition();
728 oldSidebarWidgetIds.splice( i, 1 );
729 newSidebarWidgetIds.push( self.params.widget_id );
731 oldSidebarWidgetsSetting( oldSidebarWidgetIds );
732 newSidebarWidgetsSetting( newSidebarWidgetIds );
739 * Highlight widgets in preview when interacted with in the Customizer
741 _setupHighlightEffects: function() {
744 // Highlight whenever hovering or clicking over the form
745 this.container.on( 'mouseenter click', function() {
746 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
749 // Highlight when the setting is updated
750 this.setting.bind( function() {
751 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
756 * Set up event handlers for widget updating
758 _setupUpdateUI: function() {
759 var self = this, $widgetRoot, $widgetContent,
760 $saveBtn, updateWidgetDebounced, formSyncHandler;
762 $widgetRoot = this.container.find( '.widget:first' );
763 $widgetContent = $widgetRoot.find( '.widget-content:first' );
765 // Configure update button
766 $saveBtn = this.container.find( '.widget-control-save' );
767 $saveBtn.val( l10n.saveBtnLabel );
768 $saveBtn.attr( 'title', l10n.saveBtnTooltip );
769 $saveBtn.removeClass( 'button-primary' ).addClass( 'button-secondary' );
770 $saveBtn.on( 'click', function( e ) {
772 self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
775 updateWidgetDebounced = _.debounce( function() {
779 // Trigger widget form update when hitting Enter within an input
780 $widgetContent.on( 'keydown', 'input', function( e ) {
781 if ( 13 === e.which ) { // Enter
783 self.updateWidget( { ignoreActiveElement: true } );
787 // Handle widgets that support live previews
788 $widgetContent.on( 'change input propertychange', ':input', function( e ) {
789 if ( ! self.liveUpdateMode ) {
792 if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) {
793 updateWidgetDebounced();
797 // Remove loading indicators when the setting is saved and the preview updates
798 this.setting.previewer.channel.bind( 'synced', function() {
799 self.container.removeClass( 'previewer-loading' );
802 api.previewer.bind( 'widget-updated', function( updatedWidgetId ) {
803 if ( updatedWidgetId === self.params.widget_id ) {
804 self.container.removeClass( 'previewer-loading' );
808 formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
809 if ( formSyncHandler ) {
810 $( document ).on( 'widget-synced', function( e, widget ) {
811 if ( $widgetRoot.is( widget ) ) {
812 formSyncHandler.apply( document, arguments );
819 * Update widget control to indicate whether it is currently rendered.
821 * Overrides api.Control.toggle()
825 * @param {Boolean} active
826 * @param {Object} args
827 * @param {Callback} args.completeCallback
829 onChangeActive: function ( active, args ) {
830 // Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments
831 this.container.toggleClass( 'widget-rendered', active );
832 if ( args.completeCallback ) {
833 args.completeCallback();
838 * Set up event handlers for widget removal
840 _setupRemoveUI: function() {
841 var self = this, $removeBtn, replaceDeleteWithRemove;
843 // Configure remove button
844 $removeBtn = this.container.find( 'a.widget-control-remove' );
845 $removeBtn.on( 'click', function( e ) {
848 // Find an adjacent element to add focus to when this widget goes away
849 var $adjacentFocusTarget;
850 if ( self.container.next().is( '.customize-control-widget_form' ) ) {
851 $adjacentFocusTarget = self.container.next().find( '.widget-action:first' );
852 } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) {
853 $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' );
855 $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' );
858 self.container.slideUp( function() {
859 var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
862 if ( ! sidebarsWidgetsControl ) {
866 sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
867 i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
872 sidebarWidgetIds.splice( i, 1 );
873 sidebarsWidgetsControl.setting( sidebarWidgetIds );
875 $adjacentFocusTarget.focus(); // keyboard accessibility
879 replaceDeleteWithRemove = function() {
880 $removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the link as "Delete"
881 $removeBtn.attr( 'title', l10n.removeBtnTooltip );
884 if ( this.params.is_new ) {
885 api.bind( 'saved', replaceDeleteWithRemove );
887 replaceDeleteWithRemove();
892 * Find all inputs in a widget container that should be considered when
893 * comparing the loaded form with the sanitized form, whose fields will
894 * be aligned to copy the sanitized over. The elements returned by this
895 * are passed into this._getInputsSignature(), and they are iterated
896 * over when copying sanitized values over to the the form loaded.
898 * @param {jQuery} container element in which to look for inputs
899 * @returns {jQuery} inputs
902 _getInputs: function( container ) {
903 return $( container ).find( ':input[name]' );
907 * Iterate over supplied inputs and create a signature string for all of them together.
908 * This string can be used to compare whether or not the form has all of the same fields.
910 * @param {jQuery} inputs
914 _getInputsSignature: function( inputs ) {
915 var inputsSignatures = _( inputs ).map( function( input ) {
916 var $input = $( input ), signatureParts;
918 if ( $input.is( ':checkbox, :radio' ) ) {
919 signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ];
921 signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ];
924 return signatureParts.join( ',' );
927 return inputsSignatures.join( ';' );
931 * Get the state for an input depending on its type.
933 * @param {jQuery|Element} input
934 * @returns {string|boolean|array|*}
937 _getInputState: function( input ) {
939 if ( input.is( ':radio, :checkbox' ) ) {
940 return input.prop( 'checked' );
941 } else if ( input.is( 'select[multiple]' ) ) {
942 return input.find( 'option:selected' ).map( function () {
943 return $( this ).val();
951 * Update an input's state based on its type.
953 * @param {jQuery|Element} input
954 * @param {string|boolean|array|*} state
957 _setInputState: function ( input, state ) {
959 if ( input.is( ':radio, :checkbox' ) ) {
960 input.prop( 'checked', state );
961 } else if ( input.is( 'select[multiple]' ) ) {
962 if ( ! $.isArray( state ) ) {
965 // Make sure all state items are strings since the DOM value is a string
966 state = _.map( state, function ( value ) {
967 return String( value );
970 input.find( 'option' ).each( function () {
971 $( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) );
978 /***********************************************************************
979 * Begin public API methods
980 **********************************************************************/
983 * @return {wp.customize.controlConstructor.sidebar_widgets[]}
985 getSidebarWidgetsControl: function() {
986 var settingId, sidebarWidgetsControl;
988 settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']';
989 sidebarWidgetsControl = api.control( settingId );
991 if ( ! sidebarWidgetsControl ) {
995 return sidebarWidgetsControl;
999 * Submit the widget form via Ajax and get back the updated instance,
1000 * along with the new widget control form to render.
1002 * @param {object} [args]
1003 * @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used
1004 * @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.
1005 * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
1007 updateWidget: function( args ) {
1008 var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
1009 updateNumber, params, data, $inputs, processing, jqxhr, isChanged;
1014 ignoreActiveElement: false
1017 instanceOverride = args.instance;
1018 completeCallback = args.complete;
1020 this._updateCount += 1;
1021 updateNumber = this._updateCount;
1023 $widgetRoot = this.container.find( '.widget:first' );
1024 $widgetContent = $widgetRoot.find( '.widget-content:first' );
1026 // Remove a previous error message
1027 $widgetContent.find( '.widget-error' ).remove();
1029 this.container.addClass( 'widget-form-loading' );
1030 this.container.addClass( 'previewer-loading' );
1031 processing = api.state( 'processing' );
1032 processing( processing() + 1 );
1034 if ( ! this.liveUpdateMode ) {
1035 this.container.addClass( 'widget-form-disabled' );
1039 params.action = 'update-widget';
1040 params.wp_customize = 'on';
1041 params.nonce = api.Widgets.data.nonce;
1042 params.theme = api.settings.theme.stylesheet;
1043 params.customized = wp.customize.previewer.query().customized;
1045 data = $.param( params );
1046 $inputs = this._getInputs( $widgetContent );
1048 // Store the value we're submitting in data so that when the response comes back,
1049 // we know if it got sanitized; if there is no difference in the sanitized value,
1050 // then we do not need to touch the UI and mess up the user's ongoing editing.
1051 $inputs.each( function() {
1052 $( this ).data( 'state' + updateNumber, self._getInputState( this ) );
1055 if ( instanceOverride ) {
1056 data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } );
1058 data += '&' + $inputs.serialize();
1060 data += '&' + $widgetContent.find( '~ :input' ).serialize();
1062 if ( this._previousUpdateRequest ) {
1063 this._previousUpdateRequest.abort();
1065 jqxhr = $.post( wp.ajax.settings.url, data );
1066 this._previousUpdateRequest = jqxhr;
1068 jqxhr.done( function( r ) {
1069 var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse,
1070 isLiveUpdateAborted = false;
1072 // Check if the user is logged out.
1074 api.previewer.preview.iframe.hide();
1075 api.previewer.login().done( function() {
1076 self.updateWidget( args );
1077 api.previewer.preview.iframe.show();
1082 // Check for cheaters.
1084 api.previewer.cheatin();
1089 sanitizedForm = $( '<div>' + r.data.form + '</div>' );
1090 $sanitizedInputs = self._getInputs( sanitizedForm );
1091 hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs );
1093 // Restore live update mode if sanitized fields are now aligned with the existing fields
1094 if ( hasSameInputsInResponse && ! self.liveUpdateMode ) {
1095 self.liveUpdateMode = true;
1096 self.container.removeClass( 'widget-form-disabled' );
1097 self.container.find( 'input[name="savewidget"]' ).hide();
1100 // Sync sanitized field states to existing fields if they are aligned
1101 if ( hasSameInputsInResponse && self.liveUpdateMode ) {
1102 $inputs.each( function( i ) {
1103 var $input = $( this ),
1104 $sanitizedInput = $( $sanitizedInputs[i] ),
1105 submittedState, sanitizedState, canUpdateState;
1107 submittedState = $input.data( 'state' + updateNumber );
1108 sanitizedState = self._getInputState( $sanitizedInput );
1109 $input.data( 'sanitized', sanitizedState );
1111 canUpdateState = ( ! _.isEqual( submittedState, sanitizedState ) && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
1112 if ( canUpdateState ) {
1113 self._setInputState( $input, sanitizedState );
1117 $( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] );
1119 // Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled
1120 } else if ( self.liveUpdateMode ) {
1121 self.liveUpdateMode = false;
1122 self.container.find( 'input[name="savewidget"]' ).show();
1123 isLiveUpdateAborted = true;
1125 // Otherwise, replace existing form with the sanitized form
1127 $widgetContent.html( r.data.form );
1129 self.container.removeClass( 'widget-form-disabled' );
1131 $( document ).trigger( 'widget-updated', [ $widgetRoot ] );
1135 * If the old instance is identical to the new one, there is nothing new
1136 * needing to be rendered, and so we can preempt the event for the
1137 * preview finishing loading.
1139 isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance );
1141 self.isWidgetUpdating = true; // suppress triggering another updateWidget
1142 self.setting( r.data.instance );
1143 self.isWidgetUpdating = false;
1145 // no change was made, so stop the spinner now instead of when the preview would updates
1146 self.container.removeClass( 'previewer-loading' );
1149 if ( completeCallback ) {
1150 completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
1153 // General error message
1154 message = l10n.error;
1156 if ( r.data && r.data.message ) {
1157 message = r.data.message;
1160 if ( completeCallback ) {
1161 completeCallback.call( self, message );
1163 $widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' );
1168 jqxhr.fail( function( jqXHR, textStatus ) {
1169 if ( completeCallback ) {
1170 completeCallback.call( self, textStatus );
1174 jqxhr.always( function() {
1175 self.container.removeClass( 'widget-form-loading' );
1177 $inputs.each( function() {
1178 $( this ).removeData( 'state' + updateNumber );
1181 processing( processing() - 1 );
1186 * Expand the accordion section containing a control
1188 expandControlSection: function() {
1189 api.Control.prototype.expand.call( this );
1195 * @param {Boolean} expanded
1196 * @param {Object} [params]
1197 * @returns {Boolean} false if state already applied
1199 _toggleExpanded: api.Section.prototype._toggleExpanded,
1204 * @param {Object} [params]
1205 * @returns {Boolean} false if already expanded
1207 expand: api.Section.prototype.expand,
1210 * Expand the widget form control
1212 * @deprecated 4.1.0 Use this.expand() instead.
1214 expandForm: function() {
1221 * @param {Object} [params]
1222 * @returns {Boolean} false if already collapsed
1224 collapse: api.Section.prototype.collapse,
1227 * Collapse the widget form control
1229 * @deprecated 4.1.0 Use this.collapse() instead.
1231 collapseForm: function() {
1236 * Expand or collapse the widget control
1238 * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
1240 * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility
1242 toggleForm: function( showOrHide ) {
1243 if ( typeof showOrHide === 'undefined' ) {
1244 showOrHide = ! this.expanded();
1246 this.expanded( showOrHide );
1250 * Respond to change in the expanded state.
1252 * @param {Boolean} expanded
1253 * @param {Object} args merged on top of this.defaultActiveArguments
1255 onChangeExpanded: function ( expanded, args ) {
1256 var self = this, $widget, $inside, complete, prevComplete;
1258 // If the expanded state is unchanged only manipulate container expanded states
1259 if ( args.unchanged ) {
1261 api.Control.prototype.expand.call( self, {
1262 completeCallback: args.completeCallback
1268 $widget = this.container.find( 'div.widget:first' );
1269 $inside = $widget.find( '.widget-inside:first' );
1273 if ( self.section() && api.section( self.section() ) ) {
1274 self.expandControlSection();
1277 // Close all other widget controls before expanding this one
1278 api.control.each( function( otherControl ) {
1279 if ( self.params.type === otherControl.params.type && self !== otherControl ) {
1280 otherControl.collapse();
1284 complete = function() {
1285 self.container.removeClass( 'expanding' );
1286 self.container.addClass( 'expanded' );
1287 self.container.trigger( 'expanded' );
1289 if ( args.completeCallback ) {
1290 prevComplete = complete;
1291 complete = function () {
1293 args.completeCallback();
1297 if ( self.params.is_wide ) {
1298 $inside.fadeIn( args.duration, complete );
1300 $inside.slideDown( args.duration, complete );
1303 self.container.trigger( 'expand' );
1304 self.container.addClass( 'expanding' );
1307 complete = function() {
1308 self.container.removeClass( 'collapsing' );
1309 self.container.removeClass( 'expanded' );
1310 self.container.trigger( 'collapsed' );
1312 if ( args.completeCallback ) {
1313 prevComplete = complete;
1314 complete = function () {
1316 args.completeCallback();
1320 self.container.trigger( 'collapse' );
1321 self.container.addClass( 'collapsing' );
1323 if ( self.params.is_wide ) {
1324 $inside.fadeOut( args.duration, complete );
1326 $inside.slideUp( args.duration, function() {
1327 $widget.css( { width:'', margin:'' } );
1335 * Get the position (index) of the widget in the containing sidebar
1339 getWidgetSidebarPosition: function() {
1340 var sidebarWidgetIds, position;
1342 sidebarWidgetIds = this.getSidebarWidgetsControl().setting();
1343 position = _.indexOf( sidebarWidgetIds, this.params.widget_id );
1345 if ( position === -1 ) {
1353 * Move widget up one in the sidebar
1355 moveUp: function() {
1356 this._moveWidgetByOne( -1 );
1360 * Move widget up one in the sidebar
1362 moveDown: function() {
1363 this._moveWidgetByOne( 1 );
1369 * @param {Number} offset 1|-1
1371 _moveWidgetByOne: function( offset ) {
1372 var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId;
1374 i = this.getWidgetSidebarPosition();
1376 sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting;
1377 sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // clone
1378 adjacentWidgetId = sidebarWidgetIds[i + offset];
1379 sidebarWidgetIds[i + offset] = this.params.widget_id;
1380 sidebarWidgetIds[i] = adjacentWidgetId;
1382 sidebarWidgetsSetting( sidebarWidgetIds );
1386 * Toggle visibility of the widget move area
1388 * @param {Boolean} [showOrHide]
1390 toggleWidgetMoveArea: function( showOrHide ) {
1391 var self = this, $moveWidgetArea;
1393 $moveWidgetArea = this.container.find( '.move-widget-area' );
1395 if ( typeof showOrHide === 'undefined' ) {
1396 showOrHide = ! $moveWidgetArea.hasClass( 'active' );
1400 // reset the selected sidebar
1401 $moveWidgetArea.find( '.selected' ).removeClass( 'selected' );
1403 $moveWidgetArea.find( 'li' ).filter( function() {
1404 return $( this ).data( 'id' ) === self.params.sidebar_id;
1405 } ).addClass( 'selected' );
1407 this.container.find( '.move-widget-btn' ).prop( 'disabled', true );
1410 $moveWidgetArea.toggleClass( 'active', showOrHide );
1414 * Highlight the widget control and section
1416 highlightSectionAndControl: function() {
1419 if ( this.container.is( ':hidden' ) ) {
1420 $target = this.container.closest( '.control-section' );
1422 $target = this.container;
1425 $( '.highlighted' ).removeClass( 'highlighted' );
1426 $target.addClass( 'highlighted' );
1428 setTimeout( function() {
1429 $target.removeClass( 'highlighted' );
1435 * wp.customize.Widgets.SidebarSection
1437 * Customizer section representing a widget area widget
1441 api.Widgets.SidebarSection = api.Section.extend({
1444 * Sync the section's active state back to the Backbone model's is_rendered attribute
1448 ready: function () {
1449 var section = this, registeredSidebar;
1450 api.Section.prototype.ready.call( this );
1451 registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId );
1452 section.active.bind( function ( active ) {
1453 registeredSidebar.set( 'is_rendered', active );
1455 registeredSidebar.set( 'is_rendered', section.active() );
1460 * wp.customize.Widgets.SidebarControl
1462 * Customizer control for widgets.
1463 * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type
1468 * @augments wp.customize.Control
1470 api.Widgets.SidebarControl = api.Control.extend({
1473 * Set up the control
1476 this.$controlSection = this.container.closest( '.control-section' );
1477 this.$sectionContent = this.container.closest( '.accordion-section-content' );
1480 this._setupSortable();
1481 this._setupAddition();
1482 this._applyCardinalOrderClassNames();
1486 * Update ordering of widget control forms when the setting is updated
1488 _setupModel: function() {
1491 this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
1492 var widgetFormControls, removedWidgetIds, priority;
1494 removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );
1496 // Filter out any persistent widget IDs for widgets which have been deactivated
1497 newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
1498 var parsedWidgetId = parseWidgetId( newWidgetId );
1500 return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
1503 widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
1504 var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1506 if ( ! widgetFormControl ) {
1507 widgetFormControl = self.addWidget( widgetId );
1510 return widgetFormControl;
1513 // Sort widget controls to their new positions
1514 widgetFormControls.sort( function( a, b ) {
1515 var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
1516 bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
1517 return aIndex - bIndex;
1521 _( widgetFormControls ).each( function ( control ) {
1522 control.priority( priority );
1523 control.section( self.section() );
1526 self.priority( priority ); // Make sure sidebar control remains at end
1528 // Re-sort widget form controls (including widgets form other sidebars newly moved here)
1529 self._applyCardinalOrderClassNames();
1531 // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated
1532 _( widgetFormControls ).each( function( widgetFormControl ) {
1533 widgetFormControl.params.sidebar_id = self.params.sidebar_id;
1536 // Cleanup after widget removal
1537 _( removedWidgetIds ).each( function( removedWidgetId ) {
1539 // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update
1540 setTimeout( function() {
1541 var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
1542 widget, isPresentInAnotherSidebar = false;
1544 // Check if the widget is in another sidebar
1545 api.each( function( otherSetting ) {
1546 if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) {
1550 var otherSidebarWidgets = otherSetting(), i;
1552 i = _.indexOf( otherSidebarWidgets, removedWidgetId );
1554 isPresentInAnotherSidebar = true;
1558 // If the widget is present in another sidebar, abort!
1559 if ( isPresentInAnotherSidebar ) {
1563 removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );
1565 // Detect if widget control was dragged to another sidebar
1566 wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
1568 // Delete any widget form controls for removed widgets
1569 if ( removedControl && ! wasDraggedToAnotherSidebar ) {
1570 api.control.remove( removedControl.id );
1571 removedControl.container.remove();
1574 // Move widget to inactive widgets sidebar (move it to trash) if has been previously saved
1575 // This prevents the inactive widgets sidebar from overflowing with throwaway widgets
1576 if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
1577 inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice();
1578 inactiveWidgets.push( removedWidgetId );
1579 api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() );
1582 // Make old single widget available for adding again
1583 removedIdBase = parseWidgetId( removedWidgetId ).id_base;
1584 widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
1585 if ( widget && ! widget.get( 'is_multi' ) ) {
1586 widget.set( 'is_disabled', false );
1595 * Allow widgets in sidebar to be re-ordered, and for the order to be previewed
1597 _setupSortable: function() {
1600 this.isReordering = false;
1603 * Update widget order setting when controls are re-ordered
1605 this.$sectionContent.sortable( {
1606 items: '> .customize-control-widget_form',
1607 handle: '.widget-top',
1609 tolerance: 'pointer',
1610 connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
1611 update: function() {
1612 var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
1614 widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
1615 return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
1618 self.setting( widgetIds );
1623 * Expand other Customizer sidebar section when dragging a control widget over it,
1624 * allowing the control to be dropped into another section
1626 this.$controlSection.find( '.accordion-section-title' ).droppable({
1627 accept: '.customize-control-widget_form',
1629 var section = api.section( self.section.get() );
1631 allowMultiple: true, // Prevent the section being dragged from to be collapsed
1632 completeCallback: function () {
1633 // @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed
1634 api.section.each( function ( otherSection ) {
1635 if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) {
1636 otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' );
1645 * Keyboard-accessible reordering
1647 this.container.find( '.reorder-toggle' ).on( 'click keydown', function( event ) {
1648 if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar
1652 self.toggleReordering( ! self.isReordering );
1657 * Set up UI for adding a new widget
1659 _setupAddition: function() {
1662 this.container.find( '.add-new-widget' ).on( 'click keydown', function( event ) {
1663 if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar
1667 if ( self.$sectionContent.hasClass( 'reordering' ) ) {
1671 if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
1672 api.Widgets.availableWidgetsPanel.open( self );
1674 api.Widgets.availableWidgetsPanel.close();
1680 * Add classes to the widget_form controls to assist with styling
1682 _applyCardinalOrderClassNames: function() {
1683 var widgetControls = [];
1684 _.each( this.setting(), function ( widgetId ) {
1685 var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1686 if ( widgetControl ) {
1687 widgetControls.push( widgetControl );
1691 if ( ! widgetControls.length ) {
1692 this.container.find( '.reorder-toggle' ).hide();
1695 this.container.find( '.reorder-toggle' ).show();
1698 $( widgetControls ).each( function () {
1700 .removeClass( 'first-widget' )
1701 .removeClass( 'last-widget' )
1702 .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
1705 _.first( widgetControls ).container
1706 .addClass( 'first-widget' )
1707 .find( '.move-widget-up' ).prop( 'tabIndex', -1 );
1709 _.last( widgetControls ).container
1710 .addClass( 'last-widget' )
1711 .find( '.move-widget-down' ).prop( 'tabIndex', -1 );
1715 /***********************************************************************
1716 * Begin public API methods
1717 **********************************************************************/
1720 * Enable/disable the reordering UI
1722 * @param {Boolean} showOrHide to enable/disable reordering
1724 * @todo We should have a reordering state instead and rename this to onChangeReordering
1726 toggleReordering: function( showOrHide ) {
1727 showOrHide = Boolean( showOrHide );
1729 if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
1733 this.isReordering = showOrHide;
1734 this.$sectionContent.toggleClass( 'reordering', showOrHide );
1737 _( this.getWidgetFormControls() ).each( function( formControl ) {
1738 formControl.collapse();
1741 this.$sectionContent.find( '.first-widget .move-widget' ).focus();
1742 this.$sectionContent.find( '.add-new-widget' ).prop( 'tabIndex', -1 );
1744 this.$sectionContent.find( '.add-new-widget' ).prop( 'tabIndex', 0 );
1749 * Get the widget_form Customize controls associated with the current sidebar.
1752 * @return {wp.customize.controlConstructor.widget_form[]}
1754 getWidgetFormControls: function() {
1755 var formControls = [];
1757 _( this.setting() ).each( function( widgetId ) {
1758 var settingId = widgetIdToSettingId( widgetId ),
1759 formControl = api.control( settingId );
1760 if ( formControl ) {
1761 formControls.push( formControl );
1765 return formControls;
1769 * @param {string} widgetId or an id_base for adding a previously non-existing widget
1770 * @returns {object|false} widget_form control instance, or false on error
1772 addWidget: function( widgetId ) {
1773 var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor,
1774 parsedWidgetId = parseWidgetId( widgetId ),
1775 widgetNumber = parsedWidgetId.number,
1776 widgetIdBase = parsedWidgetId.id_base,
1777 widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
1778 settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting;
1784 if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
1788 // Set up new multi widget
1789 if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
1790 widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
1791 widgetNumber = widget.get( 'multi_number' );
1794 controlHtml = $.trim( $( '#widget-tpl-' + widget.get( 'id' ) ).html() );
1795 if ( widget.get( 'is_multi' ) ) {
1796 controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
1797 return m.replace( /__i__|%i%/g, widgetNumber );
1800 widget.set( 'is_disabled', true ); // Prevent single widget from being added again now
1803 $widget = $( controlHtml );
1805 controlContainer = $( '<li/>' )
1806 .addClass( 'customize-control' )
1807 .addClass( 'customize-control-' + controlType )
1810 // Remove icon which is visible inside the panel
1811 controlContainer.find( '> .widget-icon' ).remove();
1813 if ( widget.get( 'is_multi' ) ) {
1814 controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber );
1815 controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber );
1818 widgetId = controlContainer.find( '[name="widget-id"]' ).val();
1820 controlContainer.hide(); // to be slid-down below
1822 settingId = 'widget_' + widget.get( 'id_base' );
1823 if ( widget.get( 'is_multi' ) ) {
1824 settingId += '[' + widgetNumber + ']';
1826 controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );
1828 // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget)
1829 isExistingWidget = api.has( settingId );
1830 if ( ! isExistingWidget ) {
1832 transport: 'refresh',
1833 previewer: this.setting.previewer
1835 setting = api.create( settingId, settingId, '', settingArgs );
1836 setting.set( {} ); // mark dirty, changing from '' to {}
1839 controlConstructor = api.controlConstructor[controlType];
1840 widgetFormControl = new controlConstructor( settingId, {
1843 'default': settingId
1845 content: controlContainer,
1846 sidebar_id: self.params.sidebar_id,
1847 widget_id: widgetId,
1848 widget_id_base: widget.get( 'id_base' ),
1850 is_new: ! isExistingWidget,
1851 width: widget.get( 'width' ),
1852 height: widget.get( 'height' ),
1853 is_wide: widget.get( 'is_wide' )
1855 previewer: self.setting.previewer
1857 api.control.add( settingId, widgetFormControl );
1859 // Make sure widget is removed from the other sidebars
1860 api.each( function( otherSetting ) {
1861 if ( otherSetting.id === self.setting.id ) {
1865 if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
1869 var otherSidebarWidgets = otherSetting().slice(),
1870 i = _.indexOf( otherSidebarWidgets, widgetId );
1873 otherSidebarWidgets.splice( i );
1874 otherSetting( otherSidebarWidgets );
1878 // Add widget to this sidebar
1879 sidebarWidgets = this.setting().slice();
1880 if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
1881 sidebarWidgets.push( widgetId );
1882 this.setting( sidebarWidgets );
1885 controlContainer.slideDown( function() {
1886 if ( isExistingWidget ) {
1887 widgetFormControl.updateWidget( {
1888 instance: widgetFormControl.setting()
1893 return widgetFormControl;
1897 // Register models for custom section and control types
1898 $.extend( api.sectionConstructor, {
1899 sidebar: api.Widgets.SidebarSection
1901 $.extend( api.controlConstructor, {
1902 widget_form: api.Widgets.WidgetControl,
1903 sidebar_widgets: api.Widgets.SidebarControl
1906 // Refresh the nonce if login sends updated nonces over.
1907 api.bind( 'nonce-refresh', function( nonces ) {
1908 api.Widgets.data.nonce = nonces['update-widget'];
1912 * Init Customizer for widgets.
1914 api.bind( 'ready', function() {
1915 // Set up the widgets panel
1916 api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
1917 collection: api.Widgets.availableWidgets
1920 // Highlight widget control
1921 api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
1923 // Open and focus widget control
1924 api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
1928 * Highlight a widget control.
1930 * @param {string} widgetId
1932 api.Widgets.highlightWidgetFormControl = function( widgetId ) {
1933 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
1936 control.highlightSectionAndControl();
1941 * Focus a widget control.
1943 * @param {string} widgetId
1945 api.Widgets.focusWidgetFormControl = function( widgetId ) {
1946 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
1954 * Given a widget control, find the sidebar widgets control that contains it.
1955 * @param {string} widgetId
1956 * @return {object|null}
1958 api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
1959 var foundControl = null;
1961 // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl()
1962 api.control.each( function( control ) {
1963 if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
1964 foundControl = control;
1968 return foundControl;
1972 * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
1974 * @param {string} widgetId
1975 * @return {object|null}
1977 api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
1978 var foundControl = null;
1980 // @todo We can just use widgetIdToSettingId() here
1981 api.control.each( function( control ) {
1982 if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
1983 foundControl = control;
1987 return foundControl;
1991 * @param {String} widgetId
1994 function parseWidgetId( widgetId ) {
1995 var matches, parsed = {
2000 matches = widgetId.match( /^(.+)-(\d+)$/ );
2002 parsed.id_base = matches[1];
2003 parsed.number = parseInt( matches[2], 10 );
2005 // likely an old single widget
2006 parsed.id_base = widgetId;
2013 * @param {String} widgetId
2014 * @returns {String} settingId
2016 function widgetIdToSettingId( widgetId ) {
2017 var parsed = parseWidgetId( widgetId ), settingId;
2019 settingId = 'widget_' + parsed.id_base;
2020 if ( parsed.number ) {
2021 settingId += '[' + parsed.number + ']';
2027 })( window.wp, jQuery );