-
Notifications
You must be signed in to change notification settings - Fork 27
/
recentlyClosedTabsContextMenu.uc.js
1159 lines (1116 loc) · 43.9 KB
/
recentlyClosedTabsContextMenu.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 Undo Recently Closed Tabs in Tab Context Menu
// @version 2.1.5
// @author aminomancer
// @homepageURL https://github.com/aminomancer/uc.css.js
// @long-description
// @description
/*
Adds new menus to the context menu that appears when you right-click a tab (in the tab bar or in the [TreeStyleTab][] sidebar): one lists recently closed tabs so you can restore them, and another lists recently closed windows. These are basically the same functions that exist in the history toolbar button's popup, but I think the tab context menu is a more convenient location for them.
Also optionally adds a context menu to the history panel's subview pages for "Recently closed tabs" and "Recently closed windows" with various functions for interacting with the closed tabs and their session history. You can right-click a closed tab item to open the context menu, then click "Remove from List" to get rid of it.
You can click "Remove from History" to not only remove the closed tab item, but also forget all of the tab's history — that is, every page it navigated to. The same can be done with recently closed windows. From this menu you can also restore a tab in a new window or private window, bookmark a closed tab/window, and more.
This script also adds a new preference `userChrome.tabs.recentlyClosedTabs.middle-click-to-remove` which changes the behavior when you click a recently closed tab/window item in the history panel. Middle clicking a tab or window item will remove it from the list (just like one of the context menu items). Ctrl+clicking a tab item it will open it in a new tab (instead of restoring it in its former place), and Ctrl+Shift+clicking it will open it in a new window.
[TreeStyleTab]: https://addons.mozilla.org/firefox/addon/tree-style-tab/
*/
// @downloadURL https://cdn.jsdelivr.net/gh/aminomancer/uc.css.js@master/JS/recentlyClosedTabsContextMenu.uc.js
// @updateURL https://cdn.jsdelivr.net/gh/aminomancer/uc.css.js@master/JS/recentlyClosedTabsContextMenu.uc.js
// @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==
class UndoListInTabmenu {
// user preferences. add these in about:config if you want them to persist
// between script updates without having to reapply them.
static config = {
// set this to false if you don't want popup windows to be listed in
// recently closed windows.
"Include popup windows": Services.prefs.getBoolPref(
"recentlyClosedTabsContextMenu.includePopupWindows",
true
),
/* in vanilla firefox there isn't any way to tell whether a closed tab was a
container tab. you just have to restore it to find out. with this setting,
you can show the container's color as a stripe on the edge of the tab's
menuitem/button. */
"Show container tab colors": {
// show on items in built-in popup panels like the history toolbar
// button's popup menu and the hamburger/app menu.
inPopupPanels: Services.prefs.getBoolPref(
"recentlyClosedTabsContextMenu.showContainerTabColors.inPopupPanels",
true
),
// show on items in the context menus made by this script, and in the
// built-in history menu in the main titlebar menu bar. if both inMenupopups
// and inPopupPanels are false, container colors won't show anywhere.
inMenupopups: Services.prefs.getBoolPref(
"recentlyClosedTabsContextMenu.showContainerTabColors.inMenupopups",
true
),
// restore window items can contain more than one tab with different
// containers. so some users may want to disable container colors on
// window items. I prefer showing the color because it will show the color
// for the window's active tab — that's how it shows all other tab
// information. it shows the favicon and title for the closed window's
// active tab, since it's not practical to show info for every tab. so it
// might as well show the active tab's container too.
showForWindows: Services.prefs.getBoolPref(
"recentlyClosedTabsContextMenu.showContainerTabColors.showForWindows",
true
),
},
// you can set this to false if you don't want a context menu to open when
// you right-click an item in one of the "recently closed tab/window"
// panels. this won't affect the main context menus added by the script,
// since you can't open a context menu from inside a context menu. this only
// affects *panels*, e.g., the "recently closed tabs" subview that you can
// open when you click the history toolbar button or the hamburger button.
// if you have no idea what I'm talking about, an easy way to tell the
// difference between a menu and a panel is to look at the background color
// of the menu. with firefox's default built-in dark theme, menus have a
// much darker gray background than panels.
"Enable context menus in panels": true,
// the user-facing strings. change these if your firefox language is not english.
l10n: {
// displayed next to popup windows in the recently closed windows list.
// intended to help distinguish regular windows from popup windows, which
// are often more transient and generated by websites' scripts. if you set
// "Include popup windows" to false, this won't show up in the context
// menus since they won't show popup windows at all. but it will still
// show up in the recently closed windows list in the history panel. this
// can't be localized automatically so for non-english languages you'll
// have to write the label yourself. if you don't want popup windows to be
// labeled at all, just change this to ""
"Popup window label": "(popup)",
// one of the letters in the "Recently Closed Tabs" menu label is
// underlined. this is the menu's access key. pressing this key while the
// context menu is open will automatically select the menu. in English
// this key is "T" and in other languages it will usually be the first
// letter of the last word. it handles right-to-left languages
// appropriately. but it has no way of knowing whether the last word of
// the label means "tabs" or "recently" or "closed"; it just expects a
// grammatical structure similar to English. that is not a safe
// assumption, but there's not much I can do about it without implementing
// special behavior for every language, and I'm not exactly a linguist.
// it's a lot easier for you to just choose your own access key if you
// don't like the key it's automatically choosing for you. the key you
// enter here does not have to actually be a letter that's present in the
// label. if you put "Q" for example, it would still work. it would just
// add (Q) to the end of the label instead of underlining a letter.
// obviously you want to input a letter that actually exists on your
// keyboard so you'll be able to use it. if you leave this preference
// empty, the script will fall back to the automatic selection behavior.
"Tabs access key": "",
// just like the previous preference, but for the "Recently Closed
// Windows" menu. in English this is "W" by default. if you use this or
// the "New Tab" item's access key a lot you may want to change it, since
// they both use "W" as their access key. when two menu items have the
// same accesskey, pressing it will just cycle between the two without
// activating either. this item was added after I wrote the script, and I
// can't really change it because the access key is calculated
// automatically, based on the first letter of the last word.
"Windows access key": "",
// these are for the context menu that opens when you right-click
// a recently-closed item in a popup panel
Restore: { label: "Restore", accesskey: "R" },
"Restore in New Window": {
label: "Restore in New Window",
accesskey: "N",
},
"Restore in New Private Window": {
label: "Restore in New Private Window",
accesskey: "P",
},
"Remove from List": { label: "Remove from List", accesskey: "L" },
"Remove from History": { label: "Remove from History", accesskey: "H" },
"Bookmark Page": { label: "Bookmark Page", accesskey: "B" },
},
};
constructor() {
this.create = UC_API.Utils.createElement;
this.config = UndoListInTabmenu.config;
XPCOMUtils.defineLazyPreferenceGetter(
this,
"closedTabsFromClosedWindowsEnabled",
"browser.sessionstore.closedTabsFromClosedWindows"
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
"closedTabsFromAllWindowsEnabled",
"browser.sessionstore.closedTabsFromAllWindows"
);
this.registerSheet();
// set up context menu for TST, if it's installed. it'll set up even if TST
// is disabled, since otherwise we'd have to listen for addon
// disabling/enabling, and it's too much work to set up an addon manager
// listener. but that doesn't matter, since if TST is disabled, its sidebar
// will never be opened, and most of the setup is triggered by the sidebar
// opening.
this.attachSidebarListener();
// set up the built-in tabs bar context menu.
this.makePopups(document.getElementById("tabContextMenu"));
// this context menu shows when you right-click an empty area in the tab strip.
this.makePopups(document.getElementById("toolbar-context-menu"));
this.modMethods();
}
// if the recently closed windows menu is empty, or it's only full of popups
// and the user set "Include popup windows" to false, we should hide the menu.
get shouldHideWindows() {
let windowData = SessionStore.getClosedWindowData();
return (
!windowData.length ||
(!this.config["Include popup windows"] &&
windowData.every(w => w.isPopup))
);
}
// get a fluent localization interface. we can't use data-l10n-id since that would
// automatically remove the menus' accesskeys, and we want them to have accesskeys.
get l10n() {
if (!this._l10n) {
this._l10n = new Localization(
["browser/menubar.ftl", "browser/recentlyClosed.ftl"],
true
);
}
return this._l10n;
}
// if TST is installed, listen for its sidebar opening
async attachSidebarListener() {
let TST = await AddonManager.getAddonByID("[email protected]");
if (TST) {
window.SidebarController._switcherTarget.addEventListener(
"SidebarShown",
this
);
}
}
// when a TST sidebar is created, add context menus.
// when context menu is opened, hide/show the menus.
handleEvent(e) {
let sidebarContext = document
.getElementById("sidebar")
?.document?.getElementById("contentAreaContextMenu");
switch (e.type) {
case "SidebarShown":
// if there's no content area context menu inside the sidebar document,
// it means a native sidebar is open. (not an extension sidebar) we
// don't need to remove the DOM nodes since firefox already deleted the
// whole document. just delete the references so we don't get confused
// when rebuilding them later.
if (!sidebarContext) {
delete this.sidebarContextUndoListPopup;
delete this.sidebarUndoWindowPopup;
break;
}
// make the popups and listen for the context menu showing. also set an
// attribute to avoid duplicating everything if there's a repeat event
// for whatever reason. the content area context menu actually sticks
// around if you switch from one extension sidebar to another, but we
// delete our menu items if the sidebar is switched to anything but TST.
if (
window.SidebarController.currentID ===
"treestyletab_piro_sakura_ne_jp-sidebar-action"
) {
if (sidebarContext.hasAttribute("undo-list-init")) break;
sidebarContext.setAttribute("undo-list-init", true);
sidebarContext.addEventListener("popupshowing", this);
this.makeSidebarPopups(sidebarContext);
} else {
// destroy everything
if (!sidebarContext.hasAttribute("undo-list-init")) break;
sidebarContext.removeAttribute("undo-list-init", true);
sidebarContext.removeEventListener("popupshowing", this);
this.destroySidebarPopups();
}
break;
case "popupshowing":
// the sidebar context menu is showing, so we should hide/show the menus depending
// on whether they're empty closed tab list is empty so should be hidden
if (SessionStore.getClosedTabCountForWindow(window) == 0) {
this.sidebarTabMenu.hidden = true;
this.sidebarTabMenu.style.removeProperty("display");
} else {
this.sidebarTabMenu.hidden = false;
this.sidebarTabMenu.style.display = "flex";
}
// closed window list is empty so should be hidden
if (this.shouldHideWindows) {
this.sidebarWindowMenu.hidden = true;
this.sidebarWindowMenu.style.removeProperty("display");
} else {
this.sidebarWindowMenu.hidden = false;
this.sidebarWindowMenu.style.display = "flex";
}
break;
}
}
// return the localized label for "recently closed tabs"
get closedTabsLabel() {
return (
this._closedTabsLabel ||
(this._closedTabsLabel = this.l10n.formatMessagesSync([
"menu-history-undo-menu",
])[0].attributes[0].value)
);
}
// return the localized label for "recently closed windows"
get closedWindowsLabel() {
return (
this._closedWindowsLabel ||
(this._closedWindowsLabel = this.l10n.formatMessagesSync([
"menu-history-undo-window-menu",
])[0].attributes[0].value)
);
}
/**
* create context menu items
* @param {object} context (the context menu to add menus to)
*/
makePopups(context) {
let undoItem = context.querySelector(`[id*="undoCloseTab"]`);
// Recently Closed Windows
let windowMenu = this.create(document, "menu", {
id: `${context.id}-historyUndoWindowMenu3`,
class: "recently-closed-windows-menu",
"data-l10n-id": "menu-history-undo-window-menu",
});
undoItem.after(windowMenu);
windowMenu.appendChild(
this.create(document, "menupopup", {
onpopupshowing: `undoTabMenu.populateSubmenu(this, "Window");`,
})
);
// Recently Closed Tabs
let tabMenu = this.create(document, "menu", {
id: `${context.id}-tabContextUndoList`,
class: "recently-closed-tabs-menu",
"data-l10n-id": "menu-history-undo-menu",
});
undoItem.after(tabMenu);
tabMenu.appendChild(
this.create(document, "menupopup", {
onpopupshowing: `undoTabMenu.populateSubmenu(this, "Tab");`,
})
);
// every time the context menu opens, handle access keys and enabling/disabling
// of the menus. menus need to be hidden if there aren't any recently closed
// tabs/windows in sessionstore, or else the menus will be awkwardly empty.
context.addEventListener("popupshowing", e => {
if (e.target !== context) return;
// if you right-click an empty area in the tab strip, (e.g. if there
// aren't enough tabs to overflow the strip) you get a different context
// menu. this is the same context menu you get when you right-click a
// toolbar button in the navbar. so we have to add separate menuitems to
// this context menu. and since this context menu doesn't only relate to
// tabs, we have to hide the new menuitems in other circumstances, like
// when right-clicking a toolbar button.
if (e.target.id === "toolbar-context-menu") {
let toolbarItem = e.target.triggerNode;
if (toolbarItem && toolbarItem.localName == "toolbarpaletteitem") {
toolbarItem = toolbarItem.firstElementChild;
} else if (toolbarItem && toolbarItem.localName != "toolbar") {
while (toolbarItem && toolbarItem.parentElement) {
let parent = toolbarItem.parentElement;
if (
(parent.classList &&
parent.classList.contains("customization-target")) ||
parent.getAttribute("overflowfortoolbar") || // Needs to work in the overflow list as well.
parent.localName == "toolbarpaletteitem" ||
parent.localName == "toolbar"
) {
break;
}
toolbarItem = parent;
}
} else {
toolbarItem = null;
}
if (toolbarItem.id !== "tabbrowser-tabs") {
tabMenu.hidden = true;
windowMenu.hidden = true;
return;
}
}
let winWords = windowMenu.label.split(" ");
windowMenu.accessKey =
this.config.l10n["Windows access key"] ||
(RTL_UI
? windowMenu.label.substr(0, 1)
: winWords[winWords.length - 1]?.substr(0, 1) || "W");
let tabWords = tabMenu.label.split(" ");
tabMenu.accessKey =
this.config.l10n["Tabs access key"] ||
(RTL_UI
? tabMenu.label.substr(0, 1)
: tabWords[tabWords.length - 1]?.substr(0, 1) || "T");
// closed tab list is empty so should be hidden
tabMenu.hidden = !!(SessionStore.getClosedTabCountForWindow(window) == 0);
// closed window list is empty so should be hidden
windowMenu.hidden = !!window.undoTabMenu.shouldHideWindows;
});
}
/**
* create context menu items (for sidebar)
* @param {object} context (the context menu to add menus to)
*/
makeSidebarPopups(context) {
let doc = context.ownerDocument;
// Recently Closed Tabs
let tabWords = this.closedTabsLabel.split(" ");
this.sidebarTabMenu = this.create(doc, "menu", {
id: "sidebarTabContextUndoList",
label: this.closedTabsLabel,
accesskey:
this.config.l10n["Tabs access key"] ||
(RTL_UI
? this.closedTabsLabel.substr(0, 1)
: tabWords[tabWords.length - 1]?.substr(0, 1) || "T"),
});
context.appendChild(this.sidebarTabMenu);
this.sidebarContextUndoListPopup = this.sidebarTabMenu.appendChild(
this.create(doc, "menupopup", {
onpopupshowing: `window.top.undoTabMenu.populateSidebarSubmenu(this, "Tab")`,
})
);
// Recently Closed Windows
let winWords = this.closedWindowsLabel.split(" ");
this.sidebarWindowMenu = this.create(doc, "menu", {
id: "sidebarHistoryUndoWindowMenu3",
label: this.closedWindowsLabel,
accesskey:
this.config.l10n["Windows access key"] ||
(RTL_UI
? this.closedWindowsLabel.substr(0, 1)
: winWords[winWords.length - 1]?.substr(0, 1) || "W"),
});
context.appendChild(this.sidebarWindowMenu);
this.sidebarUndoWindowPopup = this.sidebarWindowMenu.appendChild(
this.create(doc, "menupopup", {
onpopupshowing: `window.top.undoTabMenu.populateSidebarSubmenu(this, "Window")`,
})
);
}
// clean up all the sidebar context menu stuff we created
destroySidebarPopups() {
this.sidebarTabMenu.remove();
this.sidebarWindowMenu.remove();
delete this.sidebarTabMenu;
delete this.sidebarWindowMenu;
}
/**
* update submenu items
* @param {object} popup (a menupopup DOM node to populate)
* @param {string} type (the type of submenu being updated; "Tab" or "Window")
*/
populateSubmenu(popup, type) {
// remove existing menuitems
while (popup.hasChildNodes()) popup.firstChild.remove();
let fragment;
// list is empty so should be hidden
const itemsCount =
SessionStore[`getClosed${type}Count${type === "Tab" ? "ForWindow" : ""}`](
window
);
if (itemsCount === 0) {
popup.parentNode.hidden = true;
return;
}
popup.parentNode.hidden = false; // enable menu if it's not empty
// make the list of menuitems
fragment = RecentlyClosedTabsAndWindowsMenuUtils[`get${type}sFragment`](
window,
"menuitem",
false,
true
);
fragment.lastChild.accessKey = fragment.lastChild.label.substr(0, 1) || "R";
popup.appendChild(fragment); // populate menu
}
/**
* update sidebar submenu items
* @param {object} popup (a menupopup DOM node to populate)
* @param {string} type (the type of submenu being updated; "Tab" or "Window")
*/
populateSidebarSubmenu(popup, type) {
// remove existing menuitems
while (popup.hasChildNodes()) popup.firstChild.remove();
let fragment;
// list is empty so should be hidden
const itemsCount =
SessionStore[`getClosed${type}Count${type === "Tab" ? "ForWindow" : ""}`](
window
);
if (itemsCount === 0) {
popup.parentNode.hidden = true;
return;
}
popup.parentNode.hidden = false; // enable menu if it's not empty
// make a temporary list of menuitems
fragment = RecentlyClosedTabsAndWindowsMenuUtils[`get${type}sFragment`](
window,
"menuitem",
false,
true
);
// a bit of a sketchy hack... instead of inserting the fragment directly, we
// need to create the elements *inside* the sidebar document or else they're
// missing a bunch of class methods, like content optimizations. the only
// way I could find to get them to render properly is to iterate over the
// fragment, building a new tree as we go. also, since the "oncommand"
// callbacks need access to global objects like gBrowser which don't exist
// in the context menu's scope, we need to use addEventListener instead of
// setting "oncommand" attributes. so when we get to "oncommand" we just
// parse its value into an anonymous function and attach it in THIS scope.
Object.values(fragment.children).forEach(item => {
let newItem = popup.ownerDocument.createXULElement(item.tagName);
Object.values(item.attributes).forEach(attribute => {
if (attribute.name === "key") return;
if (attribute.name === "oncommand") {
return newItem.addEventListener(
"command",
new Function("event", attribute.value)
);
}
newItem.setAttribute(attribute.name, attribute.value);
});
popup.appendChild(newItem);
});
popup.lastChild.accessKey = popup.lastChild.label.substr(0, 1) || "R";
}
modMethods() {
Object.defineProperty(RecentlyClosedTabsAndWindowsMenuUtils, "l10n", {
configurable: true,
enumerable: true,
get: () => this.l10n,
});
RecentlyClosedTabsAndWindowsMenuUtils.setImage = function (
aItem,
aElement
) {
let iconURL = aItem.image;
if (/^https?:/.test(iconURL)) iconURL = `moz-anno:favicon:${iconURL}`;
aElement.setAttribute("image", iconURL);
};
RecentlyClosedTabsAndWindowsMenuUtils.createEntry = function (
aTagName,
aIsWindowsFragment,
aIndex,
aClosedTab,
aDocument,
aMenuLabel,
aFragment,
forContext
) {
let element = aDocument.createXULElement(aTagName);
element.setAttribute("label", aMenuLabel);
if (aClosedTab.image) {
const iconURL = PlacesUIUtils.getImageURL(aClosedTab.image);
element.setAttribute("image", iconURL);
}
element.setAttribute("value", aIndex);
element.setAttribute(
"restore-type",
aIsWindowsFragment ? "window" : "tab"
);
if (aTagName == "menuitem") {
element.setAttribute(
"class",
"menuitem-iconic bookmark-item menuitem-with-favicon"
);
}
element.classList.add("recently-closed-item");
if (aIsWindowsFragment) {
element.setAttribute("oncommand", `undoCloseWindow("${aIndex}");`);
} else if (typeof aClosedTab.sourceClosedId == "number") {
// sourceClosedId is used to look up the closed window to remove it when the tab is restored
let { sourceClosedId } = aClosedTab;
element.setAttribute("source-closed-id", sourceClosedId);
element.setAttribute("value", aClosedTab.closedId);
element.removeAttribute("oncommand");
element.addEventListener(
"command",
event => {
SessionStore.undoClosedTabFromClosedWindow(
{ sourceClosedId },
aClosedTab.closedId
);
if (event.button === 1) {
gBrowser.moveTabToEnd();
}
},
{ once: true }
);
} else {
// sourceWindowId is used to look up the closed tab entry to remove it when it is restored
let { sourceWindowId } = aClosedTab;
element.setAttribute("value", aIndex);
element.setAttribute("source-window-id", sourceWindowId);
element.setAttribute(
"oncommand",
`undoCloseTab(${aIndex}, "${sourceWindowId}");if(event.button === 1){gBrowser.moveTabToEnd()};`
);
}
let tabData;
tabData = aIsWindowsFragment ? aClosedTab : aClosedTab.state;
let activeIndex = (tabData.index || tabData.entries.length) - 1;
if (activeIndex >= 0 && tabData.entries[activeIndex]) {
element.setAttribute("targetURI", tabData.entries[activeIndex].url);
}
if (aTagName != "menuitem") {
element.setAttribute(
"onclick",
`undoTabSubmenu.on${
aIsWindowsFragment ? "Window" : "Tab"
}ItemClick(event)`
);
}
if (!forContext && aTagName != "menuitem") {
element.setAttribute("tooltip", "bhTooltip");
if (UndoListInTabmenu.config["Enable context menus in panels"]) {
element.setAttribute("context", "recently-closed-menu");
}
if (aIndex == 0) {
element.setAttribute(
"key",
`key_undoClose${aIsWindowsFragment ? "Window" : "Tab"}`
);
}
}
let identity = ContextualIdentityService?.getPublicIdentityFromId(
tabData.userContextId
);
if (identity && identity.color) {
element.setAttribute("usercontextid", identity.userContextId);
element.classList.add(`identity-color-${identity.color}`);
}
aFragment.appendChild(element);
};
RecentlyClosedTabsAndWindowsMenuUtils.createRestoreAllEntry = function (
aDocument,
aFragment,
aPrefixRestoreAll,
aIsWindowsFragment,
aRestoreAllLabel,
aTagName
) {
let restoreAllElements = aDocument.createXULElement(aTagName);
restoreAllElements.classList.add("restoreallitem");
restoreAllElements.setAttribute(
"label",
RecentlyClosedTabsAndWindowsMenuUtils.l10n.formatValueSync(
aRestoreAllLabel
)
);
restoreAllElements.addEventListener(
"command",
aIsWindowsFragment
? RecentlyClosedTabsAndWindowsMenuUtils.onRestoreAllWindowsCommand
: RecentlyClosedTabsAndWindowsMenuUtils.onRestoreAllTabsCommand
);
if (aPrefixRestoreAll) {
aFragment.insertBefore(restoreAllElements, aFragment.firstChild);
} else {
aFragment.appendChild(aDocument.createXULElement("menuseparator"));
aFragment.appendChild(restoreAllElements);
}
};
RecentlyClosedTabsAndWindowsMenuUtils.getWindowsFragment = function (
aWindow,
aTagName,
aPrefixRestoreAll = false,
forContext
) {
let closedWindowData = SessionStore.getClosedWindowData();
let doc = aWindow.document;
let fragment = doc.createDocumentFragment();
if (closedWindowData.length) {
for (let i = 0; i < closedWindowData.length; i++) {
const { selected, tabs, title, isPopup } = closedWindowData[i];
const selectedTab = tabs[selected - 1];
let menuLabel =
RecentlyClosedTabsAndWindowsMenuUtils.l10n.formatValueSync(
"recently-closed-undo-close-window-label",
{ tabCount: tabs.length - 1, winTitle: title }
);
if (UndoListInTabmenu.config.l10n["Popup window label"] && isPopup) {
menuLabel = `${menuLabel} ${UndoListInTabmenu.config.l10n["Popup window label"]}`;
}
if (
!isPopup ||
UndoListInTabmenu.config["Include popup windows"] ||
!forContext
) {
RecentlyClosedTabsAndWindowsMenuUtils.createEntry(
aTagName,
true,
i,
selectedTab,
doc,
menuLabel,
fragment,
forContext
);
}
}
RecentlyClosedTabsAndWindowsMenuUtils.createRestoreAllEntry(
doc,
fragment,
aPrefixRestoreAll,
true,
aTagName == "menuitem"
? "recently-closed-menu-reopen-all-windows"
: "recently-closed-panel-reopen-all-windows",
aTagName
);
}
return fragment;
};
RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment = function (
aWindow,
aTagName,
aPrefixRestoreAll = false,
forContext
) {
let doc = aWindow.document;
const isPrivate = PrivateBrowsingUtils.isWindowPrivate(aWindow);
let fragment = doc.createDocumentFragment();
let isEmpty = true;
if (
SessionStore.getClosedTabCount({
sourceWindow: aWindow,
closedTabsFromClosedWindows: false,
})
) {
isEmpty = false;
const browserWindows = this.closedTabsFromAllWindowsEnabled
? SessionStore.getWindows(aWindow)
: [aWindow];
for (const win of browserWindows) {
let closedTabs = SessionStore.getClosedTabDataForWindow(win);
for (let i = 0; i < closedTabs.length; i++) {
RecentlyClosedTabsAndWindowsMenuUtils.createEntry(
aTagName,
false,
i,
closedTabs[i],
doc,
closedTabs[i].title,
fragment,
forContext
);
}
}
if (
!isPrivate &&
this.closedTabsFromClosedWindowsEnabled &&
SessionStore.getClosedTabCountFromClosedWindows()
) {
isEmpty = false;
const closedTabs = SessionStore.getClosedTabDataFromClosedWindows();
for (let i = 0; i < closedTabs.length; i++) {
RecentlyClosedTabsAndWindowsMenuUtils.createEntry(
aTagName,
false,
i,
closedTabs[i],
doc,
closedTabs[i].title,
fragment,
forContext
);
}
}
if (!isEmpty) {
RecentlyClosedTabsAndWindowsMenuUtils.createRestoreAllEntry(
doc,
fragment,
aPrefixRestoreAll,
false,
aTagName == "menuitem"
? "recently-closed-menu-reopen-all-tabs"
: "recently-closed-panel-reopen-all-tabs",
aTagName
);
}
}
return fragment;
};
}
registerSheet() {
let tag;
let { inPopupPanels, inMenupopups, showForWindows } =
this.config["Show container tab colors"];
if (inPopupPanels && inMenupopups) tag = "";
else if (inPopupPanels) tag = "toolbarbutton";
else if (inMenupopups) tag = "menuitem";
else return;
let restoreType = showForWindows ? "" : `[restore-type="tab"]`;
const css = `${tag}.recently-closed-item[usercontextid]${restoreType} {
background-image: linear-gradient(
to right,
var(--identity-tab-color, transparent) 0,
var(--identity-tab-color, transparent) 3px,
transparent 3px
);
}`;
let sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(
Ci.nsIStyleSheetService
);
let uri = makeURI(`data:text/css;charset=UTF=8,${encodeURIComponent(css)}`);
if (sss.sheetRegistered(uri, sss.AUTHOR_SHEET)) return;
sss.loadAndRegisterSheet(uri, sss.AUTHOR_SHEET);
}
}
class RecentlyClosedPanelContext {
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
constructor() {
this.config = UndoListInTabmenu.config;
let { l10n } = this.config;
XPCOMUtils.defineLazyPreferenceGetter(
this,
"REMOVE_ON_MID_CLICK",
"userChrome.tabs.recentlyClosedTabs.middle-click-to-remove",
false
);
this.menupopup = document.querySelector("#mainPopupSet").appendChild(
UC_API.Utils.createElement(document, "menupopup", {
id: "recently-closed-menu",
})
);
this.menupopup.addEventListener("command", this);
this.menupopup.addEventListener("popupshowing", this);
this.restore = this.menupopup.appendChild(
UC_API.Utils.createElement(document, "menuitem", {
id: "recently-closed-restore",
label: l10n.Restore.label,
accesskey: l10n.Restore.accesskey,
})
);
this.restoreInNewWindow = this.menupopup.appendChild(
UC_API.Utils.createElement(document, "menuitem", {
id: "recently-closed-restore-in-new-window",
label: l10n["Restore in New Window"].label,
accesskey: l10n["Restore in New Window"].accesskey,
})
);
this.restoreInNewPrivateWindow = this.menupopup.appendChild(
UC_API.Utils.createElement(document, "menuitem", {
id: "recently-closed-restore-in-new-private-window",
label: l10n["Restore in New Private Window"].label,
accesskey: l10n["Restore in New Private Window"].accesskey,
})
);
this.removalSeparator = this.menupopup.appendChild(
UC_API.Utils.createElement(document, "menuseparator", {
id: "recently-closed-removal-separator",
})
);
this.removeFromList = this.menupopup.appendChild(
UC_API.Utils.createElement(document, "menuitem", {
id: "recently-closed-remove-from-list",
label: l10n["Remove from List"].label,
accesskey: l10n["Remove from List"].accesskey,
})
);
this.removeFromHistory = this.menupopup.appendChild(
UC_API.Utils.createElement(document, "menuitem", {
id: "recently-closed-remove-from-history",
label: l10n["Remove from History"].label,
accesskey: l10n["Remove from History"].accesskey,
})
);
this.placesSeparator = this.menupopup.appendChild(
UC_API.Utils.createElement(document, "menuseparator", {
id: "recently-closed-places-separator",
})
);
this.bookmark = this.menupopup.appendChild(
UC_API.Utils.createElement(document, "menuitem", {
id: "recently-closed-bookmark",
label: l10n["Bookmark Page"].label,
accesskey: l10n["Bookmark Page"].accesskey,
})
);
// firefox only updates the recently closed x panels when they're initially opened.
// so if you close a tab while it's open, that tab won't be added to the panel.
Services.obs.addObserver(this, "sessionstore-closed-objects-changed");
}
goBackOrHide(panelview, force = false) {
if (!panelview.panelMultiView) return;
let multiView = PanelMultiView.forNode(panelview.panelMultiView);
if (force || !(multiView.openViews?.length > 1)) {
multiView?.hidePopup();
} else {
multiView.goBack();
}
}
updatePanel(panelview) {
if (!panelview) return;
if (panelview.id !== "PanelUI-history") {
let text = panelview.querySelector(
".panel-header > h1 > span"
).textContent;
panelview.dispatchEvent(
new CustomEvent("ViewShowing", { bubbles: true })
);
PanelView.forNode(panelview).headerText = text;
}
PanelMultiView.getViewNode(document, "appMenuRecentlyClosedTabs").disabled =
SessionStore.getClosedTabCountForWindow(window) == 0;
PanelMultiView.getViewNode(
document,
"appMenuRecentlyClosedWindows"
).disabled = SessionStore.getClosedWindowCount() == 0;
}
handleEvent(e) {
switch (e.type) {
case "popupshowing":
this.onPopupShowing();
break;
case "command":
this.onCommand(e);
break;
default:
}
}
async observe(subject, topic, data) {
if (this.updateTimer || topic !== "sessionstore-closed-objects-changed") {
return;
}
this.updateTimer = await this.sleep(15);
this.updatePanel(
document.querySelector(
"panelview[visible]:is(#appMenu-library-recentlyClosedTabs, #appMenu-library-recentlyClosedWindows, #PanelUI-history)"
)
);
delete this.updateTimer;
}
onPopupShowing() {
let button = this.menupopup.triggerNode;
this.restoreInNewWindow.hidden = this.restoreInNewPrivateWindow.hidden =
button.getAttribute("restore-type") !== "tab";
if (PrivateBrowsingUtils.isWindowPrivate(window)) {
this.restoreInNewPrivateWindow.hidden = true;
}
}
async onCommand(e) {
let button = this.menupopup.triggerNode;
let panelview = button.closest("panelview");
switch (e.target) {
case this.restore:
this.onRestore(e, button);
break;
case this.restoreInNewWindow:
this.onRestoreInNewWindow(button, panelview);
break;
case this.restoreInNewPrivateWindow:
this.onRestoreInNewWindow(button, panelview, { private: true });
break;
case this.removeFromList:
this.onRemoveFromList(button);
break;
case this.removeFromHistory:
await this.onRemoveFromHistory(button);
break;
case this.bookmark:
this.onBookmark(button, panelview);
break;
default:
return;
}
this.updatePanel(panelview);
}
onRestore(e, button) {
switch (button.getAttribute("restore-type")) {
case "tab":
this.onRestoreTab(e, button);
break;
case "window":
undoCloseWindow(button.getAttribute("value"));
break;
}
button.remove();
}
onRestoreTab(e, button) {
undoCloseTab(Number(button.getAttribute("value")));
if (e.button === 1) gBrowser.moveTabToEnd();
}
onRestoreInNewWindow(button, panelview, params = {}) {
// open a new window
if (PrivateBrowsingUtils.isWindowPrivate(window)) params.private = true;
let newWin = OpenBrowserWindow(params);
let value = button.getAttribute("value");
let tabData = SessionStore.getClosedTabDataForWindow(window)[value];
let { state } = tabData;
let init = () => {
let tabbrowser = newWin.gBrowser || newWin._gBrowser;
let tab = tabbrowser.addTrustedTab(null, {
pinned: state.pinned,
userContextId: state.userContextId,
});
let firstTab = tabbrowser.selectedTab;
tabbrowser.selectedTab = tab;
tabbrowser.removeTab(firstTab, { animate: false, byMouse: false });
// restore closed tab state into the new window's tab
SessionStore.setTabState(tab, state);
SessionStore.forgetClosedTab(window, value);
this.goBackOrHide(panelview, true);
};
// wait until the new window's tabbrowser is initialized