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;
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 ) );
685 _.template( api.Widgets.data.tpl.moveWidgetArea, {
686 sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' )
689 this.container.find( '.widget-top' ).after( $moveWidgetArea );
692 * Update available sidebars when their rendered state changes
694 updateAvailableSidebars = function() {
695 var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem,
696 renderedSidebarCount = 0;
698 selfSidebarItem = $sidebarItems.filter( function(){
699 return $( this ).data( 'id' ) === self.params.sidebar_id;
702 $sidebarItems.each( function() {
704 sidebarId, sidebar, sidebarIsRendered;
706 sidebarId = li.data( 'id' );
707 sidebar = api.Widgets.registeredSidebars.get( sidebarId );
708 sidebarIsRendered = sidebar.get( 'is_rendered' );
710 li.toggle( sidebarIsRendered );
712 if ( sidebarIsRendered ) {
713 renderedSidebarCount += 1;
716 if ( li.hasClass( 'selected' ) && ! sidebarIsRendered ) {
717 selectSidebarItem( selfSidebarItem );
721 if ( renderedSidebarCount > 1 ) {
722 self.container.find( '.move-widget' ).show();
724 self.container.find( '.move-widget' ).hide();
728 updateAvailableSidebars();
729 api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars );
732 * Handle clicks for up/down/move on the reorder nav
734 $reorderNav = this.container.find( '.widget-reorder-nav' );
735 $reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() {
736 $( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' );
737 } ).on( 'click keypress', function( event ) {
738 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
743 if ( $( this ).is( '.move-widget' ) ) {
744 self.toggleWidgetMoveArea();
746 var isMoveDown = $( this ).is( '.move-widget-down' ),
747 isMoveUp = $( this ).is( '.move-widget-up' ),
748 i = self.getWidgetSidebarPosition();
750 if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) {
756 wp.a11y.speak( l10n.widgetMovedUp );
759 wp.a11y.speak( l10n.widgetMovedDown );
762 $( this ).focus(); // re-focus after the container was moved
767 * Handle selecting a sidebar to move to
769 this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( event ) {
770 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
773 event.preventDefault();
774 selectSidebarItem( $( this ) );
778 * Move widget to another sidebar
780 this.container.find( '.move-widget-btn' ).click( function() {
781 self.getSidebarWidgetsControl().toggleReordering( false );
783 var oldSidebarId = self.params.sidebar_id,
784 newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ),
785 oldSidebarWidgetsSetting, newSidebarWidgetsSetting,
786 oldSidebarWidgetIds, newSidebarWidgetIds, i;
788 oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' );
789 newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' );
790 oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() );
791 newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() );
793 i = self.getWidgetSidebarPosition();
794 oldSidebarWidgetIds.splice( i, 1 );
795 newSidebarWidgetIds.push( self.params.widget_id );
797 oldSidebarWidgetsSetting( oldSidebarWidgetIds );
798 newSidebarWidgetsSetting( newSidebarWidgetIds );
805 * Highlight widgets in preview when interacted with in the Customizer
807 _setupHighlightEffects: function() {
810 // Highlight whenever hovering or clicking over the form
811 this.container.on( 'mouseenter click', function() {
812 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
815 // Highlight when the setting is updated
816 this.setting.bind( function() {
817 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
822 * Set up event handlers for widget updating
824 _setupUpdateUI: function() {
825 var self = this, $widgetRoot, $widgetContent,
826 $saveBtn, updateWidgetDebounced, formSyncHandler;
828 $widgetRoot = this.container.find( '.widget:first' );
829 $widgetContent = $widgetRoot.find( '.widget-content:first' );
831 // Configure update button
832 $saveBtn = this.container.find( '.widget-control-save' );
833 $saveBtn.val( l10n.saveBtnLabel );
834 $saveBtn.attr( 'title', l10n.saveBtnTooltip );
835 $saveBtn.removeClass( 'button-primary' ).addClass( 'button-secondary' );
836 $saveBtn.on( 'click', function( e ) {
838 self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
841 updateWidgetDebounced = _.debounce( function() {
845 // Trigger widget form update when hitting Enter within an input
846 $widgetContent.on( 'keydown', 'input', function( e ) {
847 if ( 13 === e.which ) { // Enter
849 self.updateWidget( { ignoreActiveElement: true } );
853 // Handle widgets that support live previews
854 $widgetContent.on( 'change input propertychange', ':input', function( e ) {
855 if ( ! self.liveUpdateMode ) {
858 if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) {
859 updateWidgetDebounced();
863 // Remove loading indicators when the setting is saved and the preview updates
864 this.setting.previewer.channel.bind( 'synced', function() {
865 self.container.removeClass( 'previewer-loading' );
868 api.previewer.bind( 'widget-updated', function( updatedWidgetId ) {
869 if ( updatedWidgetId === self.params.widget_id ) {
870 self.container.removeClass( 'previewer-loading' );
874 formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
875 if ( formSyncHandler ) {
876 $( document ).on( 'widget-synced', function( e, widget ) {
877 if ( $widgetRoot.is( widget ) ) {
878 formSyncHandler.apply( document, arguments );
885 * Update widget control to indicate whether it is currently rendered.
887 * Overrides api.Control.toggle()
891 * @param {Boolean} active
892 * @param {Object} args
893 * @param {Callback} args.completeCallback
895 onChangeActive: function ( active, args ) {
896 // Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments
897 this.container.toggleClass( 'widget-rendered', active );
898 if ( args.completeCallback ) {
899 args.completeCallback();
904 * Set up event handlers for widget removal
906 _setupRemoveUI: function() {
907 var self = this, $removeBtn, replaceDeleteWithRemove;
909 // Configure remove button
910 $removeBtn = this.container.find( 'a.widget-control-remove' );
911 $removeBtn.on( 'click', function( e ) {
914 // Find an adjacent element to add focus to when this widget goes away
915 var $adjacentFocusTarget;
916 if ( self.container.next().is( '.customize-control-widget_form' ) ) {
917 $adjacentFocusTarget = self.container.next().find( '.widget-action:first' );
918 } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) {
919 $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' );
921 $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' );
924 self.container.slideUp( function() {
925 var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
928 if ( ! sidebarsWidgetsControl ) {
932 sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
933 i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
938 sidebarWidgetIds.splice( i, 1 );
939 sidebarsWidgetsControl.setting( sidebarWidgetIds );
941 $adjacentFocusTarget.focus(); // keyboard accessibility
945 replaceDeleteWithRemove = function() {
946 $removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the link as "Delete"
947 $removeBtn.attr( 'title', l10n.removeBtnTooltip );
950 if ( this.params.is_new ) {
951 api.bind( 'saved', replaceDeleteWithRemove );
953 replaceDeleteWithRemove();
958 * Find all inputs in a widget container that should be considered when
959 * comparing the loaded form with the sanitized form, whose fields will
960 * be aligned to copy the sanitized over. The elements returned by this
961 * are passed into this._getInputsSignature(), and they are iterated
962 * over when copying sanitized values over to the the form loaded.
964 * @param {jQuery} container element in which to look for inputs
965 * @returns {jQuery} inputs
968 _getInputs: function( container ) {
969 return $( container ).find( ':input[name]' );
973 * Iterate over supplied inputs and create a signature string for all of them together.
974 * This string can be used to compare whether or not the form has all of the same fields.
976 * @param {jQuery} inputs
980 _getInputsSignature: function( inputs ) {
981 var inputsSignatures = _( inputs ).map( function( input ) {
982 var $input = $( input ), signatureParts;
984 if ( $input.is( ':checkbox, :radio' ) ) {
985 signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ];
987 signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ];
990 return signatureParts.join( ',' );
993 return inputsSignatures.join( ';' );
997 * Get the state for an input depending on its type.
999 * @param {jQuery|Element} input
1000 * @returns {string|boolean|array|*}
1003 _getInputState: function( input ) {
1005 if ( input.is( ':radio, :checkbox' ) ) {
1006 return input.prop( 'checked' );
1007 } else if ( input.is( 'select[multiple]' ) ) {
1008 return input.find( 'option:selected' ).map( function () {
1009 return $( this ).val();
1017 * Update an input's state based on its type.
1019 * @param {jQuery|Element} input
1020 * @param {string|boolean|array|*} state
1023 _setInputState: function ( input, state ) {
1025 if ( input.is( ':radio, :checkbox' ) ) {
1026 input.prop( 'checked', state );
1027 } else if ( input.is( 'select[multiple]' ) ) {
1028 if ( ! $.isArray( state ) ) {
1031 // Make sure all state items are strings since the DOM value is a string
1032 state = _.map( state, function ( value ) {
1033 return String( value );
1036 input.find( 'option' ).each( function () {
1037 $( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) );
1044 /***********************************************************************
1045 * Begin public API methods
1046 **********************************************************************/
1049 * @return {wp.customize.controlConstructor.sidebar_widgets[]}
1051 getSidebarWidgetsControl: function() {
1052 var settingId, sidebarWidgetsControl;
1054 settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']';
1055 sidebarWidgetsControl = api.control( settingId );
1057 if ( ! sidebarWidgetsControl ) {
1061 return sidebarWidgetsControl;
1065 * Submit the widget form via Ajax and get back the updated instance,
1066 * along with the new widget control form to render.
1068 * @param {object} [args]
1069 * @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used
1070 * @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.
1071 * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
1073 updateWidget: function( args ) {
1074 var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
1075 updateNumber, params, data, $inputs, processing, jqxhr, isChanged;
1077 // The updateWidget logic requires that the form fields to be fully present.
1078 self.embedWidgetContent();
1083 ignoreActiveElement: false
1086 instanceOverride = args.instance;
1087 completeCallback = args.complete;
1089 this._updateCount += 1;
1090 updateNumber = this._updateCount;
1092 $widgetRoot = this.container.find( '.widget:first' );
1093 $widgetContent = $widgetRoot.find( '.widget-content:first' );
1095 // Remove a previous error message
1096 $widgetContent.find( '.widget-error' ).remove();
1098 this.container.addClass( 'widget-form-loading' );
1099 this.container.addClass( 'previewer-loading' );
1100 processing = api.state( 'processing' );
1101 processing( processing() + 1 );
1103 if ( ! this.liveUpdateMode ) {
1104 this.container.addClass( 'widget-form-disabled' );
1108 params.action = 'update-widget';
1109 params.wp_customize = 'on';
1110 params.nonce = api.Widgets.data.nonce;
1111 params.theme = api.settings.theme.stylesheet;
1112 params.customized = wp.customize.previewer.query().customized;
1114 data = $.param( params );
1115 $inputs = this._getInputs( $widgetContent );
1117 // Store the value we're submitting in data so that when the response comes back,
1118 // we know if it got sanitized; if there is no difference in the sanitized value,
1119 // then we do not need to touch the UI and mess up the user's ongoing editing.
1120 $inputs.each( function() {
1121 $( this ).data( 'state' + updateNumber, self._getInputState( this ) );
1124 if ( instanceOverride ) {
1125 data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } );
1127 data += '&' + $inputs.serialize();
1129 data += '&' + $widgetContent.find( '~ :input' ).serialize();
1131 if ( this._previousUpdateRequest ) {
1132 this._previousUpdateRequest.abort();
1134 jqxhr = $.post( wp.ajax.settings.url, data );
1135 this._previousUpdateRequest = jqxhr;
1137 jqxhr.done( function( r ) {
1138 var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse,
1139 isLiveUpdateAborted = false;
1141 // Check if the user is logged out.
1143 api.previewer.preview.iframe.hide();
1144 api.previewer.login().done( function() {
1145 self.updateWidget( args );
1146 api.previewer.preview.iframe.show();
1151 // Check for cheaters.
1153 api.previewer.cheatin();
1158 sanitizedForm = $( '<div>' + r.data.form + '</div>' );
1159 $sanitizedInputs = self._getInputs( sanitizedForm );
1160 hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs );
1162 // Restore live update mode if sanitized fields are now aligned with the existing fields
1163 if ( hasSameInputsInResponse && ! self.liveUpdateMode ) {
1164 self.liveUpdateMode = true;
1165 self.container.removeClass( 'widget-form-disabled' );
1166 self.container.find( 'input[name="savewidget"]' ).hide();
1169 // Sync sanitized field states to existing fields if they are aligned
1170 if ( hasSameInputsInResponse && self.liveUpdateMode ) {
1171 $inputs.each( function( i ) {
1172 var $input = $( this ),
1173 $sanitizedInput = $( $sanitizedInputs[i] ),
1174 submittedState, sanitizedState, canUpdateState;
1176 submittedState = $input.data( 'state' + updateNumber );
1177 sanitizedState = self._getInputState( $sanitizedInput );
1178 $input.data( 'sanitized', sanitizedState );
1180 canUpdateState = ( ! _.isEqual( submittedState, sanitizedState ) && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
1181 if ( canUpdateState ) {
1182 self._setInputState( $input, sanitizedState );
1186 $( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] );
1188 // Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled
1189 } else if ( self.liveUpdateMode ) {
1190 self.liveUpdateMode = false;
1191 self.container.find( 'input[name="savewidget"]' ).show();
1192 isLiveUpdateAborted = true;
1194 // Otherwise, replace existing form with the sanitized form
1196 $widgetContent.html( r.data.form );
1198 self.container.removeClass( 'widget-form-disabled' );
1200 $( document ).trigger( 'widget-updated', [ $widgetRoot ] );
1204 * If the old instance is identical to the new one, there is nothing new
1205 * needing to be rendered, and so we can preempt the event for the
1206 * preview finishing loading.
1208 isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance );
1210 self.isWidgetUpdating = true; // suppress triggering another updateWidget
1211 self.setting( r.data.instance );
1212 self.isWidgetUpdating = false;
1214 // no change was made, so stop the spinner now instead of when the preview would updates
1215 self.container.removeClass( 'previewer-loading' );
1218 if ( completeCallback ) {
1219 completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
1222 // General error message
1223 message = l10n.error;
1225 if ( r.data && r.data.message ) {
1226 message = r.data.message;
1229 if ( completeCallback ) {
1230 completeCallback.call( self, message );
1232 $widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' );
1237 jqxhr.fail( function( jqXHR, textStatus ) {
1238 if ( completeCallback ) {
1239 completeCallback.call( self, textStatus );
1243 jqxhr.always( function() {
1244 self.container.removeClass( 'widget-form-loading' );
1246 $inputs.each( function() {
1247 $( this ).removeData( 'state' + updateNumber );
1250 processing( processing() - 1 );
1255 * Expand the accordion section containing a control
1257 expandControlSection: function() {
1258 api.Control.prototype.expand.call( this );
1264 * @param {Boolean} expanded
1265 * @param {Object} [params]
1266 * @returns {Boolean} false if state already applied
1268 _toggleExpanded: api.Section.prototype._toggleExpanded,
1273 * @param {Object} [params]
1274 * @returns {Boolean} false if already expanded
1276 expand: api.Section.prototype.expand,
1279 * Expand the widget form control
1281 * @deprecated 4.1.0 Use this.expand() instead.
1283 expandForm: function() {
1290 * @param {Object} [params]
1291 * @returns {Boolean} false if already collapsed
1293 collapse: api.Section.prototype.collapse,
1296 * Collapse the widget form control
1298 * @deprecated 4.1.0 Use this.collapse() instead.
1300 collapseForm: function() {
1305 * Expand or collapse the widget control
1307 * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
1309 * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility
1311 toggleForm: function( showOrHide ) {
1312 if ( typeof showOrHide === 'undefined' ) {
1313 showOrHide = ! this.expanded();
1315 this.expanded( showOrHide );
1319 * Respond to change in the expanded state.
1321 * @param {Boolean} expanded
1322 * @param {Object} args merged on top of this.defaultActiveArguments
1324 onChangeExpanded: function ( expanded, args ) {
1325 var self = this, $widget, $inside, complete, prevComplete;
1327 self.embedWidgetControl(); // Make sure the outer form is embedded so that the expanded state can be set in the UI.
1329 self.embedWidgetContent();
1332 // If the expanded state is unchanged only manipulate container expanded states
1333 if ( args.unchanged ) {
1335 api.Control.prototype.expand.call( self, {
1336 completeCallback: args.completeCallback
1342 $widget = this.container.find( 'div.widget:first' );
1343 $inside = $widget.find( '.widget-inside:first' );
1347 if ( self.section() && api.section( self.section() ) ) {
1348 self.expandControlSection();
1351 // Close all other widget controls before expanding this one
1352 api.control.each( function( otherControl ) {
1353 if ( self.params.type === otherControl.params.type && self !== otherControl ) {
1354 otherControl.collapse();
1358 complete = function() {
1359 self.container.removeClass( 'expanding' );
1360 self.container.addClass( 'expanded' );
1361 self.container.trigger( 'expanded' );
1363 if ( args.completeCallback ) {
1364 prevComplete = complete;
1365 complete = function () {
1367 args.completeCallback();
1371 if ( self.params.is_wide ) {
1372 $inside.fadeIn( args.duration, complete );
1374 $inside.slideDown( args.duration, complete );
1377 self.container.trigger( 'expand' );
1378 self.container.addClass( 'expanding' );
1381 complete = function() {
1382 self.container.removeClass( 'collapsing' );
1383 self.container.removeClass( 'expanded' );
1384 self.container.trigger( 'collapsed' );
1386 if ( args.completeCallback ) {
1387 prevComplete = complete;
1388 complete = function () {
1390 args.completeCallback();
1394 self.container.trigger( 'collapse' );
1395 self.container.addClass( 'collapsing' );
1397 if ( self.params.is_wide ) {
1398 $inside.fadeOut( args.duration, complete );
1400 $inside.slideUp( args.duration, function() {
1401 $widget.css( { width:'', margin:'' } );
1409 * Get the position (index) of the widget in the containing sidebar
1413 getWidgetSidebarPosition: function() {
1414 var sidebarWidgetIds, position;
1416 sidebarWidgetIds = this.getSidebarWidgetsControl().setting();
1417 position = _.indexOf( sidebarWidgetIds, this.params.widget_id );
1419 if ( position === -1 ) {
1427 * Move widget up one in the sidebar
1429 moveUp: function() {
1430 this._moveWidgetByOne( -1 );
1434 * Move widget up one in the sidebar
1436 moveDown: function() {
1437 this._moveWidgetByOne( 1 );
1443 * @param {Number} offset 1|-1
1445 _moveWidgetByOne: function( offset ) {
1446 var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId;
1448 i = this.getWidgetSidebarPosition();
1450 sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting;
1451 sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // clone
1452 adjacentWidgetId = sidebarWidgetIds[i + offset];
1453 sidebarWidgetIds[i + offset] = this.params.widget_id;
1454 sidebarWidgetIds[i] = adjacentWidgetId;
1456 sidebarWidgetsSetting( sidebarWidgetIds );
1460 * Toggle visibility of the widget move area
1462 * @param {Boolean} [showOrHide]
1464 toggleWidgetMoveArea: function( showOrHide ) {
1465 var self = this, $moveWidgetArea;
1467 $moveWidgetArea = this.container.find( '.move-widget-area' );
1469 if ( typeof showOrHide === 'undefined' ) {
1470 showOrHide = ! $moveWidgetArea.hasClass( 'active' );
1474 // reset the selected sidebar
1475 $moveWidgetArea.find( '.selected' ).removeClass( 'selected' );
1477 $moveWidgetArea.find( 'li' ).filter( function() {
1478 return $( this ).data( 'id' ) === self.params.sidebar_id;
1479 } ).addClass( 'selected' );
1481 this.container.find( '.move-widget-btn' ).prop( 'disabled', true );
1484 $moveWidgetArea.toggleClass( 'active', showOrHide );
1488 * Highlight the widget control and section
1490 highlightSectionAndControl: function() {
1493 if ( this.container.is( ':hidden' ) ) {
1494 $target = this.container.closest( '.control-section' );
1496 $target = this.container;
1499 $( '.highlighted' ).removeClass( 'highlighted' );
1500 $target.addClass( 'highlighted' );
1502 setTimeout( function() {
1503 $target.removeClass( 'highlighted' );
1509 * wp.customize.Widgets.WidgetsPanel
1511 * Customizer panel containing the widget area sections.
1515 api.Widgets.WidgetsPanel = api.Panel.extend({
1518 * Add and manage the display of the no-rendered-areas notice.
1522 ready: function () {
1525 api.Panel.prototype.ready.call( panel );
1527 panel.deferred.embedded.done(function() {
1528 var panelMetaContainer, noRenderedAreasNotice, shouldShowNotice;
1529 panelMetaContainer = panel.container.find( '.panel-meta' );
1530 noRenderedAreasNotice = $( '<div></div>', {
1531 'class': 'no-widget-areas-rendered-notice'
1533 noRenderedAreasNotice.append( $( '<em></em>', {
1534 text: l10n.noAreasRendered
1536 panelMetaContainer.append( noRenderedAreasNotice );
1538 shouldShowNotice = function() {
1539 return ( 0 === _.filter( panel.sections(), function( section ) {
1540 return section.active();
1545 * Set the initial visibility state for rendered notice.
1546 * Update the visibility of the notice whenever a reflow happens.
1548 noRenderedAreasNotice.toggle( shouldShowNotice() );
1549 api.previewer.deferred.active.done( function () {
1550 noRenderedAreasNotice.toggle( shouldShowNotice() );
1552 api.bind( 'pane-contents-reflowed', function() {
1553 var duration = ( 'resolved' === api.previewer.deferred.active.state() ) ? 'fast' : 0;
1554 if ( shouldShowNotice() ) {
1555 noRenderedAreasNotice.slideDown( duration );
1557 noRenderedAreasNotice.slideUp( duration );
1564 * Allow an active widgets panel to be contextually active even when it has no active sections (widget areas).
1566 * This ensures that the widgets panel appears even when there are no
1567 * sidebars displayed on the URL currently being previewed.
1571 * @returns {boolean}
1573 isContextuallyActive: function() {
1575 return panel.active();
1580 * wp.customize.Widgets.SidebarSection
1582 * Customizer section representing a widget area widget
1586 api.Widgets.SidebarSection = api.Section.extend({
1589 * Sync the section's active state back to the Backbone model's is_rendered attribute
1593 ready: function () {
1594 var section = this, registeredSidebar;
1595 api.Section.prototype.ready.call( this );
1596 registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId );
1597 section.active.bind( function ( active ) {
1598 registeredSidebar.set( 'is_rendered', active );
1600 registeredSidebar.set( 'is_rendered', section.active() );
1605 * wp.customize.Widgets.SidebarControl
1607 * Customizer control for widgets.
1608 * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type
1613 * @augments wp.customize.Control
1615 api.Widgets.SidebarControl = api.Control.extend({
1618 * Set up the control
1621 this.$controlSection = this.container.closest( '.control-section' );
1622 this.$sectionContent = this.container.closest( '.accordion-section-content' );
1625 this._setupSortable();
1626 this._setupAddition();
1627 this._applyCardinalOrderClassNames();
1631 * Update ordering of widget control forms when the setting is updated
1633 _setupModel: function() {
1636 this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
1637 var widgetFormControls, removedWidgetIds, priority;
1639 removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );
1641 // Filter out any persistent widget IDs for widgets which have been deactivated
1642 newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
1643 var parsedWidgetId = parseWidgetId( newWidgetId );
1645 return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
1648 widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
1649 var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1651 if ( ! widgetFormControl ) {
1652 widgetFormControl = self.addWidget( widgetId );
1655 return widgetFormControl;
1658 // Sort widget controls to their new positions
1659 widgetFormControls.sort( function( a, b ) {
1660 var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
1661 bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
1662 return aIndex - bIndex;
1666 _( widgetFormControls ).each( function ( control ) {
1667 control.priority( priority );
1668 control.section( self.section() );
1671 self.priority( priority ); // Make sure sidebar control remains at end
1673 // Re-sort widget form controls (including widgets form other sidebars newly moved here)
1674 self._applyCardinalOrderClassNames();
1676 // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated
1677 _( widgetFormControls ).each( function( widgetFormControl ) {
1678 widgetFormControl.params.sidebar_id = self.params.sidebar_id;
1681 // Cleanup after widget removal
1682 _( removedWidgetIds ).each( function( removedWidgetId ) {
1684 // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update
1685 setTimeout( function() {
1686 var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
1687 widget, isPresentInAnotherSidebar = false;
1689 // Check if the widget is in another sidebar
1690 api.each( function( otherSetting ) {
1691 if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) {
1695 var otherSidebarWidgets = otherSetting(), i;
1697 i = _.indexOf( otherSidebarWidgets, removedWidgetId );
1699 isPresentInAnotherSidebar = true;
1703 // If the widget is present in another sidebar, abort!
1704 if ( isPresentInAnotherSidebar ) {
1708 removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );
1710 // Detect if widget control was dragged to another sidebar
1711 wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
1713 // Delete any widget form controls for removed widgets
1714 if ( removedControl && ! wasDraggedToAnotherSidebar ) {
1715 api.control.remove( removedControl.id );
1716 removedControl.container.remove();
1719 // Move widget to inactive widgets sidebar (move it to trash) if has been previously saved
1720 // This prevents the inactive widgets sidebar from overflowing with throwaway widgets
1721 if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
1722 inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice();
1723 inactiveWidgets.push( removedWidgetId );
1724 api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() );
1727 // Make old single widget available for adding again
1728 removedIdBase = parseWidgetId( removedWidgetId ).id_base;
1729 widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
1730 if ( widget && ! widget.get( 'is_multi' ) ) {
1731 widget.set( 'is_disabled', false );
1740 * Allow widgets in sidebar to be re-ordered, and for the order to be previewed
1742 _setupSortable: function() {
1745 this.isReordering = false;
1748 * Update widget order setting when controls are re-ordered
1750 this.$sectionContent.sortable( {
1751 items: '> .customize-control-widget_form',
1752 handle: '.widget-top',
1754 tolerance: 'pointer',
1755 connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
1756 update: function() {
1757 var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
1759 widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
1760 return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
1763 self.setting( widgetIds );
1768 * Expand other Customizer sidebar section when dragging a control widget over it,
1769 * allowing the control to be dropped into another section
1771 this.$controlSection.find( '.accordion-section-title' ).droppable({
1772 accept: '.customize-control-widget_form',
1774 var section = api.section( self.section.get() );
1776 allowMultiple: true, // Prevent the section being dragged from to be collapsed
1777 completeCallback: function () {
1778 // @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed
1779 api.section.each( function ( otherSection ) {
1780 if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) {
1781 otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' );
1790 * Keyboard-accessible reordering
1792 this.container.find( '.reorder-toggle' ).on( 'click', function() {
1793 self.toggleReordering( ! self.isReordering );
1798 * Set up UI for adding a new widget
1800 _setupAddition: function() {
1803 this.container.find( '.add-new-widget' ).on( 'click', function() {
1804 var addNewWidgetBtn = $( this );
1806 if ( self.$sectionContent.hasClass( 'reordering' ) ) {
1810 if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
1811 addNewWidgetBtn.attr( 'aria-expanded', 'true' );
1812 api.Widgets.availableWidgetsPanel.open( self );
1814 addNewWidgetBtn.attr( 'aria-expanded', 'false' );
1815 api.Widgets.availableWidgetsPanel.close();
1821 * Add classes to the widget_form controls to assist with styling
1823 _applyCardinalOrderClassNames: function() {
1824 var widgetControls = [];
1825 _.each( this.setting(), function ( widgetId ) {
1826 var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1827 if ( widgetControl ) {
1828 widgetControls.push( widgetControl );
1832 if ( ! widgetControls.length ) {
1833 this.container.find( '.reorder-toggle' ).hide();
1836 this.container.find( '.reorder-toggle' ).show();
1839 $( widgetControls ).each( function () {
1841 .removeClass( 'first-widget' )
1842 .removeClass( 'last-widget' )
1843 .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
1846 _.first( widgetControls ).container
1847 .addClass( 'first-widget' )
1848 .find( '.move-widget-up' ).prop( 'tabIndex', -1 );
1850 _.last( widgetControls ).container
1851 .addClass( 'last-widget' )
1852 .find( '.move-widget-down' ).prop( 'tabIndex', -1 );
1856 /***********************************************************************
1857 * Begin public API methods
1858 **********************************************************************/
1861 * Enable/disable the reordering UI
1863 * @param {Boolean} showOrHide to enable/disable reordering
1865 * @todo We should have a reordering state instead and rename this to onChangeReordering
1867 toggleReordering: function( showOrHide ) {
1868 var addNewWidgetBtn = this.$sectionContent.find( '.add-new-widget' ),
1869 reorderBtn = this.container.find( '.reorder-toggle' ),
1870 widgetsTitle = this.$sectionContent.find( '.widget-title' );
1872 showOrHide = Boolean( showOrHide );
1874 if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
1878 this.isReordering = showOrHide;
1879 this.$sectionContent.toggleClass( 'reordering', showOrHide );
1882 _( this.getWidgetFormControls() ).each( function( formControl ) {
1883 formControl.collapse();
1886 addNewWidgetBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
1887 reorderBtn.attr( 'aria-label', l10n.reorderLabelOff );
1888 wp.a11y.speak( l10n.reorderModeOn );
1889 // Hide widget titles while reordering: title is already in the reorder controls.
1890 widgetsTitle.attr( 'aria-hidden', 'true' );
1892 addNewWidgetBtn.removeAttr( 'tabindex aria-hidden' );
1893 reorderBtn.attr( 'aria-label', l10n.reorderLabelOn );
1894 wp.a11y.speak( l10n.reorderModeOff );
1895 widgetsTitle.attr( 'aria-hidden', 'false' );
1900 * Get the widget_form Customize controls associated with the current sidebar.
1903 * @return {wp.customize.controlConstructor.widget_form[]}
1905 getWidgetFormControls: function() {
1906 var formControls = [];
1908 _( this.setting() ).each( function( widgetId ) {
1909 var settingId = widgetIdToSettingId( widgetId ),
1910 formControl = api.control( settingId );
1911 if ( formControl ) {
1912 formControls.push( formControl );
1916 return formControls;
1920 * @param {string} widgetId or an id_base for adding a previously non-existing widget
1921 * @returns {object|false} widget_form control instance, or false on error
1923 addWidget: function( widgetId ) {
1924 var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor,
1925 parsedWidgetId = parseWidgetId( widgetId ),
1926 widgetNumber = parsedWidgetId.number,
1927 widgetIdBase = parsedWidgetId.id_base,
1928 widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
1929 settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting;
1935 if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
1939 // Set up new multi widget
1940 if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
1941 widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
1942 widgetNumber = widget.get( 'multi_number' );
1945 controlHtml = $.trim( $( '#widget-tpl-' + widget.get( 'id' ) ).html() );
1946 if ( widget.get( 'is_multi' ) ) {
1947 controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
1948 return m.replace( /__i__|%i%/g, widgetNumber );
1951 widget.set( 'is_disabled', true ); // Prevent single widget from being added again now
1954 $widget = $( controlHtml );
1956 controlContainer = $( '<li/>' )
1957 .addClass( 'customize-control' )
1958 .addClass( 'customize-control-' + controlType )
1961 // Remove icon which is visible inside the panel
1962 controlContainer.find( '> .widget-icon' ).remove();
1964 if ( widget.get( 'is_multi' ) ) {
1965 controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber );
1966 controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber );
1969 widgetId = controlContainer.find( '[name="widget-id"]' ).val();
1971 controlContainer.hide(); // to be slid-down below
1973 settingId = 'widget_' + widget.get( 'id_base' );
1974 if ( widget.get( 'is_multi' ) ) {
1975 settingId += '[' + widgetNumber + ']';
1977 controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );
1979 // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget)
1980 isExistingWidget = api.has( settingId );
1981 if ( ! isExistingWidget ) {
1983 transport: 'refresh',
1984 previewer: this.setting.previewer
1986 setting = api.create( settingId, settingId, '', settingArgs );
1987 setting.set( {} ); // mark dirty, changing from '' to {}
1990 controlConstructor = api.controlConstructor[controlType];
1991 widgetFormControl = new controlConstructor( settingId, {
1994 'default': settingId
1996 content: controlContainer,
1997 sidebar_id: self.params.sidebar_id,
1998 widget_id: widgetId,
1999 widget_id_base: widget.get( 'id_base' ),
2001 is_new: ! isExistingWidget,
2002 width: widget.get( 'width' ),
2003 height: widget.get( 'height' ),
2004 is_wide: widget.get( 'is_wide' ),
2007 previewer: self.setting.previewer
2009 api.control.add( settingId, widgetFormControl );
2011 // Make sure widget is removed from the other sidebars
2012 api.each( function( otherSetting ) {
2013 if ( otherSetting.id === self.setting.id ) {
2017 if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
2021 var otherSidebarWidgets = otherSetting().slice(),
2022 i = _.indexOf( otherSidebarWidgets, widgetId );
2025 otherSidebarWidgets.splice( i );
2026 otherSetting( otherSidebarWidgets );
2030 // Add widget to this sidebar
2031 sidebarWidgets = this.setting().slice();
2032 if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
2033 sidebarWidgets.push( widgetId );
2034 this.setting( sidebarWidgets );
2037 controlContainer.slideDown( function() {
2038 if ( isExistingWidget ) {
2039 widgetFormControl.updateWidget( {
2040 instance: widgetFormControl.setting()
2045 return widgetFormControl;
2049 // Register models for custom panel, section, and control types
2050 $.extend( api.panelConstructor, {
2051 widgets: api.Widgets.WidgetsPanel
2053 $.extend( api.sectionConstructor, {
2054 sidebar: api.Widgets.SidebarSection
2056 $.extend( api.controlConstructor, {
2057 widget_form: api.Widgets.WidgetControl,
2058 sidebar_widgets: api.Widgets.SidebarControl
2061 // Refresh the nonce if login sends updated nonces over.
2062 api.bind( 'nonce-refresh', function( nonces ) {
2063 api.Widgets.data.nonce = nonces['update-widget'];
2067 * Init Customizer for widgets.
2069 api.bind( 'ready', function() {
2070 // Set up the widgets panel
2071 api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
2072 collection: api.Widgets.availableWidgets
2075 // Highlight widget control
2076 api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
2078 // Open and focus widget control
2079 api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
2083 * Highlight a widget control.
2085 * @param {string} widgetId
2087 api.Widgets.highlightWidgetFormControl = function( widgetId ) {
2088 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
2091 control.highlightSectionAndControl();
2096 * Focus a widget control.
2098 * @param {string} widgetId
2100 api.Widgets.focusWidgetFormControl = function( widgetId ) {
2101 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
2109 * Given a widget control, find the sidebar widgets control that contains it.
2110 * @param {string} widgetId
2111 * @return {object|null}
2113 api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
2114 var foundControl = null;
2116 // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl()
2117 api.control.each( function( control ) {
2118 if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
2119 foundControl = control;
2123 return foundControl;
2127 * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
2129 * @param {string} widgetId
2130 * @return {object|null}
2132 api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
2133 var foundControl = null;
2135 // @todo We can just use widgetIdToSettingId() here
2136 api.control.each( function( control ) {
2137 if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
2138 foundControl = control;
2142 return foundControl;
2146 * @param {String} widgetId
2149 function parseWidgetId( widgetId ) {
2150 var matches, parsed = {
2155 matches = widgetId.match( /^(.+)-(\d+)$/ );
2157 parsed.id_base = matches[1];
2158 parsed.number = parseInt( matches[2], 10 );
2160 // likely an old single widget
2161 parsed.id_base = widgetId;
2168 * @param {String} widgetId
2169 * @returns {String} settingId
2171 function widgetIdToSettingId( widgetId ) {
2172 var parsed = parseWidgetId( widgetId ), settingId;
2174 settingId = 'widget_' + parsed.id_base;
2175 if ( parsed.number ) {
2176 settingId += '[' + parsed.number + ']';
2182 })( window.wp, jQuery );