-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathHistorySubmenus2@Merci.chao.uc.js
More file actions
790 lines (692 loc) · 27.2 KB
/
Copy pathHistorySubmenus2@Merci.chao.uc.js
File metadata and controls
790 lines (692 loc) · 27.2 KB
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
// ==UserScript==
// @name History Submenus II
// @description Add sub-menus to History Menu for previous days' history.
// @version 2026-05-06
// @author Merci chao
// @homepageURL https://github.com/Merci-chao/userChrome.js#history-submenus-ii
// @changelogURL https://github.com/Merci-chao/userChrome.js#changelog-1
// @supportURL https://github.com/Merci-chao/userChrome.js/issues/new
// @updateURL https://github.com/Merci-chao/userChrome.js/raw/refs/heads/main/HistorySubmenus2@Merci.chao.uc.js
// ==/UserScript==
/* global
Services, openURL, gNotificationBox, ChromeUtils, Cc, Cu, Ci,
BookmarksEventHandler, PlacesUtils, HistoryMenu, PlacesMenu, PlacesViewBase,
*/
if (document.documentElement.matches(`[windowtype="navigator:browser"]:not([chromehidden~=toolbar])`)) {
const SCRIPT_NAME = "History Submenus II";
const SCRIPT_FILE_NAME = "HistorySubmenus2@Merci.chao.uc.js";
setTimeout(() => { try {
let prefBranchStr = "extensions.HistorySubmenus2@Merci.chao.";
let defPrefs = {
historyCount: 25,
submenuCount: 7,
dateFormat: "%a",
checkUpdate: 1,
checkUpdateFrequency: 7,
checkUpdateAutoApply: 1,
};
let setDefaultPrefs = (branch, data) => Object.entries(data).forEach(([name, value]) =>
branch[`set${{string: "String", number: "Int", boolean: "Bool"}[typeof value]}Pref`](name, value));
let getPrefs = (branch, data) => Object.fromEntries(Object.entries(data).map(([name, value]) =>
[name, branch[`get${{string: "String", number: "Int", boolean: "Bool"}[typeof value]}Pref`](name)]));
setDefaultPrefs(Services.prefs.getDefaultBranch(prefBranchStr), defPrefs);
let prefs = {};
loadPrefs();
Object.keys(prefs).forEach(n => Services.prefs.addObserver(prefBranchStr + n, onPrefChange));
addEventListener("unload", e => {
if (e.target != document) return;
Object.keys(prefs).forEach(n => Services.prefs.removeObserver(prefBranchStr + n, onPrefChange));
}, true);
function onPrefChange(pref, type, name) {
name = name.replace(prefBranchStr, "");
if (name.startsWith("checkUpdate"))
return;
loadPrefs();
HistorySubmenus2.uninitPopups();
}
function loadPrefs() {
Object.assign(prefs, getPrefs(Services.prefs.getBranch(prefBranchStr), defPrefs));
}
const SCRIPT_ID = 1;
if (prefs.checkUpdate && (Date.now() / 1000 - prefs.checkUpdate) / 60 / 60 / 24 >= Math.max(prefs.checkUpdateFrequency, 1)) {
Services.prefs.setIntPref(prefBranchStr + "checkUpdate", Date.now() / 1000);
(async () => {
let auto = prefs.checkUpdateAutoApply;
let getVer = code => code?.match(/^\/\/\s*@version\s+(.+?)\s*$/mi)?.[1];
let localFileURI = new Error().stack.match(/(?<=@).+?(?=:\d+:\d+$)/m)[0];
let localScript = await (await fetch(localFileURI)).text();
let updateURL = localScript.match(/^\/\/\s*@updateURL\s+(.+?)\s*$/mi)[1];
let homeURL = "https://github.com/Merci-chao/userChrome.js";
let remoteScript = (await (await fetch(updateURL)).text()).trim();
let local = getVer(localScript);
let remote = getVer(remoteScript);
if (
!remote ||
remote.localeCompare(local, undefined, {numeric: true}) <= 0
)
return;
let l10n = {
en: {
message: `${SCRIPT_NAME} (${SCRIPT_FILE_NAME}) version ${remote} is released.`,
update: "Update Now",
updateKey: "N",
download: "Update Manually",
downloadKey: "M",
changelog: "Changelog",
changelogKey: "C",
finished: "Done",
finishedKey: "D",
later: "Remind Tomorrow",
laterKey: "R",
link: "#changelog-" + SCRIPT_ID,
done: `${SCRIPT_NAME} has been updated to version ${remote}. You may restart Firefox to apply.`,
error: `Failed to apply the update of ${SCRIPT_NAME} version ${remote}. Please ensure the file is not read-only or locked by another program:`,
},
ja: {
message: `${SCRIPT_NAME}(${SCRIPT_FILE_NAME})の新バージョン ${remote} がリリースされました。`,
update: "今すぐ更新",
download: "手動で更新",
changelog: "変更履歴",
finished: "完了",
later: "明日再通知する",
link: "/blob/main/README.jp.md#変更履歴-" + SCRIPT_ID,
done: `${SCRIPT_NAME} ${remote} に更新しました。Firefox を再起動すると変更が適用になります。`,
error: `${SCRIPT_NAME} バージョン ${remote} の更新処理に失敗しました。ファイルが読み取り専用でないこと、または他のプログラムによってロックされていないことを確認してください:`,
},
};
l10n = Object.assign(l10n.en, l10n[Services.locale.appLocaleAsLangTag.split("-")[0]]);
if (auto > 1)
install();
else
showNotification(
l10n.message,
[
{
label: l10n.update,
accessKey: l10n.updateKey,
callback: install,
primary: true,
},
{
label: l10n.download,
accessKey: l10n.downloadKey,
callback: showChangelog,
},
{
label: l10n.later,
accessKey: l10n.laterKey,
callback: () => Services.prefs.setIntPref(
prefBranchStr + "checkUpdate",
Date.now() / 1000 - (Math.max(prefs.checkUpdateFrequency, 1) - 1) * 24 * 60 * 60,
),
},
],
"chrome://browser/skin/update-badge.svg",
);
async function showNotification(label, buttons, icon, color) {
let box = await gNotificationBox.appendNotification(
"multitabrows",
{
label,
priority: gNotificationBox.PRIORITY_INFO_HIGH,
},
buttons,
true,
);
if (icon) {
let node = box.shadowRoot.querySelector(".icon");
node.src = icon;
Object.assign(node.style, {
fill: color,
color,
});
node.style.setProperty("--message-bar-icon-url", `url(${icon})`);
}
}
function install() {
let file;
try {
/*global FileUtils, NetUtil*/
file =
NetUtil.newChannel({
uri: Services.io.newURI(localFileURI),
loadUsingSystemPrincipal: true,
}).URI.QueryInterface(Ci.nsIFileURL).file;
let converter = Cc["@mozilla.org/intl/converter-output-stream;1"]
.createInstance(Ci.nsIConverterOutputStream);
converter.init(
FileUtils.openFileOutputStream(
file,
FileUtils.MODE_WRONLY | FileUtils.MODE_TRUNCATE,
),
"UTF-8",
);
converter.writeString(remoteScript);
converter.close();
if (auto < 3)
//Delay a bit to make the installation feel like it's actually running
setTimeout(() => showNotification(
l10n.done,
[
{
label: l10n.changelog,
accessKey: l10n.changelogKey,
callback: showChangelog,
primary: true,
},
{
label: l10n.finished,
accessKey: l10n.finishedKey,
callback: () => {},
},
],
"chrome://browser/skin/migration/success.svg",
"var(--panel-banner-item-update-supported-bgcolor)",
), 500);
} catch (e) {
Services.prompt.alert(window, l10n.title, [l10n.error, file?.path || localFileURI, e.message].join("\n\n"));
return true;
}
}
function showChangelog() {
openURL(homeURL + l10n.link);
}
})();
}
/* define utilities */
let HistorySubmenus2 = {
placesBundle: Services.strings.createBundle("chrome://places/locale/places.properties"),
locale: Services.locale.appLocaleAsLangTag,
prefs,
formatToken: {
yearL: "%Y",
year: "%y",
monthL: "%M",
month: "%m",
dateL: "%D",
date: "%d",
age: "%a",
monthNameL: "%N",
monthName: "%n",
monthNameN: "%e",
weekDayL: "%W",
weekDay: "%w",
weekDayN: "%k",
weekDayDeprecated: "%K",
},
formatDate(day, string) {
let {placesBundle, locale, formatToken: f} = this;
let DTF = Intl.DateTimeFormat;
let year = day.getFullYear();
let month = day.getMonth() + 1;
let monthName = new DTF(locale, {month: "short"}).format(day);
let monthNameN = new DTF(locale, {month: "narrow"}).format(day);
let monthNameL = new DTF(locale, {month: "long"}).format(day);
let date = day.getDate();
let weekDay = new DTF(locale, {weekday: "short"}).format(day);
let weekDayN = new DTF(locale, {weekday: "narrow"}).format(day);
let weekDayL = new DTF(locale, {weekday: "long"}).format(day);
let weekDayDeprecated = new DTF(locale, {weekday: "short"}).format(day);
let age = parseInt((this.getStartOfDate(new Date()) - this.getStartOfDate(day)) / 1000 / 60 / 60 / 24);
if (age < 2)
age = placesBundle.GetStringFromName("finduri-AgeInDays-is-" + age);
else
age = placesBundle.formatStringFromName("finduri-AgeInDays-is", [age], 1);
return string
.replace(new RegExp(f.year, "g"), year % 100)
.replace(new RegExp(f.yearL, "g"), year)
.replace(new RegExp(f.month, "g"), month)
.replace(new RegExp(f.monthL, "g"), month < 10 ? "0" + month : month)
.replace(new RegExp(f.date, "g"), date)
.replace(new RegExp(f.dateL, "g"), date < 10 ? "0" + date : date)
.replace(new RegExp(f.weekDay, "g"), weekDay)
.replace(new RegExp(f.weekDayL, "g"), weekDayL)
.replace(new RegExp(f.weekDayN, "g"), weekDayN)
.replace(new RegExp(f.weekDayDeprecated, "g"), weekDayDeprecated)
.replace(new RegExp(f.monthNameN, "g"), monthNameN)
.replace(new RegExp(f.monthName, "g"), monthName)
.replace(new RegExp(f.monthNameL, "g"), monthNameL)
.replace(new RegExp(f.age, "g"), age);
},
getStartOfDate(date) {
date = new Date(date.getTime());
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
},
uninitPopups() {
[...document.querySelectorAll("[historypopup=true]")].forEach(popup => {
try {
if (popup.tagName == "menupopup")
popup.parentNode._placesView?.uninit();
} catch (e) {
console.error("Failed to uninit history popup", e);
}
});
},
bind() {
this.uninitPopups();
Object.assign(window, {
HistorySubmenus2: this,
PlacesViewBase,
HistoryMenu,
})
let HMProto = HistoryMenu.prototype;
/* save the original functions of HistoryMenu */
let HistorySubmenus2_OriginalFunctions = window.HistorySubmenus2_OriginalFunctions = {
HM: {
HM_placeProperty: Object.getOwnPropertyDescriptor(HMProto, "place"),
HM_rebuildPopup: HMProto._rebuildPopup,
HM_ensureMarkers: HMProto._ensureMarkers,
HM_uninit: HMProto.uninit,
get placeProperty() {
return this.HM_placeProperty
|| Object.getOwnPropertyDescriptor(PlacesMenu.prototype, "place")
|| Object.getOwnPropertyDescriptor(PlacesViewBase.prototype, "place");
},
get rebuildPopup() {
return this.HM_rebuildPopup || PlacesMenu.prototype._rebuildPopup;
},
get ensureMarkers() {
return this.HM_ensureMarkers || PlacesMenu.prototype._ensureMarkers;
},
get uninit() {
return this.HM_uninit || PlacesMenu.prototype.uninit;
},
},
BEH: {
fillInBHTooltip: BookmarksEventHandler.fillInBHTooltip,
},
};
/* wrap the fillInBHTooltip to fill the browse time of history item */
BookmarksEventHandler.fillInBHTooltip = function BEH_fillInBHTooltip(tooltip) {
let tooltipTime = tooltip.querySelector("#bhtTimeText");
if (tooltipTime) {
let {triggerNode} = tooltip;
let node = triggerNode && triggerNode._placesNode;
if (node && triggerNode.closest("[historypopup]")) {
let date = new Date(node.time / 1000);
tooltipTime.value = new Services.intl.DateTimeFormat(HistorySubmenus2.locale, {dateStyle: "long", timeStyle: "long"})
.format(date);
tooltipTime.hidden = false;
} else
tooltipTime.hidden = true;
}
return HistorySubmenus2_OriginalFunctions.BEH.fillInBHTooltip.apply(this, arguments);
};
/*
* wrap the setter of property "place"
* since the places uri is hard coded in constructor,
* so we intercept the places uri here
*/
Object.defineProperty(HMProto, "place", {
set: function(val) {
/* update the max results property */
let currentMaxResults = /\d+/.exec(/maxResults=\d+/.exec(val));
if (currentMaxResults != (prefs.historyCount || 1))
val = val.replace("maxResults=" + currentMaxResults, "maxResults=" + (prefs.historyCount || 1));
HistorySubmenus2_OriginalFunctions.HM.placeProperty.set.call(this, val);
},
get: function() {
return HistorySubmenus2_OriginalFunctions.HM.placeProperty.get.call(this);
},
configurable: true,
enumerable: true,
});
/* properties */
HMProto._subResult = null;
HMProto._subMenus = null;
HMProto._updateSubMenus = function HM_prepareSubMenus() {
if (!prefs.submenuCount)
return false;
/* create the query result of history */
if (!this._subResult) {
let {history} = PlacesUtils;
let queries = {};
let options = {};
let queryStr = "sort=" + Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING +
"&endTimeRef=" + Ci.nsINavHistoryQuery.TIME_RELATIVE_TODAY +
"&endTime=" + (24 * 60 * 60 * 1000 * 1000);
history.queryStringToQuery(queryStr, queries, options);
this._subResult = history.executeQuery(queries.value, options.value);
/* we keep the result open since it takes 0.5s for opening each time */
this._subResult.root.containerOpen = true;
} else if (!this._subResult.root.containerOpen)
this._subResult.root.containerOpen = true;
/* prepare the result for each sub-menus */
let resultRoot = this._subResult.root;
let {childCount} = resultRoot;
let currentChildIndex = prefs.historyCount;
for (let i in this._subMenus) {
let submenu = this._subMenus[i];
// let subpopup = submenu.lastChild;
let timeOfSub = null;
let result = submenu._result = [];
/* assign the result for each sub-menu */
while (currentChildIndex < childCount) {
let child = resultRoot.getChild(currentChildIndex);
let timeOfChild = HistorySubmenus2.getStartOfDate(new Date(child.time / 1000)).getTime();
/*
* get the results for one day
* we use the integer time comparing here since date object comparing is not via time value
*/
if (!timeOfSub) {
timeOfSub = timeOfChild;
result.push(child);
} else if (timeOfChild == timeOfSub)
result.push(child);
else if (timeOfChild < timeOfSub)
break;
currentChildIndex++;
}
/* update the status of sub-menu */
if (!result.length) {
submenu.hidden = true;
submenu.removeAttribute("label");
} else {
submenu.hidden = false;
submenu.setAttribute("label", HistorySubmenus2.formatDate(new Date(timeOfSub), prefs.dateFormat));
if (submenu.open && submenu.tagName == "menu")
submenu._placesView._rebuildPopup(submenu.lastChild);
}
}
return true;
},
/*
* wrap the _rebuildPopup
* we do some preparation for sub-menus after building top-menu
*/
HMProto._rebuildPopup = function HM_rebuildPopup(popup) {
/* in case the popup has initialized before HSM2 is bound */
if (!popup.hasAttribute("historypopup")) {
popup.setAttribute("historypopup", true);
// eslint-disable-next-line no-self-assign
this.place = this.place;
}
/* call the original _rebuildPopup or the default one */
let result = HistorySubmenus2_OriginalFunctions.HM.rebuildPopup.apply(this, arguments);
/* build the sub-menus when history menu opens at the first time */
if (!this._subMenus)
this._rebuildSubMenus(popup);
/* prepare for sub-menus */
popup._endMarker.hidden = !this._updateSubMenus(popup);
/*
* a little trick, remove the additional item here
* please read HistoryMenu.prototype.place
*/
if (!prefs.historyCount) {
this._setEmptyPopupStatus(popup, true);
let lastHistory = popup._startMarker.nextSibling;
if (lastHistory._placesNode)
this._removeChild(lastHistory);
}
/* return the result of original function */
return result;
};
/*
* wrap the _ensureMarkers
* we add one more marker for history menu: sub-menus marker
*/
HMProto._ensureMarkers = function HM_ensureMarkers(popup) {
/* call the original _ensureMarkers or the default one */
let result = HistorySubmenus2_OriginalFunctions.HM.ensureMarkers.apply(this, arguments);
/* we do our jobs after the preparing of markers */
if (!popup._endSubMarker) {
popup._endSubMarker = [...popup.getElementsByClassName("endHistorySubmenusSeparator")]
.find(elt => elt.parentNode == popup._endMarker.parentNode);
if (!popup._endSubMarker)
(popup._endSubMarker = popup.insertBefore(document.createXULElement("menuseparator"), popup._endMarker.nextSibling))
.className = "endHistorySubmenusSeparator";
}
/* return the result of original function */
return result;
};
/* add a new function for building sub-menus */
HMProto._rebuildSubMenus = function HM_rebuildSubMenus(popup) {
/* remove the old ones */
this._cleanSubMenus(popup);
/* create submenus */
let fragment = document.createDocumentFragment();
for (let age = 0; age < prefs.submenuCount; age++) {
let submenu = fragment.appendChild(document.createXULElement("menu"));
submenu.className = "history-submenu menu-iconic bookmark-item";
submenu.setAttribute("query", true);
submenu.setAttribute("dayContainer", true);
/* create popup */
let subpopup = submenu.appendChild(document.createXULElement("menupopup"));
subpopup.setAttribute("placespopup", true);
subpopup.setAttribute("tooltip", popup.getAttribute("tooltip"));
subpopup.addEventListener("popupshowing", function(e) {
if (!this.parentNode._placesView) new window.HistorySubMenu(e);
}, true);
this._subMenus.push(submenu);
}
popup.insertBefore(fragment, popup._endSubMarker);
};
HMProto._cleanSubMenus = function HM_cleanSubMenus() {
if (this._subMenus)
for (let menu of this._subMenus) {
if (menu._placesView)
try {
menu._placesView.uninit();
} catch (e) {
console.warn(e);
}
menu.remove();
}
this._subMenus = [];
};
/* wrap the uninit */
HMProto.uninit = function HM_uninit() {
if (this._subResult) {
try {
this._subResult.root.containerOpen = false;
} catch (e) {
console.warn(e);
}
delete this._subResult;
}
let popup = this._rootElt;
this._cleanSubMenus(popup);
popup.removeAttribute("historypopup");
popup.removeChild(popup._endSubMarker);
popup._endMarker.hidden = true;
delete popup._endSubMarker;
let result;
try {
result = HistorySubmenus2_OriginalFunctions.HM.uninit.call(this);
} catch (e) {
console.warn(e);
delete this._viewElt._placesView;
}
return result;
};
/* view for sub-menus */
window.HistorySubMenu = class HistorySubMenu extends PlacesMenu {
constructor(popupShowingEvent) {
/*
* since the sub-menus doesn't use query result, so we give some junk places string for
* construction. but i think there should be a places uri that is better than the default "place:"...
*/
super(popupShowingEvent, "");
}
_onPopupShowing(event) {
this._rebuildPopup(event.originalTarget);
}
_rebuildPopup(popup) {
this._cleanPopup(popup);
let result = popup.parentNode._result;
let isPanelUI = popup.parentNode.matches(".subviewbutton");
let fragment = document.createDocumentFragment();
for (let r of result) {
let item = this._insertNewItemToPopup(r, fragment);
if (isPanelUI)
item.classList.add("subviewbutton");
}
popup.insertBefore(fragment, popup._endMarker);
this._setEmptyPopupStatus(popup, !result.length);
}
}
/* visit time in tooltip */
{
let bhtTimeText = document.querySelector("#bhTooltip .places-tooltip-box")
.insertBefore(document.createXULElement("label"), document.querySelector("#bhTooltip .places-tooltip-uri").nextSibling);
bhtTimeText.id = "bhtTimeText";
bhtTimeText.className = "tooltip-label";
}
document.body.appendChild(document.createElement("style")).innerHTML = /*css*/`
.HSM2-submenu {
list-style-image: url("chrome://browser/skin/history.svg");
-moz-context-properties: fill;
fill: currentColor;
}
.HSM2-submenu .toolbarbutton-text {
padding-inline-start: 8px;
}
.endHistorySubmenusSeparator:last-child,
menuseparator:not([hidden]) + .endHistorySubmenusSeparator {
visibility: collapse;
}
`;
},
PanelUI: {
_subResult: null,
_subPlaceView: null,
_subMenus: [],
enable() {
let module;
try {
try {
module = ChromeUtils.importESModule("moz-src:///browser/components/customizableui/CustomizableWidgets.sys.mjs");
// eslint-disable-next-line no-unused-vars
} catch (e) {
module = ChromeUtils.importESModule("resource:///modules/CustomizableWidgets.sys.mjs");
}
// eslint-disable-next-line no-unused-vars
} catch (e) {
module = Cu.import("resource:///modules/CustomizableWidgets.jsm");
}
let widget = module.CustomizableWidgets.find(w => w.id == "history-panelmenu");
if (widget.__HSM2_enabled)
return;
Cu.evalInSandbox(
/*js*/`
Object.assign(widget, {
__HSM2_enabled: true,
__HSM2_onViewShowing: widget.onViewShowing,
__HSM2_onPanelMultiViewHidden: widget.onPanelMultiViewHidden,
onViewShowing: function(event) {
let {target} = event,
{ownerDocument} = target,
documentGlobal = (ownerDocument.documentGlobal || ownerDocument.ownerGlobal),
{HistorySubmenus2, PlacesViewBase, HistoryMenu} = documentGlobal,
{PanelUI, prefs} = HistorySubmenus2;
let viewBody = documentGlobal.PanelMultiView.getViewNode(ownerDocument, "PanelUI-history").querySelector(".panel-subview-body");
let appHM = viewBody.querySelector("#appMenu_historyMenu");
if (!this._panelMenuView) {
/* init history panel when it is the first time to open on current window */
if (!PanelUI._subResult) {
let subPanelView = ownerDocument.getElementById("appMenu-viewCache")
.content.appendChild(ownerDocument.createXULElement("panelview"));
let body = subPanelView.appendChild(ownerDocument.createXULElement("vbox"));
body.className = "panel-subview-body";
body.setAttribute("historypopup", true);
body.tooltip = "bhTooltip";
subPanelView.id = "appMenu-HSM2-submenu";
subPanelView.addEventListener("ViewShowing", function(e) {
/* initialize sub-menu panel, a dummy places view is used */
/* the view will be uninitialized when history panel is closed */
if (!PanelUI._subPlaceView) {
PanelUI._subPlaceView = new documentGlobal.PlacesPanelview(
"place:queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY + "&maxResults=1",
body,
subPanelView,
);
body._placesNode.containerOpen = false;
}
/* build sub-menu items for the selected day */
let {_result} = e.explicitOriginalTarget;
body._placesNode = {
containerOpen: true,
childCount: _result.length,
getChild(i) {
return _result[i];
},
};
PanelUI._subPlaceView._rebuildPopup(body);
let {scrollTop} = viewBody;
let viewStack = viewBody.closest(".panel-viewstack");
let subViewShown = false;
viewStack.addEventListener("transitionstart", function f(e) {
if (e.propertyName == "transform")
if (subViewShown) {
viewStack.removeEventListener("transitionstart", f, true);
viewBody.scrollTop = scrollTop;
} else
subViewShown = true;
}, true);
}, true);
/* build sub-menus */
appHM.tooltip = "bhTooltip";
appHM.setAttribute("historypopup", true);
}
/* build the top level of history panel */
let descriptor = Object.getOwnPropertyDescriptor(PlacesViewBase.prototype, "place");
let {set} = descriptor;
descriptor.set = function(val) {
set.call(this, val.replace(/maxResults=\\d+/, "maxResults=" + (prefs.historyCount || 1)));
};
Object.defineProperty(PlacesViewBase.prototype, "place", descriptor);
this.__HSM2_onViewShowing.apply(this, arguments);
descriptor.set = set;
Object.defineProperty(PlacesViewBase.prototype, "place", descriptor);
} else
this.__HSM2_onViewShowing.apply(this, arguments);
if (PanelUI._subMenus.length != prefs.submenuCount) {
HistoryMenu.prototype._cleanSubMenus.call(PanelUI);
appHM.parentNode.querySelector(".HSM2-endSubMarker")?.remove();
let frag = ownerDocument.createDocumentFragment();
frag.appendChild(ownerDocument.createXULElement("toolbarseparator")).className = "HSM2-endSubMarker";
PanelUI._subMenus = new Array(prefs.submenuCount).fill().map(() => {
let btn = frag.appendChild(ownerDocument.createXULElement("toolbarbutton"));
btn.setAttribute("closemenu", "none");
btn.addEventListener("command", function() {
documentGlobal.PanelUI.showSubView("appMenu-HSM2-submenu", this);
}, true);
btn.className = "HSM2-submenu subviewbutton subviewbutton-iconic subviewbutton-nav";
return btn;
});
if (prefs.submenuCount)
appHM.parentNode.insertBefore(frag, appHM.nextSibling);
}
[...target.querySelectorAll("#appMenu_historyMenu, #appMenu_historyMenu + .HSM2-endSubMarker")]
.forEach(e => e.collapsed = !prefs.historyCount);
/* update the label and results of each sub-menus */
HistoryMenu.prototype._updateSubMenus.call(PanelUI);
},
onPanelMultiViewHidden: function(event) {
this.__HSM2_onPanelMultiViewHidden.apply(this, arguments);
/* uninitialize the view of sub-menu panel to prevent some strange problems, e.g. the places context menu does not work */
let {PanelUI} = event.target.ownerDocument.defaultView.HistorySubmenus2;
if (PanelUI._subPlaceView) {
PanelUI._subResult.root.containerOpen = false;
PanelUI._subPlaceView.uninit();
PanelUI._subPlaceView = null;
}
},
});
`,
Object.assign(new Cu.Sandbox(Services.scriptSecurityManager.getSystemPrincipal()), {widget}),
);
},
},
};
HistorySubmenus2.bind();
HistorySubmenus2.PanelUI.enable();
} catch (e) {
alert([SCRIPT_FILE_NAME, e, e.stack].join("\n"));
console.error(e);
} });
}