forked from aminomancer/uc.css.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verticalTabsPane.uc.js
2328 lines (2306 loc) · 119 KB
/
verticalTabsPane.uc.js
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
// ==UserScript==
// @name Vertical Tabs Pane
// @version 1.5.6
// @author aminomancer
// @homepage https://github.com/aminomancer/uc.css.js
// @description Create a vertical pane across from the sidebar that functions like the vertical
// tab pane in Microsoft Edge. It doesn't hide the tab bar since people have different preferences
// on how to do that, but it sets an attribute on the root element that you can use to hide the
// regular tab bar while the vertical pane is open, for example :root[vertical-tabs] #TabsToolbar...
// By default, the pane is resizable just like the sidebar is. And like the pane in Edge, you can
// press a button to collapse it, and it will hide the tab labels and become a thin strip that just
// shows the tabs' favicons. Hovering the collapsed pane will expand it without moving the browser
// content. As with the [vertical-tabs] attribute, this "unpinned" state is reflected on the root
// element, so you can select it like :root[vertical-tabs-unpinned]... Like the sidebar, the state
// of the pane is stored between windows and recorded in preferences. There's no need to edit these
// preferences directly. There are a few other preferences that can be edited in about:config, but
// they can all be changed on the fly by opening the context menu within the pane. The new tab
// button and the individual tabs all have their own context menus, but right-clicking anything else
// will open the pane's context menu, which has options for changing these preferences. "Move Pane
// to Right/Left" will change which side the pane (and by extension, the sidebar) is displayed on,
// relative to the browser content. Since the pane always mirrors the position of the sidebar,
// moving the pane to the right will move the sidebar to the left, and vice versa. "Reverse Tab
// Order" changes the direction of the pane so that newer tabs are displayed on top rather than on
// bottom. "Expand Pane on Hover/Focus" causes the pane to expand on hover when it's collapsed. When
// you collapse the pane with the unpin button, it collapses to a small width and then temporarily
// expands if you hover it, after a delay of 100ms. Then when your mouse leaves the pane, it
// collapses again, after a delay of 100ms. Both of these delays can be changed with the "Configure
// Hover Delay" and "Configure Hover Out Delay" options in the context menu, or in about:config. For
// languages other than English, the labels and tooltips can be modified directly in the l10n object
// below.
// @license This Source Code Form is subject to the terms of the Creative Commons Attribution-NonCommercial-ShareAlike International License, v. 4.0. If a copy of the CC BY-NC-SA 4.0 was not distributed with this file, You can obtain one at http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
// ==/UserScript==
(function () {
let config = {
// localization strings. change these if your UI is not in english.
l10n: {
"Button label": `Vertical Tabs`, // label and tooltip for the toolbar button
"Button tooltip": `Toggle vertical tabs`,
"Collapse button tooltip": `Collapse pane`,
"Pin button tooltip": `Pin pane`,
// labels for the context menu
context: {
"Move Pane to Right": "Move Pane to Right",
"Move Pane to Left": "Move Pane to Left",
"Expand Pane": "Expand Pane on Hover/Focus",
"Reverse Tab Order": "Reverse Tab Order",
"Configure Hover Delay": "Configure Hover Delay",
"Configure Hover Out Delay": "Configure Hover Out Delay",
},
// strings for the hover delay config prompt
prompt: {
"Hover delay title": "Hover delay (in milliseconds)",
"Hover delay description":
"How long should the collapsed pane wait before expanding?",
"Hover out delay title": "Hover out delay (in milliseconds)",
"Hover out delay description":
"How long should the expanded pane wait before collapsing?",
"Invalid": "Invalid input!",
"Invalid description": "This preference must be a positive integer.",
},
},
// settings for the hotkey
hotkey: {
enabled: true, // set to false if you don't want any hotkey
modifiers: "accel alt", // valid modifiers are "alt", "shift", "ctrl", "meta" and "accel". accel is equal to ctrl on windows and linux, but meta (cmd ⌘) on macOS. meta is the windows key on windows. it's variable on linux.
key: "V", // the actual key. valid keys are letters, the hyphen key - and F1-F12. digits and F13-F24 are not supported by firefox.
},
};
if (location.href !== "chrome://browser/content/browser.xhtml") return;
let prefSvc = Services.prefs;
let closedPref = "userChrome.tabs.verticalTabsPane.closed";
let unpinnedPref = "userChrome.tabs.verticalTabsPane.unpinned";
let noExpandPref = "userChrome.tabs.verticalTabsPane.no-expand-on-hover";
let widthPref = "userChrome.tabs.verticalTabsPane.width";
let reversePref = "userChrome.tabs.verticalTabsPane.reverse-order";
let hoverDelayPref = "userChrome.tabs.verticalTabsPane.hover-delay";
let hoverOutDelayPref = "userChrome.tabs.verticalTabsPane.hover-out-delay";
let userContextPref = "privacy.userContext.enabled";
let containerOnClickPref = "privacy.userContext.newTabContainerOnLeftClick.enabled";
/**
* create a DOM node with given parameters
* @param {object} aDoc (which document to create the element in)
* @param {string} tag (an HTML tag name, like "button" or "p")
* @param {object} props (an object containing attribute name/value pairs, e.g. class: ".bookmark-item")
* @param {boolean} isHTML (if true, create an HTML element. if omitted or false, create a XUL element. generally avoid HTML when modding the UI, most UI elements are actually XUL elements.)
* @returns the created DOM node
*/
function create(aDoc, tag, props, isHTML = false) {
let el = isHTML ? aDoc.createElement(tag) : aDoc.createXULElement(tag);
for (let prop in props) {
el.setAttribute(prop, props[prop]);
}
return el;
}
/**
* set or remove multiple attributes for a given node
* @param {object} el (a DOM node)
* @param {object} attrs (an object of attribute name/value pairs)
* @returns the DOM node
*/
function setAttributes(el, attrs) {
for (let [name, value] of Object.entries(attrs))
if (value) el.setAttribute(name, value);
else el.removeAttribute(name);
}
class VerticalTabsPaneBase {
static preferences = [
{ name: closedPref, value: false },
{ name: unpinnedPref, value: false },
{ name: noExpandPref, value: false },
{ name: widthPref, value: 350 },
{ name: reversePref, value: false },
{ name: hoverDelayPref, value: 100 },
{ name: hoverOutDelayPref, value: 100 },
];
constructor() {
this.preferences = VerticalTabsPaneBase.preferences;
this.registerSheet();
// ensure E10SUtils are available. required for showing tab's process ID in its tooltip, if the pref for that is enabled.
if (!window.E10SUtils)
XPCOMUtils.defineLazyModuleGetters(this, {
E10SUtils: "resource://gre/modules/E10SUtils.jsm",
});
else this.E10SUtils = window.E10SUtils;
// get some localized strings for the tooltip
XPCOMUtils.defineLazyGetter(this, "l10n", function () {
return new Localization(["browser/browser.ftl"], true);
});
this.formatFluentStrings();
Services.obs.addObserver(this, "vertical-tabs-pane-toggle");
// build the DOM
this.pane = document.getElementById("vertical-tabs-pane");
this.splitter = document.getElementById("vertical-tabs-splitter");
this.contextMenu = document.getElementById("mainPopupSet").appendChild(
create(document, "menupopup", {
id: "vertical-tabs-context-menu",
})
);
this.innerBox = this.pane.appendChild(
create(document, "vbox", { id: "vertical-tabs-inner-box" })
);
this.buttonsRow = this.innerBox.appendChild(
create(document, "hbox", {
id: "vertical-tabs-buttons-row",
})
);
this.contextMenu._menuitemPosition = this.contextMenu.appendChild(
create(document, "menuitem", {
id: "vertical-tabs-context-position",
label: config.l10n.context["Move Pane to Right"],
oncommand: `Services.prefs.setBoolPref(SidebarUI.POSITION_START_PREF, true);`,
})
);
this.contextMenu._menuitemExpand = this.contextMenu.appendChild(
create(document, "menuitem", {
id: "vertical-tabs-context-expand",
label: config.l10n.context["Expand Pane"],
type: "checkbox",
oncommand: `Services.prefs.setBoolPref("userChrome.tabs.verticalTabsPane.no-expand-on-hover", !this.getAttribute("checked"));`,
})
);
this.contextMenu._menuitemReverse = this.contextMenu.appendChild(
create(document, "menuitem", {
id: "vertical-tabs-context-reverse",
label: config.l10n.context["Reverse Tab Order"],
type: "checkbox",
oncommand: `Services.prefs.setBoolPref("userChrome.tabs.verticalTabsPane.reverse-order", this.getAttribute("checked"));`,
})
);
this.contextMenu._menuitemHoverDelay = this.contextMenu.appendChild(
create(document, "menuitem", {
id: "vertical-tabs-context-hover-delay",
label: config.l10n.context["Configure Hover Delay"],
oncommand: `verticalTabsPane.promptForIntPref("userChrome.tabs.verticalTabsPane.hover-delay")`,
})
);
this.contextMenu._menuitemHoverOutDelay = this.contextMenu.appendChild(
create(document, "menuitem", {
id: "vertical-tabs-context-hover-out-delay",
label: config.l10n.context["Configure Hover Out Delay"],
oncommand: `verticalTabsPane.promptForIntPref("userChrome.tabs.verticalTabsPane.hover-out-delay")`,
})
);
// tab stops let us focus elements in the tabs pane by hitting tab to cycle through toolbars, just as in vanilla firefox.
this.buttonsTabStop = this.buttonsRow.appendChild(
create(document, "toolbartabstop", { "aria-hidden": true })
);
this.newTabButton = this.buttonsRow.appendChild(
document.getElementById("new-tab-button").cloneNode(true)
);
this.newTabButton.id = "vertical-tabs-new-tab-button";
this.newTabButton.setAttribute("flex", "1");
this.newTabButton.setAttribute("class", "subviewbutton subviewbutton-iconic");
this.newTabButton.tooltipText = GetDynamicShortcutTooltipText("new-tab-button");
this.pinPaneButton = this.buttonsRow.appendChild(
create(document, "toolbarbutton", {
id: "vertical-tabs-pin-button",
class: "subviewbutton subviewbutton-iconic no-label",
tooltiptext: config.l10n["Collapse button tooltip"],
})
);
this.pinPaneButton.addEventListener("command", (e) => {
this.pane.getAttribute("unpinned")
? this.pane.removeAttribute("unpinned")
: this.unpin();
this.resetPinnedTooltip();
});
this.closePaneButton = this.buttonsRow.appendChild(
create(document, "toolbarbutton", {
id: "vertical-tabs-close-button",
class: "subviewbutton subviewbutton-iconic no-label",
tooltiptext: config.l10n["Button tooltip"],
})
);
if (key_toggleVerticalTabs)
this.closePaneButton.tooltipText += ` (${ShortcutUtils.prettifyShortcut(
key_toggleVerticalTabs
)})`;
this.closePaneButton.addEventListener("command", (e) => this.toggle());
this.innerBox.appendChild(create(document, "toolbarseparator"));
this.scrollboxTabStop = this.innerBox.appendChild(
create(document, "toolbartabstop", { "aria-hidden": true })
);
this.containerNode = this.innerBox.appendChild(
create(document, "arrowscrollbox", {
id: "vertical-tabs-list",
tooltip: "vertical-tabs-tooltip",
context: "tabContextMenu",
orient: "vertical",
flex: "1",
})
);
// build a modified clone of the built-in tabs tooltip for use in the pane.
let vanillaTooltip = document.getElementById("tabbrowser-tab-tooltip");
this.tabTooltip = vanillaTooltip.cloneNode(true);
vanillaTooltip.after(this.tabTooltip);
this.tabTooltip.id = "vertical-tabs-tooltip";
this.tabTooltip.setAttribute(
"onpopupshowing",
`verticalTabsPane.createTabTooltip(event)`
);
// this is a map of all the rows, and you can get a specific row from it by passing a tab (like a real <tab> element from the built-in tab bar)
this.tabToElement = new Map();
this.listenersRegistered = false;
// set up preferences if they don't already exist
this.preferences.forEach((pref) => {
if (!prefSvc.prefHasUserValue(pref.name))
prefSvc[`set${typeof pref.value === "number" ? "Int" : "Bool"}Pref`](
pref.name,
pref.value
);
});
prefSvc.addObserver("userChrome.tabs.verticalTabsPane", this);
prefSvc.addObserver("privacy.userContext", this);
prefSvc.addObserver(SidebarUI.POSITION_START_PREF, this);
// re-initialize the sidebar's positionstart pref callback since we changed it earlier at the bottom to make it also move the vertical tabs pane.
XPCOMUtils.defineLazyPreferenceGetter(
SidebarUI,
"_positionStart",
SidebarUI.POSITION_START_PREF,
true,
SidebarUI.setPosition.bind(SidebarUI)
);
// destroy the scrollbuttons.
["#scrollbutton-up", "#scrollbutton-down"].forEach((id) =>
this.containerNode.shadowRoot.querySelector(id).remove()
);
this.l10nIfNeeded();
// the pref observer changes stuff in the script when the pref is changed.
// but when the script initially starts, the prefs haven't been changed so that logic isn't immediately invoked.
// we have to invoke it manually, as if the prefs had been changed.
let readPref = (pref) => this.observe(prefSvc, "nsPref:read", pref);
readPref(noExpandPref);
readPref(hoverDelayPref);
readPref(hoverOutDelayPref);
if (!this.hoverDelay) this.hoverDelay = 100;
if (!this.hoverOutDelay) this.hoverOutDelay = 100;
// we don't want to read some of these prefs until we know whether the window was opened by another window with a pane,
// because instead of reading from prefs we can adopt the pane state from the previous window.
// normally in my scripts I update prefs like this every time they're changed, which would mean, for example,
// changing the pane's width in one window would instantly update the pane's width in every other window.
// that's not how firefox's built-in sidebar works, though. when you open a window, the sidebar state is taken from the previous window.
// but changing the sidebar in that window won't affect the sidebar in the previous window.
// sidebar state isn't permanently stored anywhere until the last window is closed. (basically, when the app has been closed)
// so to keep this consistent with the sidebar we're gonna use the previous window as the main source of state, and use prefs as a fallback.
// the prefs will be set when the last window is closed (see the uninit function at the bottom)
SessionStore.promiseInitialized.then(() => {
if (window.closed) return;
readPref(reversePref);
readPref(userContextPref);
readPref(SidebarUI.POSITION_START_PREF);
// try to adopt from previous window, otherwise restore from prefs.
let sourceWindow = window.opener;
if (sourceWindow)
if (!sourceWindow.closed && sourceWindow.location.protocol == "chrome:")
if (this.adoptFromWindow(sourceWindow)) return;
readPref(widthPref);
readPref(unpinnedPref);
readPref(closedPref);
});
}
// get the root element, e.g. what you'd select in CSS with :root
get root() {
return this._root || (this._root = document.documentElement);
}
// return all the DOM nodes for tab rows in the pane.
get rows() {
return this.tabToElement.values();
}
// return the row for the active/selected tab.
get selectedRow() {
return this.containerNode.querySelector(".all-tabs-item[selected]");
}
// all of these events will be listened for on the pane itself
get paneEvents() {
return this._paneEvents || (this._paneEvents = ["mouseenter", "mouseleave", "focus"]);
}
// these events target the containerNode — the arrowscrollbox
get dragEvents() {
return (
this._dragEvents ||
(this._dragEvents = ["dragstart", "dragleave", "dragover", "drop", "dragend"])
);
}
// these events target the vanilla tab bar, gBrowser.tabContainer
get tabEvents() {
return (
this._tabEvents ||
(this._tabEvents = [
"TabAttrModified",
"TabClose",
"TabMove",
"TabHide",
"TabShow",
"TabPinned",
"TabUnpinned",
"TabSelect",
"TabBrowserDiscarded",
])
);
}
// this creates (and caches) a tree walker. tree walkers are basically interfaces for finding nodes in order.
// we get to specify which direction we're looking in, forward or backward, and we get to specify a filter function that rules out types of elements.
// this one accepts tabstops, buttons, toolbarbuttons, and checkboxes, but rules out disabled or hidden nodes, and rules out everything else.
// this is what tells us which element to focus when pressing the right/left arrow keys.
get horizontalWalker() {
if (this._horizontalWalker) return this._horizontalWalker;
return (this._horizontalWalker = document.createTreeWalker(
this.pane,
NodeFilter.SHOW_ELEMENT,
(node) => {
if (node.tagName == "toolbartabstop") return NodeFilter.FILTER_ACCEPT;
if (node.disabled || node.hidden) return NodeFilter.FILTER_REJECT;
if (
node.tagName == "button" ||
node.tagName == "toolbarbutton" ||
node.tagName == "checkbox"
) {
if (!node.hasAttribute("tabindex")) node.setAttribute("tabindex", "-1");
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_SKIP;
}
));
}
// this one tells us which element to focus when pressing the up/down arrow keys.
// it's just like the other but it skips secondary buttons. (mute and close buttons)
// this way we can arrow up/down to navigate through tabs very quickly, and arrow left/right to focus the mute and close buttons.
get verticalWalker() {
if (this._verticalWalker) return this._verticalWalker;
return (this._verticalWalker = document.createTreeWalker(
this.pane,
NodeFilter.SHOW_ELEMENT,
(node) => {
if (node.tagName == "toolbartabstop") return NodeFilter.FILTER_ACCEPT;
if (node.disabled || node.hidden) return NodeFilter.FILTER_REJECT;
if (
node.tagName == "button" ||
node.tagName == "toolbarbutton" ||
node.tagName == "checkbox"
) {
if (node.classList.contains("all-tabs-secondary-button"))
return NodeFilter.FILTER_SKIP;
if (!node.hasAttribute("tabindex")) node.setAttribute("tabindex", "-1");
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_SKIP;
}
));
}
// make an array containing all the context menus that can be opened by right-clicking something inside the pane.
get contextMenus() {
let menus = [];
let contextDefs = [...this.pane.querySelectorAll("[context]")];
contextDefs.push(this.pane);
contextDefs.forEach((node) => {
let menu = document.getElementById(node.getAttribute("context"));
if (menus.indexOf(menu) === -1) menus.push(menu);
});
return menus;
}
// we want to prevent the pane from collapsing when a context menu is opened from inside it.
// since document.popupNode was recently removed, we have to manually locate every context menu,
// and check if it's open by checking the triggerNode property. if the triggerNode is inside the pane,
// we prevent the pane from collapsing and instead add a popuphidden event listener,
// so it instead collapses once the pane has been closed.
// imo this is a good reason to bring document.popupNode back, but I don't have any power over that.
get openMenu() {
let menus = this.contextMenus;
if (!menus.length) return false;
let openMenu = false;
menus.forEach((menu) => {
if (menu.triggerNode && this.pane.contains(menu.triggerNode)) openMenu = menu;
});
return openMenu;
}
// grab the localized strings for the built-in tab sound pseudo-tooltip, e.g. "PLAYING" or "AUTOPLAY BLOCKED".
// we lowercase these and append them to the end of the tooltip title if the sound overlay is hovered.
async formatFluentStrings() {
let [playingString, mutedString, blockedString, pipString] =
await this.l10n.formatValues([
"browser-tab-audio-playing2",
"browser-tab-audio-muted2",
"browser-tab-audio-blocked",
"browser-tab-audio-pip",
]);
this.fluentStrings = {
playingString,
mutedString,
blockedString,
pipString,
};
}
/**
* this tells us which tabs to not make rows for. in this case we only exclude hidden tabs.
* tabs are normally only hidden by certain extensions, e.g. an addon that makes tab groups.
* @param {object} tab (a <tab> element from the vanilla tab bar)
* @returns {boolean} false if the tab should be excluded from the vertical tabs pane
*/
filterFn(tab) {
return !tab.hidden;
}
/**
* get the initial state for the pane from a previous window. this is what happens when you open a new window (not the first window of a session)
* @param {object} sourceWindow (a window object, the window from which the new window was opened)
* @returns {boolean} true if state was successfully restored from source window, false if state must be restored from preferences.
*/
adoptFromWindow(sourceWindow) {
let sourceUI = sourceWindow.verticalTabsPane;
if (!sourceUI || !sourceUI.pane) return false;
this.pane.setAttribute(
"width",
sourceUI.pane.width || sourceUI.pane.getBoundingClientRect().width
);
let sourcePinned = !!sourceUI.pane.getAttribute("unpinned");
sourcePinned ? this.unpin() : this.pane.removeAttribute("unpinned");
sourcePinned
? this.root.setAttribute("vertical-tabs-unpinned", true)
: this.root.removeAttribute("vertical-tabs-unpinned");
this.resetPinnedTooltip();
sourceUI.pane.hidden ? this.close() : this.open();
return true;
}
/**
* for a given descendant of a tab row, return the actual tab row element.
* @param {object} el (a DOM node contained within a tab row)
* @returns the ancestor tab row
*/
findRow(el) {
return el.classList.contains("all-tabs-item") ? el : el.closest(".all-tabs-item");
}
// change the pin/unpin button's tooltip so it reflects the current state.
// if the pane is pinned, the button should say "Collapse pane" and if it's unpinned it should say "Pin pane"
resetPinnedTooltip() {
let newVal = this.pane.getAttribute("unpinned");
this.pinPaneButton.tooltipText =
config.l10n[newVal ? "Pin button tooltip" : "Collapse button tooltip"];
}
/**
* launch a modal prompt (attached to the window) asking the user to set the hover/hover out delay.
* the prompt has an input box containing the current value. it will accept any positive integer.
* this is invoked by the "configure hover delay" context menu items.
* @param {string} pref (which pref the prompt should change)
* @returns an error prompt if the input is invalid, which returns back to this input prompt
*/
promptForIntPref(pref) {
let val, title, text;
switch (pref) {
case hoverDelayPref:
val = this.hoverDelay ?? 100;
title = config.l10n.prompt["Hover delay title"];
text = config.l10n.prompt["Hover delay description"];
break;
case hoverOutDelayPref:
val = this.hoverOutDelay ?? 100;
title = config.l10n.prompt["Hover out delay title"];
text = config.l10n.prompt["Hover out delay description"];
break;
}
let input = { value: val };
let win = Services.wm.getMostRecentWindow(null);
let ok = Services.prompt.prompt(win, title, text, input, null, { value: 0 });
if (!ok) return;
let int = parseInt(input.value, 10);
let onFail = () => {
Services.prompt.alert(
win,
config.l10n.prompt.Invalid,
config.l10n.prompt["Invalid description"]
);
this.promptForIntPref(pref);
};
if (!(int >= 0)) return onFail();
else
try {
prefSvc.setIntPref(pref, int);
} catch (e) {
return onFail();
}
}
/**
* universal event handler — we generally pass the whole class to addEventListener and let this function decide which callback to invoke.
* @param {object} e (an event object)
*/
handleEvent(e) {
let { tab } = e.target;
switch (e.type) {
case "mousedown":
this._onMouseDown(e, tab);
break;
case "mouseup":
this._onMouseUp(e, tab);
break;
case "click":
this._onClick(e);
break;
case "command":
this._onCommand(e, tab);
break;
case "mouseover":
this.warmupRowTab(e, tab);
break;
case "mouseenter":
this._onMouseEnter(e);
break;
case "mouseleave":
this._onMouseLeave(e);
break;
case "deactivate":
this._onDeactivate(e);
break;
case "TabHide":
case "TabShow":
case "TabPinned":
case "TabUnpinned":
case "TabAttrModified":
case "TabBrowserDiscarded":
this._tabAttrModified(e.target);
break;
case "TabClose":
this._tabClose(e.target);
break;
case "TabMove":
this._moveTab(e.target);
break;
case "dragstart":
this._onDragStart(e, tab);
break;
case "dragleave":
this._onDragLeave(e);
break;
case "dragover":
this._onDragOver(e);
break;
case "dragend":
this._onDragEnd(e);
break;
case "drop":
this._onDrop(e);
break;
case "keydown":
this._onKeyDown(e);
break;
case "focus":
this._onFocus(e);
break;
case "blur":
e.currentTarget === this.pane ? this._onPaneBlur(e) : this._onButtonBlur(e);
break;
case "TabMultiSelect":
this._onTabMultiSelect();
break;
case "TabSelect":
if (this.isOpen)
this.tabToElement.get(e.target).scrollIntoView({ block: "nearest" });
break;
}
}
/**
* notification observer. used to receive notifications about prefs changing, or notifications telling us to toggle the pane
* @param {object} subject (the subject of the notification)
* @param {string} topic (the topic "nsPref:changed" is passed to our observer when a pref is changed. we use "vertical-tabs-pane-toggle" to toggle the pane)
* @param {string} data (additional data is often passed, e.g. the name of the preference that changed)
*/
observe(subject, topic, data) {
switch (topic) {
case "vertical-tabs-pane-toggle":
if (subject === window) this.toggle();
break;
case "nsPref:changed":
case "nsPref:read":
this._onPrefChanged(subject, data);
break;
}
}
/**
* for a given preference, get its value, regardless of the preference type.
* @param {object} root (an object with nsIPrefBranch interface — reflects the preference branch we're watching, or just the root)
* @param {string} pref (a preference string)
* @returns the preference's value
*/
getPref(root, pref) {
switch (root.getPrefType(pref)) {
case root.PREF_BOOL:
return root.getBoolPref(pref);
case root.PREF_INT:
return root.getIntPref(pref);
case root.PREF_STRING:
return root.getStringPref(pref);
default:
return null;
}
}
/**
* universal preference observer. when a preference is changed, do something about it.
* @param {object} sub (an object with nsIPrefBranch interface — reflects the preference branch we're watching, or just the root)
* @param {string} pref (the preference that changed)
*/
_onPrefChanged(sub, pref) {
let value = this.getPref(sub, pref);
switch (pref) {
case widthPref:
if (value === null) value = 350;
this.pane.width = value;
break;
case closedPref:
value ? this.close() : this.open();
break;
case unpinnedPref:
value ? this.unpin() : this.pane.removeAttribute("unpinned");
value
? this.root.setAttribute("vertical-tabs-unpinned", true)
: this.root.removeAttribute("vertical-tabs-unpinned");
this.resetPinnedTooltip();
break;
case noExpandPref:
this.noExpand = value;
if (value) {
this.pane.setAttribute("no-expand", true);
this.pane.removeAttribute("expanded");
this.contextMenu._menuitemExpand.removeAttribute("checked");
} else {
this.pane.removeAttribute("no-expand");
this.contextMenu._menuitemExpand.setAttribute("checked", true);
}
break;
case reversePref:
this.reversed = value;
if (this.isOpen) {
for (let item of this.rows) item.remove();
this.tabToElement = new Map();
this._populate();
}
if (value) this.contextMenu._menuitemReverse.setAttribute("checked", true);
else this.contextMenu._menuitemReverse.removeAttribute("checked");
break;
case hoverDelayPref:
this.hoverDelay = value ?? 100;
break;
case hoverOutDelayPref:
this.hoverOutDelay = value ?? 100;
case userContextPref:
case containerOnClickPref:
this.handlePrivacyChange();
break;
case SidebarUI.POSITION_START_PREF:
let menuitem = this.contextMenu._menuitemPosition;
if (value) {
menuitem.label = config.l10n.context["Move Pane to Left"];
menuitem.setAttribute(
"oncommand",
`Services.prefs.setBoolPref(SidebarUI.POSITION_START_PREF, false);`
);
} else {
menuitem.label = config.l10n.context["Move Pane to Right"];
menuitem.setAttribute(
"oncommand",
`Services.prefs.setBoolPref(SidebarUI.POSITION_START_PREF, true);`
);
}
break;
}
}
toggle() {
this.isOpen ? this.close() : this.open();
}
open() {
this.pane.hidden = this.splitter.hidden = false;
this.pane.setAttribute("checked", true);
this.isOpen = true;
this.root.setAttribute("vertical-tabs", true);
if (!this.listenersRegistered) this._populate();
}
close() {
if (this.pane.contains(document.activeElement)) document.activeElement.blur();
this.pane.hidden = this.splitter.hidden = true;
this.pane.removeAttribute("checked");
this.isOpen = false;
this.root.setAttribute("vertical-tabs", false);
this._cleanup();
}
// set the active tab
_selectTab(tab) {
if (gBrowser.selectedTab != tab) gBrowser.selectedTab = tab;
else gBrowser.tabContainer._handleTabSelect();
}
// fill the pane with tab rows
_populate() {
let fragment = document.createDocumentFragment();
for (let tab of gBrowser.tabs)
if (this.filterFn(tab))
fragment[this.reversed ? `prepend` : `appendChild`](this._createRow(tab));
this._addElement(fragment);
this._setupListeners();
for (let row of this.rows) this._setImageAttributes(row, row.tab);
this.selectedRow.scrollIntoView({ block: "nearest", behavior: "instant" });
}
/**
* add an element to the tab container/arrowscrollbox
* @param {object} elementOrFragment (a DOM element or document fragment to add to the container)
*/
_addElement(elementOrFragment) {
this.containerNode.insertBefore(elementOrFragment, this.insertBefore);
}
// invoked when closing the pane. set everything back to default.
_cleanup() {
for (let item of this.rows) item.remove();
this.tabToElement = new Map();
this._cleanupListeners();
clearTimeout(this.hoverOutTimer);
clearTimeout(this.hoverTimer);
this.hoverOutQueued = false;
this.hoverQueued = false;
this.pane.removeAttribute("expanded");
}
// invoked when opening the pane. add all the event listeners.
// this way the script is less wasteful when the pane is closed.
_setupListeners() {
this.listenersRegistered = true;
window.addEventListener("deactivate", this);
this.tabEvents.forEach((ev) => gBrowser.tabContainer.addEventListener(ev, this));
this.dragEvents.forEach((ev) => this.containerNode.addEventListener(ev, this));
this.paneEvents.forEach((ev) => this.pane.addEventListener(ev, this));
if (gToolbarKeyNavEnabled) this.pane.addEventListener("keydown", this);
this.pane.addEventListener("blur", this, true);
gBrowser.addEventListener("TabMultiSelect", this, false);
for (let stop of this.pane.getElementsByTagName("toolbartabstop"))
stop.addEventListener("focus", this);
}
// invoked when closing the pane. clear all the aforementioned event listeners.
_cleanupListeners() {
window.removeEventListener("deactivate", this);
this.tabEvents.forEach((ev) => gBrowser.tabContainer.removeEventListener(ev, this));
this.dragEvents.forEach((ev) => this.containerNode.removeEventListener(ev, this));
this.paneEvents.forEach((ev) => this.pane.removeEventListener(ev, this));
this.pane.removeEventListener("keydown", this);
this.pane.removeEventListener("blur", this, true);
gBrowser.removeEventListener("TabMultiSelect", this, false);
for (let stop of this.pane.getElementsByTagName("toolbartabstop"))
stop.removeEventListener("focus", this);
this.listenersRegistered = false;
}
/**
* callback when a tab attribute is modified. a response to the TabAttrModified custom event dispatched by gBrowser.
* this is what we use to update most of the tab attributes, like busy, soundplaying, etc.
* @param {object} tab (a tab element from the real tab bar)
*/
_tabAttrModified(tab) {
let item = this.tabToElement.get(tab);
if (item) {
if (!this.filterFn(tab)) this._removeItem(item, tab);
else this._setRowAttributes(item, tab);
} else if (this.filterFn(tab)) this._addTab(tab);
}
/**
* the key implies that we're moving a tab, but this doesn't tell us where to move the tab to.
* in reality, this just removes a tab and adds it back. it simply gets called when a tab gets moved by other means,
* so we delete the row and _addTab places it in the same position as its corresponding tab.
* meaning we can't actually move a tab this way, this just helps the tabs pane mirror the real tab bar.
* @param {object} tab (a tab element)
*/
_moveTab(tab) {
let item = this.tabToElement.get(tab);
if (item) {
this._removeItem(item, tab);
this._addTab(tab);
this.selectedRow.scrollIntoView({ block: "nearest", behavior: "instant" });
}
}
/**
* invoked by the above functions. if a tab's attributes change and it's somehow not in the pane already, add it.
* this adds a dom node for a given tab and places it in a position reflecting the tab's real position.
* @param {object} newTab (a tab element that's not already in the pane)
*/
_addTab(newTab) {
if (!this.filterFn(newTab)) return;
let newRow = this._createRow(newTab);
let nextTab = newTab.nextElementSibling;
while (nextTab && !this.filterFn(nextTab)) nextTab = nextTab.nextElementSibling;
let nextRow = this.tabToElement.get(nextTab);
if (this.reversed) {
if (nextRow) nextRow.after(newRow);
else this.containerNode.prepend(newRow);
} else {
if (nextRow) nextRow.parentNode.insertBefore(newRow, nextRow);
else this._addElement(newRow);
}
}
/**
* invoked when a tab is closed from outside the pane. since the tab no longer exists, remove it from the pane.
* @param {object} tab (a tab element)
*/
_tabClose(tab) {
let item = this.tabToElement.get(tab);
if (item) this._removeItem(item, tab);
}
/**
* remove a tab/item pair from the map, and remove the item from the DOM.
* @param {object} item (a row element, e.g. with class all-tabs-item)
* @param {object} tab (a corresponding tab element — every all-tabs-item has a reference to its corresponding tab in property "tab")
*/
_removeItem(item, tab) {
this.tabToElement.delete(tab);
item.remove();
}
/**
* for a given tab, create a row in the pane's container.
* @param {object} tab (a tab element)
* @returns a row element
*/
_createRow(tab) {
let row = create(document, "toolbaritem", {
class: "all-tabs-item",
draggable: true,
});
if (this.className) row.classList.add(this.className);
row.tab = tab;
row.addEventListener("command", this);
row.addEventListener("mousedown", this);
row.addEventListener("mouseup", this);
row.addEventListener("click", this);
row.addEventListener("mouseover", this);
this.tabToElement.set(tab, row);
// main button
row.mainButton = row.appendChild(
create(document, "toolbarbutton", {
class: "all-tabs-button subviewbutton subviewbutton-iconic",
flex: "1",
crop: "right",
})
);
row.mainButton.tab = tab;
// audio button
row.audioButton = row.appendChild(
create(document, "toolbarbutton", {
class: "all-tabs-secondary-button subviewbutton subviewbutton-iconic",
closemenu: "none",
"toggle-mute": "true",
})
);
row.audioButton.tab = tab;
// close button
row.closeButton = row.appendChild(
create(document, "toolbarbutton", {
class: "all-tabs-secondary-button subviewbutton subviewbutton-iconic",
"close-button": "true",
})
);
row.closeButton.tab = tab;
// sound overlay — it only shows when the pane is collapsed
row.soundOverlay = row.appendChild(
create(document, "image", { class: "sound-overlay" }, true)
);
row.soundOverlay.tab = tab;
this._setRowAttributes(row, tab);
return row;
}
/**
* for a given row/tab pair, set the row's attributes equal to the tab's.
* this gets invoked on various events whereupon we need to update a row's display
* @param {object} row (a row element)
* @param {object} tab (a tab element)
*/
_setRowAttributes(row, tab) {
// attributes to set on the row
setAttributes(row, {
selected: tab.selected,
pinned: tab.pinned,
pending: tab.getAttribute("pending"),
multiselected: tab.getAttribute("multiselected"),
muted: tab.muted,
soundplaying: tab.soundPlaying,
"activemedia-blocked": tab.activeMediaBlocked,
pictureinpicture: tab.pictureinpicture,
notselectedsinceload: tab.getAttribute("notselectedsinceload"),
});
// we need to use classes for the usercontext/container, since the built-in CSS that sets the identity color & icon uses classes, not attributes.
if (tab.userContextId) {
let idColor = ContextualIdentityService.getPublicIdentityFromId(
tab.userContextId
)?.color;
row.className = idColor
? `all-tabs-item identity-color-${idColor}`
: "all-tabs-item";
row.setAttribute("usercontextid", tab.userContextId);
} else {
row.className = "all-tabs-item";
row.removeAttribute("usercontextid");
}
// set attributes on the main button, in particular the tab title and favicon.
let busy = tab.getAttribute("busy");
setAttributes(row.mainButton, {
busy,
label: tab.label,
image: !busy && tab.getAttribute("image"),
iconloadingprincipal: tab.getAttribute("iconloadingprincipal"),
});
this._setImageAttributes(row, tab);
// decide which icon to display for the audio button, or whether it should be displayed at all.
setAttributes(row.audioButton, {
muted: tab.muted,
soundplaying: tab.soundPlaying,
"activemedia-blocked": tab.activeMediaBlocked,
pictureinpicture: tab.pictureinpicture,
hidden: !(
tab.muted ||
tab.soundPlaying ||
tab.activeMediaBlocked ||
tab.pictureinpicture
),
});
}
/**
* show a throbber in place of the favicon while a tab is loading.
* @param {object} row (a row element)
* @param {object} tab (a row element)
*/
_setImageAttributes(row, tab) {
let image = row.mainButton.icon;
if (image) {
let busy = tab.getAttribute("busy");
let progress = tab.getAttribute("progress");
setAttributes(image, { busy, progress });
if (busy) image.classList.add("tab-throbber-tabslist");
else image.classList.remove("tab-throbber-tabslist");
}
}
get mouseTargetRect() {
return windowUtils.getBoundsWithoutFlushing(this.pane);
}
/**
* get the previous or next node for a given TreeWalker
* @param {object} walker (a TreeWalker object)
* @param {boolean} prev (whether to walk backwards or forwards)
* @returns the next eligible DOM node to focus
*/
getNewFocus(walker, prev) {
return prev ? walker.previousNode() : walker.nextNode();
}
/**
* cycle focus between buttons in the pane
* @param {boolean} prev (whether to go backwards or forwards)
* @param {boolean} horizontal (whether we're navigating with left/right or up/down)
*/
navigateButtons(prev, horizontal) {
let walker = horizontal ? this.horizontalWalker : this.verticalWalker;
let oldFocus = document.activeElement;
walker.currentNode = oldFocus;
let newFocus = this.getNewFocus(walker, prev);
while (newFocus && newFocus.tagName == "toolbartabstop")
newFocus = this.getNewFocus(walker, prev);