File: browser-sidebar.js

package info (click to toggle)
firefox 141.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,550,588 kB
  • sloc: cpp: 7,426,506; javascript: 6,367,238; ansic: 3,707,351; python: 1,369,002; xml: 623,983; asm: 426,918; java: 184,324; sh: 64,488; makefile: 19,203; objc: 13,059; perl: 12,955; yacc: 4,583; cs: 3,846; pascal: 3,352; lex: 1,720; ruby: 1,071; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10
file content (2417 lines) | stat: -rw-r--r-- 77,632 bytes parent folder | download | duplicates (2)
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
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * SidebarController handles logic such as toggling sidebar panels,
 * dynamically adding menubar menu items for the View -> Sidebar menu,
 * and provides APIs for sidebar extensions, etc.
 */

const { DeferredTask } = ChromeUtils.importESModule(
  "resource://gre/modules/DeferredTask.sys.mjs"
);

const toolsNameMap = {
  viewGenaiChatSidebar: "aichat",
  viewTabsSidebar: "syncedtabs",
  viewHistorySidebar: "history",
  viewBookmarksSidebar: "bookmarks",
  viewCPMSidebar: "passwords",
};
const EXPAND_ON_HOVER_DEBOUNCE_RATE_MS = 200;
const EXPAND_ON_HOVER_DEBOUNCE_TIMEOUT_MS = 1000;
const LAUNCHER_SPLITTER_WIDTH = 4;

