]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/js/customize-widgets.js
WordPress 4.7.2
[autoinstalls/wordpress.git] / wp-admin / js / customize-widgets.js
1 /* global _wpCustomizeWidgetsSettings */
2 (function( wp, $ ){
3
4         if ( ! wp || ! wp.customize ) { return; }
5
6         // Set up our namespace...
7         var api = wp.customize,
8                 l10n;
9
10         api.Widgets = api.Widgets || {};
11         api.Widgets.savedWidgetIds = {};
12
13         // Link settings
14         api.Widgets.data = _wpCustomizeWidgetsSettings || {};
15         l10n = api.Widgets.data.l10n;
16         delete api.Widgets.data.l10n;
17
18         /**
19          * wp.customize.Widgets.WidgetModel
20          *
21          * A single widget model.
22          *
23          * @constructor
24          * @augments Backbone.Model
25          */
26         api.Widgets.WidgetModel = Backbone.Model.extend({
27                 id: null,
28                 temp_id: null,
29                 classname: null,
30                 control_tpl: null,
31                 description: null,
32                 is_disabled: null,
33                 is_multi: null,
34                 multi_number: null,
35                 name: null,
36                 id_base: null,
37                 transport: null,
38                 params: [],
39                 width: null,
40                 height: null,
41                 search_matched: true
42         });
43
44         /**
45          * wp.customize.Widgets.WidgetCollection
46          *
47          * Collection for widget models.
48          *
49          * @constructor
50          * @augments Backbone.Model
51          */
52         api.Widgets.WidgetCollection = Backbone.Collection.extend({
53                 model: api.Widgets.WidgetModel,
54
55                 // Controls searching on the current widget collection
56                 // and triggers an update event
57                 doSearch: function( value ) {
58
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 ) {
62                                 return;
63                         }
64
65                         // Updates terms with the value passed
66                         this.terms = value;
67
68                         // If we have terms, run a search...
69                         if ( this.terms.length > 0 ) {
70                                 this.search( this.terms );
71                         }
72
73                         // If search is blank, set all the widgets as they matched the search to reset the views.
74                         if ( this.terms === '' ) {
75                                 this.each( function ( widget ) {
76                                         widget.set( 'search_matched', true );
77                                 } );
78                         }
79                 },
80
81                 // Performs a search within the collection
82                 // @uses RegExp
83                 search: function( term ) {
84                         var match, haystack;
85
86                         // Escape the term string for RegExp meta characters
87                         term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
88
89                         // Consider spaces as word delimiters and match the whole string
90                         // so matching terms can be combined
91                         term = term.replace( / /g, ')(?=.*' );
92                         match = new RegExp( '^(?=.*' + term + ').+', 'i' );
93
94                         this.each( function ( data ) {
95                                 haystack = [ data.get( 'name' ), data.get( 'id' ), data.get( 'description' ) ].join( ' ' );
96                                 data.set( 'search_matched', match.test( haystack ) );
97                         } );
98                 }
99         });
100         api.Widgets.availableWidgets = new api.Widgets.WidgetCollection( api.Widgets.data.availableWidgets );
101
102         /**
103          * wp.customize.Widgets.SidebarModel
104          *
105          * A single sidebar model.
106          *
107          * @constructor
108          * @augments Backbone.Model
109          */
110         api.Widgets.SidebarModel = Backbone.Model.extend({
111                 after_title: null,
112                 after_widget: null,
113                 before_title: null,
114                 before_widget: null,
115                 'class': null,
116                 description: null,
117                 id: null,
118                 name: null,
119                 is_rendered: false
120         });
121
122         /**
123          * wp.customize.Widgets.SidebarCollection
124          *
125          * Collection for sidebar models.
126          *
127          * @constructor
128          * @augments Backbone.Collection
129          */
130         api.Widgets.SidebarCollection = Backbone.Collection.extend({
131                 model: api.Widgets.SidebarModel
132         });
133         api.Widgets.registeredSidebars = new api.Widgets.SidebarCollection( api.Widgets.data.registeredSidebars );
134
135         /**
136          * wp.customize.Widgets.AvailableWidgetsPanelView
137          *
138          * View class for the available widgets panel.
139          *
140          * @constructor
141          * @augments wp.Backbone.View
142          * @augments Backbone.View
143          */
144         api.Widgets.AvailableWidgetsPanelView = wp.Backbone.View.extend({
145
146                 el: '#available-widgets',
147
148                 events: {
149                         'input #widgets-search': 'search',
150                         'keyup #widgets-search': 'search',
151                         'focus .widget-tpl' : 'focus',
152                         'click .widget-tpl' : '_submit',
153                         'keypress .widget-tpl' : '_submit',
154                         'keydown' : 'keyboardAccessible'
155                 },
156
157                 // Cache current selected widget
158                 selected: null,
159
160                 // Cache sidebar control which has opened panel
161                 currentSidebarControl: null,
162                 $search: null,
163                 $clearResults: null,
164                 searchMatchesCount: null,
165
166                 initialize: function() {
167                         var self = this;
168
169                         this.$search = $( '#widgets-search' );
170
171                         this.$clearResults = this.$el.find( '.clear-results' );
172
173                         _.bindAll( this, 'close' );
174
175                         this.listenTo( this.collection, 'change', this.updateList );
176
177                         this.updateList();
178
179                         // Set the initial search count to the number of available widgets.
180                         this.searchMatchesCount = this.collection.length;
181
182                         // If the available widgets panel is open and the customize controls are
183                         // interacted with (i.e. available widgets panel is blurred) then close the
184                         // available widgets panel. Also close on back button click.
185                         $( '#customize-controls, #available-widgets .customize-section-title' ).on( 'click keydown', function( e ) {
186                                 var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' );
187                                 if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) {
188                                         self.close();
189                                 }
190                         } );
191
192                         // Clear the search results and trigger a `keyup` event to fire a new search.
193                         this.$clearResults.on( 'click', function() {
194                                 self.$search.val( '' ).focus().trigger( 'keyup' );
195                         } );
196
197                         // Close the panel if the URL in the preview changes
198                         api.previewer.bind( 'url', this.close );
199                 },
200
201                 // Performs a search and handles selected widget
202                 search: function( event ) {
203                         var firstVisible;
204
205                         this.collection.doSearch( event.target.value );
206                         // Update the search matches count.
207                         this.updateSearchMatchesCount();
208                         // Announce how many search results.
209                         this.announceSearchMatches();
210
211                         // Remove a widget from being selected if it is no longer visible
212                         if ( this.selected && ! this.selected.is( ':visible' ) ) {
213                                 this.selected.removeClass( 'selected' );
214                                 this.selected = null;
215                         }
216
217                         // If a widget was selected but the filter value has been cleared out, clear selection
218                         if ( this.selected && ! event.target.value ) {
219                                 this.selected.removeClass( 'selected' );
220                                 this.selected = null;
221                         }
222
223                         // If a filter has been entered and a widget hasn't been selected, select the first one shown
224                         if ( ! this.selected && event.target.value ) {
225                                 firstVisible = this.$el.find( '> .widget-tpl:visible:first' );
226                                 if ( firstVisible.length ) {
227                                         this.select( firstVisible );
228                                 }
229                         }
230
231                         // Toggle the clear search results button.
232                         if ( '' !== event.target.value ) {
233                                 this.$clearResults.addClass( 'is-visible' );
234                         } else if ( '' === event.target.value ) {
235                                 this.$clearResults.removeClass( 'is-visible' );
236                         }
237
238                         // Set a CSS class on the search container when there are no search results.
239                         if ( ! this.searchMatchesCount ) {
240                                 this.$el.addClass( 'no-widgets-found' );
241                         } else {
242                                 this.$el.removeClass( 'no-widgets-found' );
243                         }
244                 },
245
246                 // Update the count of the available widgets that have the `search_matched` attribute.
247                 updateSearchMatchesCount: function() {
248                         this.searchMatchesCount = this.collection.where({ search_matched: true }).length;
249                 },
250
251                 // Send a message to the aria-live region to announce how many search results.
252                 announceSearchMatches: _.debounce( function() {
253                         var message = l10n.widgetsFound.replace( '%d', this.searchMatchesCount ) ;
254
255                         if ( ! this.searchMatchesCount ) {
256                                 message = l10n.noWidgetsFound;
257                         }
258
259                         wp.a11y.speak( message );
260                 }, 500 ),
261
262                 // Changes visibility of available widgets
263                 updateList: function() {
264                         this.collection.each( function( widget ) {
265                                 var widgetTpl = $( '#widget-tpl-' + widget.id );
266                                 widgetTpl.toggle( widget.get( 'search_matched' ) && ! widget.get( 'is_disabled' ) );
267                                 if ( widget.get( 'is_disabled' ) && widgetTpl.is( this.selected ) ) {
268                                         this.selected = null;
269                                 }
270                         } );
271                 },
272
273                 // Highlights a widget
274                 select: function( widgetTpl ) {
275                         this.selected = $( widgetTpl );
276                         this.selected.siblings( '.widget-tpl' ).removeClass( 'selected' );
277                         this.selected.addClass( 'selected' );
278                 },
279
280                 // Highlights a widget on focus
281                 focus: function( event ) {
282                         this.select( $( event.currentTarget ) );
283                 },
284
285                 // Submit handler for keypress and click on widget
286                 _submit: function( event ) {
287                         // Only proceed with keypress if it is Enter or Spacebar
288                         if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
289                                 return;
290                         }
291
292                         this.submit( $( event.currentTarget ) );
293                 },
294
295                 // Adds a selected widget to the sidebar
296                 submit: function( widgetTpl ) {
297                         var widgetId, widget, widgetFormControl;
298
299                         if ( ! widgetTpl ) {
300                                 widgetTpl = this.selected;
301                         }
302
303                         if ( ! widgetTpl || ! this.currentSidebarControl ) {
304                                 return;
305                         }
306
307                         this.select( widgetTpl );
308
309                         widgetId = $( this.selected ).data( 'widget-id' );
310                         widget = this.collection.findWhere( { id: widgetId } );
311                         if ( ! widget ) {
312                                 return;
313                         }
314
315                         widgetFormControl = this.currentSidebarControl.addWidget( widget.get( 'id_base' ) );
316                         if ( widgetFormControl ) {
317                                 widgetFormControl.focus();
318                         }
319
320                         this.close();
321                 },
322
323                 // Opens the panel
324                 open: function( sidebarControl ) {
325                         this.currentSidebarControl = sidebarControl;
326
327                         // Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens
328                         _( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) {
329                                 if ( control.params.is_wide ) {
330                                         control.collapseForm();
331                                 }
332                         } );
333
334                         $( 'body' ).addClass( 'adding-widget' );
335
336                         this.$el.find( '.selected' ).removeClass( 'selected' );
337
338                         // Reset search
339                         this.collection.doSearch( '' );
340
341                         if ( ! api.settings.browser.mobile ) {
342                                 this.$search.focus();
343                         }
344                 },
345
346                 // Closes the panel
347                 close: function( options ) {
348                         options = options || {};
349
350                         if ( options.returnFocus && this.currentSidebarControl ) {
351                                 this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
352                         }
353
354                         this.currentSidebarControl = null;
355                         this.selected = null;
356
357                         $( 'body' ).removeClass( 'adding-widget' );
358
359                         this.$search.val( '' );
360                 },
361
362                 // Add keyboard accessiblity to the panel
363                 keyboardAccessible: function( event ) {
364                         var isEnter = ( event.which === 13 ),
365                                 isEsc = ( event.which === 27 ),
366                                 isDown = ( event.which === 40 ),
367                                 isUp = ( event.which === 38 ),
368                                 isTab = ( event.which === 9 ),
369                                 isShift = ( event.shiftKey ),
370                                 selected = null,
371                                 firstVisible = this.$el.find( '> .widget-tpl:visible:first' ),
372                                 lastVisible = this.$el.find( '> .widget-tpl:visible:last' ),
373                                 isSearchFocused = $( event.target ).is( this.$search ),
374                                 isLastWidgetFocused = $( event.target ).is( '.widget-tpl:visible:last' );
375
376                         if ( isDown || isUp ) {
377                                 if ( isDown ) {
378                                         if ( isSearchFocused ) {
379                                                 selected = firstVisible;
380                                         } else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) {
381                                                 selected = this.selected.nextAll( '.widget-tpl:visible:first' );
382                                         }
383                                 } else if ( isUp ) {
384                                         if ( isSearchFocused ) {
385                                                 selected = lastVisible;
386                                         } else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) {
387                                                 selected = this.selected.prevAll( '.widget-tpl:visible:first' );
388                                         }
389                                 }
390
391                                 this.select( selected );
392
393                                 if ( selected ) {
394                                         selected.focus();
395                                 } else {
396                                         this.$search.focus();
397                                 }
398
399                                 return;
400                         }
401
402                         // If enter pressed but nothing entered, don't do anything
403                         if ( isEnter && ! this.$search.val() ) {
404                                 return;
405                         }
406
407                         if ( isEnter ) {
408                                 this.submit();
409                         } else if ( isEsc ) {
410                                 this.close( { returnFocus: true } );
411                         }
412
413                         if ( this.currentSidebarControl && isTab && ( isShift && isSearchFocused || ! isShift && isLastWidgetFocused ) ) {
414                                 this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
415                                 event.preventDefault();
416                         }
417                 }
418         });
419
420         /**
421          * Handlers for the widget-synced event, organized by widget ID base.
422          * Other widgets may provide their own update handlers by adding
423          * listeners for the widget-synced event.
424          */
425         api.Widgets.formSyncHandlers = {
426
427                 /**
428                  * @param {jQuery.Event} e
429                  * @param {jQuery} widget
430                  * @param {String} newForm
431                  */
432                 rss: function( e, widget, newForm ) {
433                         var oldWidgetError = widget.find( '.widget-error:first' ),
434                                 newWidgetError = $( '<div>' + newForm + '</div>' ).find( '.widget-error:first' );
435
436                         if ( oldWidgetError.length && newWidgetError.length ) {
437                                 oldWidgetError.replaceWith( newWidgetError );
438                         } else if ( oldWidgetError.length ) {
439                                 oldWidgetError.remove();
440                         } else if ( newWidgetError.length ) {
441                                 widget.find( '.widget-content:first' ).prepend( newWidgetError );
442                         }
443                 }
444         };
445
446         /**
447          * wp.customize.Widgets.WidgetControl
448          *
449          * Customizer control for widgets.
450          * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type
451          *
452          * @constructor
453          * @augments wp.customize.Control
454          */
455         api.Widgets.WidgetControl = api.Control.extend({
456                 defaultExpandedArguments: {
457                         duration: 'fast',
458                         completeCallback: $.noop
459                 },
460
461                 /**
462                  * @since 4.1.0
463                  */
464                 initialize: function( id, options ) {
465                         var control = this;
466
467                         control.widgetControlEmbedded = false;
468                         control.widgetContentEmbedded = false;
469                         control.expanded = new api.Value( false );
470                         control.expandedArgumentsQueue = [];
471                         control.expanded.bind( function( expanded ) {
472                                 var args = control.expandedArgumentsQueue.shift();
473                                 args = $.extend( {}, control.defaultExpandedArguments, args );
474                                 control.onChangeExpanded( expanded, args );
475                         });
476                         control.altNotice = true;
477
478                         api.Control.prototype.initialize.call( control, id, options );
479                 },
480
481                 /**
482                  * Set up the control.
483                  *
484                  * @since 3.9.0
485                  */
486                 ready: function() {
487                         var control = this;
488
489                         /*
490                          * Embed a placeholder once the section is expanded. The full widget
491                          * form content will be embedded once the control itself is expanded,
492                          * and at this point the widget-added event will be triggered.
493                          */
494                         if ( ! control.section() ) {
495                                 control.embedWidgetControl();
496                         } else {
497                                 api.section( control.section(), function( section ) {
498                                         var onExpanded = function( isExpanded ) {
499                                                 if ( isExpanded ) {
500                                                         control.embedWidgetControl();
501                                                         section.expanded.unbind( onExpanded );
502                                                 }
503                                         };
504                                         if ( section.expanded() ) {
505                                                 onExpanded( true );
506                                         } else {
507                                                 section.expanded.bind( onExpanded );
508                                         }
509                                 } );
510                         }
511                 },
512
513                 /**
514                  * Embed the .widget element inside the li container.
515                  *
516                  * @since 4.4.0
517                  */
518                 embedWidgetControl: function() {
519                         var control = this, widgetControl;
520
521                         if ( control.widgetControlEmbedded ) {
522                                 return;
523                         }
524                         control.widgetControlEmbedded = true;
525
526                         widgetControl = $( control.params.widget_control );
527                         control.container.append( widgetControl );
528
529                         control._setupModel();
530                         control._setupWideWidget();
531                         control._setupControlToggle();
532
533                         control._setupWidgetTitle();
534                         control._setupReorderUI();
535                         control._setupHighlightEffects();
536                         control._setupUpdateUI();
537                         control._setupRemoveUI();
538                 },
539
540                 /**
541                  * Embed the actual widget form inside of .widget-content and finally trigger the widget-added event.
542                  *
543                  * @since 4.4.0
544                  */
545                 embedWidgetContent: function() {
546                         var control = this, widgetContent;
547
548                         control.embedWidgetControl();
549                         if ( control.widgetContentEmbedded ) {
550                                 return;
551                         }
552                         control.widgetContentEmbedded = true;
553
554                         widgetContent = $( control.params.widget_content );
555                         control.container.find( '.widget-content:first' ).append( widgetContent );
556
557                         /*
558                          * Trigger widget-added event so that plugins can attach any event
559                          * listeners and dynamic UI elements.
560                          */
561                         $( document ).trigger( 'widget-added', [ control.container.find( '.widget:first' ) ] );
562
563                 },
564
565                 /**
566                  * Handle changes to the setting
567                  */
568                 _setupModel: function() {
569                         var self = this, rememberSavedWidgetId;
570
571                         // Remember saved widgets so we know which to trash (move to inactive widgets sidebar)
572                         rememberSavedWidgetId = function() {
573                                 api.Widgets.savedWidgetIds[self.params.widget_id] = true;
574                         };
575                         api.bind( 'ready', rememberSavedWidgetId );
576                         api.bind( 'saved', rememberSavedWidgetId );
577
578                         this._updateCount = 0;
579                         this.isWidgetUpdating = false;
580                         this.liveUpdateMode = true;
581
582                         // Update widget whenever model changes
583                         this.setting.bind( function( to, from ) {
584                                 if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) {
585                                         self.updateWidget( { instance: to } );
586                                 }
587                         } );
588                 },
589
590                 /**
591                  * Add special behaviors for wide widget controls
592                  */
593                 _setupWideWidget: function() {
594                         var self = this, $widgetInside, $widgetForm, $customizeSidebar,
595                                 $themeControlsContainer, positionWidget;
596
597                         if ( ! this.params.is_wide ) {
598                                 return;
599                         }
600
601                         $widgetInside = this.container.find( '.widget-inside' );
602                         $widgetForm = $widgetInside.find( '> .form' );
603                         $customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' );
604                         this.container.addClass( 'wide-widget-control' );
605
606                         this.container.find( '.widget-content:first' ).css( {
607                                 'max-width': this.params.width,
608                                 'min-height': this.params.height
609                         } );
610
611                         /**
612                          * Keep the widget-inside positioned so the top of fixed-positioned
613                          * element is at the same top position as the widget-top. When the
614                          * widget-top is scrolled out of view, keep the widget-top in view;
615                          * likewise, don't allow the widget to drop off the bottom of the window.
616                          * If a widget is too tall to fit in the window, don't let the height
617                          * exceed the window height so that the contents of the widget control
618                          * will become scrollable (overflow:auto).
619                          */
620                         positionWidget = function() {
621                                 var offsetTop = self.container.offset().top,
622                                         windowHeight = $( window ).height(),
623                                         formHeight = $widgetForm.outerHeight(),
624                                         top;
625                                 $widgetInside.css( 'max-height', windowHeight );
626                                 top = Math.max(
627                                         0, // prevent top from going off screen
628                                         Math.min(
629                                                 Math.max( offsetTop, 0 ), // distance widget in panel is from top of screen
630                                                 windowHeight - formHeight // flush up against bottom of screen
631                                         )
632                                 );
633                                 $widgetInside.css( 'top', top );
634                         };
635
636                         $themeControlsContainer = $( '#customize-theme-controls' );
637                         this.container.on( 'expand', function() {
638                                 positionWidget();
639                                 $customizeSidebar.on( 'scroll', positionWidget );
640                                 $( window ).on( 'resize', positionWidget );
641                                 $themeControlsContainer.on( 'expanded collapsed', positionWidget );
642                         } );
643                         this.container.on( 'collapsed', function() {
644                                 $customizeSidebar.off( 'scroll', positionWidget );
645                                 $( window ).off( 'resize', positionWidget );
646                                 $themeControlsContainer.off( 'expanded collapsed', positionWidget );
647                         } );
648
649                         // Reposition whenever a sidebar's widgets are changed
650                         api.each( function( setting ) {
651                                 if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) {
652                                         setting.bind( function() {
653                                                 if ( self.container.hasClass( 'expanded' ) ) {
654                                                         positionWidget();
655                                                 }
656                                         } );
657                                 }
658                         } );
659                 },
660
661                 /**
662                  * Show/hide the control when clicking on the form title, when clicking
663                  * the close button
664                  */
665                 _setupControlToggle: function() {
666                         var self = this, $closeBtn;
667
668                         this.container.find( '.widget-top' ).on( 'click', function( e ) {
669                                 e.preventDefault();
670                                 var sidebarWidgetsControl = self.getSidebarWidgetsControl();
671                                 if ( sidebarWidgetsControl.isReordering ) {
672                                         return;
673                                 }
674                                 self.expanded( ! self.expanded() );
675                         } );
676
677                         $closeBtn = this.container.find( '.widget-control-close' );
678                         $closeBtn.on( 'click', function( e ) {
679                                 e.preventDefault();
680                                 self.collapse();
681                                 self.container.find( '.widget-top .widget-action:first' ).focus(); // keyboard accessibility
682                         } );
683                 },
684
685                 /**
686                  * Update the title of the form if a title field is entered
687                  */
688                 _setupWidgetTitle: function() {
689                         var self = this, updateTitle;
690
691                         updateTitle = function() {
692                                 var title = self.setting().title,
693                                         inWidgetTitle = self.container.find( '.in-widget-title' );
694
695                                 if ( title ) {
696                                         inWidgetTitle.text( ': ' + title );
697                                 } else {
698                                         inWidgetTitle.text( '' );
699                                 }
700                         };
701                         this.setting.bind( updateTitle );
702                         updateTitle();
703                 },
704
705                 /**
706                  * Set up the widget-reorder-nav
707                  */
708                 _setupReorderUI: function() {
709                         var self = this, selectSidebarItem, $moveWidgetArea,
710                                 $reorderNav, updateAvailableSidebars, template;
711
712                         /**
713                          * select the provided sidebar list item in the move widget area
714                          *
715                          * @param {jQuery} li
716                          */
717                         selectSidebarItem = function( li ) {
718                                 li.siblings( '.selected' ).removeClass( 'selected' );
719                                 li.addClass( 'selected' );
720                                 var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id );
721                                 self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar );
722                         };
723
724                         /**
725                          * Add the widget reordering elements to the widget control
726                          */
727                         this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) );
728
729
730                         template = _.template( api.Widgets.data.tpl.moveWidgetArea );
731                         $moveWidgetArea = $( template( {
732                                         sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' )
733                                 } )
734                         );
735                         this.container.find( '.widget-top' ).after( $moveWidgetArea );
736
737                         /**
738                          * Update available sidebars when their rendered state changes
739                          */
740                         updateAvailableSidebars = function() {
741                                 var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem,
742                                         renderedSidebarCount = 0;
743
744                                 selfSidebarItem = $sidebarItems.filter( function(){
745                                         return $( this ).data( 'id' ) === self.params.sidebar_id;
746                                 } );
747
748                                 $sidebarItems.each( function() {
749                                         var li = $( this ),
750                                                 sidebarId, sidebar, sidebarIsRendered;
751
752                                         sidebarId = li.data( 'id' );
753                                         sidebar = api.Widgets.registeredSidebars.get( sidebarId );
754                                         sidebarIsRendered = sidebar.get( 'is_rendered' );
755
756                                         li.toggle( sidebarIsRendered );
757
758                                         if ( sidebarIsRendered ) {
759                                                 renderedSidebarCount += 1;
760                                         }
761
762                                         if ( li.hasClass( 'selected' ) && ! sidebarIsRendered ) {
763                                                 selectSidebarItem( selfSidebarItem );
764                                         }
765                                 } );
766
767                                 if ( renderedSidebarCount > 1 ) {
768                                         self.container.find( '.move-widget' ).show();
769                                 } else {
770                                         self.container.find( '.move-widget' ).hide();
771                                 }
772                         };
773
774                         updateAvailableSidebars();
775                         api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars );
776
777                         /**
778                          * Handle clicks for up/down/move on the reorder nav
779                          */
780                         $reorderNav = this.container.find( '.widget-reorder-nav' );
781                         $reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() {
782                                 $( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' );
783                         } ).on( 'click keypress', function( event ) {
784                                 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
785                                         return;
786                                 }
787                                 $( this ).focus();
788
789                                 if ( $( this ).is( '.move-widget' ) ) {
790                                         self.toggleWidgetMoveArea();
791                                 } else {
792                                         var isMoveDown = $( this ).is( '.move-widget-down' ),
793                                                 isMoveUp = $( this ).is( '.move-widget-up' ),
794                                                 i = self.getWidgetSidebarPosition();
795
796                                         if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) {
797                                                 return;
798                                         }
799
800                                         if ( isMoveUp ) {
801                                                 self.moveUp();
802                                                 wp.a11y.speak( l10n.widgetMovedUp );
803                                         } else {
804                                                 self.moveDown();
805                                                 wp.a11y.speak( l10n.widgetMovedDown );
806                                         }
807
808                                         $( this ).focus(); // re-focus after the container was moved
809                                 }
810                         } );
811
812                         /**
813                          * Handle selecting a sidebar to move to
814                          */
815                         this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( event ) {
816                                 if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
817                                         return;
818                                 }
819                                 event.preventDefault();
820                                 selectSidebarItem( $( this ) );
821                         } );
822
823                         /**
824                          * Move widget to another sidebar
825                          */
826                         this.container.find( '.move-widget-btn' ).click( function() {
827                                 self.getSidebarWidgetsControl().toggleReordering( false );
828
829                                 var oldSidebarId = self.params.sidebar_id,
830                                         newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ),
831                                         oldSidebarWidgetsSetting, newSidebarWidgetsSetting,
832                                         oldSidebarWidgetIds, newSidebarWidgetIds, i;
833
834                                 oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' );
835                                 newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' );
836                                 oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() );
837                                 newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() );
838
839                                 i = self.getWidgetSidebarPosition();
840                                 oldSidebarWidgetIds.splice( i, 1 );
841                                 newSidebarWidgetIds.push( self.params.widget_id );
842
843                                 oldSidebarWidgetsSetting( oldSidebarWidgetIds );
844                                 newSidebarWidgetsSetting( newSidebarWidgetIds );
845
846                                 self.focus();
847                         } );
848                 },
849
850                 /**
851                  * Highlight widgets in preview when interacted with in the Customizer
852                  */
853                 _setupHighlightEffects: function() {
854                         var self = this;
855
856                         // Highlight whenever hovering or clicking over the form
857                         this.container.on( 'mouseenter click', function() {
858                                 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
859                         } );
860
861                         // Highlight when the setting is updated
862                         this.setting.bind( function() {
863                                 self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
864                         } );
865                 },
866
867                 /**
868                  * Set up event handlers for widget updating
869                  */
870                 _setupUpdateUI: function() {
871                         var self = this, $widgetRoot, $widgetContent,
872                                 $saveBtn, updateWidgetDebounced, formSyncHandler;
873
874                         $widgetRoot = this.container.find( '.widget:first' );
875                         $widgetContent = $widgetRoot.find( '.widget-content:first' );
876
877                         // Configure update button
878                         $saveBtn = this.container.find( '.widget-control-save' );
879                         $saveBtn.val( l10n.saveBtnLabel );
880                         $saveBtn.attr( 'title', l10n.saveBtnTooltip );
881                         $saveBtn.removeClass( 'button-primary' );
882                         $saveBtn.on( 'click', function( e ) {
883                                 e.preventDefault();
884                                 self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
885                         } );
886
887                         updateWidgetDebounced = _.debounce( function() {
888                                 self.updateWidget();
889                         }, 250 );
890
891                         // Trigger widget form update when hitting Enter within an input
892                         $widgetContent.on( 'keydown', 'input', function( e ) {
893                                 if ( 13 === e.which ) { // Enter
894                                         e.preventDefault();
895                                         self.updateWidget( { ignoreActiveElement: true } );
896                                 }
897                         } );
898
899                         // Handle widgets that support live previews
900                         $widgetContent.on( 'change input propertychange', ':input', function( e ) {
901                                 if ( ! self.liveUpdateMode ) {
902                                         return;
903                                 }
904                                 if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) {
905                                         updateWidgetDebounced();
906                                 }
907                         } );
908
909                         // Remove loading indicators when the setting is saved and the preview updates
910                         this.setting.previewer.channel.bind( 'synced', function() {
911                                 self.container.removeClass( 'previewer-loading' );
912                         } );
913
914                         api.previewer.bind( 'widget-updated', function( updatedWidgetId ) {
915                                 if ( updatedWidgetId === self.params.widget_id ) {
916                                         self.container.removeClass( 'previewer-loading' );
917                                 }
918                         } );
919
920                         formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
921                         if ( formSyncHandler ) {
922                                 $( document ).on( 'widget-synced', function( e, widget ) {
923                                         if ( $widgetRoot.is( widget ) ) {
924                                                 formSyncHandler.apply( document, arguments );
925                                         }
926                                 } );
927                         }
928                 },
929
930                 /**
931                  * Update widget control to indicate whether it is currently rendered.
932                  *
933                  * Overrides api.Control.toggle()
934                  *
935                  * @since 4.1.0
936                  *
937                  * @param {Boolean}   active
938                  * @param {Object}    args
939                  * @param {Callback}  args.completeCallback
940                  */
941                 onChangeActive: function ( active, args ) {
942                         // Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments
943                         this.container.toggleClass( 'widget-rendered', active );
944                         if ( args.completeCallback ) {
945                                 args.completeCallback();
946                         }
947                 },
948
949                 /**
950                  * Set up event handlers for widget removal
951                  */
952                 _setupRemoveUI: function() {
953                         var self = this, $removeBtn, replaceDeleteWithRemove;
954
955                         // Configure remove button
956                         $removeBtn = this.container.find( 'a.widget-control-remove' );
957                         $removeBtn.on( 'click', function( e ) {
958                                 e.preventDefault();
959
960                                 // Find an adjacent element to add focus to when this widget goes away
961                                 var $adjacentFocusTarget;
962                                 if ( self.container.next().is( '.customize-control-widget_form' ) ) {
963                                         $adjacentFocusTarget = self.container.next().find( '.widget-action:first' );
964                                 } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) {
965                                         $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' );
966                                 } else {
967                                         $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' );
968                                 }
969
970                                 self.container.slideUp( function() {
971                                         var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
972                                                 sidebarWidgetIds, i;
973
974                                         if ( ! sidebarsWidgetsControl ) {
975                                                 return;
976                                         }
977
978                                         sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
979                                         i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
980                                         if ( -1 === i ) {
981                                                 return;
982                                         }
983
984                                         sidebarWidgetIds.splice( i, 1 );
985                                         sidebarsWidgetsControl.setting( sidebarWidgetIds );
986
987                                         $adjacentFocusTarget.focus(); // keyboard accessibility
988                                 } );
989                         } );
990
991                         replaceDeleteWithRemove = function() {
992                                 $removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the link as "Delete"
993                                 $removeBtn.attr( 'title', l10n.removeBtnTooltip );
994                         };
995
996                         if ( this.params.is_new ) {
997                                 api.bind( 'saved', replaceDeleteWithRemove );
998                         } else {
999                                 replaceDeleteWithRemove();
1000                         }
1001                 },
1002
1003                 /**
1004                  * Find all inputs in a widget container that should be considered when
1005                  * comparing the loaded form with the sanitized form, whose fields will
1006                  * be aligned to copy the sanitized over. The elements returned by this
1007                  * are passed into this._getInputsSignature(), and they are iterated
1008                  * over when copying sanitized values over to the form loaded.
1009                  *
1010                  * @param {jQuery} container element in which to look for inputs
1011                  * @returns {jQuery} inputs
1012                  * @private
1013                  */
1014                 _getInputs: function( container ) {
1015                         return $( container ).find( ':input[name]' );
1016                 },
1017
1018                 /**
1019                  * Iterate over supplied inputs and create a signature string for all of them together.
1020                  * This string can be used to compare whether or not the form has all of the same fields.
1021                  *
1022                  * @param {jQuery} inputs
1023                  * @returns {string}
1024                  * @private
1025                  */
1026                 _getInputsSignature: function( inputs ) {
1027                         var inputsSignatures = _( inputs ).map( function( input ) {
1028                                 var $input = $( input ), signatureParts;
1029
1030                                 if ( $input.is( ':checkbox, :radio' ) ) {
1031                                         signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ];
1032                                 } else {
1033                                         signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ];
1034                                 }
1035
1036                                 return signatureParts.join( ',' );
1037                         } );
1038
1039                         return inputsSignatures.join( ';' );
1040                 },
1041
1042                 /**
1043                  * Get the state for an input depending on its type.
1044                  *
1045                  * @param {jQuery|Element} input
1046                  * @returns {string|boolean|array|*}
1047                  * @private
1048                  */
1049                 _getInputState: function( input ) {
1050                         input = $( input );
1051                         if ( input.is( ':radio, :checkbox' ) ) {
1052                                 return input.prop( 'checked' );
1053                         } else if ( input.is( 'select[multiple]' ) ) {
1054                                 return input.find( 'option:selected' ).map( function () {
1055                                         return $( this ).val();
1056                                 } ).get();
1057                         } else {
1058                                 return input.val();
1059                         }
1060                 },
1061
1062                 /**
1063                  * Update an input's state based on its type.
1064                  *
1065                  * @param {jQuery|Element} input
1066                  * @param {string|boolean|array|*} state
1067                  * @private
1068                  */
1069                 _setInputState: function ( input, state ) {
1070                         input = $( input );
1071                         if ( input.is( ':radio, :checkbox' ) ) {
1072                                 input.prop( 'checked', state );
1073                         } else if ( input.is( 'select[multiple]' ) ) {
1074                                 if ( ! $.isArray( state ) ) {
1075                                         state = [];
1076                                 } else {
1077                                         // Make sure all state items are strings since the DOM value is a string
1078                                         state = _.map( state, function ( value ) {
1079                                                 return String( value );
1080                                         } );
1081                                 }
1082                                 input.find( 'option' ).each( function () {
1083                                         $( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) );
1084                                 } );
1085                         } else {
1086                                 input.val( state );
1087                         }
1088                 },
1089
1090                 /***********************************************************************
1091                  * Begin public API methods
1092                  **********************************************************************/
1093
1094                 /**
1095                  * @return {wp.customize.controlConstructor.sidebar_widgets[]}
1096                  */
1097                 getSidebarWidgetsControl: function() {
1098                         var settingId, sidebarWidgetsControl;
1099
1100                         settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']';
1101                         sidebarWidgetsControl = api.control( settingId );
1102
1103                         if ( ! sidebarWidgetsControl ) {
1104                                 return;
1105                         }
1106
1107                         return sidebarWidgetsControl;
1108                 },
1109
1110                 /**
1111                  * Submit the widget form via Ajax and get back the updated instance,
1112                  * along with the new widget control form to render.
1113                  *
1114                  * @param {object} [args]
1115                  * @param {Object|null} [args.instance=null]  When the model changes, the instance is sent here; otherwise, the inputs from the form are used
1116                  * @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.
1117                  * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
1118                  */
1119                 updateWidget: function( args ) {
1120                         var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
1121                                 updateNumber, params, data, $inputs, processing, jqxhr, isChanged;
1122
1123                         // The updateWidget logic requires that the form fields to be fully present.
1124                         self.embedWidgetContent();
1125
1126                         args = $.extend( {
1127                                 instance: null,
1128                                 complete: null,
1129                                 ignoreActiveElement: false
1130                         }, args );
1131
1132                         instanceOverride = args.instance;
1133                         completeCallback = args.complete;
1134
1135                         this._updateCount += 1;
1136                         updateNumber = this._updateCount;
1137
1138                         $widgetRoot = this.container.find( '.widget:first' );
1139                         $widgetContent = $widgetRoot.find( '.widget-content:first' );
1140
1141                         // Remove a previous error message
1142                         $widgetContent.find( '.widget-error' ).remove();
1143
1144                         this.container.addClass( 'widget-form-loading' );
1145                         this.container.addClass( 'previewer-loading' );
1146                         processing = api.state( 'processing' );
1147                         processing( processing() + 1 );
1148
1149                         if ( ! this.liveUpdateMode ) {
1150                                 this.container.addClass( 'widget-form-disabled' );
1151                         }
1152
1153                         params = {};
1154                         params.action = 'update-widget';
1155                         params.wp_customize = 'on';
1156                         params.nonce = api.settings.nonce['update-widget'];
1157                         params.customize_theme = api.settings.theme.stylesheet;
1158                         params.customized = wp.customize.previewer.query().customized;
1159
1160                         data = $.param( params );
1161                         $inputs = this._getInputs( $widgetContent );
1162
1163                         // Store the value we're submitting in data so that when the response comes back,
1164                         // we know if it got sanitized; if there is no difference in the sanitized value,
1165                         // then we do not need to touch the UI and mess up the user's ongoing editing.
1166                         $inputs.each( function() {
1167                                 $( this ).data( 'state' + updateNumber, self._getInputState( this ) );
1168                         } );
1169
1170                         if ( instanceOverride ) {
1171                                 data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } );
1172                         } else {
1173                                 data += '&' + $inputs.serialize();
1174                         }
1175                         data += '&' + $widgetContent.find( '~ :input' ).serialize();
1176
1177                         if ( this._previousUpdateRequest ) {
1178                                 this._previousUpdateRequest.abort();
1179                         }
1180                         jqxhr = $.post( wp.ajax.settings.url, data );
1181                         this._previousUpdateRequest = jqxhr;
1182
1183                         jqxhr.done( function( r ) {
1184                                 var message, sanitizedForm,     $sanitizedInputs, hasSameInputsInResponse,
1185                                         isLiveUpdateAborted = false;
1186
1187                                 // Check if the user is logged out.
1188                                 if ( '0' === r ) {
1189                                         api.previewer.preview.iframe.hide();
1190                                         api.previewer.login().done( function() {
1191                                                 self.updateWidget( args );
1192                                                 api.previewer.preview.iframe.show();
1193                                         } );
1194                                         return;
1195                                 }
1196
1197                                 // Check for cheaters.
1198                                 if ( '-1' === r ) {
1199                                         api.previewer.cheatin();
1200                                         return;
1201                                 }
1202
1203                                 if ( r.success ) {
1204                                         sanitizedForm = $( '<div>' + r.data.form + '</div>' );
1205                                         $sanitizedInputs = self._getInputs( sanitizedForm );
1206                                         hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs );
1207
1208                                         // Restore live update mode if sanitized fields are now aligned with the existing fields
1209                                         if ( hasSameInputsInResponse && ! self.liveUpdateMode ) {
1210                                                 self.liveUpdateMode = true;
1211                                                 self.container.removeClass( 'widget-form-disabled' );
1212                                                 self.container.find( 'input[name="savewidget"]' ).hide();
1213                                         }
1214
1215                                         // Sync sanitized field states to existing fields if they are aligned
1216                                         if ( hasSameInputsInResponse && self.liveUpdateMode ) {
1217                                                 $inputs.each( function( i ) {
1218                                                         var $input = $( this ),
1219                                                                 $sanitizedInput = $( $sanitizedInputs[i] ),
1220                                                                 submittedState, sanitizedState, canUpdateState;
1221
1222                                                         submittedState = $input.data( 'state' + updateNumber );
1223                                                         sanitizedState = self._getInputState( $sanitizedInput );
1224                                                         $input.data( 'sanitized', sanitizedState );
1225
1226                                                         canUpdateState = ( ! _.isEqual( submittedState, sanitizedState ) && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
1227                                                         if ( canUpdateState ) {
1228                                                                 self._setInputState( $input, sanitizedState );
1229                                                         }
1230                                                 } );
1231
1232                                                 $( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] );
1233
1234                                         // Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled
1235                                         } else if ( self.liveUpdateMode ) {
1236                                                 self.liveUpdateMode = false;
1237                                                 self.container.find( 'input[name="savewidget"]' ).show();
1238                                                 isLiveUpdateAborted = true;
1239
1240                                         // Otherwise, replace existing form with the sanitized form
1241                                         } else {
1242                                                 $widgetContent.html( r.data.form );
1243
1244                                                 self.container.removeClass( 'widget-form-disabled' );
1245
1246                                                 $( document ).trigger( 'widget-updated', [ $widgetRoot ] );
1247                                         }
1248
1249                                         /**
1250                                          * If the old instance is identical to the new one, there is nothing new
1251                                          * needing to be rendered, and so we can preempt the event for the
1252                                          * preview finishing loading.
1253                                          */
1254                                         isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance );
1255                                         if ( isChanged ) {
1256                                                 self.isWidgetUpdating = true; // suppress triggering another updateWidget
1257                                                 self.setting( r.data.instance );
1258                                                 self.isWidgetUpdating = false;
1259                                         } else {
1260                                                 // no change was made, so stop the spinner now instead of when the preview would updates
1261                                                 self.container.removeClass( 'previewer-loading' );
1262                                         }
1263
1264                                         if ( completeCallback ) {
1265                                                 completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
1266                                         }
1267                                 } else {
1268                                         // General error message
1269                                         message = l10n.error;
1270
1271                                         if ( r.data && r.data.message ) {
1272                                                 message = r.data.message;
1273                                         }
1274
1275                                         if ( completeCallback ) {
1276                                                 completeCallback.call( self, message );
1277                                         } else {
1278                                                 $widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' );
1279                                         }
1280                                 }
1281                         } );
1282
1283                         jqxhr.fail( function( jqXHR, textStatus ) {
1284                                 if ( completeCallback ) {
1285                                         completeCallback.call( self, textStatus );
1286                                 }
1287                         } );
1288
1289                         jqxhr.always( function() {
1290                                 self.container.removeClass( 'widget-form-loading' );
1291
1292                                 $inputs.each( function() {
1293                                         $( this ).removeData( 'state' + updateNumber );
1294                                 } );
1295
1296                                 processing( processing() - 1 );
1297                         } );
1298                 },
1299
1300                 /**
1301                  * Expand the accordion section containing a control
1302                  */
1303                 expandControlSection: function() {
1304                         api.Control.prototype.expand.call( this );
1305                 },
1306
1307                 /**
1308                  * @since 4.1.0
1309                  *
1310                  * @param {Boolean} expanded
1311                  * @param {Object} [params]
1312                  * @returns {Boolean} false if state already applied
1313                  */
1314                 _toggleExpanded: api.Section.prototype._toggleExpanded,
1315
1316                 /**
1317                  * @since 4.1.0
1318                  *
1319                  * @param {Object} [params]
1320                  * @returns {Boolean} false if already expanded
1321                  */
1322                 expand: api.Section.prototype.expand,
1323
1324                 /**
1325                  * Expand the widget form control
1326                  *
1327                  * @deprecated 4.1.0 Use this.expand() instead.
1328                  */
1329                 expandForm: function() {
1330                         this.expand();
1331                 },
1332
1333                 /**
1334                  * @since 4.1.0
1335                  *
1336                  * @param {Object} [params]
1337                  * @returns {Boolean} false if already collapsed
1338                  */
1339                 collapse: api.Section.prototype.collapse,
1340
1341                 /**
1342                  * Collapse the widget form control
1343                  *
1344                  * @deprecated 4.1.0 Use this.collapse() instead.
1345                  */
1346                 collapseForm: function() {
1347                         this.collapse();
1348                 },
1349
1350                 /**
1351                  * Expand or collapse the widget control
1352                  *
1353                  * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
1354                  *
1355                  * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility
1356                  */
1357                 toggleForm: function( showOrHide ) {
1358                         if ( typeof showOrHide === 'undefined' ) {
1359                                 showOrHide = ! this.expanded();
1360                         }
1361                         this.expanded( showOrHide );
1362                 },
1363
1364                 /**
1365                  * Respond to change in the expanded state.
1366                  *
1367                  * @param {Boolean} expanded
1368                  * @param {Object} args  merged on top of this.defaultActiveArguments
1369                  */
1370                 onChangeExpanded: function ( expanded, args ) {
1371                         var self = this, $widget, $inside, complete, prevComplete, expandControl;
1372
1373                         self.embedWidgetControl(); // Make sure the outer form is embedded so that the expanded state can be set in the UI.
1374                         if ( expanded ) {
1375                                 self.embedWidgetContent();
1376                         }
1377
1378                         // If the expanded state is unchanged only manipulate container expanded states
1379                         if ( args.unchanged ) {
1380                                 if ( expanded ) {
1381                                         api.Control.prototype.expand.call( self, {
1382                                                 completeCallback:  args.completeCallback
1383                                         });
1384                                 }
1385                                 return;
1386                         }
1387
1388                         $widget = this.container.find( 'div.widget:first' );
1389                         $inside = $widget.find( '.widget-inside:first' );
1390
1391                         expandControl = function() {
1392
1393                                 // Close all other widget controls before expanding this one
1394                                 api.control.each( function( otherControl ) {
1395                                         if ( self.params.type === otherControl.params.type && self !== otherControl ) {
1396                                                 otherControl.collapse();
1397                                         }
1398                                 } );
1399
1400                                 complete = function() {
1401                                         self.container.removeClass( 'expanding' );
1402                                         self.container.addClass( 'expanded' );
1403                                         self.container.trigger( 'expanded' );
1404                                 };
1405                                 if ( args.completeCallback ) {
1406                                         prevComplete = complete;
1407                                         complete = function () {
1408                                                 prevComplete();
1409                                                 args.completeCallback();
1410                                         };
1411                                 }
1412
1413                                 if ( self.params.is_wide ) {
1414                                         $inside.fadeIn( args.duration, complete );
1415                                 } else {
1416                                         $inside.slideDown( args.duration, complete );
1417                                 }
1418
1419                                 self.container.trigger( 'expand' );
1420                                 self.container.addClass( 'expanding' );
1421                         };
1422
1423                         if ( expanded ) {
1424                                 if ( api.section.has( self.section() ) ) {
1425                                         api.section( self.section() ).expand( {
1426                                                 completeCallback: expandControl
1427                                         } );
1428                                 } else {
1429                                         expandControl();
1430                                 }
1431                         } else {
1432
1433                                 complete = function() {
1434                                         self.container.removeClass( 'collapsing' );
1435                                         self.container.removeClass( 'expanded' );
1436                                         self.container.trigger( 'collapsed' );
1437                                 };
1438                                 if ( args.completeCallback ) {
1439                                         prevComplete = complete;
1440                                         complete = function () {
1441                                                 prevComplete();
1442                                                 args.completeCallback();
1443                                         };
1444                                 }
1445
1446                                 self.container.trigger( 'collapse' );
1447                                 self.container.addClass( 'collapsing' );
1448
1449                                 if ( self.params.is_wide ) {
1450                                         $inside.fadeOut( args.duration, complete );
1451                                 } else {
1452                                         $inside.slideUp( args.duration, function() {
1453                                                 $widget.css( { width:'', margin:'' } );
1454                                                 complete();
1455                                         } );
1456                                 }
1457                         }
1458                 },
1459
1460                 /**
1461                  * Get the position (index) of the widget in the containing sidebar
1462                  *
1463                  * @returns {Number}
1464                  */
1465                 getWidgetSidebarPosition: function() {
1466                         var sidebarWidgetIds, position;
1467
1468                         sidebarWidgetIds = this.getSidebarWidgetsControl().setting();
1469                         position = _.indexOf( sidebarWidgetIds, this.params.widget_id );
1470
1471                         if ( position === -1 ) {
1472                                 return;
1473                         }
1474
1475                         return position;
1476                 },
1477
1478                 /**
1479                  * Move widget up one in the sidebar
1480                  */
1481                 moveUp: function() {
1482                         this._moveWidgetByOne( -1 );
1483                 },
1484
1485                 /**
1486                  * Move widget up one in the sidebar
1487                  */
1488                 moveDown: function() {
1489                         this._moveWidgetByOne( 1 );
1490                 },
1491
1492                 /**
1493                  * @private
1494                  *
1495                  * @param {Number} offset 1|-1
1496                  */
1497                 _moveWidgetByOne: function( offset ) {
1498                         var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId;
1499
1500                         i = this.getWidgetSidebarPosition();
1501
1502                         sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting;
1503                         sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // clone
1504                         adjacentWidgetId = sidebarWidgetIds[i + offset];
1505                         sidebarWidgetIds[i + offset] = this.params.widget_id;
1506                         sidebarWidgetIds[i] = adjacentWidgetId;
1507
1508                         sidebarWidgetsSetting( sidebarWidgetIds );
1509                 },
1510
1511                 /**
1512                  * Toggle visibility of the widget move area
1513                  *
1514                  * @param {Boolean} [showOrHide]
1515                  */
1516                 toggleWidgetMoveArea: function( showOrHide ) {
1517                         var self = this, $moveWidgetArea;
1518
1519                         $moveWidgetArea = this.container.find( '.move-widget-area' );
1520
1521                         if ( typeof showOrHide === 'undefined' ) {
1522                                 showOrHide = ! $moveWidgetArea.hasClass( 'active' );
1523                         }
1524
1525                         if ( showOrHide ) {
1526                                 // reset the selected sidebar
1527                                 $moveWidgetArea.find( '.selected' ).removeClass( 'selected' );
1528
1529                                 $moveWidgetArea.find( 'li' ).filter( function() {
1530                                         return $( this ).data( 'id' ) === self.params.sidebar_id;
1531                                 } ).addClass( 'selected' );
1532
1533                                 this.container.find( '.move-widget-btn' ).prop( 'disabled', true );
1534                         }
1535
1536                         $moveWidgetArea.toggleClass( 'active', showOrHide );
1537                 },
1538
1539                 /**
1540                  * Highlight the widget control and section
1541                  */
1542                 highlightSectionAndControl: function() {
1543                         var $target;
1544
1545                         if ( this.container.is( ':hidden' ) ) {
1546                                 $target = this.container.closest( '.control-section' );
1547                         } else {
1548                                 $target = this.container;
1549                         }
1550
1551                         $( '.highlighted' ).removeClass( 'highlighted' );
1552                         $target.addClass( 'highlighted' );
1553
1554                         setTimeout( function() {
1555                                 $target.removeClass( 'highlighted' );
1556                         }, 500 );
1557                 }
1558         } );
1559
1560         /**
1561          * wp.customize.Widgets.WidgetsPanel
1562          *
1563          * Customizer panel containing the widget area sections.
1564          *
1565          * @since 4.4.0
1566          */
1567         api.Widgets.WidgetsPanel = api.Panel.extend({
1568
1569                 /**
1570                  * Add and manage the display of the no-rendered-areas notice.
1571                  *
1572                  * @since 4.4.0
1573                  */
1574                 ready: function () {
1575                         var panel = this;
1576
1577                         api.Panel.prototype.ready.call( panel );
1578
1579                         panel.deferred.embedded.done(function() {
1580                                 var panelMetaContainer, noRenderedAreasNotice, shouldShowNotice;
1581                                 panelMetaContainer = panel.container.find( '.panel-meta' );
1582                                 noRenderedAreasNotice = $( '<div></div>', {
1583                                         'class': 'no-widget-areas-rendered-notice'
1584                                 });
1585                                 noRenderedAreasNotice.append( $( '<em></em>', {
1586                                         text: l10n.noAreasRendered
1587                                 } ) );
1588                                 panelMetaContainer.append( noRenderedAreasNotice );
1589
1590                                 shouldShowNotice = function() {
1591                                         return ( 0 === _.filter( panel.sections(), function( section ) {
1592                                                 return section.active();
1593                                         } ).length );
1594                                 };
1595
1596                                 /*
1597                                  * Set the initial visibility state for rendered notice.
1598                                  * Update the visibility of the notice whenever a reflow happens.
1599                                  */
1600                                 noRenderedAreasNotice.toggle( shouldShowNotice() );
1601                                 api.previewer.deferred.active.done( function () {
1602                                         noRenderedAreasNotice.toggle( shouldShowNotice() );
1603                                 });
1604                                 api.bind( 'pane-contents-reflowed', function() {
1605                                         var duration = ( 'resolved' === api.previewer.deferred.active.state() ) ? 'fast' : 0;
1606                                         if ( shouldShowNotice() ) {
1607                                                 noRenderedAreasNotice.slideDown( duration );
1608                                         } else {
1609                                                 noRenderedAreasNotice.slideUp( duration );
1610                                         }
1611                                 });
1612                         });
1613                 },
1614
1615                 /**
1616                  * Allow an active widgets panel to be contextually active even when it has no active sections (widget areas).
1617                  *
1618                  * This ensures that the widgets panel appears even when there are no
1619                  * sidebars displayed on the URL currently being previewed.
1620                  *
1621                  * @since 4.4.0
1622                  *
1623                  * @returns {boolean}
1624                  */
1625                 isContextuallyActive: function() {
1626                         var panel = this;
1627                         return panel.active();
1628                 }
1629         });
1630
1631         /**
1632          * wp.customize.Widgets.SidebarSection
1633          *
1634          * Customizer section representing a widget area widget
1635          *
1636          * @since 4.1.0
1637          */
1638         api.Widgets.SidebarSection = api.Section.extend({
1639
1640                 /**
1641                  * Sync the section's active state back to the Backbone model's is_rendered attribute
1642                  *
1643                  * @since 4.1.0
1644                  */
1645                 ready: function () {
1646                         var section = this, registeredSidebar;
1647                         api.Section.prototype.ready.call( this );
1648                         registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId );
1649                         section.active.bind( function ( active ) {
1650                                 registeredSidebar.set( 'is_rendered', active );
1651                         });
1652                         registeredSidebar.set( 'is_rendered', section.active() );
1653                 }
1654         });
1655
1656         /**
1657          * wp.customize.Widgets.SidebarControl
1658          *
1659          * Customizer control for widgets.
1660          * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type
1661          *
1662          * @since 3.9.0
1663          *
1664          * @constructor
1665          * @augments wp.customize.Control
1666          */
1667         api.Widgets.SidebarControl = api.Control.extend({
1668
1669                 /**
1670                  * Set up the control
1671                  */
1672                 ready: function() {
1673                         this.$controlSection = this.container.closest( '.control-section' );
1674                         this.$sectionContent = this.container.closest( '.accordion-section-content' );
1675
1676                         this._setupModel();
1677                         this._setupSortable();
1678                         this._setupAddition();
1679                         this._applyCardinalOrderClassNames();
1680                 },
1681
1682                 /**
1683                  * Update ordering of widget control forms when the setting is updated
1684                  */
1685                 _setupModel: function() {
1686                         var self = this;
1687
1688                         this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
1689                                 var widgetFormControls, removedWidgetIds, priority;
1690
1691                                 removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );
1692
1693                                 // Filter out any persistent widget IDs for widgets which have been deactivated
1694                                 newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
1695                                         var parsedWidgetId = parseWidgetId( newWidgetId );
1696
1697                                         return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
1698                                 } );
1699
1700                                 widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
1701                                         var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1702
1703                                         if ( ! widgetFormControl ) {
1704                                                 widgetFormControl = self.addWidget( widgetId );
1705                                         }
1706
1707                                         return widgetFormControl;
1708                                 } );
1709
1710                                 // Sort widget controls to their new positions
1711                                 widgetFormControls.sort( function( a, b ) {
1712                                         var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
1713                                                 bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
1714                                         return aIndex - bIndex;
1715                                 });
1716
1717                                 priority = 0;
1718                                 _( widgetFormControls ).each( function ( control ) {
1719                                         control.priority( priority );
1720                                         control.section( self.section() );
1721                                         priority += 1;
1722                                 });
1723                                 self.priority( priority ); // Make sure sidebar control remains at end
1724
1725                                 // Re-sort widget form controls (including widgets form other sidebars newly moved here)
1726                                 self._applyCardinalOrderClassNames();
1727
1728                                 // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated
1729                                 _( widgetFormControls ).each( function( widgetFormControl ) {
1730                                         widgetFormControl.params.sidebar_id = self.params.sidebar_id;
1731                                 } );
1732
1733                                 // Cleanup after widget removal
1734                                 _( removedWidgetIds ).each( function( removedWidgetId ) {
1735
1736                                         // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update
1737                                         setTimeout( function() {
1738                                                 var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
1739                                                         widget, isPresentInAnotherSidebar = false;
1740
1741                                                 // Check if the widget is in another sidebar
1742                                                 api.each( function( otherSetting ) {
1743                                                         if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) {
1744                                                                 return;
1745                                                         }
1746
1747                                                         var otherSidebarWidgets = otherSetting(), i;
1748
1749                                                         i = _.indexOf( otherSidebarWidgets, removedWidgetId );
1750                                                         if ( -1 !== i ) {
1751                                                                 isPresentInAnotherSidebar = true;
1752                                                         }
1753                                                 } );
1754
1755                                                 // If the widget is present in another sidebar, abort!
1756                                                 if ( isPresentInAnotherSidebar ) {
1757                                                         return;
1758                                                 }
1759
1760                                                 removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );
1761
1762                                                 // Detect if widget control was dragged to another sidebar
1763                                                 wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
1764
1765                                                 // Delete any widget form controls for removed widgets
1766                                                 if ( removedControl && ! wasDraggedToAnotherSidebar ) {
1767                                                         api.control.remove( removedControl.id );
1768                                                         removedControl.container.remove();
1769                                                 }
1770
1771                                                 // Move widget to inactive widgets sidebar (move it to trash) if has been previously saved
1772                                                 // This prevents the inactive widgets sidebar from overflowing with throwaway widgets
1773                                                 if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
1774                                                         inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice();
1775                                                         inactiveWidgets.push( removedWidgetId );
1776                                                         api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() );
1777                                                 }
1778
1779                                                 // Make old single widget available for adding again
1780                                                 removedIdBase = parseWidgetId( removedWidgetId ).id_base;
1781                                                 widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
1782                                                 if ( widget && ! widget.get( 'is_multi' ) ) {
1783                                                         widget.set( 'is_disabled', false );
1784                                                 }
1785                                         } );
1786
1787                                 } );
1788                         } );
1789                 },
1790
1791                 /**
1792                  * Allow widgets in sidebar to be re-ordered, and for the order to be previewed
1793                  */
1794                 _setupSortable: function() {
1795                         var self = this;
1796
1797                         this.isReordering = false;
1798
1799                         /**
1800                          * Update widget order setting when controls are re-ordered
1801                          */
1802                         this.$sectionContent.sortable( {
1803                                 items: '> .customize-control-widget_form',
1804                                 handle: '.widget-top',
1805                                 axis: 'y',
1806                                 tolerance: 'pointer',
1807                                 connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
1808                                 update: function() {
1809                                         var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
1810
1811                                         widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
1812                                                 return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
1813                                         } );
1814
1815                                         self.setting( widgetIds );
1816                                 }
1817                         } );
1818
1819                         /**
1820                          * Expand other Customizer sidebar section when dragging a control widget over it,
1821                          * allowing the control to be dropped into another section
1822                          */
1823                         this.$controlSection.find( '.accordion-section-title' ).droppable({
1824                                 accept: '.customize-control-widget_form',
1825                                 over: function() {
1826                                         var section = api.section( self.section.get() );
1827                                         section.expand({
1828                                                 allowMultiple: true, // Prevent the section being dragged from to be collapsed
1829                                                 completeCallback: function () {
1830                                                         // @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed
1831                                                         api.section.each( function ( otherSection ) {
1832                                                                 if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) {
1833                                                                         otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' );
1834                                                                 }
1835                                                         } );
1836                                                 }
1837                                         });
1838                                 }
1839                         });
1840
1841                         /**
1842                          * Keyboard-accessible reordering
1843                          */
1844                         this.container.find( '.reorder-toggle' ).on( 'click', function() {
1845                                 self.toggleReordering( ! self.isReordering );
1846                         } );
1847                 },
1848
1849                 /**
1850                  * Set up UI for adding a new widget
1851                  */
1852                 _setupAddition: function() {
1853                         var self = this;
1854
1855                         this.container.find( '.add-new-widget' ).on( 'click', function() {
1856                                 var addNewWidgetBtn = $( this );
1857
1858                                 if ( self.$sectionContent.hasClass( 'reordering' ) ) {
1859                                         return;
1860                                 }
1861
1862                                 if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
1863                                         addNewWidgetBtn.attr( 'aria-expanded', 'true' );
1864                                         api.Widgets.availableWidgetsPanel.open( self );
1865                                 } else {
1866                                         addNewWidgetBtn.attr( 'aria-expanded', 'false' );
1867                                         api.Widgets.availableWidgetsPanel.close();
1868                                 }
1869                         } );
1870                 },
1871
1872                 /**
1873                  * Add classes to the widget_form controls to assist with styling
1874                  */
1875                 _applyCardinalOrderClassNames: function() {
1876                         var widgetControls = [];
1877                         _.each( this.setting(), function ( widgetId ) {
1878                                 var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
1879                                 if ( widgetControl ) {
1880                                         widgetControls.push( widgetControl );
1881                                 }
1882                         });
1883
1884                         if ( 0 === widgetControls.length || ( 1 === api.Widgets.registeredSidebars.length && widgetControls.length <= 1 ) ) {
1885                                 this.container.find( '.reorder-toggle' ).hide();
1886                                 return;
1887                         } else {
1888                                 this.container.find( '.reorder-toggle' ).show();
1889                         }
1890
1891                         $( widgetControls ).each( function () {
1892                                 $( this.container )
1893                                         .removeClass( 'first-widget' )
1894                                         .removeClass( 'last-widget' )
1895                                         .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
1896                         });
1897
1898                         _.first( widgetControls ).container
1899                                 .addClass( 'first-widget' )
1900                                 .find( '.move-widget-up' ).prop( 'tabIndex', -1 );
1901
1902                         _.last( widgetControls ).container
1903                                 .addClass( 'last-widget' )
1904                                 .find( '.move-widget-down' ).prop( 'tabIndex', -1 );
1905                 },
1906
1907
1908                 /***********************************************************************
1909                  * Begin public API methods
1910                  **********************************************************************/
1911
1912                 /**
1913                  * Enable/disable the reordering UI
1914                  *
1915                  * @param {Boolean} showOrHide to enable/disable reordering
1916                  *
1917                  * @todo We should have a reordering state instead and rename this to onChangeReordering
1918                  */
1919                 toggleReordering: function( showOrHide ) {
1920                         var addNewWidgetBtn = this.$sectionContent.find( '.add-new-widget' ),
1921                                 reorderBtn = this.container.find( '.reorder-toggle' ),
1922                                 widgetsTitle = this.$sectionContent.find( '.widget-title' );
1923
1924                         showOrHide = Boolean( showOrHide );
1925
1926                         if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
1927                                 return;
1928                         }
1929
1930                         this.isReordering = showOrHide;
1931                         this.$sectionContent.toggleClass( 'reordering', showOrHide );
1932
1933                         if ( showOrHide ) {
1934                                 _( this.getWidgetFormControls() ).each( function( formControl ) {
1935                                         formControl.collapse();
1936                                 } );
1937
1938                                 addNewWidgetBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
1939                                 reorderBtn.attr( 'aria-label', l10n.reorderLabelOff );
1940                                 wp.a11y.speak( l10n.reorderModeOn );
1941                                 // Hide widget titles while reordering: title is already in the reorder controls.
1942                                 widgetsTitle.attr( 'aria-hidden', 'true' );
1943                         } else {
1944                                 addNewWidgetBtn.removeAttr( 'tabindex aria-hidden' );
1945                                 reorderBtn.attr( 'aria-label', l10n.reorderLabelOn );
1946                                 wp.a11y.speak( l10n.reorderModeOff );
1947                                 widgetsTitle.attr( 'aria-hidden', 'false' );
1948                         }
1949                 },
1950
1951                 /**
1952                  * Get the widget_form Customize controls associated with the current sidebar.
1953                  *
1954                  * @since 3.9.0
1955                  * @return {wp.customize.controlConstructor.widget_form[]}
1956                  */
1957                 getWidgetFormControls: function() {
1958                         var formControls = [];
1959
1960                         _( this.setting() ).each( function( widgetId ) {
1961                                 var settingId = widgetIdToSettingId( widgetId ),
1962                                         formControl = api.control( settingId );
1963                                 if ( formControl ) {
1964                                         formControls.push( formControl );
1965                                 }
1966                         } );
1967
1968                         return formControls;
1969                 },
1970
1971                 /**
1972                  * @param {string} widgetId or an id_base for adding a previously non-existing widget
1973                  * @returns {object|false} widget_form control instance, or false on error
1974                  */
1975                 addWidget: function( widgetId ) {
1976                         var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor,
1977                                 parsedWidgetId = parseWidgetId( widgetId ),
1978                                 widgetNumber = parsedWidgetId.number,
1979                                 widgetIdBase = parsedWidgetId.id_base,
1980                                 widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
1981                                 settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting;
1982
1983                         if ( ! widget ) {
1984                                 return false;
1985                         }
1986
1987                         if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
1988                                 return false;
1989                         }
1990
1991                         // Set up new multi widget
1992                         if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
1993                                 widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
1994                                 widgetNumber = widget.get( 'multi_number' );
1995                         }
1996
1997                         controlHtml = $.trim( $( '#widget-tpl-' + widget.get( 'id' ) ).html() );
1998                         if ( widget.get( 'is_multi' ) ) {
1999                                 controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
2000                                         return m.replace( /__i__|%i%/g, widgetNumber );
2001                                 } );
2002                         } else {
2003                                 widget.set( 'is_disabled', true ); // Prevent single widget from being added again now
2004                         }
2005
2006                         $widget = $( controlHtml );
2007
2008                         controlContainer = $( '<li/>' )
2009                                 .addClass( 'customize-control' )
2010                                 .addClass( 'customize-control-' + controlType )
2011                                 .append( $widget );
2012
2013                         // Remove icon which is visible inside the panel
2014                         controlContainer.find( '> .widget-icon' ).remove();
2015
2016                         if ( widget.get( 'is_multi' ) ) {
2017                                 controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber );
2018                                 controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber );
2019                         }
2020
2021                         widgetId = controlContainer.find( '[name="widget-id"]' ).val();
2022
2023                         controlContainer.hide(); // to be slid-down below
2024
2025                         settingId = 'widget_' + widget.get( 'id_base' );
2026                         if ( widget.get( 'is_multi' ) ) {
2027                                 settingId += '[' + widgetNumber + ']';
2028                         }
2029                         controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );
2030
2031                         // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget)
2032                         isExistingWidget = api.has( settingId );
2033                         if ( ! isExistingWidget ) {
2034                                 settingArgs = {
2035                                         transport: api.Widgets.data.selectiveRefreshableWidgets[ widget.get( 'id_base' ) ] ? 'postMessage' : 'refresh',
2036                                         previewer: this.setting.previewer
2037                                 };
2038                                 setting = api.create( settingId, settingId, '', settingArgs );
2039                                 setting.set( {} ); // mark dirty, changing from '' to {}
2040                         }
2041
2042                         controlConstructor = api.controlConstructor[controlType];
2043                         widgetFormControl = new controlConstructor( settingId, {
2044                                 params: {
2045                                         settings: {
2046                                                 'default': settingId
2047                                         },
2048                                         content: controlContainer,
2049                                         sidebar_id: self.params.sidebar_id,
2050                                         widget_id: widgetId,
2051                                         widget_id_base: widget.get( 'id_base' ),
2052                                         type: controlType,
2053                                         is_new: ! isExistingWidget,
2054                                         width: widget.get( 'width' ),
2055                                         height: widget.get( 'height' ),
2056                                         is_wide: widget.get( 'is_wide' ),
2057                                         active: true
2058                                 },
2059                                 previewer: self.setting.previewer
2060                         } );
2061                         api.control.add( settingId, widgetFormControl );
2062
2063                         // Make sure widget is removed from the other sidebars
2064                         api.each( function( otherSetting ) {
2065                                 if ( otherSetting.id === self.setting.id ) {
2066                                         return;
2067                                 }
2068
2069                                 if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
2070                                         return;
2071                                 }
2072
2073                                 var otherSidebarWidgets = otherSetting().slice(),
2074                                         i = _.indexOf( otherSidebarWidgets, widgetId );
2075
2076                                 if ( -1 !== i ) {
2077                                         otherSidebarWidgets.splice( i );
2078                                         otherSetting( otherSidebarWidgets );
2079                                 }
2080                         } );
2081
2082                         // Add widget to this sidebar
2083                         sidebarWidgets = this.setting().slice();
2084                         if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
2085                                 sidebarWidgets.push( widgetId );
2086                                 this.setting( sidebarWidgets );
2087                         }
2088
2089                         controlContainer.slideDown( function() {
2090                                 if ( isExistingWidget ) {
2091                                         widgetFormControl.updateWidget( {
2092                                                 instance: widgetFormControl.setting()
2093                                         } );
2094                                 }
2095                         } );
2096
2097                         return widgetFormControl;
2098                 }
2099         } );
2100
2101         // Register models for custom panel, section, and control types
2102         $.extend( api.panelConstructor, {
2103                 widgets: api.Widgets.WidgetsPanel
2104         });
2105         $.extend( api.sectionConstructor, {
2106                 sidebar: api.Widgets.SidebarSection
2107         });
2108         $.extend( api.controlConstructor, {
2109                 widget_form: api.Widgets.WidgetControl,
2110                 sidebar_widgets: api.Widgets.SidebarControl
2111         });
2112
2113         /**
2114          * Init Customizer for widgets.
2115          */
2116         api.bind( 'ready', function() {
2117                 // Set up the widgets panel
2118                 api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
2119                         collection: api.Widgets.availableWidgets
2120                 });
2121
2122                 // Highlight widget control
2123                 api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
2124
2125                 // Open and focus widget control
2126                 api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
2127         } );
2128
2129         /**
2130          * Highlight a widget control.
2131          *
2132          * @param {string} widgetId
2133          */
2134         api.Widgets.highlightWidgetFormControl = function( widgetId ) {
2135                 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
2136
2137                 if ( control ) {
2138                         control.highlightSectionAndControl();
2139                 }
2140         },
2141
2142         /**
2143          * Focus a widget control.
2144          *
2145          * @param {string} widgetId
2146          */
2147         api.Widgets.focusWidgetFormControl = function( widgetId ) {
2148                 var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
2149
2150                 if ( control ) {
2151                         control.focus();
2152                 }
2153         },
2154
2155         /**
2156          * Given a widget control, find the sidebar widgets control that contains it.
2157          * @param {string} widgetId
2158          * @return {object|null}
2159          */
2160         api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
2161                 var foundControl = null;
2162
2163                 // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl()
2164                 api.control.each( function( control ) {
2165                         if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
2166                                 foundControl = control;
2167                         }
2168                 } );
2169
2170                 return foundControl;
2171         };
2172
2173         /**
2174          * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
2175          *
2176          * @param {string} widgetId
2177          * @return {object|null}
2178          */
2179         api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
2180                 var foundControl = null;
2181
2182                 // @todo We can just use widgetIdToSettingId() here
2183                 api.control.each( function( control ) {
2184                         if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
2185                                 foundControl = control;
2186                         }
2187                 } );
2188
2189                 return foundControl;
2190         };
2191
2192         /**
2193          * Initialize Edit Menu button in Nav Menu widget.
2194          */
2195         $( document ).on( 'widget-added', function( event, widgetContainer ) {
2196                 var parsedWidgetId, widgetControl, navMenuSelect, editMenuButton;
2197                 parsedWidgetId = parseWidgetId( widgetContainer.find( '> .widget-inside > .form > .widget-id' ).val() );
2198                 if ( 'nav_menu' !== parsedWidgetId.id_base ) {
2199                         return;
2200                 }
2201                 widgetControl = api.control( 'widget_nav_menu[' + String( parsedWidgetId.number ) + ']' );
2202                 if ( ! widgetControl ) {
2203                         return;
2204                 }
2205                 navMenuSelect = widgetContainer.find( 'select[name*="nav_menu"]' );
2206                 editMenuButton = widgetContainer.find( '.edit-selected-nav-menu > button' );
2207                 if ( 0 === navMenuSelect.length || 0 === editMenuButton.length ) {
2208                         return;
2209                 }
2210                 navMenuSelect.on( 'change', function() {
2211                         if ( api.section.has( 'nav_menu[' + navMenuSelect.val() + ']' ) ) {
2212                                 editMenuButton.parent().show();
2213                         } else {
2214                                 editMenuButton.parent().hide();
2215                         }
2216                 });
2217                 editMenuButton.on( 'click', function() {
2218                         var section = api.section( 'nav_menu[' + navMenuSelect.val() + ']' );
2219                         if ( section ) {
2220                                 focusConstructWithBreadcrumb( section, widgetControl );
2221                         }
2222                 } );
2223         } );
2224
2225         /**
2226          * Focus (expand) one construct and then focus on another construct after the first is collapsed.
2227          *
2228          * This overrides the back button to serve the purpose of breadcrumb navigation.
2229          *
2230          * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} focusConstruct - The object to initially focus.
2231          * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} returnConstruct - The object to return focus.
2232          */
2233         function focusConstructWithBreadcrumb( focusConstruct, returnConstruct ) {
2234                 focusConstruct.focus();
2235                 function onceCollapsed( isExpanded ) {
2236                         if ( ! isExpanded ) {
2237                                 focusConstruct.expanded.unbind( onceCollapsed );
2238                                 returnConstruct.focus();
2239                         }
2240                 }
2241                 focusConstruct.expanded.bind( onceCollapsed );
2242         }
2243
2244         /**
2245          * @param {String} widgetId
2246          * @returns {Object}
2247          */
2248         function parseWidgetId( widgetId ) {
2249                 var matches, parsed = {
2250                         number: null,
2251                         id_base: null
2252                 };
2253
2254                 matches = widgetId.match( /^(.+)-(\d+)$/ );
2255                 if ( matches ) {
2256                         parsed.id_base = matches[1];
2257                         parsed.number = parseInt( matches[2], 10 );
2258                 } else {
2259                         // likely an old single widget
2260                         parsed.id_base = widgetId;
2261                 }
2262
2263                 return parsed;
2264         }
2265
2266         /**
2267          * @param {String} widgetId
2268          * @returns {String} settingId
2269          */
2270         function widgetIdToSettingId( widgetId ) {
2271                 var parsed = parseWidgetId( widgetId ), settingId;
2272
2273                 settingId = 'widget_' + parsed.id_base;
2274                 if ( parsed.number ) {
2275                         settingId += '[' + parsed.number + ']';
2276                 }
2277
2278                 return settingId;
2279         }
2280
2281 })( window.wp, jQuery );