1 /* global _wpCustomizeWidgetsSettings */
4 if ( ! wp || ! wp.customize ) { return; }
6 // Set up our namespace...
7 var api = wp.customize,
10 api.Widgets = api.Widgets || {};
11 api.Widgets.savedWidgetIds = {};
14 api.Widgets.data = _wpCustomizeWidgetsSettings || {};
15 l10n = api.Widgets.data.l10n;
16 delete api.Widgets.data.l10n;
19 * wp.customize.Widgets.WidgetModel
21 * A single widget model.
24 * @augments Backbone.Model
26 api.Widgets.WidgetModel = Backbone.Model.extend({
45 * wp.customize.Widgets.WidgetCollection
47 * Collection for widget models.
50 * @augments Backbone.Model
52 api.Widgets.WidgetCollection = Backbone.Collection.extend({
53 model: api.Widgets.WidgetModel,
55 // Controls searching on the current widget collection
56 // and triggers an update event
57 doSearch: function( value ) {
59 // Don't do anything if we've already done this search
60 // Useful because the search handler fires multiple times per keystroke
61 if ( this.terms === value ) {
65 // Updates terms with the value passed
68 // If we have terms, run a search...
69 if ( this.terms.length > 0 ) {
70 this.search( this.terms );
73 // If search is blank, show all themes
74 // Useful for resetting the views when you clean the input
75 if ( this.terms === '' ) {
76 this.each( function ( widget ) {
77 widget.set( 'search_matched', true );
82 // Performs a search within the collection
84 search: function( term ) {
87 // Escape the term string for RegExp meta characters
88 term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
90 // Consider spaces as word delimiters and match the whole string
91 // so matching terms can be combined
92 term = term.replace( / /g, ')(?=.*' );
93 match = new RegExp( '^(?=.*' + term + ').+', 'i' );
95 this.each( function ( data ) {
96 haystack = [ data.get( 'name' ), data.get( 'id' ), data.get( 'description' ) ].join( ' ' );
97 data.set( 'search_matched', match.test( haystack ) );
101 api.Widgets.availableWidgets = new api.Widgets.WidgetCollection( api.Widgets.data.availableWidgets );
104 * wp.customize.Widgets.SidebarModel
106 * A single sidebar model.
109 * @augments Backbone.Model
111 api.Widgets.SidebarModel = Backbone.Model.extend({
124 * wp.customize.Widgets.SidebarCollection
126 * Collection for sidebar models.
129 * @augments Backbone.Collection
131 api.Widgets.SidebarCollection = Backbone.Collection.extend({
132 model: api.Widgets.SidebarModel
134 api.Widgets.registeredSidebars = new api.Widgets.SidebarCollection( api.Widgets.data.registeredSidebars );
137 * wp.customize.Widgets.AvailableWidgetsPanelView
139 * View class for the available widgets panel.
142 * @augments wp.Backbone.View
143 * @augments Backbone.View
145 api.Widgets.AvailableWidgetsPanelView = wp.Backbone.View.extend({
147 el: '#available-widgets',
150 'input #widgets-search': 'search',
151 'keyup #widgets-search': 'search',
152 'change #widgets-search': 'search',
153 'search #widgets-search': 'search',
154 'focus .widget-tpl' : 'focus',
155 'click .widget-tpl' : '_submit',
156 'keypress .widget-tpl' : '_submit',
157 'keydown' : 'keyboardAccessible'
160 // Cache current selected widget
163 // Cache sidebar control which has opened panel
164 currentSidebarControl: null,
167 initialize: function() {
170 this.$search = $( '#widgets-search' );
172 _.bindAll( this, 'close' );
174 this.listenTo( this.collection, 'change', this.updateList );
178 // If the available widgets panel is open and the customize controls are
179 // interacted with (i.e. available widgets panel is blurred) then close the
180 // available widgets panel. Also close on back button click.
181 $( '#customize-controls, #available-widgets .customize-section-title' ).on( 'click keydown', function( e ) {
182 var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' );
183 if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) {
188 // Close the panel if the URL in the preview changes
189 api.previewer.bind( 'url', this.close );
192 // Performs a search and handles selected widget
193 search: function( event ) {
196 this.collection.doSearch( event.target.value );
198 // Remove a widget from being selected if it is no longer visible
199 if ( this.selected && ! this.selected.is( ':visible' ) ) {
200 this.selected.removeClass( 'selected' );
201 this.selected = null;
204 // If a widget was selected but the filter value has been cleared out, clear selection
205 if ( this.selected && ! event.target.value ) {
206 this.selected.removeClass( 'selected' );
207 this.selected = null;
210 // If a filter has been entered and a widget hasn't been selected, select the first one shown
211 if ( ! this.selected && event.target.value ) {
212 firstVisible = this.$el.find( '> .widget-tpl:visible:first' );
213 if ( firstVisible.length ) {
214 this.select( firstVisible );
219 // Changes visibility of available widgets
220 updateList: function() {
221 this.collection.each( function( widget ) {
222 var widgetTpl = $( '#widget-tpl-' + widget.id );
223 widgetTpl.toggle( widget.get( 'search_matched' ) && ! widget.get( 'is_disabled' ) );
224 if ( widget.get( 'is_disabled' ) && widgetTpl.is( this.selected ) ) {
225 this.selected = null;
230 // Highlights a widget
231 select: function( widgetTpl ) {
232 this.selected = $( widgetTpl );
233 this.selected.siblings( '.widget-tpl' ).removeClass( 'selected' );
234 this.selected.addClass( 'selected' );
237 // Highlights a widget on focus
238 focus: function( event ) {
239 this.select( $( event.currentTarget ) );
242 // Submit handler for keypress and click on widget
243 _submit: function( event ) {
244 // Only proceed with keypress if it is Enter or Spacebar
245 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
249 this.submit( $( event.currentTarget ) );
252 // Adds a selected widget to the sidebar
253 submit: function( widgetTpl ) {
254 var widgetId, widget, widgetFormControl;
257 widgetTpl = this.selected;
260 if ( ! widgetTpl || ! this.currentSidebarControl ) {
264 this.select( widgetTpl );
266 widgetId = $( this.selected ).data( 'widget-id' );
267 widget = this.collection.findWhere( { id: widgetId } );
272 widgetFormControl = this.currentSidebarControl.addWidget( widget.get( 'id_base' ) );
273 if ( widgetFormControl ) {
274 widgetFormControl.focus();
281 open: function( sidebarControl ) {
282 this.currentSidebarControl = sidebarControl;
284 // Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens
285 _( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) {
286 if ( control.params.is_wide ) {
287 control.collapseForm();
291 $( 'body' ).addClass( 'adding-widget' );
293 this.$el.find( '.selected' ).removeClass( 'selected' );
296 this.collection.doSearch( '' );
298 if ( ! api.settings.browser.mobile ) {
299 this.$search.focus();
304 close: function( options ) {
305 options = options || {};
307 if ( options.returnFocus && this.currentSidebarControl ) {
308 this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
311 this.currentSidebarControl = null;
312 this.selected = null;
314 $( 'body' ).removeClass( 'adding-widget' );
316 this.$search.val( '' );
319 // Add keyboard accessiblity to the panel
320 keyboardAccessible: function( event ) {
321 var isEnter = ( event.which === 13 ),
322 isEsc = ( event.which === 27 ),
323 isDown = ( event.which === 40 ),
324 isUp = ( event.which === 38 ),
325 isTab = ( event.which === 9 ),
326 isShift = ( event.shiftKey ),
328 firstVisible = this.$el.find( '> .widget-tpl:visible:first' ),
329 lastVisible = this.$el.find( '> .widget-tpl:visible:last' ),
330 isSearchFocused = $( event.target ).is( this.$search ),
331 isLastWidgetFocused = $( event.target ).is( '.widget-tpl:visible:last' );
333 if ( isDown || isUp ) {
335 if ( isSearchFocused ) {
336 selected = firstVisible;
337 } else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) {
338 selected = this.selected.nextAll( '.widget-tpl:visible:first' );
341 if ( isSearchFocused ) {
342 selected = lastVisible;
343 } else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) {
344 selected = this.selected.prevAll( '.widget-tpl:visible:first' );
348 this.select( selected );
353 this.$search.focus();
359 // If enter pressed but nothing entered, don't do anything
360 if ( isEnter && ! this.$search.val() ) {
366 } else if ( isEsc ) {
367 this.close( { returnFocus: true } );
370 if ( this.currentSidebarControl && isTab && ( isShift && isSearchFocused || ! isShift && isLastWidgetFocused ) ) {
371 this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
372 event.preventDefault();
378 * Handlers for the widget-synced event, organized by widget ID base.
379 * Other widgets may provide their own update handlers by adding
380 * listeners for the widget-synced event.
382 api.Widgets.formSyncHandlers = {
385 * @param {jQuery.Event} e
386 * @param {jQuery} widget
387 * @param {String} newForm
389 rss: function( e, widget, newForm ) {
390 var oldWidgetError = widget.find( '.widget-error:first' ),
391 newWidgetError = $( '<div>' + newForm + '</div>' ).find( '.widget-error:first' );
393 if ( oldWidgetError.length && newWidgetError.length ) {
394 oldWidgetError.replaceWith( newWidgetError );
395 } else if ( oldWidgetError.length ) {
396 oldWidgetError.remove();
397 } else if ( newWidgetError.length ) {
398 widget.find( '.widget-content:first' ).prepend( newWidgetError );
404 * wp.customize.Widgets.WidgetControl
406 * Customizer control for widgets.
407 * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type
410 * @augments wp.customize.Control
412 api.Widgets.WidgetControl = api.Control.extend({
413 defaultExpandedArguments: {
415 completeCallback: $.noop
421 initialize: function( id, options ) {
424 control.widgetControlEmbedded = false;
425 control.widgetContentEmbedded = false;
426 control.expanded = new api.Value( false );
427 control.expandedArgumentsQueue = [];
428 control.expanded.bind( function( expanded ) {
429 var args = control.expandedArgumentsQueue.shift();
430 args = $.extend( {}, control.defaultExpandedArguments, args );
431 control.onChangeExpanded( expanded, args );
434 api.Control.prototype.initialize.call( control, id, options );
438 * Set up the control.
446 * Embed a placeholder once the section is expanded. The full widget
447 * form content will be embedded once the control itself is expanded,
448 * and at this point the widget-added event will be triggered.
450 if ( ! control.section() ) {
451 control.embedWidgetControl();
453 api.section( control.section(), function( section ) {
454 var onExpanded = function( isExpanded ) {
456 control.embedWidgetControl();
457 section.expanded.unbind( onExpanded );
460 if ( section.expanded() ) {
463 section.expanded.bind( onExpanded );
470 * Embed the .widget element inside the li container.
474 embedWidgetControl: function() {
475 var control = this, widgetControl;
477 if ( control.widgetControlEmbedded ) {
480 control.widgetControlEmbedded = true;
482 widgetControl = $( control.params.widget_control );
483 control.container.append( widgetControl );
485 control._setupModel();
486 control._setupWideWidget();
487 control._setupControlToggle();
489 control._setupWidgetTitle();
490 control._setupReorderUI();
491 control._setupHighlightEffects();
492 control._setupUpdateUI();
493 control._setupRemoveUI();
497 * Embed the actual widget form inside of .widget-content and finally trigger the widget-added event.
501 embedWidgetContent: function() {
502 var control = this, widgetContent;
504 control.embedWidgetControl();
505 if ( control.widgetContentEmbedded ) {
508 control.widgetContentEmbedded = true;
510 widgetContent = $( control.params.widget_content );
511 control.container.find( '.widget-content:first' ).append( widgetContent );
514 * Trigger widget-added event so that plugins can attach any event
515 * listeners and dynamic UI elements.
517 $( document ).trigger( 'widget-added', [ control.container.find( '.widget:first' ) ] );
522 * Handle changes to the setting
524 _setupModel: function() {
525 var self = this, rememberSavedWidgetId;
527 // Remember saved widgets so we know which to trash (move to inactive widgets sidebar)
528 rememberSavedWidgetId = function() {
529 api.Widgets.savedWidgetIds[self.params.widget_id] = true;
531 api.bind( 'ready', rememberSavedWidgetId );
532 api.bind( 'saved', rememberSavedWidgetId );
534 this._updateCount = 0;
535 this.isWidgetUpdating = false;
536 this.liveUpdateMode = true;
538 // Update widget whenever model changes
539 this.setting.bind( function( to, from ) {
540 if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) {
541 self.updateWidget( { instance: to } );
547 * Add special behaviors for wide widget controls
549 _setupWideWidget: function() {
550 var self = this, $widgetInside, $widgetForm, $customizeSidebar,
551 $themeControlsContainer, positionWidget;
553 if ( ! this.params.is_wide ) {
557 $widgetInside = this.container.find( '.widget-inside' );
558 $widgetForm = $widgetInside.find( '> .form' );
559 $customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' );
560 this.container.addClass( 'wide-widget-control' );
562 this.container.find( '.widget-content:first' ).css( {
563 'max-width': this.params.width,
564 'min-height': this.params.height
568 * Keep the widget-inside positioned so the top of fixed-positioned
569 * element is at the same top position as the widget-top. When the
570 * widget-top is scrolled out of view, keep the widget-top in view;
571 * likewise, don't allow the widget to drop off the bottom of the window.
572 * If a widget is too tall to fit in the window, don't let the height
573 * exceed the window height so that the contents of the widget control
574 * will become scrollable (overflow:auto).
576 positionWidget = function() {
577 var offsetTop = self.container.offset().top,
578 windowHeight = $( window ).height(),
579 formHeight = $widgetForm.outerHeight(),
581 $widgetInside.css( 'max-height', windowHeight );
583 0, // prevent top from going off screen
585 Math.max( offsetTop, 0 ), // distance widget in panel is from top of screen
586 windowHeight - formHeight // flush up against bottom of screen
589 $widgetInside.css( 'top', top );
592 $themeControlsContainer = $( '#customize-theme-controls' );
593 this.container.on( 'expand', function() {
595 $customizeSidebar.on( 'scroll', positionWidget );
596 $( window ).on( 'resize', positionWidget );
597 $themeControlsContainer.on( 'expanded collapsed', positionWidget );
599 this.container.on( 'collapsed', function() {
600 $customizeSidebar.off( 'scroll', positionWidget );
601 $( window ).off( 'resize', positionWidget );
602 $themeControlsContainer.off( 'expanded collapsed', positionWidget );
605 // Reposition whenever a sidebar's widgets are changed
606 api.each( function( setting ) {
607 if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) {
608 setting.bind( function() {
609 if ( self.container.hasClass( 'expanded' ) ) {
618 * Show/hide the control when clicking on the form title, when clicking
621 _setupControlToggle: function() {
622 var self = this, $closeBtn;
624 this.container.find( '.widget-top' ).on( 'click', function( e ) {
626 var sidebarWidgetsControl = self.getSidebarWidgetsControl();
627 if ( sidebarWidgetsControl.isReordering ) {
630 self.expanded( ! self.expanded() );
633 $closeBtn = this.container.find( '.widget-control-close' );
634 $closeBtn.on( 'click', function( e ) {
637 self.container.find( '.widget-top .widget-action:first' ).focus(); // keyboard accessibility
642 * Update the title of the form if a title field is entered
644 _setupWidgetTitle: function() {
645 var self = this, updateTitle;
647 updateTitle = function() {
648 var title = self.setting().title,
649 inWidgetTitle = self.container.find( '.in-widget-title' );
652 inWidgetTitle.text( ': ' + title );
654 inWidgetTitle.text( '' );
657 this.setting.bind( updateTitle );
662 * Set up the widget-reorder-nav
664 _setupReorderUI: function() {
665 var self = this, selectSidebarItem, $moveWidgetArea,
666 $reorderNav, updateAvailableSidebars, template;
669 * select the provided sidebar list item in the move widget area
673 selectSidebarItem = function( li ) {
674 li.siblings( '.selected' ).removeClass( 'selected' );
675 li.addClass( 'selected' );
676 var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id );
677 self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar );
681 * Add the widget reordering elements to the widget control
683 this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) );
686 template = _.template( api.Widgets.data.tpl.moveWidgetArea );
687 $moveWidgetArea = $( template( {
688 sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' )
691 this.container.find( '.widget-top' ).after( $moveWidgetArea );
694 * Update available sidebars when their rendered state changes
696 updateAvailableSidebars = function() {
697 var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem,
698 renderedSidebarCount = 0;
700 selfSidebarItem = $sidebarItems.filter( function(){
701 return $( this ).data( 'id' ) === self.params.sidebar_id;
704 $sidebarItems.each( function() {
706 sidebarId, sidebar, sidebarIsRendered;
708 sidebarId = li.data( 'id' );
709 sidebar = api.Widgets.registeredSidebars.get( sidebarId );
710 sidebarIsRendered = sidebar.get( 'is_rendered' );
712 li.toggle( sidebarIsRendered );
714 if ( sidebarIsRendered ) {
715 renderedSidebarCount += 1;
718 if ( li.hasClass( 'selected' ) && ! sidebarIsRendered ) {
719 selectSidebarItem( selfSidebarItem );
723 if ( renderedSidebarCount > 1 ) {
724 self.container.find( '.move-widget' ).show();
726 self.container.find( '.move-widget' ).hide();
730 updateAvailableSidebars();
731 api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars );
734 * Handle clicks for up/down/move on the reorder nav
736 $reorderNav = this.container.find( '.widget-reorder-nav' );
737 $reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() {
738 $( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' );
739 } ).on( 'click keypress', function( event ) {
740 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
745 if ( $( this ).is( '.move-widget' ) ) {
746 self.toggleWidgetMoveArea();
748 var isMoveDown = $( this ).is( '.move-widget-down' ),
749 isMoveUp = $( this ).is( '.move-widget-up' ),
750 i = self.getWidgetSidebarPosition();
752 if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) {
758 wp.a11y.speak( l10n.widgetMovedUp );
761 wp.a11y.speak( l10n.widgetMovedDown );
764 $( this ).focus(); // re-focus after the container was moved
769 * Handle selecting a sidebar to move to
771 this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( event ) {
772 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
775 event.preventDefault();
776 selectSidebarItem( $( this ) );
780 * Move widget to another sidebar
782 this.container.find( '.move-widget-btn' ).click( function() {
783 self.getSidebarWidgetsControl().toggleReordering( false );
785 var oldSidebarId = self.params.sidebar_id,
786 newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ),
787 oldSidebarWidgetsSetting, newSidebarWidgetsSetting,
788 oldSidebarWidgetIds, newSidebarWidgetIds, i;
790 oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' );
791 newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' );
792 oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() );
793 newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() );
795 i = self.getWidgetSidebarPosition();
796 oldSidebarWidgetIds.splice( i, 1 );
797 newSidebarWidgetIds.push( self.params.widget_id );
799 oldSidebarWidgetsSetting( oldSidebarWidgetIds );
800 newSidebarWidgetsSetting( newSidebarWidgetIds );
807 * Highlight widgets in preview when interacted with in the Customizer
809 _setupHighlightEffects: function() {
812 // Highlight whenever hovering or clicking over the form
813 this.container.on( 'mouseenter click', function() {
814 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
817 // Highlight when the setting is updated
818 this.setting.bind( function() {
819 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
824 * Set up event handlers for widget updating
826 _setupUpdateUI: function() {
827 var self = this, $widgetRoot, $widgetContent,
828 $saveBtn, updateWidgetDebounced, formSyncHandler;
830 $widgetRoot = this.container.find( '.widget:first' );
831 $widgetContent = $widgetRoot.find( '.widget-content:first' );
833 // Configure update button
834 $saveBtn = this.container.find( '.widget-control-save' );
835 $saveBtn.val( l10n.saveBtnLabel );
836 $saveBtn.attr( 'title', l10n.saveBtnTooltip );
837 $saveBtn.removeClass( 'button-primary' ).addClass( 'button-secondary' );
838 $saveBtn.on( 'click', function( e ) {
840 self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
843 updateWidgetDebounced = _.debounce( function() {
847 // Trigger widget form update when hitting Enter within an input
848 $widgetContent.on( 'keydown', 'input', function( e ) {
849 if ( 13 === e.which ) { // Enter
851 self.updateWidget( { ignoreActiveElement: true } );
855 // Handle widgets that support live previews
856 $widgetContent.on( 'change input propertychange', ':input', function( e ) {
857 if ( ! self.liveUpdateMode ) {
860 if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) {
861 updateWidgetDebounced();
865 // Remove loading indicators when the setting is saved and the preview updates
866 this.setting.previewer.channel.bind( 'synced', function() {
867 self.container.removeClass( 'previewer-loading' );
870 api.previewer.bind( 'widget-updated', function( updatedWidgetId ) {
871 if ( updatedWidgetId === self.params.widget_id ) {
872 self.container.removeClass( 'previewer-loading' );
876 formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
877 if ( formSyncHandler ) {
878 $( document ).on( 'widget-synced', function( e, widget ) {
879 if ( $widgetRoot.is( widget ) ) {
880 formSyncHandler.apply( document, arguments );
887 * Update widget control to indicate whether it is currently rendered.
889 * Overrides api.Control.toggle()
893 * @param {Boolean} active
894 * @param {Object} args
895 * @param {Callback} args.completeCallback
897 onChangeActive: function ( active, args ) {
898 // Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments
899 this.container.toggleClass( 'widget-rendered', active );
900 if ( args.completeCallback ) {
901 args.completeCallback();
906 * Set up event handlers for widget removal
908 _setupRemoveUI: function() {
909 var self = this, $removeBtn, replaceDeleteWithRemove;
911 // Configure remove button
912 $removeBtn = this.container.find( 'a.widget-control-remove' );
913 $removeBtn.on( 'click', function( e ) {
916 // Find an adjacent element to add focus to when this widget goes away
917 var $adjacentFocusTarget;
918 if ( self.container.next().is( '.customize-control-widget_form' ) ) {
919 $adjacentFocusTarget = self.container.next().find( '.widget-action:first' );
920 } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) {
921 $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' );
923 $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' );
926 self.container.slideUp( function() {
927 var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
930 if ( ! sidebarsWidgetsControl ) {
934 sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
935 i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
940 sidebarWidgetIds.splice( i, 1 );
941 sidebarsWidgetsControl.setting( sidebarWidgetIds );
943 $adjacentFocusTarget.focus(); // keyboard accessibility
947 replaceDeleteWithRemove = function() {
948 $removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the link as "Delete"
949 $removeBtn.attr( 'title', l10n.removeBtnTooltip );
952 if ( this.params.is_new ) {
953 api.bind( 'saved', replaceDeleteWithRemove );
955 replaceDeleteWithRemove();
960 * Find all inputs in a widget container that should be considered when
961 * comparing the loaded form with the sanitized form, whose fields will
962 * be aligned to copy the sanitized over. The elements returned by this
963 * are passed into this._getInputsSignature(), and they are iterated
964 * over when copying sanitized values over to the form loaded.
966 * @param {jQuery} container element in which to look for inputs
967 * @returns {jQuery} inputs
970 _getInputs: function( container ) {
971 return $( container ).find( ':input[name]' );
975 * Iterate over supplied inputs and create a signature string for all of them together.
976 * This string can be used to compare whether or not the form has all of the same fields.
978 * @param {jQuery} inputs
982 _getInputsSignature: function( inputs ) {
983 var inputsSignatures = _( inputs ).map( function( input ) {
984 var $input = $( input ), signatureParts;
986 if ( $input.is( ':checkbox, :radio' ) ) {
987 signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ];
989 signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ];
992 return signatureParts.join( ',' );
995 return inputsSignatures.join( ';' );
999 * Get the state for an input depending on its type.
1001 * @param {jQuery|Element} input
1002 * @returns {string|boolean|array|*}
1005 _getInputState: function( input ) {
1007 if ( input.is( ':radio, :checkbox' ) ) {
1008 return input.prop( 'checked' );
1009 } else if ( input.is( 'select[multiple]' ) ) {
1010 return input.find( 'option:selected' ).map( function () {
1011 return $( this ).val();
1019 * Update an input's state based on its type.
1021 * @param {jQuery|Element} input
1022 * @param {string|boolean|array|*} state
1025 _setInputState: function ( input, state ) {
1027 if ( input.is( ':radio, :checkbox' ) ) {
1028 input.prop( 'checked', state );
1029 } else if ( input.is( 'select[multiple]' ) ) {
1030 if ( ! $.isArray( state ) ) {
1033 // Make sure all state items are strings since the DOM value is a string
1034 state = _.map( state, function ( value ) {
1035 return String( value );
1038 input.find( 'option' ).each( function () {
1039 $( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) );
1046 /***********************************************************************
1047 * Begin public API methods
1048 **********************************************************************/
1051 * @return {wp.customize.controlConstructor.sidebar_widgets[]}
1053 getSidebarWidgetsControl: function() {
1054 var settingId, sidebarWidgetsControl;
1056 settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']';
1057 sidebarWidgetsControl = api.control( settingId );
1059 if ( ! sidebarWidgetsControl ) {
1063 return sidebarWidgetsControl;
1067 * Submit the widget form via Ajax and get back the updated instance,
1068 * along with the new widget control form to render.
1070 * @param {object} [args]
1071 * @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used
1072 * @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.
1073 * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
1075 updateWidget: function( args ) {
1076 var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
1077 updateNumber, params, data, $inputs, processing, jqxhr, isChanged;
1079 // The updateWidget logic requires that the form fields to be fully present.
1080 self.embedWidgetContent();
1085 ignoreActiveElement: false
1088 instanceOverride = args.instance;
1089 completeCallback = args.complete;
1091 this._updateCount += 1;
1092 updateNumber = this._updateCount;
1094 $widgetRoot = this.container.find( '.widget:first' );
1095 $widgetContent = $widgetRoot.find( '.widget-content:first' );
1097 // Remove a previous error message
1098 $widgetContent.find( '.widget-error' ).remove();
1100 this.container.addClass( 'widget-form-loading' );
1101 this.container.addClass( 'previewer-loading' );
1102 processing = api.state( 'processing' );
1103 processing( processing() + 1 );
1105 if ( ! this.liveUpdateMode ) {
1106 this.container.addClass( 'widget-form-disabled' );
1110 params.action = 'update-widget';
1111 params.wp_customize = 'on';
1112 params.nonce = api.settings.nonce['update-widget'];
1113 params.theme = api.settings.theme.stylesheet;
1114 params.customized = wp.customize.previewer.query().customized;
1116 data = $.param( params );
1117 $inputs = this._getInputs( $widgetContent );
1119 // Store the value we're submitting in data so that when the response comes back,
1120 // we know if it got sanitized; if there is no difference in the sanitized value,
1121 // then we do not need to touch the UI and mess up the user's ongoing editing.
1122 $inputs.each( function() {
1123 $( this ).data( 'state' + updateNumber, self._getInputState( this ) );
1126 if ( instanceOverride ) {
1127 data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } );
1129 data += '&' + $inputs.serialize();
1131 data += '&' + $widgetContent.find( '~ :input' ).serialize();
1133 if ( this._previousUpdateRequest ) {
1134 this._previousUpdateRequest.abort();
1136 jqxhr = $.post( wp.ajax.settings.url, data );
1137 this._previousUpdateRequest = jqxhr;
1139 jqxhr.done( function( r ) {
1140 var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse,
1141 isLiveUpdateAborted = false;
1143 // Check if the user is logged out.
1145 api.previewer.preview.iframe.hide();
1146 api.previewer.login().done( function() {
1147 self.updateWidget( args );
1148 api.previewer.preview.iframe.show();
1153 // Check for cheaters.
1155 api.previewer.cheatin();
1160 sanitizedForm = $( '<div>' + r.data.form + '</div>' );
1161 $sanitizedInputs = self._getInputs( sanitizedForm );
1162 hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs );
1164 // Restore live update mode if sanitized fields are now aligned with the existing fields
1165 if ( hasSameInputsInResponse && ! self.liveUpdateMode ) {
1166 self.liveUpdateMode = true;
1167 self.container.removeClass( 'widget-form-disabled' );
1168 self.container.find( 'input[name="savewidget"]' ).hide();
1171 // Sync sanitized field states to existing fields if they are aligned
1172 if ( hasSameInputsInResponse && self.liveUpdateMode ) {
1173 $inputs.each( function( i ) {
1174 var $input = $( this ),
1175 $sanitizedInput = $( $sanitizedInputs[i] ),
1176 submittedState, sanitizedState, canUpdateState;
1178 submittedState = $input.data( 'state' + updateNumber );
1179 sanitizedState = self._getInputState( $sanitizedInput );
1180 $input.data( 'sanitized', sanitizedState );
1182 canUpdateState = ( ! _.isEqual( submittedState, sanitizedState ) && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
1183 if ( canUpdateState ) {
1184 self._setInputState( $input, sanitizedState );
1188 $( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] );
1190 // Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled
1191 } else if ( self.liveUpdateMode ) {
1192 self.liveUpdateMode = false;
1193 self.container.find( 'input[name="savewidget"]' ).show();
1194 isLiveUpdateAborted = true;
1196 // Otherwise, replace existing form with the sanitized form
1198 $widgetContent.html( r.data.form );
1200 self.container.removeClass( 'widget-form-disabled' );
1202 $( document ).trigger( 'widget-updated', [ $widgetRoot ] );
1206 * If the old instance is identical to the new one, there is nothing new
1207 * needing to be rendered, and so we can preempt the event for the
1208 * preview finishing loading.
1210 isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance );
1212 self.isWidgetUpdating = true; // suppress triggering another updateWidget
1213 self.setting( r.data.instance );
1214 self.isWidgetUpdating = false;
1216 // no change was made, so stop the spinner now instead of when the preview would updates
1217 self.container.removeClass( 'previewer-loading' );
1220 if ( completeCallback ) {
1221 completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
1224 // General error message
1225 message = l10n.error;
1227 if ( r.data && r.data.message ) {
1228 message = r.data.message;
1231 if ( completeCallback ) {
1232 completeCallback.call( self, message );
1234 $widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' );
1239 jqxhr.fail( function( jqXHR, textStatus ) {
1240 if ( completeCallback ) {
1241 completeCallback.call( self, textStatus );
1245 jqxhr.always( function() {
1246 self.container.removeClass( 'widget-form-loading' );
1248 $inputs.each( function() {
1249 $( this ).removeData( 'state' + updateNumber );
1252 processing( processing() - 1 );
1257 * Expand the accordion section containing a control
1259 expandControlSection: function() {
1260 api.Control.prototype.expand.call( this );
1266 * @param {Boolean} expanded
1267 * @param {Object} [params]
1268 * @returns {Boolean} false if state already applied
1270 _toggleExpanded: api.Section.prototype._toggleExpanded,
1275 * @param {Object} [params]
1276 * @returns {Boolean} false if already expanded
1278 expand: api.Section.prototype.expand,
1281 * Expand the widget form control
1283 * @deprecated 4.1.0 Use this.expand() instead.
1285 expandForm: function() {
1292 * @param {Object} [params]
1293 * @returns {Boolean} false if already collapsed
1295 collapse: api.Section.prototype.collapse,
1298 * Collapse the widget form control
1300 * @deprecated 4.1.0 Use this.collapse() instead.
1302 collapseForm: function() {
1307 * Expand or collapse the widget control
1309 * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
1311 * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility
1313 toggleForm: function( showOrHide ) {
1314 if ( typeof showOrHide === 'undefined' ) {
1315 showOrHide = ! this.expanded();
1317 this.expanded( showOrHide );
1321 * Respond to change in the expanded state.
1323 * @param {Boolean} expanded
1324 * @param {Object} args merged on top of this.defaultActiveArguments
1326 onChangeExpanded: function ( expanded, args ) {
1327 var self = this, $widget, $inside, complete, prevComplete;
1329 self.embedWidgetControl(); // Make sure the outer form is embedded so that the expanded state can be set in the UI.
1331 self.embedWidgetContent();
1334 // If the expanded state is unchanged only manipulate container expanded states
1335 if ( args.unchanged ) {
1337 api.Control.prototype.expand.call( self, {
1338 completeCallback: args.completeCallback
1344 $widget = this.container.find( 'div.widget:first' );
1345 $inside = $widget.find( '.widget-inside:first' );
1349 if ( self.section() && api.section( self.section() ) ) {
1350 self.expandControlSection();
1353 // Close all other widget controls before expanding this one
1354 api.control.each( function( otherControl ) {
1355 if ( self.params.type === otherControl.params.type && self !== otherControl ) {
1356 otherControl.collapse();
1360 complete = function() {
1361 self.container.removeClass( 'expanding' );
1362 self.container.addClass( 'expanded' );
1363 self.container.trigger( 'expanded' );
1365 if ( args.completeCallback ) {
1366 prevComplete = complete;
1367 complete = function () {
1369 args.completeCallback();
1373 if ( self.params.is_wide ) {
1374 $inside.fadeIn( args.duration, complete );
1376 $inside.slideDown( args.duration, complete );
1379 self.container.trigger( 'expand' );
1380 self.container.addClass( 'expanding' );
1383 complete = function() {
1384 self.container.removeClass( 'collapsing' );
1385 self.container.removeClass( 'expanded' );
1386 self.container.trigger( 'collapsed' );
1388 if ( args.completeCallback ) {
1389 prevComplete = complete;
1390 complete = function () {
1392 args.completeCallback();
1396 self.container.trigger( 'collapse' );
1397 self.container.addClass( 'collapsing' );
1399 if ( self.params.is_wide ) {
1400 $inside.fadeOut( args.duration, complete );
1402 $inside.slideUp( args.duration, function() {
1403 $widget.css( { width:'', margin:'' } );
1411 * Get the position (index) of the widget in the containing sidebar
1415 getWidgetSidebarPosition: function() {
1416 var sidebarWidgetIds, position;
1418 sidebarWidgetIds = this.getSidebarWidgetsControl().setting();
1419 position = _.indexOf( sidebarWidgetIds, this.params.widget_id );
1421 if ( position === -1 ) {
1429 * Move widget up one in the sidebar
1431 moveUp: function() {
1432 this._moveWidgetByOne( -1 );
1436 * Move widget up one in the sidebar
1438 moveDown: function() {
1439 this._moveWidgetByOne( 1 );
1445 * @param {Number} offset 1|-1
1447 _moveWidgetByOne: function( offset ) {
1448 var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId;
1450 i = this.getWidgetSidebarPosition();
1452 sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting;
1453 sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // clone
1454 adjacentWidgetId = sidebarWidgetIds[i + offset];
1455 sidebarWidgetIds[i + offset] = this.params.widget_id;
1456 sidebarWidgetIds[i] = adjacentWidgetId;
1458 sidebarWidgetsSetting( sidebarWidgetIds );
1462 * Toggle visibility of the widget move area
1464 * @param {Boolean} [showOrHide]
1466 toggleWidgetMoveArea: function( showOrHide ) {
1467 var self = this, $moveWidgetArea;
1469 $moveWidgetArea = this.container.find( '.move-widget-area' );
1471 if ( typeof showOrHide === 'undefined' ) {
1472 showOrHide = ! $moveWidgetArea.hasClass( 'active' );
1476 // reset the selected sidebar
1477 $moveWidgetArea.find( '.selected' ).removeClass( 'selected' );
1479 $moveWidgetArea.find( 'li' ).filter( function() {
1480 return $( this ).data( 'id' ) === self.params.sidebar_id;
1481 } ).addClass( 'selected' );
1483 this.container.find( '.move-widget-btn' ).prop( 'disabled', true );
1486 $moveWidgetArea.toggleClass( 'active', showOrHide );
1490 * Highlight the widget control and section
1492 highlightSectionAndControl: function() {
1495 if ( this.container.is( ':hidden' ) ) {
1496 $target = this.container.closest( '.control-section' );
1498 $target = this.container;
1501 $( '.highlighted' ).removeClass( 'highlighted' );
1502 $target.addClass( 'highlighted' );
1504 setTimeout( function() {
1505 $target.removeClass( 'highlighted' );
1511 * wp.customize.Widgets.WidgetsPanel
1513 * Customizer panel containing the widget area sections.
1517 api.Widgets.WidgetsPanel = api.Panel.extend({
1520 * Add and manage the display of the no-rendered-areas notice.
1524 ready: function () {
1527 api.Panel.prototype.ready.call( panel );
1529 panel.deferred.embedded.done(function() {
1530 var panelMetaContainer, noRenderedAreasNotice, shouldShowNotice;
1531 panelMetaContainer = panel.container.find( '.panel-meta' );
1532 noRenderedAreasNotice = $( '<div></div>', {
1533 'class': 'no-widget-areas-rendered-notice'
1535 noRenderedAreasNotice.append( $( '<em></em>', {
1536 text: l10n.noAreasRendered
1538 panelMetaContainer.append( noRenderedAreasNotice );
1540 shouldShowNotice = function() {
1541 return ( 0 === _.filter( panel.sections(), function( section ) {
1542 return section.active();
1547 * Set the initial visibility state for rendered notice.
1548 * Update the visibility of the notice whenever a reflow happens.
1550 noRenderedAreasNotice.toggle( shouldShowNotice() );
1551 api.previewer.deferred.active.done( function () {
1552 noRenderedAreasNotice.toggle( shouldShowNotice() );
1554 api.bind( 'pane-contents-reflowed', function() {
1555 var duration = ( 'resolved' === api.previewer.deferred.active.state() ) ? 'fast' : 0;
1556 if ( shouldShowNotice() ) {
1557 noRenderedAreasNotice.slideDown( duration );
1559 noRenderedAreasNotice.slideUp( duration );
1566 * Allow an active widgets panel to be contextually active even when it has no active sections (widget areas).
1568 * This ensures that the widgets panel appears even when there are no
1569 * sidebars displayed on the URL currently being previewed.
1573 * @returns {boolean}
1575 isContextuallyActive: function() {
1577 return panel.active();
1582 * wp.customize.Widgets.SidebarSection
1584 * Customizer section representing a widget area widget
1588 api.Widgets.SidebarSection = api.Section.extend({
1591 * Sync the section's active state back to the Backbone model's is_rendered attribute
1595 ready: function () {
1596 var section = this, registeredSidebar;
1597 api.Section.prototype.ready.call( this );
1598 registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId );
1599 section.active.bind( function ( active ) {
1600 registeredSidebar.set( 'is_rendered', active );
1602 registeredSidebar.set( 'is_rendered', section.active() );
1607 * wp.customize.Widgets.SidebarControl
1609 * Customizer control for widgets.
1610 * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type
1615 * @augments wp.customize.Control
1617 api.Widgets.SidebarControl = api.Control.extend({
1620 * Set up the control
1623 this.$controlSection = this.container.closest( '.control-section' );
1624 this.$sectionContent = this.container.closest( '.accordion-section-content' );
1627 this._setupSortable();
1628 this._setupAddition();
1629 this._applyCardinalOrderClassNames();
1633 * Update ordering of widget control forms when the setting is updated
1635 _setupModel: function() {
1638 this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
1639 var widgetFormControls, removedWidgetIds, priority;
1641 removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );
1643 // Filter out any persistent widget IDs for widgets which have been deactivated
1644 newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
1645 var parsedWidgetId = parseWidgetId( newWidgetId );
1647 return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
1650 widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
1651 var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1653 if ( ! widgetFormControl ) {
1654 widgetFormControl = self.addWidget( widgetId );
1657 return widgetFormControl;
1660 // Sort widget controls to their new positions
1661 widgetFormControls.sort( function( a, b ) {
1662 var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
1663 bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
1664 return aIndex - bIndex;
1668 _( widgetFormControls ).each( function ( control ) {
1669 control.priority( priority );
1670 control.section( self.section() );
1673 self.priority( priority ); // Make sure sidebar control remains at end
1675 // Re-sort widget form controls (including widgets form other sidebars newly moved here)
1676 self._applyCardinalOrderClassNames();
1678 // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated
1679 _( widgetFormControls ).each( function( widgetFormControl ) {
1680 widgetFormControl.params.sidebar_id = self.params.sidebar_id;
1683 // Cleanup after widget removal
1684 _( removedWidgetIds ).each( function( removedWidgetId ) {
1686 // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update
1687 setTimeout( function() {
1688 var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
1689 widget, isPresentInAnotherSidebar = false;
1691 // Check if the widget is in another sidebar
1692 api.each( function( otherSetting ) {
1693 if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) {
1697 var otherSidebarWidgets = otherSetting(), i;
1699 i = _.indexOf( otherSidebarWidgets, removedWidgetId );
1701 isPresentInAnotherSidebar = true;
1705 // If the widget is present in another sidebar, abort!
1706 if ( isPresentInAnotherSidebar ) {
1710 removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );
1712 // Detect if widget control was dragged to another sidebar
1713 wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
1715 // Delete any widget form controls for removed widgets
1716 if ( removedControl && ! wasDraggedToAnotherSidebar ) {
1717 api.control.remove( removedControl.id );
1718 removedControl.container.remove();
1721 // Move widget to inactive widgets sidebar (move it to trash) if has been previously saved
1722 // This prevents the inactive widgets sidebar from overflowing with throwaway widgets
1723 if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
1724 inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice();
1725 inactiveWidgets.push( removedWidgetId );
1726 api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() );
1729 // Make old single widget available for adding again
1730 removedIdBase = parseWidgetId( removedWidgetId ).id_base;
1731 widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
1732 if ( widget && ! widget.get( 'is_multi' ) ) {
1733 widget.set( 'is_disabled', false );
1742 * Allow widgets in sidebar to be re-ordered, and for the order to be previewed
1744 _setupSortable: function() {
1747 this.isReordering = false;
1750 * Update widget order setting when controls are re-ordered
1752 this.$sectionContent.sortable( {
1753 items: '> .customize-control-widget_form',
1754 handle: '.widget-top',
1756 tolerance: 'pointer',
1757 connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
1758 update: function() {
1759 var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
1761 widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
1762 return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
1765 self.setting( widgetIds );
1770 * Expand other Customizer sidebar section when dragging a control widget over it,
1771 * allowing the control to be dropped into another section
1773 this.$controlSection.find( '.accordion-section-title' ).droppable({
1774 accept: '.customize-control-widget_form',
1776 var section = api.section( self.section.get() );
1778 allowMultiple: true, // Prevent the section being dragged from to be collapsed
1779 completeCallback: function () {
1780 // @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed
1781 api.section.each( function ( otherSection ) {
1782 if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) {
1783 otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' );
1792 * Keyboard-accessible reordering
1794 this.container.find( '.reorder-toggle' ).on( 'click', function() {
1795 self.toggleReordering( ! self.isReordering );
1800 * Set up UI for adding a new widget
1802 _setupAddition: function() {
1805 this.container.find( '.add-new-widget' ).on( 'click', function() {
1806 var addNewWidgetBtn = $( this );
1808 if ( self.$sectionContent.hasClass( 'reordering' ) ) {
1812 if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
1813 addNewWidgetBtn.attr( 'aria-expanded', 'true' );
1814 api.Widgets.availableWidgetsPanel.open( self );
1816 addNewWidgetBtn.attr( 'aria-expanded', 'false' );
1817 api.Widgets.availableWidgetsPanel.close();
1823 * Add classes to the widget_form controls to assist with styling
1825 _applyCardinalOrderClassNames: function() {
1826 var widgetControls = [];
1827 _.each( this.setting(), function ( widgetId ) {
1828 var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1829 if ( widgetControl ) {
1830 widgetControls.push( widgetControl );
1834 if ( 0 === widgetControls.length || ( 1 === api.Widgets.registeredSidebars.length && widgetControls.length <= 1 ) ) {
1835 this.container.find( '.reorder-toggle' ).hide();
1838 this.container.find( '.reorder-toggle' ).show();
1841 $( widgetControls ).each( function () {
1843 .removeClass( 'first-widget' )
1844 .removeClass( 'last-widget' )
1845 .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
1848 _.first( widgetControls ).container
1849 .addClass( 'first-widget' )
1850 .find( '.move-widget-up' ).prop( 'tabIndex', -1 );
1852 _.last( widgetControls ).container
1853 .addClass( 'last-widget' )
1854 .find( '.move-widget-down' ).prop( 'tabIndex', -1 );
1858 /***********************************************************************
1859 * Begin public API methods
1860 **********************************************************************/
1863 * Enable/disable the reordering UI
1865 * @param {Boolean} showOrHide to enable/disable reordering
1867 * @todo We should have a reordering state instead and rename this to onChangeReordering
1869 toggleReordering: function( showOrHide ) {
1870 var addNewWidgetBtn = this.$sectionContent.find( '.add-new-widget' ),
1871 reorderBtn = this.container.find( '.reorder-toggle' ),
1872 widgetsTitle = this.$sectionContent.find( '.widget-title' );
1874 showOrHide = Boolean( showOrHide );
1876 if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
1880 this.isReordering = showOrHide;
1881 this.$sectionContent.toggleClass( 'reordering', showOrHide );
1884 _( this.getWidgetFormControls() ).each( function( formControl ) {
1885 formControl.collapse();
1888 addNewWidgetBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
1889 reorderBtn.attr( 'aria-label', l10n.reorderLabelOff );
1890 wp.a11y.speak( l10n.reorderModeOn );
1891 // Hide widget titles while reordering: title is already in the reorder controls.
1892 widgetsTitle.attr( 'aria-hidden', 'true' );
1894 addNewWidgetBtn.removeAttr( 'tabindex aria-hidden' );
1895 reorderBtn.attr( 'aria-label', l10n.reorderLabelOn );
1896 wp.a11y.speak( l10n.reorderModeOff );
1897 widgetsTitle.attr( 'aria-hidden', 'false' );
1902 * Get the widget_form Customize controls associated with the current sidebar.
1905 * @return {wp.customize.controlConstructor.widget_form[]}
1907 getWidgetFormControls: function() {
1908 var formControls = [];
1910 _( this.setting() ).each( function( widgetId ) {
1911 var settingId = widgetIdToSettingId( widgetId ),
1912 formControl = api.control( settingId );
1913 if ( formControl ) {
1914 formControls.push( formControl );
1918 return formControls;
1922 * @param {string} widgetId or an id_base for adding a previously non-existing widget
1923 * @returns {object|false} widget_form control instance, or false on error
1925 addWidget: function( widgetId ) {
1926 var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor,
1927 parsedWidgetId = parseWidgetId( widgetId ),
1928 widgetNumber = parsedWidgetId.number,
1929 widgetIdBase = parsedWidgetId.id_base,
1930 widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
1931 settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting;
1937 if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
1941 // Set up new multi widget
1942 if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
1943 widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
1944 widgetNumber = widget.get( 'multi_number' );
1947 controlHtml = $.trim( $( '#widget-tpl-' + widget.get( 'id' ) ).html() );
1948 if ( widget.get( 'is_multi' ) ) {
1949 controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
1950 return m.replace( /__i__|%i%/g, widgetNumber );
1953 widget.set( 'is_disabled', true ); // Prevent single widget from being added again now
1956 $widget = $( controlHtml );
1958 controlContainer = $( '<li/>' )
1959 .addClass( 'customize-control' )
1960 .addClass( 'customize-control-' + controlType )
1963 // Remove icon which is visible inside the panel
1964 controlContainer.find( '> .widget-icon' ).remove();
1966 if ( widget.get( 'is_multi' ) ) {
1967 controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber );
1968 controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber );
1971 widgetId = controlContainer.find( '[name="widget-id"]' ).val();
1973 controlContainer.hide(); // to be slid-down below
1975 settingId = 'widget_' + widget.get( 'id_base' );
1976 if ( widget.get( 'is_multi' ) ) {
1977 settingId += '[' + widgetNumber + ']';
1979 controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );
1981 // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget)
1982 isExistingWidget = api.has( settingId );
1983 if ( ! isExistingWidget ) {
1985 transport: api.Widgets.data.selectiveRefreshableWidgets[ widget.get( 'id_base' ) ] ? 'postMessage' : 'refresh',
1986 previewer: this.setting.previewer
1988 setting = api.create( settingId, settingId, '', settingArgs );
1989 setting.set( {} ); // mark dirty, changing from '' to {}
1992 controlConstructor = api.controlConstructor[controlType];
1993 widgetFormControl = new controlConstructor( settingId, {
1996 'default': settingId
1998 content: controlContainer,
1999 sidebar_id: self.params.sidebar_id,
2000 widget_id: widgetId,
2001 widget_id_base: widget.get( 'id_base' ),
2003 is_new: ! isExistingWidget,
2004 width: widget.get( 'width' ),
2005 height: widget.get( 'height' ),
2006 is_wide: widget.get( 'is_wide' ),
2009 previewer: self.setting.previewer
2011 api.control.add( settingId, widgetFormControl );
2013 // Make sure widget is removed from the other sidebars
2014 api.each( function( otherSetting ) {
2015 if ( otherSetting.id === self.setting.id ) {
2019 if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
2023 var otherSidebarWidgets = otherSetting().slice(),
2024 i = _.indexOf( otherSidebarWidgets, widgetId );
2027 otherSidebarWidgets.splice( i );
2028 otherSetting( otherSidebarWidgets );
2032 // Add widget to this sidebar
2033 sidebarWidgets = this.setting().slice();
2034 if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
2035 sidebarWidgets.push( widgetId );
2036 this.setting( sidebarWidgets );
2039 controlContainer.slideDown( function() {
2040 if ( isExistingWidget ) {
2041 widgetFormControl.updateWidget( {
2042 instance: widgetFormControl.setting()
2047 return widgetFormControl;
2051 // Register models for custom panel, section, and control types
2052 $.extend( api.panelConstructor, {
2053 widgets: api.Widgets.WidgetsPanel
2055 $.extend( api.sectionConstructor, {
2056 sidebar: api.Widgets.SidebarSection
2058 $.extend( api.controlConstructor, {
2059 widget_form: api.Widgets.WidgetControl,
2060 sidebar_widgets: api.Widgets.SidebarControl
2064 * Init Customizer for widgets.
2066 api.bind( 'ready', function() {
2067 // Set up the widgets panel
2068 api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
2069 collection: api.Widgets.availableWidgets
2072 // Highlight widget control
2073 api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
2075 // Open and focus widget control
2076 api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
2080 * Highlight a widget control.
2082 * @param {string} widgetId
2084 api.Widgets.highlightWidgetFormControl = function( widgetId ) {
2085 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
2088 control.highlightSectionAndControl();
2093 * Focus a widget control.
2095 * @param {string} widgetId
2097 api.Widgets.focusWidgetFormControl = function( widgetId ) {
2098 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
2106 * Given a widget control, find the sidebar widgets control that contains it.
2107 * @param {string} widgetId
2108 * @return {object|null}
2110 api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
2111 var foundControl = null;
2113 // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl()
2114 api.control.each( function( control ) {
2115 if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
2116 foundControl = control;
2120 return foundControl;
2124 * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
2126 * @param {string} widgetId
2127 * @return {object|null}
2129 api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
2130 var foundControl = null;
2132 // @todo We can just use widgetIdToSettingId() here
2133 api.control.each( function( control ) {
2134 if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
2135 foundControl = control;
2139 return foundControl;
2143 * @param {String} widgetId
2146 function parseWidgetId( widgetId ) {
2147 var matches, parsed = {
2152 matches = widgetId.match( /^(.+)-(\d+)$/ );
2154 parsed.id_base = matches[1];
2155 parsed.number = parseInt( matches[2], 10 );
2157 // likely an old single widget
2158 parsed.id_base = widgetId;
2165 * @param {String} widgetId
2166 * @returns {String} settingId
2168 function widgetIdToSettingId( widgetId ) {
2169 var parsed = parseWidgetId( widgetId ), settingId;
2171 settingId = 'widget_' + parsed.id_base;
2172 if ( parsed.number ) {
2173 settingId += '[' + parsed.number + ']';
2179 })( window.wp, jQuery );