var SidebarController = {
  makeSidebar({ elementId, ...rest }, commandID) {
    const sidebar = {
      get sourceL10nEl() {
        return document.getElementById(elementId);
      },
      get title() {
        let element = document.getElementById(elementId);
        return element?.getAttribute("label");
      },
      ...rest,
    };

    const toolID = toolsNameMap[commandID];
    if (toolID) {
      XPCOMUtils.defineLazyPreferenceGetter(
        sidebar,
        "attention",
        `sidebar.notification.badge.${toolID}`,
        false,
        (_pref, _prev) => this.handleToolBadges(toolID)
      );
      sidebar.attention;
    }

    return sidebar;
  },

  registerPrefSidebar(pref, commandID, config) {
    const sidebar = this.makeSidebar(config, commandID);
    this._sidebars.set(commandID, sidebar);

    let switcherMenuitem;
    const updateMenus = visible => {
      // Hide the sidebar if it is open and should not be visible,
      // and unset the current command and lastOpenedId so they do not
      // re-open the next time the sidebar does.
      if (!visible && this._state.command == commandID) {
        this._state.command = "";
        this.lastOpenedId = null;
        this.hide();
      }

      // Update visibility of View -> Sidebar menu item.
      const viewItem = document.getElementById(sidebar.menuId);
      if (viewItem) {
        viewItem.hidden = !visible;
      }

      let menuItem = document.getElementById(config.elementId);
      // Add/remove switcher menu item.
      if (visible && !menuItem) {
        switcherMenuitem = this.createMenuItem(commandID, sidebar);
        switcherMenuitem.setAttribute("id", config.elementId);
        switcherMenuitem.removeAttribute("type");
        const separator = this._switcherPanel.querySelector("menuseparator");
        separator.parentNode.insertBefore(switcherMenuitem, separator);
      } else {
        switcherMenuitem?.remove();
      }

      window.dispatchEvent(new CustomEvent("SidebarItemChanged"));
    };

    // Detect pref changes and handle initial state.
    XPCOMUtils.defineLazyPreferenceGetter(
      sidebar,
      "visible",
      pref,
      false,
      (_pref, _prev, val) => updateMenus(val)
    );
    this.promiseInitialized.then(() => updateMenus(sidebar.visible));
  },

  get sidebars() {
    if (this._sidebars) {
      return this._sidebars;
    }

    return this.generateSidebarsMap();
  },

  generateSidebarsMap() {
    this._sidebars = new Map([
      [
        "viewHistorySidebar",
        this.makeSidebar({
          elementId: "sidebar-switcher-history",
          url: this.sidebarRevampEnabled
            ? "chrome://browser/content/sidebar/sidebar-history.html"
            : "chrome://browser/content/places/historySidebar.xhtml",
          menuId: "menu_historySidebar",
          triggerButtonId: "appMenuViewHistorySidebar",
          keyId: "key_gotoHistory",
          menuL10nId: "menu-view-history-button",
          revampL10nId: "sidebar-menu-history-label",
          iconUrl: "chrome://browser/skin/history.svg",
          contextMenuId: this.sidebarRevampEnabled
            ? "sidebar-history-context-menu"
            : undefined,
          gleanEvent: Glean.history.sidebarToggle,
          gleanClickEvent: Glean.sidebar.historyIconClick,
          recordSidebarVersion: true,
        }),
      ],
      [
        "viewTabsSidebar",
        this.makeSidebar({
          elementId: "sidebar-switcher-tabs",
          url: this.sidebarRevampEnabled
            ? "chrome://browser/content/sidebar/sidebar-syncedtabs.html"
            : "chrome://browser/content/syncedtabs/sidebar.xhtml",
          menuId: "menu_tabsSidebar",
          classAttribute: "sync-ui-item",
          menuL10nId: "menu-view-synced-tabs-sidebar",
          revampL10nId: "sidebar-menu-synced-tabs-label",
          iconUrl: "chrome://browser/skin/synced-tabs.svg",
          contextMenuId: this.sidebarRevampEnabled
            ? "sidebar-synced-tabs-context-menu"
            : undefined,
          gleanClickEvent: Glean.sidebar.syncedTabsIconClick,
        }),
      ],
      [
        "viewBookmarksSidebar",
        this.makeSidebar({
          elementId: "sidebar-switcher-bookmarks",
          url: "chrome://browser/content/places/bookmarksSidebar.xhtml",
          menuId: "menu_bookmarksSidebar",
          keyId: "viewBookmarksSidebarKb",
          menuL10nId: "menu-view-bookmarks",
          revampL10nId: "sidebar-menu-bookmarks-label",
          iconUrl: "chrome://browser/skin/bookmark-hollow.svg",
          disabled: true,
          gleanEvent: Glean.bookmarks.sidebarToggle,
          gleanClickEvent: Glean.sidebar.bookmarksIconClick,
          recordSidebarVersion: true,
        }),
      ],
    ]);

    this.registerPrefSidebar(
      "browser.ml.chat.enabled",
      "viewGenaiChatSidebar",
      {
        elementId: "sidebar-switcher-genai-chat",
        url: "chrome://browser/content/genai/chat.html",
        keyId: "viewGenaiChatSidebarKb",
        menuId: "menu_genaiChatSidebar",
        menuL10nId: "menu-view-genai-chat",
        // Bug 1900915 to expose as conditional tool
        revampL10nId: "sidebar-menu-genai-chat-label",
        iconUrl: "chrome://global/skin/icons/highlights.svg",
        gleanClickEvent: Glean.sidebar.chatbotIconClick,
      }
    );

    this.registerPrefSidebar(
      "browser.contextual-password-manager.enabled",
      "viewCPMSidebar",
      {
        elementId: "sidebar-switcher-megalist",
        url: "chrome://global/content/megalist/megalist.html",
        menuId: "menu_megalistSidebar",
        menuL10nId: "menu-view-contextual-password-manager",
        revampL10nId: "sidebar-menu-contextual-password-manager-label",
        iconUrl: "chrome://browser/skin/login.svg",
        gleanEvent: Glean.contextualManager.sidebarToggle,
      }
    );

    if (this.sidebarRevampEnabled) {
      this._sidebars.set("viewCustomizeSidebar", {
        url: "chrome://browser/content/sidebar/sidebar-customize.html",
        revampL10nId: "sidebar-menu-customize-label",
        iconUrl: "chrome://global/skin/icons/settings.svg",
        gleanEvent: Glean.sidebarCustomize.panelToggle,
        visible: false,
      });
    }

    return this._sidebars;
  },

  /**
   * Returns a map of tools and extensions for use in the sidebar
   */
  get toolsAndExtensions() {
    if (this._toolsAndExtensions) {
      return this._toolsAndExtensions;
    }

    this._toolsAndExtensions = new Map();
    this.getTools().forEach(tool => {
      this._toolsAndExtensions.set(tool.commandID, tool);
    });
    this.getExtensions().forEach(extension => {
      this._toolsAndExtensions.set(extension.commandID, extension);
    });
    return this._toolsAndExtensions;
  },

  // Avoid getting the browser element from init() to avoid triggering the
  // <browser> constructor during startup if the sidebar is hidden.
  get browser() {
    if (this._browser) {
      return this._browser;
    }
    return (this._browser = document.getElementById("sidebar"));
  },
  POSITION_START_PREF: "sidebar.position_start",
  DEFAULT_SIDEBAR_ID: "viewBookmarksSidebar",
  TOOLS_PREF: "sidebar.main.tools",
  VISIBILITY_PREF: "sidebar.visibility",

  // lastOpenedId is set in show() but unlike currentID it's not cleared out on hide
  // and isn't persisted across windows
  lastOpenedId: null,

  _box: null,
  _pinnedTabsContainer: null,
  _pinnedTabsItemsWrapper: null,
  // The constructor of this label accesses the browser element due to the
  // control="sidebar" attribute, so avoid getting this label during startup.
  get _title() {
    if (this.__title) {
      return this.__title;
    }
    return (this.__title = document.getElementById("sidebar-title"));
  },
  _splitter: null,
  _reversePositionButton: null,
  _switcherPanel: null,
  _switcherTarget: null,
  _switcherArrow: null,
  _inited: false,
  _uninitializing: false,
  _switcherListenersAdded: false,
  _verticalNewTabListenerAdded: false,
  _localesObserverAdded: false,
  _mainResizeObserverAdded: false,
  _mainResizeObserver: null,
  _ongoingAnimations: [],

  /**
   * @type {MutationObserver | null}
   */
  _observer: null,

  _initDeferred: Promise.withResolvers(),

  get promiseInitialized() {
    return this._initDeferred.promise;
  },

  get initialized() {
    return this._inited;
  },

  get uninitializing() {
    return this._uninitializing;
  },

  get inSingleTabWindow() {
    return (
      !window.toolbar.visible ||
      window.document.documentElement.hasAttribute("taskbartab")
    );
  },

  get sidebarContainer() {
    if (!this._sidebarContainer) {
      // This is the *parent* of the `sidebar-main` component.
      // TODO: Rename this element in the markup in order to avoid confusion. (Bug 1904860)
      this._sidebarContainer = document.getElementById("sidebar-main");
    }
    return this._sidebarContainer;
  },

  get sidebarMain() {
    if (!this._sidebarMain) {
      this._sidebarMain = document.querySelector("sidebar-main");
    }
    return this._sidebarMain;
  },

  get contentArea() {
    if (!this._contentArea) {
      this._contentArea = document.getElementById("tabbrowser-tabbox");
    }
    return this._contentArea;
  },

  get toolbarButton() {
    if (!this._toolbarButton) {
      this._toolbarButton = document.getElementById("sidebar-button");
    }
    return this._toolbarButton;
  },

  get isLauncherDragging() {
    return this._launcherSplitter.getAttribute("state") === "dragging";
  },

  get isPinnedTabsDragging() {
    return this._pinnedTabsSplitter.getAttribute("state") === "dragging";
  },

  init() {
    // Initialize global state manager.
    this.SidebarManager;

    // Initialize per-window state manager.
    if (!this._state) {
      this._state = new this.SidebarState(this);
    }

    this._pinnedTabsContainer = document.getElementById(
      "pinned-tabs-container"
    );
    this._pinnedTabsItemsWrapper =
      this._pinnedTabsContainer.shadowRoot.querySelector(
        "[part=items-wrapper]"
      );
    this._box = document.getElementById("sidebar-box");
    this._splitter = document.getElementById("sidebar-splitter");
    this._launcherSplitter = document.getElementById(
      "sidebar-launcher-splitter"
    );
    this._pinnedTabsSplitter = document.getElementById(
      "vertical-pinned-tabs-splitter"
    );
    this._reversePositionButton = document.getElementById(
      "sidebar-reverse-position"
    );
    this._switcherPanel = document.getElementById("sidebarMenu-popup");
    this._switcherTarget = document.getElementById("sidebar-switcher-target");
    this._switcherArrow = document.getElementById("sidebar-switcher-arrow");
    this._openPopupsCount = 0;
    if (
      Services.prefs.getBoolPref(
        "browser.tabs.allow_transparent_browser",
        false
      )
    ) {
      this.browser.setAttribute("transparent", "true");
    }

    const menubar = document.getElementById("viewSidebarMenu");
    const currentMenuItems = new Set(
      Array.from(menubar.childNodes, item => item.id)
    );
    for (const [commandID, sidebar] of this.sidebars.entries()) {
      if (
        !Object.hasOwn(sidebar, "extensionId") &&
        commandID !== "viewCustomizeSidebar" &&
        !currentMenuItems.has(sidebar.menuId)
      ) {
        // registerExtension() already creates menu items for extensions.
        const menuitem = this.createMenuItem(commandID, sidebar);
        menubar.appendChild(menuitem);
      }
    }
    if (this._mainResizeObserver) {
      this._mainResizeObserver.disconnect();
      this._mainResizeObserverAdded = false;
    }
    this._mainResizeObserver = new ResizeObserver(([entry]) =>
      this._handleLauncherResize(entry)
    );

    if (this.sidebarRevampEnabled && !BrowserHandler.kiosk) {
      if (!customElements.get("sidebar-main")) {
        ChromeUtils.importESModule(
          "chrome://browser/content/sidebar/sidebar-main.mjs",
          { global: "current" }
        );
      }
      this.revampComponentsLoaded = true;
      this._state.initializeState();
      document.getElementById("sidebar-header").hidden = true;
      if (!this._mainResizeObserverAdded) {
        this._mainResizeObserver.observe(this.sidebarMain);
        this._mainResizeObserverAdded = true;
      }
      if (!this._browserResizeObserver) {
        this._browserResizeObserver = () => {
          // Report resize events to Glean.
          const current = this.browser.getBoundingClientRect().width;
          const previous = this._browserWidth;
          const percentage = (current / window.innerWidth) * 100;
          Glean.sidebar.resize.record({
            current: Math.round(current),
            previous: Math.round(previous),
            percentage: Math.round(percentage),
          });
          this._recordBrowserSize();
        };
        this._splitter.addEventListener("command", this._browserResizeObserver);
      }
      this._enableLauncherDragging();
      this._enablePinnedTabsSplitterDragging();

      // Record Glean metrics.
      this.recordVisibilitySetting();
      this.recordPositionSetting();
      this.recordTabsLayoutSetting();
    } else {
      this._switcherCloseButton = document.getElementById("sidebar-close");
      if (!this._switcherListenersAdded) {
        this._switcherCloseButton.addEventListener("command", () => {
          this.hide();
        });
        this._switcherTarget.addEventListener("command", () => {
          this.toggleSwitcherPanel();
        });
        this._switcherTarget.addEventListener("keydown", event => {
          this.handleKeydown(event);
        });
        this._switcherListenersAdded = true;
      }
      this._disableLauncherDragging();
      this._disablePinnedTabsDragging();
    }
    // We need to update the tab strip for vertical tabs during init
    // as there will be no tabstrip-orientation-change event
    if (CustomizableUI.verticalTabsEnabled) {
      this.toggleTabstrip();
    }

    // sets the sidebar to the left or right, based on a pref
    this.setPosition();

    this._inited = true;

    if (!this._localesObserverAdded) {
      Services.obs.addObserver(this, "intl:app-locales-changed");
      this._localesObserverAdded = true;
    }
    if (!this._tabstripOrientationObserverAdded) {
      Services.obs.addObserver(this, "tabstrip-orientation-change");
      this._tabstripOrientationObserverAdded = true;
    }

    requestIdleCallback(() => {
      const windowPrivacyMatches =
        !window.opener || this.windowPrivacyMatches(window.opener, window);
      // If other sources (like session store or source window) haven't set the
      // UI state at this point, load the backup state. (Do not load the backup
      // state if this is a popup, or we are coming from a window of a different
      // privacy level.)
      if (
        !this.uiStateInitialized &&
        !this.inSingleTabWindow &&
        (this.sidebarRevampEnabled || windowPrivacyMatches)
      ) {
        const backupState = this.SidebarManager.getBackupState();
        this.initializeUIState(backupState);
      }
    });
    this._initDeferred.resolve();
  },

  uninit() {
    // Set a flag to allow us to ignore pref changes while the host document is being unloaded.
    this._uninitializing = true;

    // If this is the last browser window, persist various values that should be
    // remembered for after a restart / reopening a browser window.
    let enumerator = Services.wm.getEnumerator("navigator:browser");
    if (!enumerator.hasMoreElements()) {
      let xulStore = Services.xulStore;
      xulStore.persist(this._title, "value");

      const currentState = this.getUIState();
      this.SidebarManager.setBackupState(currentState);
    }

    Services.obs.removeObserver(this, "intl:app-locales-changed");
    Services.obs.removeObserver(this, "tabstrip-orientation-change");
    delete this._tabstripOrientationObserverAdded;

    CustomizableUI.removeListener(this);

    if (this._observer) {
      this._observer.disconnect();
      this._observer = null;
    }

    if (this._mainResizeObserver) {
      this._mainResizeObserver.disconnect();
      this._mainResizeObserver = null;
    }

    if (this.revampComponentsLoaded) {
      // Explicitly disconnect the `sidebar-main` element so that listeners
      // setup by reactive controllers will also be removed.
      this.sidebarMain.remove();
    }
    this._splitter.removeEventListener("command", this._browserResizeObserver);
    this._disableLauncherDragging();
    this._disablePinnedTabsDragging();
  },

  /**
   * Handle the launcher being resized (either manually or programmatically).
   *
   * @param {ResizeObserverEntry} entry
   */
  _handleLauncherResize(entry) {
    this._state.launcherWidth = entry.contentBoxSize[0].inlineSize;
    if (this.isLauncherDragging) {
      this._state.launcherDragActive = true;
    }
    if (this._state.visibilitySetting === "expand-on-hover") {
      this.setLauncherCollapsedWidth();
    }
  },

  getUIState() {
    if (this.inSingleTabWindow) {
      return null;
    }
    return this._state.getProperties();
  },

  /**
   * Load the UI state information given by session store, backup state, or
   * adopted window.
   *
   * @param {SidebarStateProps} state
   */
  async initializeUIState(state) {
    if (!state) {
      return;
    }
    const isValidSidebar = !state.command || this.sidebars.has(state.command);
    if (!isValidSidebar) {
      state.command = "";
    }

    const hasOpenPanel =
      state.panelOpen &&
      state.command &&
      this.sidebars.has(state.command) &&
      this.currentID !== state.command;
    if (hasOpenPanel) {
      // There's a panel to show, so ignore the contradictory hidden property.
      delete state.hidden;
    }
    await this.promiseInitialized;
    await this.waitUntilStable(); // Finish currently scheduled tasks.
    await this._state.loadInitialState(state);
    await this.waitUntilStable(); // Finish newly scheduled tasks.
    this.updateToolbarButton();
    if (this.sidebarRevampVisibility === "expand-on-hover") {
      await this.toggleExpandOnHover(true);
    }
    this.uiStateInitialized = true;
  },

  /**
   * Toggle the vertical tabs preference.
   */
  toggleVerticalTabs() {
    Services.prefs.setBoolPref(
      "sidebar.verticalTabs",
      !this.sidebarVerticalTabsEnabled
    );
  },

  /**
   * The handler for Services.obs.addObserver.
   */
  observe(_subject, topic, _data) {
    switch (topic) {
      case "intl:app-locales-changed": {
        if (this.isOpen) {
          // The <tree> component used in history and bookmarks, but it does not
          // support live switching the app locale. Reload the entire sidebar to
          // invalidate any old text.
          this.hide({ dismissPanel: false });
          this.showInitially(this.lastOpenedId);
          break;
        }
        if (this.revampComponentsLoaded) {
          this.sidebarMain.requestUpdate();
        }
        break;
      }
      case "tabstrip-orientation-change": {
        this.promiseInitialized.then(() => this.toggleTabstrip());
        break;
      }
    }
  },

  /**
   * Ensure the title stays in sync with the source element, which updates for
   * l10n changes.
   *
   * @param {HTMLElement} [element]
   */
  observeTitleChanges(element) {
    if (!element) {
      return;
    }
    let observer = this._observer;
    if (!observer) {
      observer = new MutationObserver(() => {
        // it's possible for lastOpenedId to be null here
        this.title = this.sidebars.get(this.lastOpenedId)?.title;
      });
      // Re-use the observer.
      this._observer = observer;
    }
    observer.disconnect();
    observer.observe(element, {
      attributes: true,
      attributeFilter: ["label"],
    });
  },

  /**
   * Opens the switcher panel if it's closed, or closes it if it's open.
   */
  toggleSwitcherPanel() {
    if (
      this._switcherPanel.state == "open" ||
      this._switcherPanel.state == "showing"
    ) {
      this.hideSwitcherPanel();
    } else if (this._switcherPanel.state == "closed") {
      this.showSwitcherPanel();
    }
  },

  /**
   * Handles keydown on the the switcherTarget button
   *
   * @param  {Event} event
   */
  handleKeydown(event) {
    switch (event.key) {
      case "Enter":
      case " ": {
        this.toggleSwitcherPanel();
        event.stopPropagation();
        event.preventDefault();
        break;
      }
      case "Escape": {
        this.hideSwitcherPanel();
        event.stopPropagation();
        event.preventDefault();
        break;
      }
    }
  },

  hideSwitcherPanel() {
    this._switcherPanel.hidePopup();
  },

  showSwitcherPanel() {
    this._switcherPanel.addEventListener(
      "popuphiding",
      () => {
        this._switcherTarget.classList.remove("active");
        this._switcherTarget.setAttribute("aria-expanded", false);
      },
      { once: true }
    );

    // Combine start/end position with ltr/rtl to set the label in the popup appropriately.
    let label =
      this._positionStart == RTL_UI
        ? gNavigatorBundle.getString("sidebar.moveToLeft")
        : gNavigatorBundle.getString("sidebar.moveToRight");
    this._reversePositionButton.setAttribute("label", label);

    // Open the sidebar switcher popup, anchored off the switcher toggle
    this._switcherPanel.hidden = false;
    this._switcherPanel.openPopup(this._switcherTarget);

    this._switcherTarget.classList.add("active");
    this._switcherTarget.setAttribute("aria-expanded", true);
  },

  updateShortcut({ keyId }) {
    let menuitem = this._switcherPanel?.querySelector(`[key="${keyId}"]`);
    if (!menuitem) {
      // If the menu item doesn't exist yet then the accel text will be set correctly
      // upon creation so there's nothing to do now.
      return;
    }
    menuitem.removeAttribute("acceltext");
  },

  /**
   * Change the pref that will trigger a call to setPosition
   */
  reversePosition() {
    Services.prefs.setBoolPref(this.POSITION_START_PREF, !this._positionStart);
  },

  /**
   * Read the positioning pref and position the sidebar and the splitter
   * appropriately within the browser container.
   */
  setPosition() {
    // First reset all ordinals to match DOM ordering.
    let contentArea = document.getElementById("tabbrowser-tabbox");
    let browser = document.getElementById("browser");
    [...browser.children].forEach((node, i) => {
      node.style.order = i + 1;
    });
    let sidebarContainer = document.getElementById("sidebar-main");
    let sidebarMain = document.querySelector("sidebar-main");
    if (!this._positionStart) {
      // DOM ordering is:     sidebar-main | launcher-splitter | sidebar-box | splitter | tabbrowser-tabbox
      // Want to display as:  tabbrowser-tabbox | splitter |  sidebar-box  | launcher-splitter | sidebar-main
      // First switch order of sidebar-main and tabbrowser-tabbox
      let mainOrdinal = this.sidebarContainer.style.order;
      this.sidebarContainer.style.order = contentArea.style.order;
      contentArea.style.order = mainOrdinal;
      // Then swap launcher-splitter and splitter
      let splitterOrdinal = this._splitter.style.order;
      this._splitter.style.order = this._launcherSplitter.style.order;
      this._launcherSplitter.style.order = splitterOrdinal;
    }
    // Indicate we've switched ordering to the box
    this._box.toggleAttribute("sidebar-positionend", !this._positionStart);
    sidebarMain.toggleAttribute("sidebar-positionend", !this._positionStart);
    contentArea.toggleAttribute("sidebar-positionend", !this._positionStart);
    sidebarContainer.toggleAttribute(
      "sidebar-positionend",
      !this._positionStart
    );
    this.toolbarButton &&
      this.toolbarButton.toggleAttribute(
        "sidebar-positionend",
        !this._positionStart
      );

    this.hideSwitcherPanel();

    let content = SidebarController.browser.contentWindow;
    if (content && content.updatePosition) {
      content.updatePosition();
    }
  },

  /**
   * Show/hide new sidebar based on sidebar.revamp pref
   */
  async toggleRevampSidebar() {
    await this.promiseInitialized;
    let wasOpen = this.isOpen;
    if (wasOpen) {
      this.hide({ dismissPanel: false });
    }
    // Reset sidebars map but preserve any existing extensions
    let extensionsArr = [];
    for (const [commandID, sidebar] of this.sidebars.entries()) {
      if (sidebar.hasOwnProperty("extensionId")) {
        extensionsArr.push({ commandID, sidebar });
      }
    }
    this.sidebars = this.generateSidebarsMap();
    for (const extension of extensionsArr) {
      this.sidebars.set(extension.commandID, extension.sidebar);
    }
    if (!this.sidebarRevampEnabled) {
      this._state.launcherVisible = false;
      document.getElementById("sidebar-header").hidden = false;
      // Disable vertical tabs if revamped sidebar is turned off
      if (this.sidebarVerticalTabsEnabled) {
        Services.prefs.setBoolPref("sidebar.verticalTabs", false);
      }
    } else {
      // initial launcher visibleness with sidebar.revamp is is one of the
      // default properties managed by SidebarState
      this._state.launcherVisible = this._state.defaultLauncherVisible;
    }
    if (!this._sidebars.get(this.lastOpenedId)) {
      this.lastOpenedId = this.DEFAULT_SIDEBAR_ID;
      wasOpen = false;
    }
    this.updateToolbarButton();
    this._inited = false;
    this.init();

    // Reopen the panel in the new or old sidebar now that we've inited
    if (wasOpen) {
      this.toggle();
    }
  },

  /**
   * Try and adopt the status of the sidebar from another window.
   *
   * @param {Window} sourceWindow - Window to use as a source for sidebar status.
   * @returns {boolean} true if we adopted the state, or false if the caller should
   * initialize the state itself.
   */
  async adoptFromWindow(sourceWindow) {
    // If the opener had a sidebar, open the same sidebar in our window.
    // The opener can be the hidden window too, if we're coming from the state
    // where no windows are open, and the hidden window has no sidebar box.
    let sourceController = sourceWindow.SidebarController;
    if (!sourceController || !sourceController._box) {
      // no source UI or no _box means we also can't adopt the state.
      return false;
    }

    // If window is a popup, hide the sidebar
    if (this.inSingleTabWindow && this.sidebarRevampEnabled) {
      document.getElementById("sidebar-main").hidden = true;
      return false;
    }
    // Adopt the other window's UI state (it too could be a popup)
    // We get the properties directly forom the SidebarState instance as in this case
    // we need the command property even if no panel is currently open.
    const sourceState = sourceController.inPopup
      ? null
      : sourceController._state?.getProperties();
    await this.initializeUIState(sourceState);

    return true;
  },

  windowPrivacyMatches(w1, w2) {
    return (
      PrivateBrowsingUtils.isWindowPrivate(w1) ===
      PrivateBrowsingUtils.isWindowPrivate(w2)
    );
  },

  /**
   * If loading a sidebar was delayed on startup, start the load now.
   */
  async startDelayedLoad() {
    if (this.inSingleTabWindow) {
      this._state.launcherVisible = false;
      return;
    }

    let sourceWindow = window.opener;
    // No source window means this is the initial window.  If we're being
    // opened from another window, check that it is one we might open a sidebar
    // for.
    if (sourceWindow) {
      if (
        sourceWindow.closed ||
        sourceWindow.location.protocol != "chrome:" ||
        (!this.sidebarRevampEnabled &&
          !this.windowPrivacyMatches(sourceWindow, window))
      ) {
        return;
      }
      // Try to adopt the sidebar state from the source window
      if (await this.adoptFromWindow(sourceWindow)) {
        this.uiStateInitialized = true;
        return;
      }
    }

    // If we're not adopting settings from a parent window, set them now.
    let wasOpen = this._box.getAttribute("checked");
    if (!wasOpen) {
      return;
    }

    let commandID = this._state.command;
    if (commandID && this.sidebars.has(commandID)) {
      this.showInitially(commandID);
    } else {
      this._box.removeAttribute("checked");
      // Update the state, because the element it
      // refers to no longer exists, so we should assume this sidebar
      // panel has been uninstalled. (249883)
      this._state.command = "";
      // On a startup in which the startup cache was invalidated (e.g. app update)
      // extensions will not be started prior to delayedLoad, thus the
      // sidebarcommand element will not exist yet.  Store the commandID so
      // extensions may reopen if necessary.  A startup cache invalidation
      // can be forced (for testing) by deleting compatibility.ini from the
      // profile.
      this.lastOpenedId = commandID;
    }
    this.uiStateInitialized = true;
  },

  /**
   * Fire a "SidebarShown" event on the sidebar to give any interested parties
   * a chance to update the button or whatever.
   */
  _fireShowEvent() {
    let event = new CustomEvent("SidebarShown", { bubbles: true });
    this._switcherTarget.dispatchEvent(event);
  },

  /**
   * Report the current browser width to Glean, and store it internally.
   */
  _recordBrowserSize() {
    this._browserWidth = this.browser.getBoundingClientRect().width;
    Glean.sidebar.width.set(this._browserWidth);
  },

  /**
   * Fire a "SidebarFocused" event on the sidebar's |window| to give the sidebar
   * a chance to adjust focus as needed. An additional event is needed, because
   * we don't want to focus the sidebar when it's opened on startup or in a new
   * window, only when the user opens the sidebar.
   */
  _fireFocusedEvent() {
    let event = new CustomEvent("SidebarFocused", { bubbles: true });
    this.browser.contentWindow.dispatchEvent(event);
  },

  /**
   * True if the sidebar is currently open.
   */
  get isOpen() {
    return this._box ? !this._box.hidden : false;
  },

  /**
   * The ID of the current sidebar.
   */
  get currentID() {
    return this.isOpen ? this._state.command : "";
  },

  /**
   * The context menu of the current sidebar.
   */
  get currentContextMenu() {
    const sidebar = this.sidebars.get(this.currentID);
    if (!sidebar) {
      return null;
    }
    return document.getElementById(sidebar.contextMenuId);
  },

  get launcherVisible() {
    return this._state?.launcherVisible;
  },

  get launcherEverVisible() {
    return this._state?.launcherEverVisible;
  },

  get title() {
    return this._title.value;
  },

  set title(value) {
    this._title.value = value;
  },

  /**
   * Toggle the visibility of the sidebar. If the sidebar is hidden or is open
   * with a different commandID, then the sidebar will be opened using the
   * specified commandID. Otherwise the sidebar will be hidden.
   *
   * @param  {string}  commandID     ID of the sidebar.
   * @param  {DOMNode} [triggerNode] Node, usually a button, that triggered the
   *                                 visibility toggling of the sidebar.
   * @returns {Promise}
   */
  toggle(commandID = this.lastOpenedId, triggerNode) {
    if (
      CustomizationHandler.isCustomizing() ||
      CustomizationHandler.isExitingCustomizeMode
    ) {
      return Promise.resolve();
    }
    // First priority for a default value is this.lastOpenedId which is set during show()
    // and not reset in hide(), unlike currentID. If show() hasn't been called and we don't
    // have a persisted command either, or the command doesn't exist anymore, then
    // fallback to a default sidebar.
    if (!commandID) {
      commandID = this._state.command;
    }
    if (!commandID || !this.sidebars.has(commandID)) {
      if (this.sidebarRevampEnabled && this.sidebars.size) {
        commandID = this.sidebars.keys().next().value;
      } else {
        commandID = this.DEFAULT_SIDEBAR_ID;
      }
    }

    if (this.isOpen && commandID == this.currentID) {
      // Revamp sidebar: this case is a dismissal of the current sidebar panel. The launcher should stay open
      // For legacy sidebar, this is a "sidebar" toggle and the current panel should be remembered
      this.hide({ triggerNode, dismissPanel: this.sidebarRevampEnabled });
      this.updateToolbarButton();
      return Promise.resolve();
    }
    return this.show(commandID, triggerNode);
  },

  _getRects(animatingElements) {
    return animatingElements.map(e => [
      e.hidden,
      e.getBoundingClientRect().toJSON(),
    ]);
  },

  /**
   * Wait for Lit updates and ongoing animations to complete.
   *
   * @returns {Promise}
   */
  async waitUntilStable() {
    if (!this.sidebarRevampEnabled) {
      // Legacy sidebar doesn't have animations, nothing to await.
      return null;
    }
    const tasks = [this.sidebarMain.updateComplete];
    if (this._ongoingAnimations?.length) {
      tasks.push(
        ...this._ongoingAnimations.map(animation => animation.finished)
      );
    }
    return Promise.allSettled(tasks);
  },

  async _animateSidebarMain() {
    let tabbox = document.getElementById("tabbrowser-tabbox");
    let animatingElements;
    if (document.documentElement.hasAttribute("sidebar-expand-on-hover")) {
      animatingElements = [this.sidebarContainer];
    } else {
      animatingElements = [
        this.sidebarContainer,
        this._box,
        this._splitter,
        tabbox,
      ];
    }
    let resetElements = () => {
      for (let el of animatingElements) {
        el.style.minWidth =
          el.style.maxWidth =
          el.style.marginLeft =
          el.style.marginRight =
          el.style.display =
            "";
      }
      this.sidebarContainer.toggleAttribute(
        "sidebar-ongoing-animations",
        false
      );
      this._box.toggleAttribute("sidebar-ongoing-animations", false);
      tabbox.toggleAttribute("sidebar-ongoing-animations", false);
    };
    if (this._ongoingAnimations.length) {
      this._ongoingAnimations.forEach(a => a.cancel());
      this._ongoingAnimations = [];
      resetElements();
    }

    let fromRects = this._getRects(animatingElements);

    // We need to wait for lit to re-render, and us to get the final width.
    // This is a bit unfortunate but alas...
    await new Promise(resolve => {
      queueMicrotask(() => resolve(this.sidebarMain.updateComplete));
    });
    let toRects = this._getRects(animatingElements);

    const options = {
      duration: document.documentElement.hasAttribute("sidebar-expand-on-hover")
        ? this._animationExpandOnHoverDurationMs
        : this._animationDurationMs,
      easing: "ease-in-out",
    };
    let animations = [];
    let sidebarOnLeft = this._positionStart != RTL_UI;
    let sidebarShift = 0;
    for (let i = 0; i < animatingElements.length; ++i) {
      const el = animatingElements[i];
      const [wasHidden, from] = fromRects[i];
      const [isHidden, to] = toRects[i];

      // For the sidebar, we need some special cases to make the animation
      // nicer (keeping the icon positions).
      const isSidebar = el === this.sidebarContainer;

      if (wasHidden != isHidden) {
        if (wasHidden) {
          from.left = from.right = sidebarOnLeft ? to.left : to.right;
        } else {
          to.left = to.right = sidebarOnLeft ? from.left : from.right;
        }
      }
      const widthGrowth = to.width - from.width;
      if (isSidebar) {
        sidebarShift = widthGrowth;
      }

      let fromTranslate = sidebarOnLeft
        ? from.left - to.left
        : from.right - to.right;
      let toTranslate = 0;

      // We fix the element to the larger width during the animation if needed,
      // but keeping the right flex width, and thus our original position, with
      // a negative margin.
      el.style.minWidth =
        el.style.maxWidth =
        el.style.marginLeft =
        el.style.marginRight =
        el.style.display =
          "";
      if (isHidden && !wasHidden) {
        el.style.display = "flex";
      }

      if (widthGrowth < 0) {
        el.style.minWidth = el.style.maxWidth = from.width + "px";
        el.style["margin-" + (sidebarOnLeft ? "right" : "left")] =
          widthGrowth + "px";
        if (isSidebar) {
          toTranslate = sidebarOnLeft ? widthGrowth : -widthGrowth;
        } else if (el === this._box) {
          // This is very hacky, but this code doesn't deal well with
          // more than two elements moving, and this is the less invasive change.
          // It would be better to treat "sidebar + sidebar-box" as a unit.
          // We only hit this when completely hiding the box.
          fromTranslate = sidebarOnLeft ? -sidebarShift : sidebarShift;
          toTranslate = sidebarOnLeft
            ? fromTranslate + widthGrowth
            : fromTranslate - widthGrowth;
        }
      } else if (isSidebar) {
        fromTranslate += sidebarOnLeft ? -widthGrowth : widthGrowth;
      }

      animations.push(
        el.animate(
          [
            { translate: `${fromTranslate}px 0 0` },
            { translate: `${toTranslate}px 0 0` },
          ],
          options
        )
      );
      if (!isSidebar || !this._positionStart) {
        continue;
      }
      // We want to keep the buttons in place during the animation, for which
      // we might need to compensate.
      if (!this._state.launcherExpanded) {
        animations.push(
          this.sidebarMain.animate(
            [{ translate: "0" }, { translate: `${-toTranslate}px 0 0` }],
            options
          )
        );
      } else {
        animations.push(
          this.sidebarMain.animate(
            [{ translate: `${-fromTranslate}px 0 0` }, { translate: "0" }],
            options
          )
        );
      }
    }
    this._ongoingAnimations = animations;
    this.sidebarContainer.toggleAttribute("sidebar-ongoing-animations", true);
    this.sidebarMain.toggleAttribute("sidebar-ongoing-animations", true);
    this._box.toggleAttribute("sidebar-ongoing-animations", true);
    tabbox.toggleAttribute("sidebar-ongoing-animations", true);
    await Promise.allSettled(animations.map(a => a.finished));
    if (this._ongoingAnimations === animations) {
      this._ongoingAnimations = [];
      resetElements();
    }
  },

  /**
   * For sidebar.revamp=true only, handle the keyboard or sidebar-button command to toggle the sidebar state
   */
  async handleToolbarButtonClick() {
    if (this.inSingleTabWindow || this.uninitializing) {
      return;
    }

    const initialExpandedValue = this._state.launcherExpanded;

    // What toggle means depends on the sidebar.visibility pref.
    const expandOnToggle = ["always-show", "expand-on-hover"].includes(
      this.sidebarRevampVisibility
    );

    // when the launcher is toggled open by the user, we disable expand-on-hover interactions.
    if (this.sidebarRevampVisibility === "expand-on-hover") {
      await this.toggleExpandOnHover(initialExpandedValue);
    }

    if (this._animationEnabled && !window.gReduceMotion) {
      this._animateSidebarMain();
    }

    if (expandOnToggle) {
      // just expand/collapse the launcher
      this._state.updateVisibility(true, !initialExpandedValue);
      this.updateToolbarButton();
      return;
    }

    const shouldShowLauncher = !this._state.launcherVisible;
    // show/hide the launcher
    this._state.updateVisibility(shouldShowLauncher);
    // if we're showing and there was panel open, open it again
    if (shouldShowLauncher && this._state.command) {
      await this.show(this._state.command);
    } else if (!shouldShowLauncher) {
      // hide the open panel. It will re-open next time as we don't change the command value
      this.hide({ dismissPanel: false });
    }
    this.updateToolbarButton();
  },

  /**
   * Update `checked` state and tooltip text of the toolbar button.
   */
  updateToolbarButton(toolbarButton = this.toolbarButton) {
    if (!toolbarButton || this.inSingleTabWindow) {
      return;
    }
    if (!this.sidebarRevampEnabled) {
      toolbarButton.dataset.l10nId = "show-sidebars";
      toolbarButton.checked = this.isOpen;
    } else {
      let sidebarToggleKey = document.getElementById("toggleSidebarKb");
      const shortcut = ShortcutUtils.prettifyShortcut(sidebarToggleKey);
      toolbarButton.dataset.l10nArgs = JSON.stringify({ shortcut });
      // we need to use the pref rather than SidebarController's getter here
      // as the getter might not have the new value yet
      const isVerticalTabs = Services.prefs.getBoolPref("sidebar.verticalTabs");
      if (isVerticalTabs) {
        toolbarButton.toggleAttribute("expanded", this.sidebarMain.expanded);
      } else {
        toolbarButton.toggleAttribute("expanded", false);
      }
      this.handleToolBadges();
      switch (this.sidebarRevampVisibility) {
        case "always-show":
        case "expand-on-hover":
          // Toolbar button controls expanded state.
          toolbarButton.checked = this.sidebarMain.expanded;
          toolbarButton.dataset.l10nId = toolbarButton.checked
            ? "sidebar-widget-collapse-sidebar2"
            : "sidebar-widget-expand-sidebar2";
          break;
        case "hide-sidebar":
          // Toolbar button controls hidden state.
          toolbarButton.checked = !this.sidebarContainer.hidden;
          toolbarButton.dataset.l10nId = toolbarButton.checked
            ? "sidebar-widget-hide-sidebar2"
            : "sidebar-widget-show-sidebar2";
          break;
      }
    }
  },

  /**
   * Handles badges display for the toolbar and sidebar.
   * Check if a tool(toolID) has requested a badge from pref (i.e) sidebar.notification.badge.{toolID})
   * Ensure that badges are shown or cleared based on the sidebar visibility and user interaction.
   *
   * @param {string|null} toolID
   */
  handleToolBadges(toolID = null) {
    const toolPrefList = this.SidebarManager.getBadgeTools();

    for (const pref of toolPrefList) {
      if (toolID && toolID !== pref) {
        continue;
      }

      const badgePref = Services.prefs.getBoolPref(
        `sidebar.notification.badge.${pref}`,
        false
      );
      const commandID = [...this.toolsAndExtensions.keys()].find(
        id => toolsNameMap[id] === pref
      );

      if (!commandID) {
        continue;
      }

      const isSidebarClosed = !this._state?.launcherVisible;
      const isCurrentView = this._state?.command === commandID;

      // Don't show sidebar badge if sidebar is open and user is already viewing the tool panel
      if (badgePref && isCurrentView && this.isOpen) {
        this.dismissSidebarBadge(commandID);
      }

      if (this.sidebarRevampEnabled && badgePref && isSidebarClosed) {
        this._showToolbarButtonBadge();
      } else {
        this._clearToolbarButtonBadge();
      }

      window.dispatchEvent(new CustomEvent("SidebarItemChanged"));
    }
  },

  _showToolbarButtonBadge() {
    const badgeEl = this.toolbarButton?.querySelector(".toolbarbutton-badge");
    return badgeEl?.classList.add("feature-callout");
  },

  _clearToolbarButtonBadge() {
    const badgeEl = this.toolbarButton?.querySelector(".toolbarbutton-badge");
    return badgeEl?.classList.remove("feature-callout");
  },

  /**
   * Set badge toolID pref false on clicking the tool icon
   *
   * @param {string} view
   */
  dismissSidebarBadge(view) {
    const prefName = `sidebar.notification.badge.${toolsNameMap[view]}`;
    if (Services.prefs.getBoolPref(prefName, false)) {
      Services.prefs.setBoolPref(prefName, false);
    }
  },

  /**
   * Enable the splitter which can be used to resize the launcher.
   */
  _enableLauncherDragging() {
    if (!this._launcherSplitter.hidden) {
      // Already showing the launcher splitter with observers connected.
      // Nothing to do.
      return;
    }
    this._panelResizeObserver = new ResizeObserver(
      ([entry]) => (this._state.panelWidth = entry.contentBoxSize[0].inlineSize)
    );
    this._panelResizeObserver.observe(this._box);

    this._launcherDropHandler = () => (this._state.launcherDragActive = false);
    this._launcherSplitter.addEventListener(
      "command",
      this._launcherDropHandler
    );

    this._launcherSplitter.hidden = false;
  },

  /**
   * Enable the splitter which can be used to resize the pinned tabs container.
   */
  _enablePinnedTabsSplitterDragging() {
    if (!this._pinnedTabsSplitter.hidden) {
      // Already showing the launcher splitter with observers connected.
      // Nothing to do.
      return;
    }
    this._pinnedTabsResizeObserver = new ResizeObserver(() => {
      if (this.isPinnedTabsDragging) {
        this._state.pinnedTabsDragActive = true;
      }
    });

    this._itemsWrapperResizeObserver = new ResizeObserver(async () => {
      await window.promiseDocumentFlushed(() => {
        // Adjust pinned tabs container height if needed
        let itemsWrapperHeight = window.windowUtils.getBoundsWithoutFlushing(
          this._pinnedTabsItemsWrapper
        ).height;
        requestAnimationFrame(() => {
          if (this._state.pinnedTabsHeight > itemsWrapperHeight) {
            this._state.pinnedTabsHeight = itemsWrapperHeight;
            if (this._state.launcherExpanded) {
              this._state.expandedPinnedTabsHeight =
                this._state.pinnedTabsHeight;
            } else {
              this._state.collapsedPinnedTabsHeight =
                this._state.pinnedTabsHeight;
            }
          }
        });
      });
    });
    this._pinnedTabsResizeObserver.observe(this._pinnedTabsContainer);
    this._itemsWrapperResizeObserver.observe(this._pinnedTabsItemsWrapper);

    this._pinnedTabsDropHandler = () =>
      (this._state.pinnedTabsDragActive = false);
    this._pinnedTabsSplitter.addEventListener(
      "command",
      this._pinnedTabsDropHandler
    );

    this._pinnedTabsSplitter.hidden = false;
  },

  /**
   * Disable the launcher splitter and remove any active observers.
   */
  _disableLauncherDragging() {
    if (this._panelResizeObserver) {
      this._panelResizeObserver.disconnect();
    }
    this._launcherSplitter.removeEventListener(
      "command",
      this._launcherDropHandler
    );

    this._launcherSplitter.hidden = true;
  },

  /**
   * Disable the pinned tabs splitter and remove any active observers.
   */
  _disablePinnedTabsDragging() {
    if (this._pinnedTabsResizeObserver) {
      this._pinnedTabsResizeObserver.disconnect();
    }
    if (this._itemsWrapperResizeObserver) {
      this._itemsWrapperResizeObserver.disconnect();
    }

    this._pinnedTabsSplitter.hidden = true;
  },

  _loadSidebarExtension(commandID) {
    let sidebar = this.sidebars.get(commandID);
    if (typeof sidebar?.onload === "function") {
      sidebar.onload();
    }
  },

  /**
   * Ensure tools reflect the current pref state
   */
  refreshTools() {
    let changed = false;
    const tools = new Set(this.sidebarRevampTools.split(","));
    this.toolsAndExtensions.forEach((tool, commandID) => {
      const toolID = toolsNameMap[commandID];
      if (toolID) {
        const expected = !tools.has(toolID);
        if (tool.disabled != expected) {
          tool.disabled = expected;
          changed = true;
        }
      }
    });
    if (changed) {
      window.dispatchEvent(new CustomEvent("SidebarItemChanged"));
    }
  },

  /**
   * Sets the disabled property for a tool when customizing sidebar options
   *
   * @param {string} commandID
   */
  toggleTool(commandID) {
    let toggledTool = this.toolsAndExtensions.get(commandID);
    toggledTool.disabled = !toggledTool.disabled;
    if (!toggledTool.disabled) {
      // If re-enabling tool, remove from the map and add it to the end
      this.toolsAndExtensions.delete(commandID);
      this.toolsAndExtensions.set(commandID, toggledTool);
    }
    // Tools are persisted via a pref.
    if (!Object.hasOwn(toggledTool, "extensionId")) {
      const tools = new Set(this.sidebarRevampTools.split(","));
      const updatedTools = tools.has(toolsNameMap[commandID])
        ? Array.from(tools).filter(
            tool => !!tool && tool != toolsNameMap[commandID]
          )
        : [
            ...Array.from(tools).filter(tool => !!tool),
            toolsNameMap[commandID],
          ];
      Services.prefs.setStringPref(this.TOOLS_PREF, updatedTools.join());
    }
    this.dismissSidebarBadge(commandID);
    window.dispatchEvent(new CustomEvent("SidebarItemChanged"));
  },

  addOrUpdateExtension(commandID, extension) {
    if (this.inSingleTabWindow) {
      return;
    }
    if (this.toolsAndExtensions.has(commandID)) {
      // Update existing extension
      let extensionToUpdate = this.toolsAndExtensions.get(commandID);
      extensionToUpdate.icon = extension.icon;
      extensionToUpdate.iconUrl = extension.iconUrl;
      extensionToUpdate.tooltiptext = extension.label;
      window.dispatchEvent(new CustomEvent("SidebarItemChanged"));
    } else {
      // Add new extension
      this.toolsAndExtensions.set(commandID, {
        view: commandID,
        extensionId: extension.extensionId,
        icon: extension.icon,
        iconUrl: extension.iconUrl,
        tooltiptext: extension.label,
        disabled: false,
      });
      window.dispatchEvent(new CustomEvent("SidebarItemAdded"));
    }
  },

  /**
   * Add menu items for a browser extension. Add the extension to the
   * `sidebars` map.
   *
   * @param {string} commandID
   * @param {object} props
   */
  registerExtension(commandID, props) {
    const sidebar = {
      title: props.title,
      url: "chrome://browser/content/webext-panels.xhtml",
      menuId: props.menuId,
      switcherMenuId: `sidebarswitcher_menu_${commandID}`,
      keyId: `ext-key-id-${commandID}`,
      label: props.title,
      icon: props.icon,
      iconUrl: props.iconUrl,
      classAttribute: "menuitem-iconic webextension-menuitem",
      // The following properties are specific to extensions
      extensionId: props.extensionId,
      onload: props.onload,
    };
    this.sidebars.set(commandID, sidebar);

    // Insert a menuitem for View->Show Sidebars.
    const menuitem = this.createMenuItem(commandID, sidebar);
    document.getElementById("viewSidebarMenu").appendChild(menuitem);
    this.addOrUpdateExtension(commandID, sidebar);

    if (!this.sidebarRevampEnabled) {
      // Insert a toolbarbutton for the sidebar dropdown selector.
      let switcherMenuitem = this.createMenuItem(commandID, sidebar);
      switcherMenuitem.setAttribute("id", sidebar.switcherMenuId);
      switcherMenuitem.removeAttribute("type");

      let separator = document.getElementById("sidebar-extensions-separator");
      separator.parentNode.insertBefore(switcherMenuitem, separator);
    }
    this._setExtensionAttributes(
      commandID,
      { icon: props.icon, iconUrl: props.iconUrl, label: props.title },
      sidebar
    );
  },

  /**
   * Create a menu item for the View>Sidebars submenu in the menubar.
   *
   * @param {string} commandID
   * @param {object} sidebar
   * @returns {Element}
   */
  createMenuItem(commandID, sidebar) {
    const menuitem = document.createXULElement("menuitem");
    menuitem.setAttribute("id", sidebar.menuId);
    menuitem.setAttribute("type", "checkbox");
    // Some menu items get checkbox type removed, so should show the sidebar
    menuitem.addEventListener("command", () =>
      this[menuitem.hasAttribute("type") ? "toggle" : "show"](commandID)
    );
    if (sidebar.classAttribute) {
      menuitem.setAttribute("class", sidebar.classAttribute);
    }
    if (sidebar.keyId) {
      menuitem.setAttribute("key", sidebar.keyId);
    }
    if (sidebar.menuL10nId) {
      menuitem.dataset.l10nId = sidebar.menuL10nId;
    }
    if (this.inSingleTabWindow) {
      menuitem.setAttribute("disabled", "true");
    }
    return menuitem;
  },

  /**
   * Update attributes on all existing menu items for a browser extension.
   *
   * @param {string} commandID
   * @param {object} attributes
   * @param {string} attributes.icon
   * @param {string} attributes.iconUrl
   * @param {string} attributes.label
   * @param {boolean} needsRefresh
   */
  setExtensionAttributes(commandID, attributes, needsRefresh) {
    const sidebar = this.sidebars.get(commandID);
    this._setExtensionAttributes(commandID, attributes, sidebar, needsRefresh);
    this.addOrUpdateExtension(commandID, sidebar);
  },

  _setExtensionAttributes(
    commandID,
    { icon, iconUrl, label },
    sidebar,
    needsRefresh = false
  ) {
    sidebar.icon = icon;
    sidebar.iconUrl = iconUrl;
    sidebar.label = label;

    const updateAttributes = el => {
      el.style.setProperty("--webextension-menuitem-image", sidebar.icon);
      el.setAttribute("label", sidebar.label);
    };

    updateAttributes(document.getElementById(sidebar.menuId), sidebar);
    const switcherMenu = document.getElementById(sidebar.switcherMenuId);
    if (switcherMenu) {
      updateAttributes(switcherMenu, sidebar);
    }
    if (this.initialized && this.currentID === commandID) {
      // Update the sidebar title if this extension is the current sidebar.
      this.title = label;
      if (this.isOpen && needsRefresh) {
        this.show(commandID);
      }
    }
  },

  /**
   * Retrieve the list of registered browser extensions.
   *
   * @returns {Array}
   */
  getExtensions() {
    const extensions = [];
    for (const [commandID, sidebar] of this.sidebars.entries()) {
      if (Object.hasOwn(sidebar, "extensionId")) {
        extensions.push({
          commandID,
          view: commandID,
          extensionId: sidebar.extensionId,
          iconUrl: sidebar.iconUrl,
          tooltiptext: sidebar.label,
          disabled: false,
        });
      }
    }
    return extensions;
  },

  /**
   * Retrieve the list of tools in the sidebar
   *
   * @returns {Array}
   */
  getTools() {
    return Object.keys(toolsNameMap)
      .filter(commandID => this.sidebars.get(commandID))
      .map(commandID => {
        const sidebar = this.sidebars.get(commandID);
        const disabled = !this.sidebarRevampTools
          .split(",")
          .includes(toolsNameMap[commandID]);
        return {
          commandID,
          view: commandID,
          iconUrl: sidebar.iconUrl,
          l10nId: sidebar.revampL10nId,
          disabled,
          // Reflect the current tool state defaulting to visible
          get hidden() {
            return !(sidebar.visible ?? true);
          },
          get attention() {
            return sidebar.attention ?? false;
          },
        };
      });
  },

  /**
   * Remove a browser extension.
   *
   * @param {string} commandID
   */
  removeExtension(commandID) {
    if (this.inSingleTabWindow) {
      return;
    }
    const sidebar = this.sidebars.get(commandID);
    if (!sidebar) {
      return;
    }
    if (this.currentID === commandID) {
      // If the extension removal is a update, we don't want to forget this panel.
      // So, let the sidebarAction extension API code remove the lastOpenedId as needed
      this.hide({ dismissPanel: false });
    }
    document.getElementById(sidebar.menuId)?.remove();
    document.getElementById(sidebar.switcherMenuId)?.remove();
    this.sidebars.delete(commandID);
    this.toolsAndExtensions.delete(commandID);
    window.dispatchEvent(new CustomEvent("SidebarItemRemoved"));
  },

  /**
   * Show the sidebar.
   *
   * This wraps the internal method, including a ping to telemetry.
   *
   * @param {string}  commandID     ID of the sidebar to use.
   * @param {DOMNode} [triggerNode] Node, usually a button, that triggered the
   *                                showing of the sidebar.
   * @returns {Promise<boolean>}
   */
  async show(commandID, triggerNode) {
    if (this.inSingleTabWindow) {
      return false;
    }
    if (this.currentID && commandID !== this.currentID) {
      // If there is currently a panel open, we are about to hide it in order
      // to show another one, so record a "hide" event on the current panel.
      this._recordPanelToggle(this.currentID, false);
    }
    this._recordPanelToggle(commandID, true);

    // Extensions without private window access wont be in the
    // sidebars map.
    if (!this.sidebars.has(commandID)) {
      return false;
    }
    return this._show(commandID).then(() => {
      this._loadSidebarExtension(commandID);

      if (triggerNode) {
        updateToggleControlLabel(triggerNode);
      }
      this.updateToolbarButton();
      this.dismissSidebarBadge(commandID);

      this._fireFocusedEvent();
      return true;
    });
  },

  /**
   * Show the sidebar, without firing the focused event or logging telemetry.
   * This is intended to be used when the sidebar is opened automatically
   * when a window opens (not triggered by user interaction).
   *
   * @param {string} commandID ID of the sidebar.
   * @returns {Promise<boolean>}
   */
  async showInitially(commandID) {
    if (this.inSingleTabWindow) {
      return false;
    }
    this._recordPanelToggle(commandID, true);

    // Extensions without private window access wont be in the
    // sidebars map.
    if (!this.sidebars.has(commandID)) {
      return false;
    }
    return this._show(commandID).then(() => {
      this._loadSidebarExtension(commandID);
      return true;
    });
  },

  /**
   * Implementation for show. Also used internally for sidebars that are shown
   * when a window is opened and we don't want to ping telemetry.
   *
   * @param {string} commandID ID of the sidebar.
   * @returns {Promise<void>}
   */
  _show(commandID) {
    return new Promise(resolve => {
      this._state.panelOpen = true;
      if (this.sidebarRevampEnabled) {
        this._box.dispatchEvent(
          new CustomEvent("sidebar-show", { detail: { viewId: commandID } })
        );
      } else {
        this.hideSwitcherPanel();
      }

      this.selectMenuItem(commandID);
      this._box.hidden = this._splitter.hidden = false;

      this._box.setAttribute("checked", "true");
      this._state.command = commandID;

      let { icon, url, title, sourceL10nEl, contextMenuId } =
        this.sidebars.get(commandID);
      if (icon) {
        this._switcherTarget.style.setProperty(
          "--webextension-menuitem-image",
          icon
        );
      } else {
        this._switcherTarget.style.removeProperty(
          "--webextension-menuitem-image"
        );
      }

      if (contextMenuId) {
        this._box.setAttribute("context", contextMenuId);
      } else {
        this._box.removeAttribute("context");
      }

      // use to live update <tree> elements if the locale changes
      this.lastOpenedId = commandID;
      // These title changes only apply to the old sidebar menu
      if (!this.sidebarRevampEnabled) {
        this.title = title;
        // Keep the title element in the switcher in sync with any l10n changes.
        this.observeTitleChanges(sourceL10nEl);
      }

      this.browser.setAttribute("src", url); // kick off async load

      if (this.browser.contentDocument.location.href != url) {
        // make sure to clear the timeout if the load is aborted
        this.browser.addEventListener("unload", () => {
          if (this.browser.loadingTimerID) {
            clearTimeout(this.browser.loadingTimerID);
            delete this.browser.loadingTimerID;
            resolve();
          }
        });
        this.browser.addEventListener(
          "load",
          () => {
            // We're handling the 'load' event before it bubbles up to the usual
            // (non-capturing) event handlers. Let it bubble up before resolving.
            this.browser.loadingTimerID = setTimeout(() => {
              delete this.browser.loadingTimerID;
              resolve();

              // Now that the currentId is updated, fire a show event.
              this._fireShowEvent();
              this._recordBrowserSize();
            }, 0);
          },
          { capture: true, once: true }
        );
      } else {
        resolve();

        // Now that the currentId is updated, fire a show event.
        this._fireShowEvent();
        this._recordBrowserSize();
      }
    });
  },

  /**
   * Hide the sidebar.
   *
   * @param {object} options - Parameter object.
   * @param {DOMNode} options.triggerNode - Node, usually a button, that triggered the
   *                                        hiding of the sidebar.
   * @param {boolean} options.dismissPanel -Only close the panel or close the whole sidebar (the default.)
   */
  hide({ triggerNode, dismissPanel = this.sidebarRevampEnabled } = {}) {
    if (!this.isOpen) {
      return;
    }

    const willHideEvent = new CustomEvent("SidebarWillHide", {
      cancelable: true,
    });
    this.browser.contentWindow?.dispatchEvent(willHideEvent);
    if (willHideEvent.defaultPrevented) {
      return;
    }

    this.hideSwitcherPanel();
    this._recordPanelToggle(this.currentID, false);
    this._state.panelOpen = false;
    if (dismissPanel) {
      // The user is explicitly closing this panel so we don't want it to
      // automatically re-open next time the sidebar is shown
      this._state.command = "";
      this.lastOpenedId = null;
    }

    if (this.sidebarRevampEnabled) {
      this._box.dispatchEvent(new CustomEvent("sidebar-hide"));
    }
    this.selectMenuItem("");

    // Replace the document currently displayed in the sidebar with about:blank
    // so that we can free memory by unloading the page. We need to explicitly
    // create a new content viewer because the old one doesn't get destroyed
    // until about:blank has loaded (which does not happen as long as the
    // element is hidden).
    this.browser.setAttribute("src", "about:blank");
    this.browser.docShell?.createAboutBlankDocumentViewer(null, null);

    this._box.removeAttribute("checked");
    this._box.removeAttribute("context");
    this._box.hidden = this._splitter.hidden = true;

    let selBrowser = gBrowser.selectedBrowser;
    selBrowser.focus();
    if (triggerNode) {
      updateToggleControlLabel(triggerNode);
    }
    this.updateToolbarButton();
  },

  /**
   * Record to Glean when any of the sidebar panels is loaded or unloaded.
   *
   * @param {string} commandID
   * @param {boolean} opened
   */
  _recordPanelToggle(commandID, opened) {
    const sidebar = this.sidebars.get(commandID);
    if (!sidebar) {
      return;
    }
    const isExtension = sidebar && Object.hasOwn(sidebar, "extensionId");
    const version = this.sidebarRevampEnabled ? "new" : "old";
    if (isExtension) {
      const addonId = sidebar.extensionId;
      const addonName = WebExtensionPolicy.getByID(addonId)?.name;
      Glean.extension.sidebarToggle.record({
        opened,
        version,
        addon_id: AMTelemetry.getTrimmedString(addonId),
        addon_name: addonName && AMTelemetry.getTrimmedString(addonName),
      });
    } else if (sidebar.gleanEvent && sidebar.recordSidebarVersion) {
      sidebar.gleanEvent.record({ opened, version });
    } else if (sidebar.gleanEvent) {
      sidebar.gleanEvent.record({ opened });
    }
  },

  /**
   * Record to Glean when any of the sidebar icons are clicked.
   *
   * @param {string} commandID - Command ID of the icon.
   * @param {boolean} expanded - Whether the sidebar was expanded when clicked.
   */
  recordIconClick(commandID, expanded) {
    const sidebar = this.sidebars.get(commandID);
    const isExtension = sidebar && Object.hasOwn(sidebar, "extensionId");
    if (isExtension) {
      const addonId = sidebar.extensionId;
      Glean.sidebar.addonIconClick.record({
        sidebar_open: expanded,
        addon_id: AMTelemetry.getTrimmedString(addonId),
      });
    } else if (sidebar.gleanClickEvent) {
      sidebar.gleanClickEvent.record({
        sidebar_open: expanded,
      });
    }
  },

  /**
   * Sets the checked state only on the menu items of the specified sidebar, or
   * none if the argument is an empty string.
   */
  selectMenuItem(commandID) {
    for (let [id, { menuId, triggerButtonId }] of this.sidebars) {
      let menu = document.getElementById(menuId);
      if (!menu) {
        continue;
      }
      let triggerbutton =
        triggerButtonId && document.getElementById(triggerButtonId);
      if (id == commandID) {
        menu.setAttribute("checked", "true");
        if (triggerbutton) {
          triggerbutton.setAttribute("checked", "true");
          updateToggleControlLabel(triggerbutton);
        }
      } else {
        menu.removeAttribute("checked");
        if (triggerbutton) {
          triggerbutton.removeAttribute("checked");
          updateToggleControlLabel(triggerbutton);
        }
      }
    }
  },

  toggleTabstrip() {
    let toVerticalTabs = CustomizableUI.verticalTabsEnabled;
    let tabStrip = gBrowser.tabContainer;
    let arrowScrollbox = tabStrip.arrowScrollbox;
    let currentScrollOrientation = arrowScrollbox.getAttribute("orient");

    if (
      (!toVerticalTabs && currentScrollOrientation !== "vertical") ||
      (toVerticalTabs && currentScrollOrientation === "vertical")
    ) {
      // Nothing to update
      return;
    }

    if (toVerticalTabs) {
      arrowScrollbox.setAttribute("orient", "vertical");
      tabStrip.setAttribute("orient", "vertical");
      this._clearToolbarButtonBadge();
    } else {
      arrowScrollbox.setAttribute("orient", "horizontal");
      tabStrip.removeAttribute("expanded");
      tabStrip.setAttribute("orient", "horizontal");
    }

    let verticalToolbar = document.getElementById(
      CustomizableUI.AREA_VERTICAL_TABSTRIP
    );
    verticalToolbar.toggleAttribute("visible", toVerticalTabs);
    // Re-render sidebar-main so that templating is updated
    // for proper keyboard navigation for Tools
    this.sidebarMain.requestUpdate();
    if (
      !this.verticalTabsEnabled &&
      this.sidebarRevampVisibility == "hide-sidebar"
    ) {
      // the sidebar.visibility pref didn't change so launcherExpanded hasn't
      // been updated; we need to set it here to un-expand the launcher
      this._state.launcherExpanded = false;
    }
  },

  debouncedMouseEnter() {
    const contentArea = document.getElementById("tabbrowser-tabbox");
    this._box.toggleAttribute("sidebar-launcher-hovered", true);
    contentArea.toggleAttribute("sidebar-launcher-hovered", true);
    this._state.launcherHoverActive = true;
    if (this._animationEnabled && !window.gReduceMotion) {
      this._animateSidebarMain();
    }
    this._state.launcherExpanded = true;
  },

  onMouseLeave() {
    this.mouseEnterTask.disarm();
    const contentArea = document.getElementById("tabbrowser-tabbox");
    this._box.toggleAttribute("sidebar-launcher-hovered", false);
    contentArea.toggleAttribute("sidebar-launcher-hovered", false);
    this._state.launcherHoverActive = false;
    if (this._animationEnabled && !window.gReduceMotion) {
      this._animateSidebarMain();
    }
    this._state.launcherExpanded = false;
  },

  onMouseEnter() {
    this.mouseEnterTask = new DeferredTask(
      () => {
        this.debouncedMouseEnter();
      },
      EXPAND_ON_HOVER_DEBOUNCE_RATE_MS,
      EXPAND_ON_HOVER_DEBOUNCE_TIMEOUT_MS
    );
    this.mouseEnterTask?.arm();
  },

  async setLauncherCollapsedWidth() {
    let browserEl = document.getElementById("browser");
    if (this.getUIState().launcherExpanded) {
      this._state.launcherExpanded = false;
    }
    await this.waitUntilStable();
    let collapsedWidth = await new Promise(resolve => {
      requestAnimationFrame(() => {
        resolve(this._getRects([this.sidebarMain])[0][1].width);
      });
    });

    browserEl.style.setProperty(
      "--sidebar-launcher-collapsed-width",
      `${collapsedWidth}px`
    );
  },

  getMouseTargetRect() {
    let launcherRect = window.windowUtils.getBoundsWithoutFlushing(
      SidebarController.sidebarMain
    );
    return {
      top: launcherRect.top,
      bottom: launcherRect.bottom,
      left: this._positionStart
        ? launcherRect.left
        : launcherRect.left + LAUNCHER_SPLITTER_WIDTH,
      right: this._positionStart
        ? launcherRect.right - LAUNCHER_SPLITTER_WIDTH
        : launcherRect.right,
    };
  },

  async handleEvent(e) {
    switch (e.type) {
      case "popupshown":
        /* Temporarily remove MousePosTracker listener when a context menu is open */
        if (e.composedTarget.id !== "tab-preview-panel") {
          this._openPopupsCount++;
          MousePosTracker.removeListener(this);
        }
        break;
      case "popuphidden":
        if (e.composedTarget.id !== "tab-preview-panel") {
          if (this._openPopupsCount < 2) {
            let isHovered;
            MousePosTracker._callListener({
              onMouseEnter: () => (isHovered = true),
              onMouseLeave: () => (isHovered = false),
              getMouseTargetRect: () => this.getMouseTargetRect(),
            });
            // Collapse sidebar after context menu is closed if needed
            if (this._state.launcherExpanded && !isHovered) {
              if (this._animationEnabled && !window.gReduceMotion) {
                this._animateSidebarMain();
              }
              this._state.launcherExpanded = false;
              await this.waitUntilStable();
            }
            MousePosTracker.addListener(this);
          }
          this._openPopupsCount--;
        }
        break;
      default:
        break;
    }
  },

  async toggleExpandOnHover(isEnabled, isDragEnded) {
    document.documentElement.toggleAttribute(
      "sidebar-expand-on-hover",
      isEnabled
    );
    if (isEnabled) {
      if (!this._state) {
        this._state = new this.SidebarState(this);
      }
      await this.waitUntilStable();
      MousePosTracker.addListener(this);
      if (!isDragEnded) {
        await this.setLauncherCollapsedWidth();
      }
      document.addEventListener("popupshown", this);
      document.addEventListener("popuphidden", this);
      // Reset user-preferred height
      this.sidebarMain.buttonGroup.style.height = this._state.launcherExpanded
        ? ""
        : "0";
    } else {
      MousePosTracker.removeListener(this);
      if (!this.mouseOverTask?.isFinalized) {
        this.mouseOverTask?.finalize();
      }
      document.removeEventListener("popupshown", this);
      document.removeEventListener("popuphidden", this);
      // Add back user-preferred height if defined
      if (
        this._state.launcherExpanded &&
        this._state.expandedToolsHeight !== undefined &&
        this.sidebarMain.buttonGroup
      ) {
        this.sidebarMain.buttonGroup.style.height =
          this._state.expandedToolsHeight;
      } else if (
        !this._state.launcherExpanded &&
        this._state.collapsedToolsHeight !== undefined &&
        this.sidebarMain.buttonGroup
      ) {
        this.sidebarMain.buttonGroup.style.height =
          this._state.collapsedToolsHeight;
      }
    }

    document.documentElement.toggleAttribute(
      "sidebar-expand-on-hover",
      isEnabled
    );
  },

  /**
   * Report visibility preference to Glean.
   *
   * @param {string} [value] - The preference value.
   */
  recordVisibilitySetting(value = this.sidebarRevampVisibility) {
    let visibilitySetting = "hide";
    if (value === "always-show") {
      visibilitySetting = "always";
    } else if (value === "expand-on-hover") {
      visibilitySetting = "expand-on-hover";
    }
    Glean.sidebar.displaySettings.set(visibilitySetting);
  },

  /**
   * Report position preference to Glean.
   *
   * @param {boolean} [value] - The preference value.
   */
  recordPositionSetting(value = this._positionStart) {
    Glean.sidebar.positionSettings.set(value !== RTL_UI ? "left" : "right");
  },

  /**
   * Report tabs layout preference to Glean.
   *
   * @param {boolean} [value] - The preference value.
   */
  recordTabsLayoutSetting(value = this.sidebarVerticalTabsEnabled) {
    Glean.sidebar.tabsLayout.set(value ? "vertical" : "horizontal");
  },
};

