forked from aminomancer/uc.css.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
undoListInTabContextMenu.uc.js
518 lines (478 loc) · 26.2 KB
/
undoListInTabContextMenu.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
// ==UserScript==
// @name Undo Recently Closed Tabs in Tab Context Menu
// @version 1.4.3
// @author aminomancer
// @homepage https://github.com/aminomancer/uc.css.js
// @description Adds new menus to the context menu that appears when you right-click a tab (in the tab bar or in the TreeStyleTabs 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. An updated script that does basically the same thing as UndoListInTabmenuToo by Alice0775, but for current versions of Firefox and with TST support. The original broke around version 86 or 87 I think.
// @compatibility Firefox 87+
// ==/UserScript==
(function () {
// user preferences:
const config = {
"Include popup windows": true, // set this to false if you don't want popup windows to be listed in recently closed windows.
"Popup window label": "(popup)", // 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 ""
"Tabs access key": "", // 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.
"Windows 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.
};
class UndoListInTabmenu {
constructor() {
this.attachSidebarListener(); // 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.makePopups(document.getElementById("tabContextMenu")); // set up the built-in tabs bar context menu.
}
// memoize session store, maybe handle some earlier versions
get ss() {
return (
this._ss ||
(this._ss =
SessionStore ||
Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore))
);
}
// 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 = this.ss.getClosedWindowData(false);
return (
!windowData.length ||
(!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 strings() {
return (
this._strings ||
(this._strings =
RecentlyClosedTabsAndWindowsMenuUtils.strings || this.generateStrings())
);
}
async generateStrings() {
let strings = await new Localization(["browser/menubar.ftl"], true);
return strings;
}
// if TST is installed, listen for its sidebar opening
async attachSidebarListener() {
let TST = await AddonManager.getAddonByID("treestyletab@piro.sakura.ne.jp");
if (TST) SidebarUI._switcherTarget.addEventListener("SidebarShown", this);
}
/**
* when a TST sidebar is created, add context menus. when context menu is opened, hide/show the menus.
* @param {object} e (event)
*/
handleEvent(e) {
let sidebarContext = 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 (SidebarUI.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, false);
this.makeSidebarPopups(sidebarContext);
} else {
// destroy everything
if (!sidebarContext.hasAttribute("undo-list-init")) break;
sidebarContext.removeAttribute("undo-list-init", true);
sidebarContext.removeEventListener("popupshowing", this, false);
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 (this.ss.getClosedTabCount(window) == 0) {
this.sidebarTabMenu.setAttribute("hidden", true);
this.sidebarTabMenu.style.removeProperty("display");
} else {
this.sidebarTabMenu.removeAttribute("hidden");
this.sidebarTabMenu.style.display = "-moz-box";
}
// closed window list is empty so should be hidden
if (this.shouldHideWindows) {
this.sidebarWindowMenu.setAttribute("hidden", true);
this.sidebarWindowMenu.style.removeProperty("display");
} else {
this.sidebarWindowMenu.removeAttribute("hidden");
this.sidebarWindowMenu.style.display = "-moz-box";
}
break;
}
}
// return the localized label for "recently closed tabs"
get closedTabsLabel() {
return (
this._closedTabsLabel ||
(this._closedTabsLabel = this.strings.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.strings.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) {
// Recently Closed Tabs
let tabMenu = document.createXULElement("menu");
tabMenu.setAttribute("id", "tabContextUndoList");
tabMenu.setAttribute("data-l10n-id", "menu-history-undo-menu"); // localized "Recently Closed Tabs"
context.appendChild(tabMenu);
this.tabContextUndoListPopup = tabMenu.appendChild(
document.createXULElement("menupopup")
);
this.tabContextUndoListPopup.setAttribute(
"onpopupshowing",
`undoTabMenu.populateSubmenu(this, "Tab");`
);
// Recently Closed Windows
let windowMenu = document.createXULElement("menu");
windowMenu.setAttribute("id", "historyUndoWindowMenu3");
windowMenu.setAttribute("data-l10n-id", "menu-history-undo-window-menu"); // localized "Recently Closed Windows"
context.appendChild(windowMenu);
this.historyUndoWindowPopup3 = windowMenu.appendChild(
document.createXULElement("menupopup")
);
this.historyUndoWindowPopup3.setAttribute(
"onpopupshowing",
`undoTabMenu.populateSubmenu(this, "Window");`
);
// 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",
function (_e) {
let winWords = windowMenu.label.split(" ");
windowMenu.accessKey =
config["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 =
config["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
if (undoTabMenu.ss.getClosedTabCount(window) == 0)
tabMenu.setAttribute("hidden", true);
else tabMenu.removeAttribute("hidden");
// closed window list is empty so should be hidden
if (undoTabMenu.shouldHideWindows) windowMenu.setAttribute("hidden", true);
else windowMenu.removeAttribute("hidden");
},
false
);
}
/**
* 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
this.sidebarTabMenu = doc.createXULElement("menu");
this.sidebarTabMenu.setAttribute("id", "sidebarTabContextUndoList");
this.sidebarTabMenu.setAttribute("label", this.closedTabsLabel); // localized "Recently Closed Tabs"
let tabWords = this.closedTabsLabel.split(" ");
this.sidebarTabMenu.accessKey =
config["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(
doc.createXULElement("menupopup")
);
this.sidebarContextUndoListPopup.setAttribute(
"onpopupshowing",
`window.top.undoTabMenu.populateSidebarSubmenu(this, "Tab")`
);
// Recently Closed Windows
this.sidebarWindowMenu = doc.createXULElement("menu");
this.sidebarWindowMenu.setAttribute("id", "sidebarHistoryUndoWindowMenu3");
this.sidebarWindowMenu.setAttribute("label", this.closedWindowsLabel); // localized "Recently Closed Windows"
let winWords = this.closedWindowsLabel.split(" ");
this.sidebarWindowMenu.accessKey =
config["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(
doc.createXULElement("menupopup")
);
this.sidebarUndoWindowPopup.setAttribute(
"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) {
while (popup.hasChildNodes()) popup.removeChild(popup.firstChild); // remove existing menuitems
let fragment;
// list is empty so should be hidden
if (this.ss[`getClosed${type}Count`](window) == 0) {
popup.parentNode.setAttribute("hidden", true);
return;
} else popup.parentNode.removeAttribute("hidden"); // enable menu if it's not empty
// make the list of menuitems
fragment = RecentlyClosedTabsAndWindowsMenuUtils[`get${type}sFragment`](
window,
"menuitem",
false,
`appmenu-reopen-all-${type.toLowerCase()}s`,
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) {
while (popup.hasChildNodes()) popup.removeChild(popup.firstChild); // remove existing menuitems
let fragment;
// list is empty so should be hidden
if (this.ss[`getClosed${type}Count`](window) == 0) {
popup.parentNode.setAttribute("hidden", true);
return;
} else popup.parentNode.removeAttribute("hidden"); // enable menu if it's not empty
// make a temporary list of menuitems
fragment = RecentlyClosedTabsAndWindowsMenuUtils[`get${type}sFragment`](
window,
"menuitem",
false,
`appmenu-reopen-all-${type.toLowerCase()}s`,
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";
}
}
// instantiate the class and override some built-in methods.
function init() {
window.undoTabMenu = new UndoListInTabmenu();
RecentlyClosedTabsAndWindowsMenuUtils.navigatorBundle = Services.strings.createBundle(
"chrome://browser/locale/browser.properties"
);
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)
RecentlyClosedTabsAndWindowsMenuUtils.setImage(aClosedTab, element);
if (!aIsWindowsFragment) element.setAttribute("value", aIndex);
if (aTagName == "menuitem")
element.setAttribute(
"class",
"menuitem-iconic bookmark-item menuitem-with-favicon"
);
element.setAttribute(
"oncommand",
`undoClose${aIsWindowsFragment ? "Window" : "Tab"}(${aIndex});`
);
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 (!aIsWindowsFragment)
element.addEventListener(
"click",
RecentlyClosedTabsAndWindowsMenuUtils._undoCloseMiddleClick
);
if (!forContext && aTagName != "menuitem") {
element.setAttribute("tooltip", "bhTooltip");
if (aIndex == 0)
element.setAttribute(
"key",
"key_undoClose" + (aIsWindowsFragment ? "Window" : "Tab")
);
}
aFragment.appendChild(element);
};
RecentlyClosedTabsAndWindowsMenuUtils.createRestoreAllEntry = function (
aDocument,
aFragment,
aPrefixRestoreAll,
aIsWindowsFragment,
aRestoreAllLabel,
aEntryCount,
aTagName
) {
let restoreAllElements = aDocument.createXULElement(aTagName);
restoreAllElements.classList.add("restoreallitem");
restoreAllElements.setAttribute(
"label",
RecentlyClosedTabsAndWindowsMenuUtils.strings.formatValueSync(aRestoreAllLabel)
);
restoreAllElements.setAttribute(
"oncommand",
"for (var i = 0; i < " +
aEntryCount +
"; i++) undoClose" +
(aIsWindowsFragment ? "Window" : "Tab") +
"();"
);
if (aPrefixRestoreAll) aFragment.insertBefore(restoreAllElements, aFragment.firstChild);
else {
aFragment.appendChild(aDocument.createXULElement("menuseparator"));
aFragment.appendChild(restoreAllElements);
}
};
RecentlyClosedTabsAndWindowsMenuUtils.getWindowsFragment = function (
aWindow,
aTagName,
aPrefixRestoreAll = false,
aRestoreAllLabel = "appmenu-reopen-all-windows",
forContext
) {
let closedWindowData = undoTabMenu.ss.getClosedWindowData(false);
let doc = aWindow.document;
let fragment = doc.createDocumentFragment();
if (closedWindowData.length) {
let menuLabelString =
RecentlyClosedTabsAndWindowsMenuUtils.navigatorBundle.GetStringFromName(
"menuUndoCloseWindowLabel"
);
let menuLabelStringSingleTab =
RecentlyClosedTabsAndWindowsMenuUtils.navigatorBundle.GetStringFromName(
"menuUndoCloseWindowSingleTabLabel"
);
for (let i = 0; i < closedWindowData.length; i++) {
let undoItem = closedWindowData[i];
let otherTabsCount = undoItem.tabs.length - 1;
let label =
otherTabsCount == 0
? menuLabelStringSingleTab
: PluralForm.get(otherTabsCount, menuLabelString);
let menuLabel = label
.replace("#1", undoItem.title)
.replace("#2", otherTabsCount);
if (config["Popup window label"] && undoItem.isPopup)
menuLabel = `${menuLabel} ${config["Popup window label"]}`;
let selectedTab = undoItem.tabs[undoItem.selected - 1];
if (!undoItem.isPopup || config["Include popup windows"] || !forContext)
RecentlyClosedTabsAndWindowsMenuUtils.createEntry(
aTagName,
true,
i,
selectedTab,
doc,
menuLabel,
fragment,
forContext
);
}
RecentlyClosedTabsAndWindowsMenuUtils.createRestoreAllEntry(
doc,
fragment,
aPrefixRestoreAll,
true,
aRestoreAllLabel,
closedWindowData.length,
aTagName
);
}
return fragment;
};
RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment = function (
aWindow,
aTagName,
aPrefixRestoreAll = false,
aRestoreAllLabel = "appmenu-reopen-all-tabs",
forContext
) {
let doc = aWindow.document;
let fragment = doc.createDocumentFragment();
if (undoTabMenu.ss.getClosedTabCount(aWindow) != 0) {
let closedTabs = undoTabMenu.ss.getClosedTabData(aWindow, false);
for (let i = 0; i < closedTabs.length; i++) {
RecentlyClosedTabsAndWindowsMenuUtils.createEntry(
aTagName,
false,
i,
closedTabs[i],
doc,
closedTabs[i].title,
fragment,
forContext
);
}
RecentlyClosedTabsAndWindowsMenuUtils.createRestoreAllEntry(
doc,
fragment,
aPrefixRestoreAll,
false,
aRestoreAllLabel,
closedTabs.length,
aTagName
);
}
return fragment;
};
}
// wait until the tab context menu exists
if (gBrowserInit.delayedStartupFinished) init();
else {
let delayedListener = (subject, topic) => {
if (topic == "browser-delayed-startup-finished" && subject == window) {
Services.obs.removeObserver(delayedListener, topic);
init();
}
};
Services.obs.addObserver(delayedListener, "browser-delayed-startup-finished");
}
})();