summaryrefslogtreecommitdiffstats
path: root/wp-admin/js/customize-widgets.js
blob: 56459ad7452e106f7fafe0cbf2ad23d25779e04c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
/**
 * @output wp-admin/js/customize-widgets.js
 */

/* global _wpCustomizeWidgetsSettings */
(function( wp, $ ){

	if ( ! wp || ! wp.customize ) { return; }

	// Set up our namespace...
	var api = wp.customize,
		l10n;

	/**
	 * @namespace wp.customize.Widgets
	 */
	api.Widgets = api.Widgets || {};
	api.Widgets.savedWidgetIds = {};

	// Link settings.
	api.Widgets.data = _wpCustomizeWidgetsSettings || {};
	l10n = api.Widgets.data.l10n;

	/**
	 * wp.customize.Widgets.WidgetModel
	 *
	 * A single widget model.
	 *
	 * @class    wp.customize.Widgets.WidgetModel
	 * @augments Backbone.Model
	 */
	api.Widgets.WidgetModel = Backbone.Model.extend(/** @lends wp.customize.Widgets.WidgetModel.prototype */{
		id: null,
		temp_id: null,
		classname: null,
		control_tpl: null,
		description: null,
		is_disabled: null,
		is_multi: null,
		multi_number: null,
		name: null,
		id_base: null,
		transport: null,
		params: [],
		width: null,
		height: null,
		search_matched: true
	});

	/**
	 * wp.customize.Widgets.WidgetCollection
	 *
	 * Collection for widget models.
	 *
	 * @class    wp.customize.Widgets.WidgetCollection
	 * @augments Backbone.Collection
	 */
	api.Widgets.WidgetCollection = Backbone.Collection.extend(/** @lends wp.customize.Widgets.WidgetCollection.prototype */{
		model: api.Widgets.WidgetModel,

		// Controls searching on the current widget collection
		// and triggers an update event.
		doSearch: function( value ) {

			// Don't do anything if we've already done this search.
			// Useful because the search handler fires multiple times per keystroke.
			if ( this.terms === value ) {
				return;
			}

			// Updates terms with the value passed.
			this.terms = value;

			// If we have terms, run a search...
			if ( this.terms.length > 0 ) {
				this.search( this.terms );
			}

			// If search is blank, set all the widgets as they matched the search to reset the views.
			if ( this.terms === '' ) {
				this.each( function ( widget ) {
					widget.set( 'search_matched', true );
				} );
			}
		},

		// Performs a search within the collection.
		// @uses RegExp
		search: function( term ) {
			var match, haystack;

			// Escape the term string for RegExp meta characters.
			term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );

			// Consider spaces as word delimiters and match the whole string
			// so matching terms can be combined.
			term = term.replace( / /g, ')(?=.*' );
			match = new RegExp( '^(?=.*' + term + ').+', 'i' );

			this.each( function ( data ) {
				haystack = [ data.get( 'name' ), data.get( 'description' ) ].join( ' ' );
				data.set( 'search_matched', match.test( haystack ) );
			} );
		}
	});
	api.Widgets.availableWidgets = new api.Widgets.WidgetCollection( api.Widgets.data.availableWidgets );

	/**
	 * wp.customize.Widgets.SidebarModel
	 *
	 * A single sidebar model.
	 *
	 * @class    wp.customize.Widgets.SidebarModel
	 * @augments Backbone.Model
	 */
	api.Widgets.SidebarModel = Backbone.Model.extend(/** @lends wp.customize.Widgets.SidebarModel.prototype */{
		after_title: null,
		after_widget: null,
		before_title: null,
		before_widget: null,
		'class': null,
		description: null,
		id: null,
		name: null,
		is_rendered: false
	});

	/**
	 * wp.customize.Widgets.SidebarCollection
	 *
	 * Collection for sidebar models.
	 *
	 * @class    wp.customize.Widgets.SidebarCollection
	 * @augments Backbone.Collection
	 */
	api.Widgets.SidebarCollection = Backbone.Collection.extend(/** @lends wp.customize.Widgets.SidebarCollection.prototype */{
		model: api.Widgets.SidebarModel
	});
	api.Widgets.registeredSidebars = new api.Widgets.SidebarCollection( api.Widgets.data.registeredSidebars );

	api.Widgets.AvailableWidgetsPanelView = wp.Backbone.View.extend(/** @lends wp.customize.Widgets.AvailableWidgetsPanelView.prototype */{

		el: '#available-widgets',

		events: {
			'input #widgets-search': 'search',
			'focus .widget-tpl' : 'focus',
			'click .widget-tpl' : '_submit',
			'keypress .widget-tpl' : '_submit',
			'keydown' : 'keyboardAccessible'
		},

		// Cache current selected widget.
		selected: null,

		// Cache sidebar control which has opened panel.
		currentSidebarControl: null,
		$search: null,
		$clearResults: null,
		searchMatchesCount: null,

		/**
		 * View class for the available widgets panel.
		 *
		 * @constructs wp.customize.Widgets.AvailableWidgetsPanelView
		 * @augments   wp.Backbone.View
		 */
		initialize: function() {
			var self = this;

			this.$search = $( '#widgets-search' );

			this.$clearResults = this.$el.find( '.clear-results' );

			_.bindAll( this, 'close' );

			this.listenTo( this.collection, 'change', this.updateList );

			this.updateList();

			// Set the initial search count to the number of available widgets.
			this.searchMatchesCount = this.collection.length;

			/*
			 * If the available widgets panel is open and the customize controls
			 * are interacted with (i.e. available widgets panel is blurred) then
			 * close the available widgets panel. Also close on back button click.
			 */
			$( '#customize-controls, #available-widgets .customize-section-title' ).on( 'click keydown', function( e ) {
				var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' );
				if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) {
					self.close();
				}
			} );

			// Clear the search results and trigger an `input` event to fire a new search.
			this.$clearResults.on( 'click', function() {
				self.$search.val( '' ).trigger( 'focus' ).trigger( 'input' );
			} );

			// Close the panel if the URL in the preview changes.
			api.previewer.bind( 'url', this.close );
		},

		/**
		 * Performs a search and handles selected widget.
		 */
		search: _.debounce( function( event ) {
			var firstVisible;

			this.collection.doSearch( event.target.value );
			// Update the search matches count.
			this.updateSearchMatchesCount();
			// Announce how many search results.
			this.announceSearchMatches();

			// Remove a widget from being selected if it is no longer visible.
			if ( this.selected && ! this.selected.is( ':visible' ) ) {
				this.selected.removeClass( 'selected' );
				this.selected = null;
			}

			// If a widget was selected but the filter value has been cleared out, clear selection.
			if ( this.selected && ! event.target.value ) {
				this.selected.removeClass( 'selected' );
				this.selected = null;
			}

			// If a filter has been entered and a widget hasn't been selected, select the first one shown.
			if ( ! this.selected && event.target.value ) {
				firstVisible = this.$el.find( '> .widget-tpl:visible:first' );
				if ( firstVisible.length ) {
					this.select( firstVisible );
				}
			}

			// Toggle the clear search results button.
			if ( '' !== event.target.value ) {
				this.$clearResults.addClass( 'is-visible' );
			} else if ( '' === event.target.value ) {
				this.$clearResults.removeClass( 'is-visible' );
			}

			// Set a CSS class on the search container when there are no search results.
			if ( ! this.searchMatchesCount ) {
				this.$el.addClass( 'no-widgets-found' );
			} else {
				this.$el.removeClass( 'no-widgets-found' );
			}
		}, 500 ),

		/**
		 * Updates the count of the available widgets that have the `search_matched` attribute.
 		 */
		updateSearchMatchesCount: function() {
			this.searchMatchesCount = this.collection.where({ search_matched: true }).length;
		},

		/**
		 * Sends a message to the aria-live region to announce how many search results.
		 */
		announceSearchMatches: function() {
			var message = l10n.widgetsFound.replace( '%d', this.searchMatchesCount ) ;

			if ( ! this.searchMatchesCount ) {
				message = l10n.noWidgetsFound;
			}

			wp.a11y.speak( message );
		},

		/**
		 * Changes visibility of available widgets.
 		 */
		updateList: function() {
			this.collection.each( function( widget ) {
				var widgetTpl = $( '#widget-tpl-' + widget.id );
				widgetTpl.toggle( widget.get( 'search_matched' ) && ! widget.get( 'is_disabled' ) );
				if ( widget.get( 'is_disabled' ) && widgetTpl.is( this.selected ) ) {
					this.selected = null;
				}
			} );
		},

		/**
		 * Highlights a widget.
 		 */
		select: function( widgetTpl ) {
			this.selected = $( widgetTpl );
			this.selected.siblings( '.widget-tpl' ).removeClass( 'selected' );
			this.selected.addClass( 'selected' );
		},

		/**
		 * Highlights a widget on focus.
		 */
		focus: function( event ) {
			this.select( $( event.currentTarget ) );
		},

		/**
		 * Handles submit for keypress and click on widget.
		 */
		_submit: function( event ) {
			// Only proceed with keypress if it is Enter or Spacebar.
			if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
				return;
			}

			this.submit( $( event.currentTarget ) );
		},

		/**
		 * Adds a selected widget to the sidebar.
 		 */
		submit: function( widgetTpl ) {
			var widgetId, widget, widgetFormControl;

			if ( ! widgetTpl ) {
				widgetTpl = this.selected;
			}

			if ( ! widgetTpl || ! this.currentSidebarControl ) {
				return;
			}

			this.select( widgetTpl );

			widgetId = $( this.selected ).data( 'widget-id' );
			widget = this.collection.findWhere( { id: widgetId } );
			if ( ! widget ) {
				return;
			}

			widgetFormControl = this.currentSidebarControl.addWidget( widget.get( 'id_base' ) );
			if ( widgetFormControl ) {
				widgetFormControl.focus();
			}

			this.close();
		},

		/**
		 * Opens the panel.
		 */
		open: function( sidebarControl ) {
			this.currentSidebarControl = sidebarControl;

			// Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens.
			_( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) {
				if ( control.params.is_wide ) {
					control.collapseForm();
				}
			} );

			if ( api.section.has( 'publish_settings' ) ) {
				api.section( 'publish_settings' ).collapse();
			}

			$( 'body' ).addClass( 'adding-widget' );

			this.$el.find( '.selected' ).removeClass( 'selected' );

			// Reset search.
			this.collection.doSearch( '' );

			if ( ! api.settings.browser.mobile ) {
				this.$search.trigger( 'focus' );
			}
		},

		/**
		 * Closes the panel.
		 */
		close: function( options ) {
			options = options || {};

			if ( options.returnFocus && this.currentSidebarControl ) {
				this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
			}

			this.currentSidebarControl = null;
			this.selected = null;

			$( 'body' ).removeClass( 'adding-widget' );

			this.$search.val( '' ).trigger( 'input' );
		},

		/**
		 * Adds keyboard accessibility to the panel.
		 */
		keyboardAccessible: function( event ) {
			var isEnter = ( event.which === 13 ),
				isEsc = ( event.which === 27 ),
				isDown = ( event.which === 40 ),
				isUp = ( event.which === 38 ),
				isTab = ( event.which === 9 ),
				isShift = ( event.shiftKey ),
				selected = null,
				firstVisible = this.$el.find( '> .widget-tpl:visible:first' ),
				lastVisible = this.$el.find( '> .widget-tpl:visible:last' ),
				isSearchFocused = $( event.target ).is( this.$search ),
				isLastWidgetFocused = $( event.target ).is( '.widget-tpl:visible:last' );

			if ( isDown || isUp ) {
				if ( isDown ) {
					if ( isSearchFocused ) {
						selected = firstVisible;
					} else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) {
						selected = this.selected.nextAll( '.widget-tpl:visible:first' );
					}
				} else if ( isUp ) {
					if ( isSearchFocused ) {
						selected = lastVisible;
					} else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) {
						selected = this.selected.prevAll( '.widget-tpl:visible:first' );
					}
				}

				this.select( selected );

				if ( selected ) {
					selected.trigger( 'focus' );
				} else {
					this.$search.trigger( 'focus' );
				}

				return;
			}

			// If enter pressed but nothing entered, don't do anything.
			if ( isEnter && ! this.$search.val() ) {
				return;
			}

			if ( isEnter ) {
				this.submit();
			} else if ( isEsc ) {
				this.close( { returnFocus: true } );
			}

			if ( this.currentSidebarControl && isTab && ( isShift && isSearchFocused || ! isShift && isLastWidgetFocused ) ) {
				this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
				event.preventDefault();
			}
		}
	});

	/**
	 * Handlers for the widget-synced event, organized by widget ID base.
	 * Other widgets may provide their own update handlers by adding
	 * listeners for the widget-synced event.
	 *
	 * @alias    wp.customize.Widgets.formSyncHandlers
	 */
	api.Widgets.formSyncHandlers = {

		/**
		 * @param {jQuery.Event} e
		 * @param {jQuery} widget
		 * @param {string} newForm
		 */
		rss: function( e, widget, newForm ) {
			var oldWidgetError = widget.find( '.widget-error:first' ),
				newWidgetError = $( '<div>' + newForm + '</div>' ).find( '.widget-error:first' );

			if ( oldWidgetError.length && newWidgetError.length ) {
				oldWidgetError.replaceWith( newWidgetError );
			} else if ( oldWidgetError.length ) {
				oldWidgetError.remove();
			} else if ( newWidgetError.length ) {
				widget.find( '.widget-content:first' ).prepend( newWidgetError );
			}
		}
	};

	api.Widgets.WidgetControl = api.Control.extend(/** @lends wp.customize.Widgets.WidgetControl.prototype */{
		defaultExpandedArguments: {
			duration: 'fast',
			completeCallback: $.noop
		},

		/**
		 * wp.customize.Widgets.WidgetControl
		 *
		 * Customizer control for widgets.
		 * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type
		 *
		 * @since 4.1.0
		 *
		 * @constructs wp.customize.Widgets.WidgetControl
		 * @augments   wp.customize.Control
		 */
		initialize: function( id, options ) {
			var control = this;

			control.widgetControlEmbedded = false;
			control.widgetContentEmbedded = false;
			control.expanded = new api.Value( false );
			control.expandedArgumentsQueue = [];
			control.expanded.bind( function( expanded ) {
				var args = control.expandedArgumentsQueue.shift();
				args = $.extend( {}, control.defaultExpandedArguments, args );
				control.onChangeExpanded( expanded, args );
			});
			control.altNotice = true;

			api.Control.prototype.initialize.call( control, id, options );
		},

		/**
		 * Set up the control.
		 *
		 * @since 3.9.0
		 */
		ready: function() {
			var control = this;

			/*
			 * Embed a placeholder once the section is expanded. The full widget
			 * form content will be embedded once the control itself is expanded,
			 * and at this point the widget-added event will be triggered.
			 */
			if ( ! control.section() ) {
				control.embedWidgetControl();
			} else {
				api.section( control.section(), function( section ) {
					var onExpanded = function( isExpanded ) {
						if ( isExpanded ) {
							control.embedWidgetControl();
							section.expanded.unbind( onExpanded );
						}
					};
					if ( section.expanded() ) {
						onExpanded( true );
					} else {
						section.expanded.bind( onExpanded );
					}
				} );
			}
		},

		/**
		 * Embed the .widget element inside the li container.
		 *
		 * @since 4.4.0
		 */
		embedWidgetControl: function() {
			var control = this, widgetControl;

			if ( control.widgetControlEmbedded ) {
				return;
			}
			control.widgetControlEmbedded = true;

			widgetControl = $( control.params.widget_control );
			control.container.append( widgetControl );

			control._setupModel();
			control._setupWideWidget();
			control._setupControlToggle();

			control._setupWidgetTitle();
			control._setupReorderUI();
			control._setupHighlightEffects();
			control._setupUpdateUI();
			control._setupRemoveUI();
		},

		/**
		 * Embed the actual widget form inside of .widget-content and finally trigger the widget-added event.
		 *
		 * @since 4.4.0
		 */
		embedWidgetContent: function() {
			var control = this, widgetContent;

			control.embedWidgetControl();
			if ( control.widgetContentEmbedded ) {
				return;
			}
			control.widgetContentEmbedded = true;

			// Update the notification container element now that the widget content has been embedded.
			control.notifications.container = control.getNotificationsContainerElement();
			control.notifications.render();

			widgetContent = $( control.params.widget_content );
			control.container.find( '.widget-content:first' ).append( widgetContent );

			/*
			 * Trigger widget-added event so that plugins can attach any event
			 * listeners and dynamic UI elements.
			 */
			$( document ).trigger( 'widget-added', [ control.container.find( '.widget:first' ) ] );

		},

		/**
		 * Handle changes to the setting
		 */
		_setupModel: function() {
			var self = this, rememberSavedWidgetId;

			// Remember saved widgets so we know which to trash (move to inactive widgets sidebar).
			rememberSavedWidgetId = function() {
				api.Widgets.savedWidgetIds[self.params.widget_id] = true;
			};
			api.bind( 'ready', rememberSavedWidgetId );
			api.bind( 'saved', rememberSavedWidgetId );

			this._updateCount = 0;
			this.isWidgetUpdating = false;
			this.liveUpdateMode = true;

			// Update widget whenever model changes.
			this.setting.bind( function( to, from ) {
				if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) {
					self.updateWidget( { instance: to } );
				}
			} );
		},

		/**
		 * Add special behaviors for wide widget controls
		 */
		_setupWideWidget: function() {
			var self = this, $widgetInside, $widgetForm, $customizeSidebar,
				$themeControlsContainer, positionWidget;

			if ( ! this.params.is_wide || $( window ).width() <= 640 /* max-width breakpoint in customize-controls.css */ ) {
				return;
			}

			$widgetInside = this.container.find( '.widget-inside' );
			$widgetForm = $widgetInside.find( '> .form' );
			$customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' );
			this.container.addClass( 'wide-widget-control' );

			this.container.find( '.form:first' ).css( {
				'max-width': this.params.width,
				'min-height': this.params.height
			} );

			/**
			 * Keep the widget-inside positioned so the top of fixed-positioned
			 * element is at the same top position as the widget-top. When the
			 * widget-top is scrolled out of view, keep the widget-top in view;
			 * likewise, don't allow the widget to drop off the bottom of the window.
			 * If a widget is too tall to fit in the window, don't let the height
			 * exceed the window height so that the contents of the widget control
			 * will become scrollable (overflow:auto).
			 */
			positionWidget = function() {
				var offsetTop = self.container.offset().top,
					windowHeight = $( window ).height(),
					formHeight = $widgetForm.outerHeight(),
					top;
				$widgetInside.css( 'max-height', windowHeight );
				top = Math.max(
					0, // Prevent top from going off screen.
					Math.min(
						Math.max( offsetTop, 0 ), // Distance widget in panel is from top of screen.
						windowHeight - formHeight // Flush up against bottom of screen.
					)
				);
				$widgetInside.css( 'top', top );
			};

			$themeControlsContainer = $( '#customize-theme-controls' );
			this.container.on( 'expand', function() {
				positionWidget();
				$customizeSidebar.on( 'scroll', positionWidget );
				$( window ).on( 'resize', positionWidget );
				$themeControlsContainer.on( 'expanded collapsed', positionWidget );
			} );
			this.container.on( 'collapsed', function() {
				$customizeSidebar.off( 'scroll', positionWidget );
				$( window ).off( 'resize', positionWidget );
				$themeControlsContainer.off( 'expanded collapsed', positionWidget );
			} );

			// Reposition whenever a sidebar's widgets are changed.
			api.each( function( setting ) {
				if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) {
					setting.bind( function() {
						if ( self.container.hasClass( 'expanded' ) ) {
							positionWidget();
						}
					} );
				}
			} );
		},

		/**
		 * Show/hide the control when clicking on the form title, when clicking
		 * the close button
		 */
		_setupControlToggle: function() {
			var self = this, $closeBtn;

			this.container.find( '.widget-top' ).on( 'click', function( e ) {
				e.preventDefault();
				var sidebarWidgetsControl = self.getSidebarWidgetsControl();
				if ( sidebarWidgetsControl.isReordering ) {
					return;
				}
				self.expanded( ! self.expanded() );
			} );

			$closeBtn = this.container.find( '.widget-control-close' );
			$closeBtn.on( 'click', function() {
				self.collapse();
				self.container.find( '.widget-top .widget-action:first' ).focus(); // Keyboard accessibility.
			} );
		},

		/**
		 * Update the title of the form if a title field is entered
		 */
		_setupWidgetTitle: function() {
			var self = this, updateTitle;

			updateTitle = function() {
				var title = self.setting().title,
					inWidgetTitle = self.container.find( '.in-widget-title' );

				if ( title ) {
					inWidgetTitle.text( ': ' + title );
				} else {
					inWidgetTitle.text( '' );
				}
			};
			this.setting.bind( updateTitle );
			updateTitle();
		},

		/**
		 * Set up the widget-reorder-nav
		 */
		_setupReorderUI: function() {
			var self = this, selectSidebarItem, $moveWidgetArea,
				$reorderNav, updateAvailableSidebars, template;

			/**
			 * select the provided sidebar list item in the move widget area
			 *
			 * @param {jQuery} li
			 */
			selectSidebarItem = function( li ) {
				li.siblings( '.selected' ).removeClass( 'selected' );
				li.addClass( 'selected' );
				var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id );
				self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar );
			};

			/**
			 * Add the widget reordering elements to the widget control
			 */
			this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) );


			template = _.template( api.Widgets.data.tpl.moveWidgetArea );
			$moveWidgetArea = $( template( {
					sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' )
				} )
			);
			this.container.find( '.widget-top' ).after( $moveWidgetArea );

			/**
			 * Update available sidebars when their rendered state changes
			 */
			updateAvailableSidebars = function() {
				var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem,
					renderedSidebarCount = 0;

				selfSidebarItem = $sidebarItems.filter( function(){
					return $( this ).data( 'id' ) === self.params.sidebar_id;
				} );

				$sidebarItems.each( function() {
					var li = $( this ),
						sidebarId, sidebar, sidebarIsRendered;

					sidebarId = li.data( 'id' );
					sidebar = api.Widgets.registeredSidebars.get( sidebarId );
					sidebarIsRendered = sidebar.get( 'is_rendered' );

					li.toggle( sidebarIsRendered );

					if ( sidebarIsRendered ) {
						renderedSidebarCount += 1;
					}

					if ( li.hasClass( 'selected' ) && ! sidebarIsRendered ) {
						selectSidebarItem( selfSidebarItem );
					}
				} );

				if ( renderedSidebarCount > 1 ) {
					self.container.find( '.move-widget' ).show();
				} else {
					self.container.find( '.move-widget' ).hide();
				}
			};

			updateAvailableSidebars();
			api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars );

			/**
			 * Handle clicks for up/down/move on the reorder nav
			 */
			$reorderNav = this.container.find( '.widget-reorder-nav' );
			$reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() {
				$( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' );
			} ).on( 'click keypress', function( event ) {
				if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
					return;
				}
				$( this ).trigger( 'focus' );

				if ( $( this ).is( '.move-widget' ) ) {
					self.toggleWidgetMoveArea();
				} else {
					var isMoveDown = $( this ).is( '.move-widget-down' ),
						isMoveUp = $( this ).is( '.move-widget-up' ),
						i = self.getWidgetSidebarPosition();

					if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) {
						return;
					}

					if ( isMoveUp ) {
						self.moveUp();
						wp.a11y.speak( l10n.widgetMovedUp );
					} else {
						self.moveDown();
						wp.a11y.speak( l10n.widgetMovedDown );
					}

					$( this ).trigger( 'focus' ); // Re-focus after the container was moved.
				}
			} );

			/**
			 * Handle selecting a sidebar to move to
			 */
			this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( event ) {
				if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
					return;
				}
				event.preventDefault();
				selectSidebarItem( $( this ) );
			} );

			/**
			 * Move widget to another sidebar
			 */
			this.container.find( '.move-widget-btn' ).click( function() {
				self.getSidebarWidgetsControl().toggleReordering( false );

				var oldSidebarId = self.params.sidebar_id,
					newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ),
					oldSidebarWidgetsSetting, newSidebarWidgetsSetting,
					oldSidebarWidgetIds, newSidebarWidgetIds, i;

				oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' );
				newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' );
				oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() );
				newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() );

				i = self.getWidgetSidebarPosition();
				oldSidebarWidgetIds.splice( i, 1 );
				newSidebarWidgetIds.push( self.params.widget_id );

				oldSidebarWidgetsSetting( oldSidebarWidgetIds );
				newSidebarWidgetsSetting( newSidebarWidgetIds );

				self.focus();
			} );
		},

		/**
		 * Highlight widgets in preview when interacted with in the Customizer
		 */
		_setupHighlightEffects: function() {
			var self = this;

			// Highlight whenever hovering or clicking over the form.
			this.container.on( 'mouseenter click', function() {
				self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
			} );

			// Highlight when the setting is updated.
			this.setting.bind( function() {
				self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
			} );
		},

		/**
		 * Set up event handlers for widget updating
		 */
		_setupUpdateUI: function() {
			var self = this, $widgetRoot, $widgetContent,
				$saveBtn, updateWidgetDebounced, formSyncHandler;

			$widgetRoot = this.container.find( '.widget:first' );
			$widgetContent = $widgetRoot.find( '.widget-content:first' );

			// Configure update button.
			$saveBtn = this.container.find( '.widget-control-save' );
			$saveBtn.val( l10n.saveBtnLabel );
			$saveBtn.attr( 'title', l10n.saveBtnTooltip );
			$saveBtn.removeClass( 'button-primary' );
			$saveBtn.on( 'click', function( e ) {
				e.preventDefault();
				self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
			} );

			updateWidgetDebounced = _.debounce( function() {
				self.updateWidget();
			}, 250 );

			// Trigger widget form update when hitting Enter within an input.
			$widgetContent.on( 'keydown', 'input', function( e ) {
				if ( 13 === e.which ) { // Enter.
					e.preventDefault();
					self.updateWidget( { ignoreActiveElement: true } );
				}
			} );

			// Handle widgets that support live previews.
			$widgetContent.on( 'change input propertychange', ':input', function( e ) {
				if ( ! self.liveUpdateMode ) {
					return;
				}
				if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) {
					updateWidgetDebounced();
				}
			} );

			// Remove loading indicators when the setting is saved and the preview updates.
			this.setting.previewer.channel.bind( 'synced', function() {
				self.container.removeClass( 'previewer-loading' );
			} );

			api.previewer.bind( 'widget-updated', function( updatedWidgetId ) {
				if ( updatedWidgetId === self.params.widget_id ) {
					self.container.removeClass( 'previewer-loading' );
				}
			} );

			formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
			if ( formSyncHandler ) {
				$( document ).on( 'widget-synced', function( e, widget ) {
					if ( $widgetRoot.is( widget ) ) {
						formSyncHandler.apply( document, arguments );
					}
				} );
			}
		},

		/**
		 * Update widget control to indicate whether it is currently rendered.
		 *
		 * Overrides api.Control.toggle()
		 *
		 * @since 4.1.0
		 *
		 * @param {boolean}   active
		 * @param {Object}    args
		 * @param {function}  args.completeCallback
		 */
		onChangeActive: function ( active, args ) {
			// Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments.
			this.container.toggleClass( 'widget-rendered', active );
			if ( args.completeCallback ) {
				args.completeCallback();
			}
		},

		/**
		 * Set up event handlers for widget removal
		 */
		_setupRemoveUI: function() {
			var self = this, $removeBtn, replaceDeleteWithRemove;

			// Configure remove button.
			$removeBtn = this.container.find( '.widget-control-remove' );
			$removeBtn.on( 'click', function() {
				// Find an adjacent element to add focus to when this widget goes away.
				var $adjacentFocusTarget;
				if ( self.container.next().is( '.customize-control-widget_form' ) ) {
					$adjacentFocusTarget = self.container.next().find( '.widget-action:first' );
				} else if ( self.container.prev().is( '.customize-control-widget_form' ) ) {
					$adjacentFocusTarget = self.container.prev().find( '.widget-action:first' );
				} else {
					$adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' );
				}

				self.container.slideUp( function() {
					var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
						sidebarWidgetIds, i;

					if ( ! sidebarsWidgetsControl ) {
						return;
					}

					sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
					i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
					if ( -1 === i ) {
						return;
					}

					sidebarWidgetIds.splice( i, 1 );
					sidebarsWidgetsControl.setting( sidebarWidgetIds );

					$adjacentFocusTarget.focus(); // Keyboard accessibility.
				} );
			} );

			replaceDeleteWithRemove = function() {
				$removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the button as "Delete".
				$removeBtn.attr( 'title', l10n.removeBtnTooltip );
			};

			if ( this.params.is_new ) {
				api.bind( 'saved', replaceDeleteWithRemove );
			} else {
				replaceDeleteWithRemove();
			}
		},

		/**
		 * Find all inputs in a widget container that should be considered when
		 * comparing the loaded form with the sanitized form, whose fields will
		 * be aligned to copy the sanitized over. The elements returned by this
		 * are passed into this._getInputsSignature(), and they are iterated
		 * over when copying sanitized values over to the form loaded.
		 *
		 * @param {jQuery} container element in which to look for inputs
		 * @return {jQuery} inputs
		 * @private
		 */
		_getInputs: function( container ) {
			return $( container ).find( ':input[name]' );
		},

		/**
		 * Iterate over supplied inputs and create a signature string for all of them together.
		 * This string can be used to compare whether or not the form has all of the same fields.
		 *
		 * @param {jQuery} inputs
		 * @return {string}
		 * @private
		 */
		_getInputsSignature: function( inputs ) {
			var inputsSignatures = _( inputs ).map( function( input ) {
				var $input = $( input ), signatureParts;

				if ( $input.is( ':checkbox, :radio' ) ) {
					signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ];
				} else {
					signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ];
				}

				return signatureParts.join( ',' );
			} );

			return inputsSignatures.join( ';' );
		},

		/**
		 * Get the state for an input depending on its type.
		 *
		 * @param {jQuery|Element} input
		 * @return {string|boolean|Array|*}
		 * @private
		 */
		_getInputState: function( input ) {
			input = $( input );
			if ( input.is( ':radio, :checkbox' ) ) {
				return input.prop( 'checked' );
			} else if ( input.is( 'select[multiple]' ) ) {
				return input.find( 'option:selected' ).map( function () {
					return $( this ).val();
				} ).get();
			} else {
				return input.val();
			}
		},

		/**
		 * Update an input's state based on its type.
		 *
		 * @param {jQuery|Element} input
		 * @param {string|boolean|Array|*} state
		 * @private
		 */
		_setInputState: function ( input, state ) {
			input = $( input );
			if ( input.is( ':radio, :checkbox' ) ) {
				input.prop( 'checked', state );
			} else if ( input.is( 'select[multiple]' ) ) {
				if ( ! Array.isArray( state ) ) {
					state = [];
				} else {
					// Make sure all state items are strings since the DOM value is a string.
					state = _.map( state, function ( value ) {
						return String( value );
					} );
				}
				input.find( 'option' ).each( function () {
					$( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) );
				} );
			} else {
				input.val( state );
			}
		},

		/***********************************************************************
		 * Begin public API methods
		 **********************************************************************/

		/**
		 * @return {wp.customize.controlConstructor.sidebar_widgets[]}
		 */
		getSidebarWidgetsControl: function() {
			var settingId, sidebarWidgetsControl;

			settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']';
			sidebarWidgetsControl = api.control( settingId );

			if ( ! sidebarWidgetsControl ) {
				return;
			}

			return sidebarWidgetsControl;
		},

		/**
		 * Submit the widget form via Ajax and get back the updated instance,
		 * along with the new widget control form to render.
		 *
		 * @param {Object} [args]
		 * @param {Object|null} [args.instance=null]  When the model changes, the instance is sent here; otherwise, the inputs from the form are used
		 * @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.
		 * @param {boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
		 */
		updateWidget: function( args ) {
			var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
				updateNumber, params, data, $inputs, processing, jqxhr, isChanged;

			// The updateWidget logic requires that the form fields to be fully present.
			self.embedWidgetContent();

			args = $.extend( {
				instance: null,
				complete: null,
				ignoreActiveElement: false
			}, args );

			instanceOverride = args.instance;
			completeCallback = args.complete;

			this._updateCount += 1;
			updateNumber = this._updateCount;

			$widgetRoot = this.container.find( '.widget:first' );
			$widgetContent = $widgetRoot.find( '.widget-content:first' );

			// Remove a previous error message.
			$widgetContent.find( '.widget-error' ).remove();

			this.container.addClass( 'widget-form-loading' );
			this.container.addClass( 'previewer-loading' );
			processing = api.state( 'processing' );
			processing( processing() + 1 );

			if ( ! this.liveUpdateMode ) {
				this.container.addClass( 'widget-form-disabled' );
			}

			params = {};
			params.action = 'update-widget';
			params.wp_customize = 'on';
			params.nonce = api.settings.nonce['update-widget'];
			params.customize_theme = api.settings.theme.stylesheet;
			params.customized = wp.customize.previewer.query().customized;

			data = $.param( params );
			$inputs = this._getInputs( $widgetContent );

			/*
			 * Store the value we're submitting in data so that when the response comes back,
			 * we know if it got sanitized; if there is no difference in the sanitized value,
			 * then we do not need to touch the UI and mess up the user's ongoing editing.
			 */
			$inputs.each( function() {
				$( this ).data( 'state' + updateNumber, self._getInputState( this ) );
			} );

			if ( instanceOverride ) {
				data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } );
			} else {
				data += '&' + $inputs.serialize();
			}
			data += '&' + $widgetContent.find( '~ :input' ).serialize();

			if ( this._previousUpdateRequest ) {
				this._previousUpdateRequest.abort();
			}
			jqxhr = $.post( wp.ajax.settings.url, data );
			this._previousUpdateRequest = jqxhr;

			jqxhr.done( function( r ) {
				var message, sanitizedForm,	$sanitizedInputs, hasSameInputsInResponse,
					isLiveUpdateAborted = false;

				// Check if the user is logged out.
				if ( '0' === r ) {
					api.previewer.preview.iframe.hide();
					api.previewer.login().done( function() {
						self.updateWidget( args );
						api.previewer.preview.iframe.show();
					} );
					return;
				}

				// Check for cheaters.
				if ( '-1' === r ) {
					api.previewer.cheatin();
					return;
				}

				if ( r.success ) {
					sanitizedForm = $( '<div>' + r.data.form + '</div>' );
					$sanitizedInputs = self._getInputs( sanitizedForm );
					hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs );

					// Restore live update mode if sanitized fields are now aligned with the existing fields.
					if ( hasSameInputsInResponse && ! self.liveUpdateMode ) {
						self.liveUpdateMode = true;
						self.container.removeClass( 'widget-form-disabled' );
						self.container.find( 'input[name="savewidget"]' ).hide();
					}

					// Sync sanitized field states to existing fields if they are aligned.
					if ( hasSameInputsInResponse && self.liveUpdateMode ) {
						$inputs.each( function( i ) {
							var $input = $( this ),
								$sanitizedInput = $( $sanitizedInputs[i] ),
								submittedState, sanitizedState,	canUpdateState;

							submittedState = $input.data( 'state' + updateNumber );
							sanitizedState = self._getInputState( $sanitizedInput );
							$input.data( 'sanitized', sanitizedState );

							canUpdateState = ( ! _.isEqual( submittedState, sanitizedState ) && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
							if ( canUpdateState ) {
								self._setInputState( $input, sanitizedState );
							}
						} );

						$( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] );

					// Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled.
					} else if ( self.liveUpdateMode ) {
						self.liveUpdateMode = false;
						self.container.find( 'input[name="savewidget"]' ).show();
						isLiveUpdateAborted = true;

					// Otherwise, replace existing form with the sanitized form.
					} else {
						$widgetContent.html( r.data.form );

						self.container.removeClass( 'widget-form-disabled' );

						$( document ).trigger( 'widget-updated', [ $widgetRoot ] );
					}

					/**
					 * If the old instance is identical to the new one, there is nothing new
					 * needing to be rendered, and so we can preempt the event for the
					 * preview finishing loading.
					 */
					isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance );
					if ( isChanged ) {
						self.isWidgetUpdating = true; // Suppress triggering another updateWidget.
						self.setting( r.data.instance );
						self.isWidgetUpdating = false;
					} else {
						// No change was made, so stop the spinner now instead of when the preview would updates.
						self.container.removeClass( 'previewer-loading' );
					}

					if ( completeCallback ) {
						completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
					}
				} else {
					// General error message.
					message = l10n.error;

					if ( r.data && r.data.message ) {
						message = r.data.message;
					}

					if ( completeCallback ) {
						completeCallback.call( self, message );
					} else {
						$widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' );
					}
				}
			} );

			jqxhr.fail( function( jqXHR, textStatus ) {
				if ( completeCallback ) {
					completeCallback.call( self, textStatus );
				}
			} );

			jqxhr.always( function() {
				self.container.removeClass( 'widget-form-loading' );

				$inputs.each( function() {
					$( this ).removeData( 'state' + updateNumber );
				} );

				processing( processing() - 1 );
			} );
		},

		/**
		 * Expand the accordion section containing a control
		 */
		expandControlSection: function() {
			api.Control.prototype.expand.call( this );
		},

		/**
		 * @since 4.1.0
		 *
		 * @param {Boolean} expanded
		 * @param {Object} [params]
		 * @return {Boolean} False if state already applied.
		 */
		_toggleExpanded: api.Section.prototype._toggleExpanded,

		/**
		 * @since 4.1.0
		 *
		 * @param {Object} [params]
		 * @return {Boolean} False if already expanded.
		 */
		expand: api.Section.prototype.expand,

		/**
		 * Expand the widget form control
		 *
		 * @deprecated 4.1.0 Use this.expand() instead.
		 */
		expandForm: function() {
			this.expand();
		},

		/**
		 * @since 4.1.0
		 *
		 * @param {Object} [params]
		 * @return {Boolean} False if already collapsed.
		 */
		collapse: api.Section.prototype.collapse,

		/**
		 * Collapse the widget form control
		 *
		 * @deprecated 4.1.0 Use this.collapse() instead.
		 */
		collapseForm: function() {
			this.collapse();
		},

		/**
		 * Expand or collapse the widget control
		 *
		 * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
		 *
		 * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility
		 */
		toggleForm: function( showOrHide ) {
			if ( typeof showOrHide === 'undefined' ) {
				showOrHide = ! this.expanded();
			}
			this.expanded( showOrHide );
		},

		/**
		 * Respond to change in the expanded state.
		 *
		 * @param {boolean} expanded
		 * @param {Object} args  merged on top of this.defaultActiveArguments
		 */
		onChangeExpanded: function ( expanded, args ) {
			var self = this, $widget, $inside, complete, prevComplete, expandControl, $toggleBtn;

			self.embedWidgetControl(); // Make sure the outer form is embedded so that the expanded state can be set in the UI.
			if ( expanded ) {
				self.embedWidgetContent();
			}

			// If the expanded state is unchanged only manipulate container expanded states.
			if ( args.unchanged ) {
				if ( expanded ) {
					api.Control.prototype.expand.call( self, {
						completeCallback:  args.completeCallback
					});
				}
				return;
			}

			$widget = this.container.find( 'div.widget:first' );
			$inside = $widget.find( '.widget-inside:first' );
			$toggleBtn = this.container.find( '.widget-top button.widget-action' );

			expandControl = function() {

				// Close all other widget controls before expanding this one.
				api.control.each( function( otherControl ) {
					if ( self.params.type === otherControl.params.type && self !== otherControl ) {
						otherControl.collapse();
					}
				} );

				complete = function() {
					self.container.removeClass( 'expanding' );
					self.container.addClass( 'expanded' );
					$widget.addClass( 'open' );
					$toggleBtn.attr( 'aria-expanded', 'true' );
					self.container.trigger( 'expanded' );
				};
				if ( args.completeCallback ) {
					prevComplete = complete;
					complete = function () {
						prevComplete();
						args.completeCallback();
					};
				}

				if ( self.params.is_wide ) {
					$inside.fadeIn( args.duration, complete );
				} else {
					$inside.slideDown( args.duration, complete );
				}

				self.container.trigger( 'expand' );
				self.container.addClass( 'expanding' );
			};

			if ( $toggleBtn.attr( 'aria-expanded' ) === 'false' ) {
				if ( api.section.has( self.section() ) ) {
					api.section( self.section() ).expand( {
						completeCallback: expandControl
					} );
				} else {
					expandControl();
				}
			} else {
				complete = function() {
					self.container.removeClass( 'collapsing' );
					self.container.removeClass( 'expanded' );
					$widget.removeClass( 'open' );
					$toggleBtn.attr( 'aria-expanded', 'false' );
					self.container.trigger( 'collapsed' );
				};
				if ( args.completeCallback ) {
					prevComplete = complete;
					complete = function () {
						prevComplete();
						args.completeCallback();
					};
				}

				self.container.trigger( 'collapse' );
				self.container.addClass( 'collapsing' );

				if ( self.params.is_wide ) {
					$inside.fadeOut( args.duration, complete );
				} else {
					$inside.slideUp( args.duration, function() {
						$widget.css( { width:'', margin:'' } );
						complete();
					} );
				}
			}
		},

		/**
		 * Get the position (index) of the widget in the containing sidebar
		 *
		 * @return {number}
		 */
		getWidgetSidebarPosition: function() {
			var sidebarWidgetIds, position;

			sidebarWidgetIds = this.getSidebarWidgetsControl().setting();
			position = _.indexOf( sidebarWidgetIds, this.params.widget_id );

			if ( position === -1 ) {
				return;
			}

			return position;
		},

		/**
		 * Move widget up one in the sidebar
		 */
		moveUp: function() {
			this._moveWidgetByOne( -1 );
		},

		/**
		 * Move widget up one in the sidebar
		 */
		moveDown: function() {
			this._moveWidgetByOne( 1 );
		},

		/**
		 * @private
		 *
		 * @param {number} offset 1|-1
		 */
		_moveWidgetByOne: function( offset ) {
			var i, sidebarWidgetsSetting, sidebarWidgetIds,	adjacentWidgetId;

			i = this.getWidgetSidebarPosition();

			sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting;
			sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // Clone.
			adjacentWidgetId = sidebarWidgetIds[i + offset];
			sidebarWidgetIds[i + offset] = this.params.widget_id;
			sidebarWidgetIds[i] = adjacentWidgetId;

			sidebarWidgetsSetting( sidebarWidgetIds );
		},

		/**
		 * Toggle visibility of the widget move area
		 *
		 * @param {boolean} [showOrHide]
		 */
		toggleWidgetMoveArea: function( showOrHide ) {
			var self = this, $moveWidgetArea;

			$moveWidgetArea = this.container.find( '.move-widget-area' );

			if ( typeof showOrHide === 'undefined' ) {
				showOrHide = ! $moveWidgetArea.hasClass( 'active' );
			}

			if ( showOrHide ) {
				// Reset the selected sidebar.
				$moveWidgetArea.find( '.selected' ).removeClass( 'selected' );

				$moveWidgetArea.find( 'li' ).filter( function() {
					return $( this ).data( 'id' ) === self.params.sidebar_id;
				} ).addClass( 'selected' );

				this.container.find( '.move-widget-btn' ).prop( 'disabled', true );
			}

			$moveWidgetArea.toggleClass( 'active', showOrHide );
		},

		/**
		 * Highlight the widget control and section
		 */
		highlightSectionAndControl: function() {
			var $target;

			if ( this.container.is( ':hidden' ) ) {
				$target = this.container.closest( '.control-section' );
			} else {
				$target = this.container;
			}

			$( '.highlighted' ).removeClass( 'highlighted' );
			$target.addClass( 'highlighted' );

			setTimeout( function() {
				$target.removeClass( 'highlighted' );
			}, 500 );
		}
	} );

	/**
	 * wp.customize.Widgets.WidgetsPanel
	 *
	 * Customizer panel containing the widget area sections.
	 *
	 * @since 4.4.0
	 *
	 * @class    wp.customize.Widgets.WidgetsPanel
	 * @augments wp.customize.Panel
	 */
	api.Widgets.WidgetsPanel = api.Panel.extend(/** @lends wp.customize.Widgets.WigetsPanel.prototype */{

		/**
		 * Add and manage the display of the no-rendered-areas notice.
		 *
		 * @since 4.4.0
		 */
		ready: function () {
			var panel = this;

			api.Panel.prototype.ready.call( panel );

			panel.deferred.embedded.done(function() {
				var panelMetaContainer, noticeContainer, updateNotice, getActiveSectionCount, shouldShowNotice;
				panelMetaContainer = panel.container.find( '.panel-meta' );

				// @todo This should use the Notifications API introduced to panels. See <https://core.trac.wordpress.org/ticket/38794>.
				noticeContainer = $( '<div></div>', {
					'class': 'no-widget-areas-rendered-notice',
					'role': 'alert'
				});
				panelMetaContainer.append( noticeContainer );

				/**
				 * Get the number of active sections in the panel.
				 *
				 * @return {number} Number of active sidebar sections.
				 */
				getActiveSectionCount = function() {
					return _.filter( panel.sections(), function( section ) {
						return 'sidebar' === section.params.type && section.active();
					} ).length;
				};

				/**
				 * Determine whether or not the notice should be displayed.
				 *
				 * @return {boolean}
				 */
				shouldShowNotice = function() {
					var activeSectionCount = getActiveSectionCount();
					if ( 0 === activeSectionCount ) {
						return true;
					} else {
						return activeSectionCount !== api.Widgets.data.registeredSidebars.length;
					}
				};

				/**
				 * Update the notice.
				 *
				 * @return {void}
				 */
				updateNotice = function() {
					var activeSectionCount = getActiveSectionCount(), someRenderedMessage, nonRenderedAreaCount, registeredAreaCount;
					noticeContainer.empty();

					registeredAreaCount = api.Widgets.data.registeredSidebars.length;
					if ( activeSectionCount !== registeredAreaCount ) {

						if ( 0 !== activeSectionCount ) {
							nonRenderedAreaCount = registeredAreaCount - activeSectionCount;
							someRenderedMessage = l10n.someAreasShown[ nonRenderedAreaCount ];
						} else {
							someRenderedMessage = l10n.noAreasShown;
						}
						if ( someRenderedMessage ) {
							noticeContainer.append( $( '<p></p>', {
								text: someRenderedMessage
							} ) );
						}

						noticeContainer.append( $( '<p></p>', {
							text: l10n.navigatePreview
						} ) );
					}
				};
				updateNotice();

				/*
				 * Set the initial visibility state for rendered notice.
				 * Update the visibility of the notice whenever a reflow happens.
				 */
				noticeContainer.toggle( shouldShowNotice() );
				api.previewer.deferred.active.done( function () {
					noticeContainer.toggle( shouldShowNotice() );
				});
				api.bind( 'pane-contents-reflowed', function() {
					var duration = ( 'resolved' === api.previewer.deferred.active.state() ) ? 'fast' : 0;
					updateNotice();
					if ( shouldShowNotice() ) {
						noticeContainer.slideDown( duration );
					} else {
						noticeContainer.slideUp( duration );
					}
				});
			});
		},

		/**
		 * Allow an active widgets panel to be contextually active even when it has no active sections (widget areas).
		 *
		 * This ensures that the widgets panel appears even when there are no
		 * sidebars displayed on the URL currently being previewed.
		 *
		 * @since 4.4.0
		 *
		 * @return {boolean}
		 */
		isContextuallyActive: function() {
			var panel = this;
			return panel.active();
		}
	});

	/**
	 * wp.customize.Widgets.SidebarSection
	 *
	 * Customizer section representing a widget area widget
	 *
	 * @since 4.1.0
	 *
	 * @class    wp.customize.Widgets.SidebarSection
	 * @augments wp.customize.Section
	 */
	api.Widgets.SidebarSection = api.Section.extend(/** @lends wp.customize.Widgets.SidebarSection.prototype */{

		/**
		 * Sync the section's active state back to the Backbone model's is_rendered attribute
		 *
		 * @since 4.1.0
		 */
		ready: function () {
			var section = this, registeredSidebar;
			api.Section.prototype.ready.call( this );
			registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId );
			section.active.bind( function ( active ) {
				registeredSidebar.set( 'is_rendered', active );
			});
			registeredSidebar.set( 'is_rendered', section.active() );
		}
	});

	/**
	 * wp.customize.Widgets.SidebarControl
	 *
	 * Customizer control for widgets.
	 * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type
	 *
	 * @since 3.9.0
	 *
	 * @class    wp.customize.Widgets.SidebarControl
	 * @augments wp.customize.Control
	 */
	api.Widgets.SidebarControl = api.Control.extend(/** @lends wp.customize.Widgets.SidebarControl.prototype */{

		/**
		 * Set up the control
		 */
		ready: function() {
			this.$controlSection = this.container.closest( '.control-section' );
			this.$sectionContent = this.container.closest( '.accordion-section-content' );

			this._setupModel();
			this._setupSortable();
			this._setupAddition();
			this._applyCardinalOrderClassNames();
		},

		/**
		 * Update ordering of widget control forms when the setting is updated
		 */
		_setupModel: function() {
			var self = this;

			this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
				var widgetFormControls, removedWidgetIds, priority;

				removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );

				// Filter out any persistent widget IDs for widgets which have been deactivated.
				newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
					var parsedWidgetId = parseWidgetId( newWidgetId );

					return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
				} );

				widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
					var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );

					if ( ! widgetFormControl ) {
						widgetFormControl = self.addWidget( widgetId );
					}

					return widgetFormControl;
				} );

				// Sort widget controls to their new positions.
				widgetFormControls.sort( function( a, b ) {
					var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
						bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
					return aIndex - bIndex;
				});

				priority = 0;
				_( widgetFormControls ).each( function ( control ) {
					control.priority( priority );
					control.section( self.section() );
					priority += 1;
				});
				self.priority( priority ); // Make sure sidebar control remains at end.

				// Re-sort widget form controls (including widgets form other sidebars newly moved here).
				self._applyCardinalOrderClassNames();

				// If the widget was dragged into the sidebar, make sure the sidebar_id param is updated.
				_( widgetFormControls ).each( function( widgetFormControl ) {
					widgetFormControl.params.sidebar_id = self.params.sidebar_id;
				} );

				// Cleanup after widget removal.
				_( removedWidgetIds ).each( function( removedWidgetId ) {

					// Using setTimeout so that when moving a widget to another sidebar,
					// the other sidebars_widgets settings get a chance to update.
					setTimeout( function() {
						var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
							widget, isPresentInAnotherSidebar = false;

						// Check if the widget is in another sidebar.
						api.each( function( otherSetting ) {
							if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) {
								return;
							}

							var otherSidebarWidgets = otherSetting(), i;

							i = _.indexOf( otherSidebarWidgets, removedWidgetId );
							if ( -1 !== i ) {
								isPresentInAnotherSidebar = true;
							}
						} );

						// If the widget is present in another sidebar, abort!
						if ( isPresentInAnotherSidebar ) {
							return;
						}

						removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );

						// Detect if widget control was dragged to another sidebar.
						wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );

						// Delete any widget form controls for removed widgets.
						if ( removedControl && ! wasDraggedToAnotherSidebar ) {
							api.control.remove( removedControl.id );
							removedControl.container.remove();
						}

						// Move widget to inactive widgets sidebar (move it to Trash) if has been previously saved.
						// This prevents the inactive widgets sidebar from overflowing with throwaway widgets.
						if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
							inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice();
							inactiveWidgets.push( removedWidgetId );
							api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() );
						}

						// Make old single widget available for adding again.
						removedIdBase = parseWidgetId( removedWidgetId ).id_base;
						widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
						if ( widget && ! widget.get( 'is_multi' ) ) {
							widget.set( 'is_disabled', false );
						}
					} );

				} );
			} );
		},

		/**
		 * Allow widgets in sidebar to be re-ordered, and for the order to be previewed
		 */
		_setupSortable: function() {
			var self = this;

			this.isReordering = false;

			/**
			 * Update widget order setting when controls are re-ordered
			 */
			this.$sectionContent.sortable( {
				items: '> .customize-control-widget_form',
				handle: '.widget-top',
				axis: 'y',
				tolerance: 'pointer',
				connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
				update: function() {
					var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;

					widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
						return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
					} );

					self.setting( widgetIds );
				}
			} );

			/**
			 * Expand other Customizer sidebar section when dragging a control widget over it,
			 * allowing the control to be dropped into another section
			 */
			this.$controlSection.find( '.accordion-section-title' ).droppable({
				accept: '.customize-control-widget_form',
				over: function() {
					var section = api.section( self.section.get() );
					section.expand({
						allowMultiple: true, // Prevent the section being dragged from to be collapsed.
						completeCallback: function () {
							// @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed.
							api.section.each( function ( otherSection ) {
								if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) {
									otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' );
								}
							} );
						}
					});
				}
			});

			/**
			 * Keyboard-accessible reordering
			 */
			this.container.find( '.reorder-toggle' ).on( 'click', function() {
				self.toggleReordering( ! self.isReordering );
			} );
		},

		/**
		 * Set up UI for adding a new widget
		 */
		_setupAddition: function() {
			var self = this;

			this.container.find( '.add-new-widget' ).on( 'click', function() {
				var addNewWidgetBtn = $( this );

				if ( self.$sectionContent.hasClass( 'reordering' ) ) {
					return;
				}

				if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
					addNewWidgetBtn.attr( 'aria-expanded', 'true' );
					api.Widgets.availableWidgetsPanel.open( self );
				} else {
					addNewWidgetBtn.attr( 'aria-expanded', 'false' );
					api.Widgets.availableWidgetsPanel.close();
				}
			} );
		},

		/**
		 * Add classes to the widget_form controls to assist with styling
		 */
		_applyCardinalOrderClassNames: function() {
			var widgetControls = [];
			_.each( this.setting(), function ( widgetId ) {
				var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
				if ( widgetControl ) {
					widgetControls.push( widgetControl );
				}
			});

			if ( 0 === widgetControls.length || ( 1 === api.Widgets.registeredSidebars.length && widgetControls.length <= 1 ) ) {
				this.container.find( '.reorder-toggle' ).hide();
				return;
			} else {
				this.container.find( '.reorder-toggle' ).show();
			}

			$( widgetControls ).each( function () {
				$( this.container )
					.removeClass( 'first-widget' )
					.removeClass( 'last-widget' )
					.find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
			});

			_.first( widgetControls ).container
				.addClass( 'first-widget' )
				.find( '.move-widget-up' ).prop( 'tabIndex', -1 );

			_.last( widgetControls ).container
				.addClass( 'last-widget' )
				.find( '.move-widget-down' ).prop( 'tabIndex', -1 );
		},


		/***********************************************************************
		 * Begin public API methods
		 **********************************************************************/

		/**
		 * Enable/disable the reordering UI
		 *
		 * @param {boolean} showOrHide to enable/disable reordering
		 *
		 * @todo We should have a reordering state instead and rename this to onChangeReordering
		 */
		toggleReordering: function( showOrHide ) {
			var addNewWidgetBtn = this.$sectionContent.find( '.add-new-widget' ),
				reorderBtn = this.container.find( '.reorder-toggle' ),
				widgetsTitle = this.$sectionContent.find( '.widget-title' );

			showOrHide = Boolean( showOrHide );

			if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
				return;
			}

			this.isReordering = showOrHide;
			this.$sectionContent.toggleClass( 'reordering', showOrHide );

			if ( showOrHide ) {
				_( this.getWidgetFormControls() ).each( function( formControl ) {
					formControl.collapse();
				} );

				addNewWidgetBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
				reorderBtn.attr( 'aria-label', l10n.reorderLabelOff );
				wp.a11y.speak( l10n.reorderModeOn );
				// Hide widget titles while reordering: title is already in the reorder controls.
				widgetsTitle.attr( 'aria-hidden', 'true' );
			} else {
				addNewWidgetBtn.removeAttr( 'tabindex aria-hidden' );
				reorderBtn.attr( 'aria-label', l10n.reorderLabelOn );
				wp.a11y.speak( l10n.reorderModeOff );
				widgetsTitle.attr( 'aria-hidden', 'false' );
			}
		},

		/**
		 * Get the widget_form Customize controls associated with the current sidebar.
		 *
		 * @since 3.9.0
		 * @return {wp.customize.controlConstructor.widget_form[]}
		 */
		getWidgetFormControls: function() {
			var formControls = [];

			_( this.setting() ).each( function( widgetId ) {
				var settingId = widgetIdToSettingId( widgetId ),
					formControl = api.control( settingId );
				if ( formControl ) {
					formControls.push( formControl );
				}
			} );

			return formControls;
		},

		/**
		 * @param {string} widgetId or an id_base for adding a previously non-existing widget.
		 * @return {Object|false} widget_form control instance, or false on error.
		 */
		addWidget: function( widgetId ) {
			var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor,
				parsedWidgetId = parseWidgetId( widgetId ),
				widgetNumber = parsedWidgetId.number,
				widgetIdBase = parsedWidgetId.id_base,
				widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
				settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting;

			if ( ! widget ) {
				return false;
			}

			if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
				return false;
			}

			// Set up new multi widget.
			if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
				widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
				widgetNumber = widget.get( 'multi_number' );
			}

			controlHtml = $( '#widget-tpl-' + widget.get( 'id' ) ).html().trim();
			if ( widget.get( 'is_multi' ) ) {
				controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
					return m.replace( /__i__|%i%/g, widgetNumber );
				} );
			} else {
				widget.set( 'is_disabled', true ); // Prevent single widget from being added again now.
			}

			$widget = $( controlHtml );

			controlContainer = $( '<li/>' )
				.addClass( 'customize-control' )
				.addClass( 'customize-control-' + controlType )
				.append( $widget );

			// Remove icon which is visible inside the panel.
			controlContainer.find( '> .widget-icon' ).remove();

			if ( widget.get( 'is_multi' ) ) {
				controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber );
				controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber );
			}

			widgetId = controlContainer.find( '[name="widget-id"]' ).val();

			controlContainer.hide(); // To be slid-down below.

			settingId = 'widget_' + widget.get( 'id_base' );
			if ( widget.get( 'is_multi' ) ) {
				settingId += '[' + widgetNumber + ']';
			}
			controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );

			// Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget).
			isExistingWidget = api.has( settingId );
			if ( ! isExistingWidget ) {
				settingArgs = {
					transport: api.Widgets.data.selectiveRefreshableWidgets[ widget.get( 'id_base' ) ] ? 'postMessage' : 'refresh',
					previewer: this.setting.previewer
				};
				setting = api.create( settingId, settingId, '', settingArgs );
				setting.set( {} ); // Mark dirty, changing from '' to {}.
			}

			controlConstructor = api.controlConstructor[controlType];
			widgetFormControl = new controlConstructor( settingId, {
				settings: {
					'default': settingId
				},
				content: controlContainer,
				sidebar_id: self.params.sidebar_id,
				widget_id: widgetId,
				widget_id_base: widget.get( 'id_base' ),
				type: controlType,
				is_new: ! isExistingWidget,
				width: widget.get( 'width' ),
				height: widget.get( 'height' ),
				is_wide: widget.get( 'is_wide' )
			} );
			api.control.add( widgetFormControl );

			// Make sure widget is removed from the other sidebars.
			api.each( function( otherSetting ) {
				if ( otherSetting.id === self.setting.id ) {
					return;
				}

				if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
					return;
				}

				var otherSidebarWidgets = otherSetting().slice(),
					i = _.indexOf( otherSidebarWidgets, widgetId );

				if ( -1 !== i ) {
					otherSidebarWidgets.splice( i );
					otherSetting( otherSidebarWidgets );
				}
			} );

			// Add widget to this sidebar.
			sidebarWidgets = this.setting().slice();
			if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
				sidebarWidgets.push( widgetId );
				this.setting( sidebarWidgets );
			}

			controlContainer.slideDown( function() {
				if ( isExistingWidget ) {
					widgetFormControl.updateWidget( {
						instance: widgetFormControl.setting()
					} );
				}
			} );

			return widgetFormControl;
		}
	} );

	// Register models for custom panel, section, and control types.
	$.extend( api.panelConstructor, {
		widgets: api.Widgets.WidgetsPanel
	});
	$.extend( api.sectionConstructor, {
		sidebar: api.Widgets.SidebarSection
	});
	$.extend( api.controlConstructor, {
		widget_form: api.Widgets.WidgetControl,
		sidebar_widgets: api.Widgets.SidebarControl
	});

	/**
	 * Init Customizer for widgets.
	 */
	api.bind( 'ready', function() {
		// Set up the widgets panel.
		api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
			collection: api.Widgets.availableWidgets
		});

		// Highlight widget control.
		api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );

		// Open and focus widget control.
		api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
	} );

	/**
	 * Highlight a widget control.
	 *
	 * @param {string} widgetId
	 */
	api.Widgets.highlightWidgetFormControl = function( widgetId ) {
		var control = api.Widgets.getWidgetFormControlForWidget( widgetId );

		if ( control ) {
			control.highlightSectionAndControl();
		}
	},

	/**
	 * Focus a widget control.
	 *
	 * @param {string} widgetId
	 */
	api.Widgets.focusWidgetFormControl = function( widgetId ) {
		var control = api.Widgets.getWidgetFormControlForWidget( widgetId );

		if ( control ) {
			control.focus();
		}
	},

	/**
	 * Given a widget control, find the sidebar widgets control that contains it.
	 * @param {string} widgetId
	 * @return {Object|null}
	 */
	api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
		var foundControl = null;

		// @todo This can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl().
		api.control.each( function( control ) {
			if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
				foundControl = control;
			}
		} );

		return foundControl;
	};

	/**
	 * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
	 *
	 * @param {string} widgetId
	 * @return {Object|null}
	 */
	api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
		var foundControl = null;

		// @todo We can just use widgetIdToSettingId() here.
		api.control.each( function( control ) {
			if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
				foundControl = control;
			}
		} );

		return foundControl;
	};

	/**
	 * Initialize Edit Menu button in Nav Menu widget.
	 */
	$( document ).on( 'widget-added', function( event, widgetContainer ) {
		var parsedWidgetId, widgetControl, navMenuSelect, editMenuButton;
		parsedWidgetId = parseWidgetId( widgetContainer.find( '> .widget-inside > .form > .widget-id' ).val() );
		if ( 'nav_menu' !== parsedWidgetId.id_base ) {
			return;
		}
		widgetControl = api.control( 'widget_nav_menu[' + String( parsedWidgetId.number ) + ']' );
		if ( ! widgetControl ) {
			return;
		}
		navMenuSelect = widgetContainer.find( 'select[name*="nav_menu"]' );
		editMenuButton = widgetContainer.find( '.edit-selected-nav-menu > button' );
		if ( 0 === navMenuSelect.length || 0 === editMenuButton.length ) {
			return;
		}
		navMenuSelect.on( 'change', function() {
			if ( api.section.has( 'nav_menu[' + navMenuSelect.val() + ']' ) ) {
				editMenuButton.parent().show();
			} else {
				editMenuButton.parent().hide();
			}
		});
		editMenuButton.on( 'click', function() {
			var section = api.section( 'nav_menu[' + navMenuSelect.val() + ']' );
			if ( section ) {
				focusConstructWithBreadcrumb( section, widgetControl );
			}
		} );
	} );

	/**
	 * Focus (expand) one construct and then focus on another construct after the first is collapsed.
	 *
	 * This overrides the back button to serve the purpose of breadcrumb navigation.
	 *
	 * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} focusConstruct - The object to initially focus.
	 * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} returnConstruct - The object to return focus.
	 */
	function focusConstructWithBreadcrumb( focusConstruct, returnConstruct ) {
		focusConstruct.focus();
		function onceCollapsed( isExpanded ) {
			if ( ! isExpanded ) {
				focusConstruct.expanded.unbind( onceCollapsed );
				returnConstruct.focus();
			}
		}
		focusConstruct.expanded.bind( onceCollapsed );
	}

	/**
	 * @param {string} widgetId
	 * @return {Object}
	 */
	function parseWidgetId( widgetId ) {
		var matches, parsed = {
			number: null,
			id_base: null
		};

		matches = widgetId.match( /^(.+)-(\d+)$/ );
		if ( matches ) {
			parsed.id_base = matches[1];
			parsed.number = parseInt( matches[2], 10 );
		} else {
			// Likely an old single widget.
			parsed.id_base = widgetId;
		}

		return parsed;
	}

	/**
	 * @param {string} widgetId
	 * @return {string} settingId
	 */
	function widgetIdToSettingId( widgetId ) {
		var parsed = parseWidgetId( widgetId ), settingId;

		settingId = 'widget_' + parsed.id_base;
		if ( parsed.number ) {
			settingId += '[' + parsed.number + ']';
		}

		return settingId;
	}

})( window.wp, jQuery );