ChromeUtils.defineESModuleGetters(SidebarController, {
  SidebarManager:
    "moz-src:///browser/components/sidebar/SidebarManager.sys.mjs",
  SidebarState: "moz-src:///browser/components/sidebar/SidebarState.sys.mjs",
});

// Add getters related to the position here, since we will want them
// available for both startDelayedLoad and init.
XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "_positionStart",
  SidebarController.POSITION_START_PREF,
  true,
  (_aPreference, _previousValue, newValue) => {
    if (
      !SidebarController.uninitializing &&
      !SidebarController.inSingleTabWindow
    ) {
      SidebarController.setPosition();
      SidebarController.recordPositionSetting(newValue);
    }
  }
);
XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "_animationEnabled",
  "sidebar.animation.enabled",
  true
);
XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "_animationDurationMs",
  "sidebar.animation.duration-ms",
  200
);
XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "_animationExpandOnHoverDurationMs",
  "sidebar.animation.expand-on-hover.duration-ms",
  400
);
XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "sidebarRevampEnabled",
  "sidebar.revamp",
  false,
  (_aPreference, _previousValue, newValue) => {
    if (!SidebarController.uninitializing) {
      SidebarController.toggleRevampSidebar();
      SidebarController._state.revampEnabled = newValue;
    }
  }
);
XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "sidebarRevampTools",
  "sidebar.main.tools",
  "",
  () => {
    if (
      !SidebarController.inSingleTabWindow &&
      !SidebarController.uninitializing
    ) {
      SidebarController.refreshTools();
    }
  }
);

XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "sidebarRevampVisibility",
  "sidebar.visibility",
  "always-show",
  (_aPreference, _previousValue, newValue) => {
    if (
      !SidebarController.inSingleTabWindow &&
      !SidebarController.uninitializing
    ) {
      SidebarController.toggleExpandOnHover(newValue === "expand-on-hover");
      SidebarController.recordVisibilitySetting(newValue);
      if (SidebarController._state) {
        // we need to use the pref rather than SidebarController's getter here
        // as the getter might not have the new value yet
        const isVerticalTabs = Services.prefs.getBoolPref(
          "sidebar.verticalTabs"
        );
        SidebarController._state.revampVisibility = newValue;
        if (
          SidebarController._animationEnabled &&
          !window.gReduceMotion &&
          newValue !== "expand-on-hover"
        ) {
          SidebarController._animateSidebarMain();
        }

        // launcher is always initially expanded with vertical tabs unless we're doing expand-on-hover
        let forceExpand = false;
        if (
          isVerticalTabs &&
          ["always-show", "hide-sidebar"].includes(newValue)
        ) {
          forceExpand = true;
        }

        // horizontal tabs and hide-sidebar = visible initially.
        // vertical tab and hide-sidebar = not visible initially
        let showLauncher = true;
        if (newValue == "hide-sidebar" && isVerticalTabs) {
          showLauncher = false;
        }
        SidebarController._state.updateVisibility(showLauncher, forceExpand);
      }
      SidebarController.updateToolbarButton();
    }
  }
);

XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "sidebarVerticalTabsEnabled",
  "sidebar.verticalTabs",
  false,
  (_aPreference, _previousValue, newValue) => {
    if (
      !SidebarController.uninitializing &&
      !SidebarController.inSingleTabWindow
    ) {
      SidebarController.recordTabsLayoutSetting(newValue);
      if (newValue) {
        SidebarController._enablePinnedTabsSplitterDragging();
      } else {
        SidebarController._disablePinnedTabsDragging();
      }
      SidebarController._state.updatePinnedTabsHeight();
      SidebarController._state.updateToolsHeight();
    }
  }
);

XPCOMUtils.defineLazyPreferenceGetter(
  SidebarController,
  "revampDefaultLauncherVisible",
  "sidebar.revamp.defaultLauncherVisible",
  false,
  (_aPreference, _previousValue, _newValue) => {
    if (
      !SidebarController.uninitializing &&
      !SidebarController.inSingleTabWindow
    ) {
      SidebarController._state.updateVisibility();
    }
  }
);