summaryrefslogtreecommitdiffstats
path: root/comm/mail/base/content/spacesToolbar.js
blob: 4155d7d0dc8bac9d397aaef55d5fbafebbbcae02 (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
/* 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/. */

"use strict";

/* import-globals-from mailCore.js */
/* import-globals-from utilityOverlay.js */

/**
 * Special vertical toolbar to organize all the buttons opening a tab.
 */
var gSpacesToolbar = {
  SUPPORTED_BADGE_STYLES: ["--spaces-button-badge-bg-color"],
  SUPPORTED_ICON_STYLES: [
    "--webextension-toolbar-image",
    "--webextension-toolbar-image-dark",
    "--webextension-toolbar-image-light",
    "--webextension-toolbar-image-2x",
    "--webextension-toolbar-image-2x-dark",
    "--webextension-toolbar-image-2x-light",
  ],
  docURL: "chrome://messenger/content/messenger.xhtml",
  /**
   * The spaces toolbar DOM element.
   *
   * @type {?HTMLElement}
   */
  element: null,
  /**
   * If the spaces toolbar has already been loaded.
   *
   * @type {boolean}
   */
  isLoaded: false,
  /**
   * If the spaces toolbar is hidden or visible.
   *
   * @type {boolean}
   */
  isHidden: false,
  /**
   * If the spaces toolbar is currently being customized.
   *
   * @type {boolean}
   */
  isCustomizing: false,
  /**
   * The DOM element panel collecting all customization options.
   */
  customizePanel: null,
  /**
   * The object storing all saved customization options:
   * - background: The toolbar background color.
   * - color: The default icon color of the buttons.
   * - accentColor: The background color of an active/current button.
   * - accentBackground: The icon color of an active/current button.
   */
  customizeData: {},

  /**
   * @callback TabInSpace
   * @param {object} tabInfo - The tabInfo object (a member of tabmail.tabInfo)
   *   for the tab.
   * @returns {0|1|2} - The relation between the tab and the space. 0 means it
   *   does not belong to the space. 1 means it is a primary tab of the space.
   *   2 means it is a secondary tab of the space.
   */
  /**
   * @callback OpenSpace
   * @param {"tab"|"window"} where - Where to open the space: in a new tab or in
   *   a new window.
   * @returns {?object | Window} - The tabInfo for the newly opened tab, or the
   *   newly opened messenger window, or null if neither was created.
   */
  /**
   * Data and methods for a space.
   *
   * @typedef {object} SpaceInfo
   * @property {string} name - The name for this space.
   * @property {boolean} allowMultipleTabs - Whether to allow the user to open
   *   multiple tabs in this space.
   * @property {HTMLButtonElement} button - The toolbar button for this space.
   * @property {?XULMenuItem} menuitem - The menuitem for this space, if
   *   available.
   * @property {TabInSpace} tabInSpace - A callback that determines whether an
   *   existing tab is considered outside this space, a primary tab of this
   *   space (a tab that is similar to the tab created by the open method) or
   *   a secondary tab of this space (a related tab that still belongs to this
   *   space).
   * @property {OpenSpace} open - A callback to open this space.
   */
  /**
   * The main spaces in this toolbar. This will be constructed on load.
   *
   * @type {?SpaceInfo[]}
   */
  spaces: null,
  /**
   * The current space the window is in, or undefined if it is not in any of the
   * known spaces.
   *
   * @type {SpaceInfo|undefined}
   */
  currentSpace: undefined,
  /**
   * The number of buttons created by add-ons.
   *
   * @returns {integer}
   */
  get addonButtonCount() {
    return document.querySelectorAll(".spaces-addon-button").length;
  },
  /**
   * The number of pixel spacing to add to the add-ons button height calculation
   * based on the current UI density.
   *
   * @type {integer}
   */
  densitySpacing: 0,
  /**
   * The button that can receive focus. Used for managing focus with a roving
   * tabindex.
   *
   * @type {?HTMLElement}
   */
  focusButton: null,

  tabMonitor: {
    monitorName: "spacesToolbarMonitor",

    onTabTitleChanged() {},
    onTabOpened() {},
    onTabPersist() {},
    onTabRestored() {},
    onTabClosing() {},

    onTabSwitched(newTabInfo, oldTabInfo) {
      // Bail out if for whatever reason something went wrong.
      if (!newTabInfo) {
        console.error(
          "Spaces Toolbar: Missing new tab on monitored tab switching"
        );
        return;
      }

      let tabSpace = gSpacesToolbar.spaces.find(space =>
        space.tabInSpace(newTabInfo)
      );
      if (gSpacesToolbar.currentSpace != tabSpace) {
        gSpacesToolbar.currentSpace?.button.classList.remove("current");
        gSpacesToolbar.currentSpace?.menuitem?.classList.remove("current");
        gSpacesToolbar.currentSpace = tabSpace;
        if (gSpacesToolbar.currentSpace) {
          gSpacesToolbar.currentSpace.button.classList.add("current");
          gSpacesToolbar.currentSpace.menuitem?.classList.add("current");
          gSpacesToolbar.setFocusButton(gSpacesToolbar.currentSpace.button);
        }

        const spaceChangeEvent = new CustomEvent("spacechange", {
          detail: tabSpace,
        });
        gSpacesToolbar.element.dispatchEvent(spaceChangeEvent);
      }
    },
  },

  /**
   * Convert an rgb() string to an hexadecimal color string.
   *
   * @param {string} color - The RGBA color string that needs conversion.
   * @returns {string} - The converted hexadecimal color.
   */
  _rgbToHex(color) {
    let rgb = color.split("(")[1].split(")")[0].split(",");

    // For each array element convert ot a base16 string and add zero if we get
    // only one character.
    let hash = rgb.map(x => parseInt(x).toString(16).padStart(2, "0"));

    return `#${hash.join("")}`;
  },

  onLoad() {
    if (this.isLoaded) {
      return;
    }

    this.element = document.getElementById("spacesToolbar");
    this.focusButton = document.getElementById("mailButton");
    let tabmail = document.getElementById("tabmail");

    this.spaces = [
      {
        name: "mail",
        button: document.getElementById("mailButton"),
        menuitem: document.getElementById("spacesPopupButtonMail"),
        tabInSpace(tabInfo) {
          switch (tabInfo.mode.name) {
            case "folder":
            case "mail3PaneTab":
            case "mailMessageTab":
              return 1;
            default:
              return 0;
          }
        },
        open(where) {
          // Prefer the current tab, else the earliest tab.
          let existingTab = [tabmail.currentTabInfo, ...tabmail.tabInfo].find(
            tabInfo => this.tabInSpace(tabInfo) == 1
          );
          let folderURI = null;
          switch (existingTab?.mode.name) {
            case "folder":
              folderURI =
                existingTab.folderDisplay.displayedFolder?.URI || null;
              break;
            case "mail3PaneTab":
              folderURI = existingTab.folder.URI || null;
              break;
          }
          if (where == "window") {
            return window.openDialog(
              "chrome://messenger/content/messenger.xhtml",
              "_blank",
              "chrome,dialog=no,all",
              folderURI,
              -1
            );
          }
          return openTab("mail3PaneTab", { folderURI }, "tab");
        },
        allowMultipleTabs: true,
      },
      {
        name: "addressbook",
        button: document.getElementById("addressBookButton"),
        menuitem: document.getElementById("spacesPopupButtonAddressBook"),
        tabInSpace(tabInfo) {
          if (tabInfo.mode.name == "addressBookTab") {
            return 1;
          }
          return 0;
        },
        open(where) {
          return openTab("addressBookTab", {}, where);
        },
      },
      {
        name: "calendar",
        button: document.getElementById("calendarButton"),
        menuitem: document.getElementById("spacesPopupButtonCalendar"),
        tabInSpace(tabInfo) {
          return tabInfo.mode.name == "calendar" ? 1 : 0;
        },
        open(where) {
          return openTab("calendar", {}, where);
        },
      },
      {
        name: "tasks",
        button: document.getElementById("tasksButton"),
        menuitem: document.getElementById("spacesPopupButtonTasks"),
        tabInSpace(tabInfo) {
          return tabInfo.mode.name == "tasks" ? 1 : 0;
        },
        open(where) {
          return openTab("tasks", {}, where);
        },
      },
      {
        name: "chat",
        button: document.getElementById("chatButton"),
        menuitem: document.getElementById("spacesPopupButtonChat"),
        tabInSpace(tabInfo) {
          return tabInfo.mode.name == "chat" ? 1 : 0;
        },
        open(where) {
          return openTab("chat", {}, where);
        },
      },
      {
        name: "settings",
        button: document.getElementById("settingsButton"),
        menuitem: document.getElementById("spacesPopupButtonSettings"),
        tabInSpace(tabInfo) {
          switch (tabInfo.mode.name) {
            case "preferencesTab":
              // A primary tab that the open method creates.
              return 1;
            case "contentTab":
              let url = tabInfo.urlbar?.value;
              if (url == "about:accountsettings" || url == "about:addons") {
                // A secondary tab, that is related to this space.
                return 2;
              }
          }
          return 0;
        },
        open(where) {
          return openTab("preferencesTab", {}, where);
        },
      },
    ];

    this.setupEventListeners();
    this.toggleToolbar(
      Services.xulStore.getValue(this.docURL, "spacesToolbar", "hidden") ==
        "true"
    );

    // The tab monitor will inform us when a different tab is selected.
    tabmail.registerTabMonitor(this.tabMonitor);

    this.customizePanel = document.getElementById(
      "spacesToolbarCustomizationPanel"
    );
    this.loadCustomization();

    this.isLoaded = true;
    window.dispatchEvent(new CustomEvent("spaces-toolbar-ready"));
    // Update the window UI after the spaces toolbar has been loaded.
    this.updateUI();
  },

  setupEventListeners() {
    this.element.addEventListener("contextmenu", event =>
      this._showContextMenu(event)
    );
    this.element.addEventListener("keydown", event => {
      this._onSpacesToolbarKeyDown(event);
    });

    // Prevent buttons from stealing the focus on click since the focus is
    // handled when a specific tab is opened or switched to.
    for (let button of document.querySelectorAll(".spaces-toolbar-button")) {
      button.onmousedown = event => event.preventDefault();
    }

    let tabmail = document.getElementById("tabmail");
    let contextMenu = document.getElementById("spacesContextMenu");
    let newTabItem = document.getElementById("spacesContextNewTabItem");
    let newWindowItem = document.getElementById("spacesContextNewWindowItem");
    let separator = document.getElementById("spacesContextMenuSeparator");

    // The space that we (last) opened the context menu for, which we share
    // between methods.
    let contextSpace;
    newTabItem.addEventListener("command", () => contextSpace.open("tab"));
    newWindowItem.addEventListener("command", () =>
      contextSpace.open("window")
    );

    let settingsContextMenu = document.getElementById("settingsContextMenu");
    document
      .getElementById("settingsContextOpenSettingsItem")
      .addEventListener("command", () => openTab("preferencesTab", {}));
    document
      .getElementById("settingsContextOpenAccountSettingsItem")
      .addEventListener("command", () =>
        openTab("contentTab", { url: "about:accountsettings" })
      );
    document
      .getElementById("settingsContextOpenAddonsItem")
      .addEventListener("command", () =>
        openTab("contentTab", { url: "about:addons" })
      );
    document
      .getElementById("settingsContextOpenCustomizeItem")
      .addEventListener("command", () => this.showCustomize());

    for (let space of this.spaces) {
      this._addButtonClickListener(space.button, () => {
        this.openSpace(tabmail, space);
      });
      space.menuitem?.addEventListener("command", () => {
        this.openSpace(tabmail, space);
      });
      if (space.name == "settings") {
        space.button.addEventListener("contextmenu", event => {
          event.stopPropagation();
          settingsContextMenu.openPopupAtScreen(
            event.screenX,
            event.screenY,
            true,
            event
          );
        });
        continue;
      }
      space.button.addEventListener("contextmenu", event => {
        event.stopPropagation();
        contextSpace = space;
        // Clean up old items.
        for (let menuitem of contextMenu.querySelectorAll(".switch-to-tab")) {
          menuitem.remove();
        }

        let existingTabs = tabmail.tabInfo.filter(space.tabInSpace);
        // Show opening in new tab if no existing tabs or can open multiple.
        // NOTE: We always show at least one item: either the switch to tab
        // items, or the new tab item.
        newTabItem.hidden = !!existingTabs.length && !space.allowMultipleTabs;
        newWindowItem.hidden = !space.allowMultipleTabs;

        for (let tabInfo of existingTabs) {
          let menuitem = document.createXULElement("menuitem");
          document.l10n.setAttributes(
            menuitem,
            "spaces-context-switch-tab-item",
            { tabName: tabInfo.title }
          );
          menuitem.classList.add("switch-to-tab", "menuitem-iconic");
          menuitem.addEventListener("command", () =>
            tabmail.switchToTab(tabInfo)
          );
          contextMenu.appendChild(menuitem);
        }
        // The separator splits the "Open in new tab" and "Open in new window"
        // items from the switch-to-tab items. Only show separator if there
        // are non-hidden items on both sides.
        separator.hidden = !existingTabs.length || !space.allowMultipleTabs;

        contextMenu.openPopupAtScreen(
          event.screenX,
          event.screenY,
          true,
          event
        );
      });
    }

    this._addButtonClickListener(
      document.getElementById("collapseButton"),
      () => this.toggleToolbar(true)
    );

    document
      .getElementById("spacesPopupButtonReveal")
      .addEventListener("command", () => {
        this.toggleToolbar(false);
      });
    this._addButtonClickListener(
      document.getElementById("spacesToolbarAddonsOverflowButton"),
      event => this.openSpacesToolbarAddonsPopup(event)
    );

    // Allow opening the pinned menu with Space or Enter keypress.
    document
      .getElementById("spacesPinnedButton")
      .addEventListener("keypress", event => {
        // Don't show the panel if the window is in customization mode.
        if (
          document.getElementById("toolbar-menubar").hasAttribute("customizing")
        ) {
          return;
        }

        if (event.key == " " || event.key == "Enter") {
          let panel = document.getElementById("spacesButtonMenuPopup");
          if (panel.state == "open") {
            panel.hidePopup();
          } else if (panel.state == "closed") {
            panel.openPopup(event.target, "after_start");
          }
        }
      });
  },

  /**
   * Handle the keypress event on the spaces toolbar.
   *
   * @param {Event} event - The keypress DOMEvent.
   */
  _onSpacesToolbarKeyDown(event) {
    if (
      !["ArrowUp", "ArrowDown", "Home", "End", " ", "Enter"].includes(event.key)
    ) {
      return;
    }

    // NOTE: Normally a button click handler would cover Enter and Space key
    // events, however we need to prevent the default behavior and explicitly
    // trigger the button click because in some tabs XUL keys or Window event
    // listeners are attached to this keys triggering specific actions.
    // TODO: Remove once we have a properly mapped global shortcut object not
    // relying on XUL keys.
    if (event.key == " " || event.key == "Enter") {
      event.preventDefault();
      event.target.click();
      return;
    }

    // Collect all currently visible buttons of the spaces toolbar.
    let buttons = [
      ...document.querySelectorAll(".spaces-toolbar-button:not([hidden])"),
    ];
    let elementIndex = buttons.indexOf(this.focusButton);

    // Find the adjacent focusable element based on the pressed key.
    switch (event.key) {
      case "ArrowUp":
        elementIndex--;
        if (elementIndex == -1) {
          elementIndex = buttons.length - 1;
        }
        break;

      case "ArrowDown":
        elementIndex++;
        if (elementIndex > buttons.length - 1) {
          elementIndex = 0;
        }
        break;

      case "Home":
        elementIndex = 0;
        break;

      case "End":
        elementIndex = buttons.length - 1;
        break;
    }

    this.setFocusButton(buttons[elementIndex], true);
  },

  /**
   * Move the focus to a new toolbar button and update the tabindex attribute.
   *
   * @param {HTMLElement} buttonToFocus - The new button to receive focus.
   * @param {boolean} [forceFocus=false] - Whether to force the focus to move
   *   onto the new button, otherwise focus will only move if the previous
   *   focusButton had focus.
   */
  setFocusButton(buttonToFocus, forceFocus = false) {
    let prevHadFocus = false;
    if (buttonToFocus != this.focusButton) {
      prevHadFocus = document.activeElement == this.focusButton;
      this.focusButton.tabIndex = -1;
      this.focusButton = buttonToFocus;
      buttonToFocus.tabIndex = 0;
    }
    // Only move the focus if the currently focused button was the active
    // element.
    if (forceFocus || prevHadFocus) {
      buttonToFocus.focus();
    }
  },

  /**
   * Add a click event listener to a spaces toolbar button.
   *
   * This method will insert focus controls for when the button is clicked.
   *
   * @param {HTMLButtonElement} button - A button that belongs to the spaces
   *   toolbar.
   * @param {Function} listener - An event listener to call when the button's
   *   click event is fired.
   */
  _addButtonClickListener(button, listener) {
    button.addEventListener("click", event => {
      // Since the button may have tabIndex = -1, we must manually move the
      // focus into the button and set it as the focusButton.
      // NOTE: We do *not* force the focus to move onto the button if it is not
      // currently already within the spaces toolbar. This is mainly to avoid
      // changing the document.activeElement before the tab's lastActiveElement
      // is set in tabmail.js.
      // NOTE: We do this before activating the button, which may move the focus
      // elsewhere, such as into a space.
      this.setFocusButton(button);
      listener(event);
    });
  },

  /**
   * Open a space by creating a new tab or switching to an existing tab.
   *
   * @param {XULElement} tabmail - The tabmail element.
   * @param {SpaceInfo} space - The space to open.
   */
  openSpace(tabmail, space) {
    // Find the earliest primary tab that belongs to this space.
    let existing = tabmail.tabInfo.find(
      tabInfo => space.tabInSpace(tabInfo) == 1
    );
    if (!existing) {
      return space.open("tab");
    } else if (this.currentSpace != space) {
      // Only switch to the tab if it is in a different space to the
      // current one. In particular, if we are in a later tab we won't
      // switch to the earliest tab.
      tabmail.switchToTab(existing);
      return existing;
    }
    return tabmail.currentTabInfo;
  },

  /**
   * Open a popup context menu at the location of the right on the toolbar.
   *
   * @param {DOMEvent} event - The click event.
   */
  _showContextMenu(event) {
    document
      .getElementById("spacesToolbarContextMenu")
      .openPopupAtScreen(event.screenX, event.screenY, true);
  },

  /**
   * Load the saved customization from the xulStore, if we have any.
   */
  async loadCustomization() {
    let xulStore = Services.xulStore;
    if (xulStore.hasValue(this.docURL, "spacesToolbar", "colors")) {
      this.customizeData = JSON.parse(
        xulStore.getValue(this.docURL, "spacesToolbar", "colors")
      );
      this.updateCustomization();
    }
  },

  /**
   * Reset the colors shown on the button colors to the default state to remove
   * any previously applied custom color.
   */
  _resetColorInputs() {
    // Update colors with the current values. If we don't have any customization
    // data, we fetch the current colors from the DOM elements.
    // IMPORTANT! Always clear the onchange method before setting a new value
    // since this method might be called after the popup is already opened.
    let bgButton = document.getElementById("spacesBackgroundColor");
    bgButton.onchange = null;
    bgButton.value =
      this.customizeData.background ||
      this._rgbToHex(getComputedStyle(this.element).backgroundColor);
    bgButton.onchange = event => {
      this.customizeData.background = event.target.value;
      this.updateCustomization();
    };

    let iconButton = document.getElementById("spacesIconsColor");
    iconButton.onchange = null;
    iconButton.value =
      this.customizeData.color ||
      this._rgbToHex(
        getComputedStyle(
          document.querySelector(".spaces-toolbar-button:not(.current)")
        ).color
      );
    iconButton.onchange = event => {
      this.customizeData.color = event.target.value;
      this.updateCustomization();
    };

    let accentStyle = getComputedStyle(
      document.getElementById("spacesAccentPlaceholder")
    );
    let accentBgButton = document.getElementById("spacesAccentBgColor");
    accentBgButton.onchange = null;
    accentBgButton.value =
      this.customizeData.accentBackground ||
      this._rgbToHex(accentStyle.backgroundColor);
    accentBgButton.onchange = event => {
      this.customizeData.accentBackground = event.target.value;
      this.updateCustomization();
    };

    let accentFgButton = document.getElementById("spacesAccentTextColor");
    accentFgButton.onchange = null;
    accentFgButton.value =
      this.customizeData.accentColor || this._rgbToHex(accentStyle.color);
    accentFgButton.onchange = event => {
      this.customizeData.accentColor = event.target.value;
      this.updateCustomization();
    };
  },

  /**
   * Update the color buttons to reflect the current state of the toolbar UI,
   * then open the customization panel.
   */
  showCustomize() {
    this.isCustomizing = true;
    // Reset the color inputs to be sure we're showing the correct colors.
    this._resetColorInputs();

    // Since we're forcing the panel to stay open with noautohide, we need to
    // listen for the Escape keypress to maintain that usability exit point.
    window.addEventListener("keypress", this.onWindowKeypress);
    this.customizePanel.openPopup(
      document.getElementById("collapseButton"),
      "end_after",
      6,
      0,
      false
    );
  },

  /**
   * Listen for the keypress event on the window after the customize panel was
   * opened to enable the closing on Escape.
   *
   * @param {Event} event - The DOM Event.
   */
  onWindowKeypress(event) {
    if (event.key == "Escape") {
      gSpacesToolbar.customizePanel.hidePopup();
    }
  },

  /**
   * Close the customization panel.
   */
  closeCustomize() {
    this.customizePanel.hidePopup();
  },

  /**
   * Reset all event listeners and store the custom colors.
   */
  onCustomizePopupHidden() {
    this.isCustomizing = false;
    // Always remove the keypress event listener set on opening.
    window.removeEventListener("keypress", this.onWindowKeypress);

    // Save the custom colors, or delete it if we don't have any.
    if (!Object.keys(this.customizeData).length) {
      Services.xulStore.removeValue(this.docURL, "spacesToolbar", "colors");
      return;
    }

    Services.xulStore.setValue(
      this.docURL,
      "spacesToolbar",
      "colors",
      JSON.stringify(this.customizeData)
    );
  },

  /**
   * Apply the customization to the CSS file.
   */
  updateCustomization() {
    let data = this.customizeData;
    let style = document.documentElement.style;

    // Toolbar background color.
    style.setProperty("--spaces-bg-color", data.background ?? null);
    // Icons color.
    style.setProperty("--spaces-button-text-color", data.color ?? null);
    // Icons color for current/active buttons.
    style.setProperty(
      "--spaces-button-active-text-color",
      data.accentColor ?? null
    );
    // Background color for current/active buttons.
    style.setProperty(
      "--spaces-button-active-bg-color",
      data.accentBackground ?? null
    );
  },

  /**
   * Reset all color customizations to show the user the default UI.
   */
  resetColorCustomization() {
    if (!matchMedia("(prefers-reduced-motion)").matches) {
      // We set an event listener for the transition of any element inside the
      // toolbar so we can reset the color for the buttons only after the
      // toolbar and its elements reverted to their original colors.
      this.element.addEventListener(
        "transitionend",
        () => {
          this._resetColorInputs();
        },
        {
          once: true,
        }
      );
    }

    this.customizeData = {};
    this.updateCustomization();

    // If the user required reduced motion, the transitionend listener will not
    // work.
    if (matchMedia("(prefers-reduced-motion)").matches) {
      this._resetColorInputs();
    }
  },

  /**
   * Toggle the spaces toolbar and toolbar buttons visibility.
   *
   * @param {boolean} state - The visibility state to update the elements.
   */
  toggleToolbar(state) {
    // Prevent the visibility change state of the spaces toolbar if we're
    // currently customizing it, in order to avoid weird positioning outcomes
    // with the customize popup panel.
    if (this.isCustomizing) {
      return;
    }

    this.isHidden = state;

    // The focused element, prior to toggling.
    let activeElement = document.activeElement;

    let pinnedButton = document.getElementById("spacesPinnedButton");
    pinnedButton.hidden = !state;
    let revealButton = document.getElementById("spacesToolbarReveal");
    revealButton.hidden = !state;
    this.element.hidden = state;

    if (state && this.element.contains(activeElement)) {
      // If the toolbar is being hidden and one of its child element was
      // focused, move the focus to the pinned button without changing the
      // focusButton attribute of this object.
      pinnedButton.focus();
    } else if (
      !state &&
      (activeElement == pinnedButton || activeElement == revealButton)
    ) {
      // If the the toolbar is being shown and the focus is on the pinned or
      // reveal button, move the focus to the previously focused button.
      this.focusButton?.focus();
    }

    // Update the window UI after the visibility state of the spaces toolbar
    // has changed.
    this.updateUI();
  },

  /**
   * Toggle the spaces toolbar from a menuitem.
   */
  toggleToolbarFromMenu() {
    this.toggleToolbar(!this.isHidden);
  },

  /**
   * Update the addons buttons and propagate toolbar visibility to a global
   * attribute.
   */
  updateUI() {
    // Interrupt if the spaces toolbar isn't loaded yet.
    if (!this.isLoaded) {
      return;
    }

    let density = Services.prefs.getIntPref("mail.uidensity", 1);
    switch (density) {
      case 0:
        this.densitySpacing = 10;
        break;
      case 1:
        this.densitySpacing = 15;
        break;
      case 2:
        this.densitySpacing = 20;
        break;
    }

    // Toggle the window attribute for those CSS selectors that need it.
    if (this.isHidden) {
      document.documentElement.removeAttribute("spacestoolbar");
    } else {
      document.documentElement.setAttribute("spacestoolbar", "true");
      this.updateAddonButtonsUI();
    }
  },

  /**
   * Reset the inline style of the various titlebars and toolbars that interact
   * with the spaces toolbar.
   */
  resetInlineStyle() {
    document.getElementById("tabmail-tabs").removeAttribute("style");
  },

  /**
   * Update the UI based on the window sizing.
   */
  onWindowResize() {
    if (!this.isLoaded) {
      return;
    }

    this.updateUImacOS();
    this.updateAddonButtonsUI();
  },

  /**
   * Update the location of buttons added by addons based on the space available
   * in the toolbar. If the number of buttons is greater than the height of the
   * visible container, move those buttons inside an overflow popup.
   */
  updateAddonButtonsUI() {
    if (this.isHidden) {
      return;
    }

    let overflowButton = document.getElementById(
      "spacesToolbarAddonsOverflowButton"
    );
    let separator = document.getElementById("spacesPopupAddonsSeparator");
    let popup = document.getElementById("spacesToolbarAddonsPopup");
    // Bail out if we don't have any add-ons button.
    if (!this.addonButtonCount) {
      if (this.focusButton == overflowButton) {
        this.setFocusButton(
          this.element.querySelector(".spaces-toolbar-button:not([hidden])")
        );
      }
      overflowButton.hidden = true;
      separator.collapsed = true;
      popup.hidePopup();
      return;
    }

    separator.collapsed = false;
    // Use the first available button's height as reference, and include the gap
    // defined by the UIDensity pref.
    let buttonHeight =
      document.querySelector(".spaces-toolbar-button").getBoundingClientRect()
        .height + this.densitySpacing;

    let containerHeight = document
      .getElementById("spacesToolbarAddonsContainer")
      .getBoundingClientRect().height;

    // Calculate the visible threshold of add-on buttons by:
    // - Multiplying the space occupied by one button for the number of the
    //   add-on buttons currently present.
    // - Subtracting the height of the add-ons container from the height
    //   occupied by all add-on buttons.
    // - Dividing the returned value by the height of a single button.
    // Doing so we will get an integer representing how many buttons might or
    // might not fit in the available area.
    let threshold = Math.ceil(
      (buttonHeight * this.addonButtonCount - containerHeight) / buttonHeight
    );

    // Always reset the visibility of all buttons to avoid unnecessary
    // calculations when needing to reveal hidden buttons.
    for (let btn of document.querySelectorAll(".spaces-addon-button[hidden]")) {
      btn.hidden = false;
    }

    // If we get a negative threshold, it means we have plenty of empty space
    // so we don't need to do anything.
    if (threshold <= 0) {
      // If the overflow button was the currently focused button, move the focus
      // to an arbitrary first available button.
      if (this.focusButton == overflowButton) {
        this.setFocusButton(
          this.element.querySelector(".spaces-toolbar-button:not([hidden])")
        );
      }
      overflowButton.hidden = true;
      popup.hidePopup();
      return;
    }

    overflowButton.hidden = false;
    // Hide as many buttons as needed based on the threshold value.
    for (let i = 0; i <= threshold; i++) {
      let btn = document.querySelector(
        `.spaces-addon-button:nth-last-child(${i})`
      );
      if (btn) {
        // If one of the hidden add-on buttons was the focused one, move the
        // focus to the overflow button.
        if (btn == this.focusButton) {
          this.setFocusButton(overflowButton);
        }
        btn.hidden = true;
      }
    }
  },

  /**
   * Update the spacesToolbar UI and adjacent tabs exclusively for macOS. This
   * is necessary mostly to tackle the changes when switching fullscreen mode.
   */
  updateUImacOS() {
    // No need to to anything if we're not on macOS.
    if (AppConstants.platform != "macosx") {
      return;
    }

    // Add inline styling to the tabmail tabs only if we're on macOS and the
    // app is in full screen mode.
    if (window.fullScreen) {
      let size = this.element.getBoundingClientRect().width;
      let style = `margin-inline-start: ${size}px;`;
      document.getElementById("tabmail-tabs").setAttribute("style", style);
      return;
    }

    // Reset the style if we exited full screen mode.
    this.resetInlineStyle();
  },

  /**
   * @typedef NativeButtonProperties
   * @property {string} title - The text of the button tooltip and menuitem value.
   * @property {string} url - The URL of the content tab to open.
   * @property {Map} iconStyles - The icon styles Map.
   * @property {?string} badgeText - The optional badge text.
   * @property {?Map} badgeStyles - The optional badge styles Map.
   */

  /**
   * Helper function for extensions in order to add buttons to the spaces
   * toolbar.
   *
   * @param {string} id - The ID of the newly created button.
   * @param {NativeButtonProperties} properties - The properties of the new button.
   *
   * @returns {Promise} - A Promise that resolves when the button is created.
   */
  async createToolbarButton(id, properties = {}) {
    return new Promise((resolve, reject) => {
      if (!this.isLoaded) {
        return reject("Unable to add spaces toolbar button! Toolbar not ready");
      }
      if (
        !id ||
        !properties.title ||
        !properties.url ||
        !properties.iconStyles
      ) {
        return reject(
          "Unable to add spaces toolbar button! Missing ID, Title, IconStyles, or space URL"
        );
      }

      // Create the button.
      let button = document.createElement("button");
      button.classList.add("spaces-toolbar-button", "spaces-addon-button");
      button.id = id;
      button.title = properties.title;
      button.tabIndex = -1;

      let badge = document.createElement("span");
      badge.classList.add("spaces-badge-container");
      button.appendChild(badge);

      let img = document.createElement("img");
      img.setAttribute("alt", "");
      button.appendChild(img);
      document
        .getElementById("spacesToolbarAddonsContainer")
        .appendChild(button);

      // Create the menuitem.
      let menuitem = document.createXULElement("menuitem");
      menuitem.classList.add(
        "spaces-addon-menuitem",
        "menuitem-iconic",
        "spaces-popup-menuitem"
      );
      menuitem.id = `${id}-menuitem`;
      menuitem.label = properties.title;
      document
        .getElementById("spacesButtonMenuPopup")
        .insertBefore(
          menuitem,
          document.getElementById("spacesPopupRevealSeparator")
        );

      // Set icons. The unified toolbar customization also relies on the CSS
      // variables of the img.
      for (let style of this.SUPPORTED_ICON_STYLES) {
        if (properties.iconStyles.has(style)) {
          img.style.setProperty(style, properties.iconStyles.get(style));
          menuitem.style.setProperty(style, properties.iconStyles.get(style));
        }
      }

      // Add space.
      gSpacesToolbar.spaces.push({
        name: id,
        button,
        menuitem,
        url: properties.url,
        isExtensionSpace: true,
        tabInSpace(tabInfo) {
          // TODO: Store the spaceButtonId in the XULStore (or somewhere), so the
          // space is recognized after a restart. Or force closing of all spaces
          // on shutdown.
          return tabInfo.spaceButtonId == this.name ? 1 : 0;
        },
        open(where) {
          // The check if we should switch to an existing tab in this space was
          // done in openSpace() and this function here should always open a new
          // tab and not switch to a tab which might have loaded the same url,
          // but belongs to a different space.
          let tab = openTab(
            "contentTab",
            { url: this.url, duplicate: true },
            where
          );
          tab.spaceButtonId = this.name;
          // TODO: Make sure the spaceButtonId is set during load, and not here,
          // where it might be too late.
          gSpacesToolbar.currentSpace = this;
          button.classList.add("current");
          return tab;
        },
      });

      // Set click actions.
      let tabmail = document.getElementById("tabmail");
      this._addButtonClickListener(button, () => {
        let space = gSpacesToolbar.spaces.find(space => space.name == id);
        this.openSpace(tabmail, space);
      });
      menuitem.addEventListener("command", () => {
        let space = gSpacesToolbar.spaces.find(space => space.name == id);
        this.openSpace(tabmail, space);
      });

      // Set badge.
      if (properties.badgeText) {
        button.classList.add("has-badge");
        badge.textContent = properties.badgeText;
      }

      if (properties.badgeStyles) {
        for (let style of this.SUPPORTED_BADGE_STYLES) {
          if (properties.badgeStyles.has(style)) {
            badge.style.setProperty(style, properties.badgeStyles.get(style));
          }
        }
      }

      this.updateAddonButtonsUI();
      return resolve();
    });
  },

  /**
   * Helper function for extensions in order to update buttons previously added
   * to the spaces toolbar.
   *
   * @param {string} id - The ID of the button that needs to be updated.
   * @param {NativeButtonProperties} properties - The new properties of the button.
   *   Not specifying the optional badgeText or badgeStyles will remove them.
   *
   * @returns {Promise} - A promise that resolves when the button is updated.
   */
  async updateToolbarButton(id, properties = {}) {
    return new Promise((resolve, reject) => {
      if (
        !id ||
        !properties.title ||
        !properties.url ||
        !properties.iconStyles
      ) {
        return reject(
          "Unable to update spaces toolbar button! Missing ID, Title, IconsStyles, or space URL"
        );
      }

      let button = document.getElementById(`${id}`);
      let menuitem = document.getElementById(`${id}-menuitem`);
      if (!button || !menuitem) {
        return reject(
          "Unable to update spaces toolbar button! Button or menuitem don't exist"
        );
      }

      button.title = properties.title;
      menuitem.label = properties.title;

      // Update icons.
      let img = button.querySelector("img");
      for (let style of this.SUPPORTED_ICON_STYLES) {
        let value = properties.iconStyles.get(style);
        img.style.setProperty(style, value ?? null);
        menuitem.style.setProperty(style, value ?? null);
      }

      // Update url.
      let space = gSpacesToolbar.spaces.find(space => space.name == id);
      if (space.url != properties.url) {
        // TODO: Reload the space, when the url is changed (or close and re-open
        // the tab).
        space.url = properties.url;
      }

      // Update badge.
      let badge = button.querySelector(".spaces-badge-container");
      if (properties.badgeText) {
        button.classList.add("has-badge");
        badge.textContent = properties.badgeText;
      } else {
        button.classList.remove("has-badge");
        badge.textContent = "";
      }

      for (let style of this.SUPPORTED_BADGE_STYLES) {
        badge.style.setProperty(
          style,
          properties.badgeStyles?.get(style) ?? null
        );
      }

      return resolve();
    });
  },

  /**
   * Helper function for extensions allowing the removal of previously created
   * buttons.
   *
   * @param {string} id - The ID of the button that needs to be removed.
   * @returns {Promise} - A promise that resolves when the button is removed.
   */
  async removeToolbarButton(id) {
    return new Promise((resolve, reject) => {
      if (!this.isLoaded) {
        return reject(
          "Unable to remove spaces toolbar button! Toolbar not ready"
        );
      }
      if (!id) {
        return reject("Unable to remove spaces toolbar button! Missing ID");
      }

      let button = document.getElementById(`${id}`);
      // If the button being removed is the currently focused one, move the
      // focus on an arbitrary first available spaces button.
      if (this.focusButton == button) {
        this.setFocusButton(
          this.element.querySelector(".spaces-toolbar-button:not([hidden])")
        );
      }

      button?.remove();
      document.getElementById(`${id}-menuitem`)?.remove();

      let space = gSpacesToolbar.spaces.find(space => space.name == id);
      let tabmail = document.getElementById("tabmail");
      let existing = tabmail.tabInfo.find(
        tabInfo => space.tabInSpace(tabInfo) == 1
      );
      if (existing) {
        tabmail.closeTab(existing);
      }

      gSpacesToolbar.spaces = gSpacesToolbar.spaces.filter(e => e.name != id);
      this.updateAddonButtonsUI();

      return resolve();
    });
  },

  /**
   * Populate the overflow container with a copy of all the currently hidden
   * buttons generated by add-ons.
   *
   * @param {DOMEvent} event - The DOM click event.
   */
  openSpacesToolbarAddonsPopup(event) {
    let popup = document.getElementById("spacesToolbarAddonsPopup");

    for (let button of document.querySelectorAll(
      ".spaces-addon-button[hidden]"
    )) {
      let menuitem = document.createXULElement("menuitem");
      menuitem.classList.add("menuitem-iconic", "spaces-popup-menuitem");
      menuitem.label = button.title;

      let img = button.querySelector("img");
      for (let style of this.SUPPORTED_ICON_STYLES) {
        menuitem.style.setProperty(
          style,
          img.style.getPropertyValue(style) ?? null
        );
      }

      menuitem.addEventListener("command", () => button.click());
      popup.appendChild(menuitem);
    }

    popup.openPopup(event.target, "after_start", 0, 0);
  },

  /**
   * Empty the overflow container.
   */
  spacesToolbarAddonsPopupClosed() {
    document.getElementById("spacesToolbarAddonsPopup").replaceChildren();
  },

  /**
   * Copy the badges from the contained menu items to the pinned button.
   * Should be called whenever one of the menu item's badge state changes.
   */
  updatePinnedBadgeState() {
    let hasBadge = Boolean(
      document.querySelector("#spacesButtonMenuPopup .has-badge")
    );
    let spacesPinnedButton = document.getElementById("spacesPinnedButton");
    spacesPinnedButton.classList.toggle("has-badge", hasBadge);
  },

  /**
   * Save the preferred state when the app is closed.
   */
  onUnload() {
    Services.xulStore.setValue(
      this.docURL,
      "spacesToolbar",
      "hidden",
      this.isHidden
    );
  },
};