-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathcommon.js
1249 lines (1087 loc) · 39.5 KB
/
common.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
/*
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
import Configs from '/extlib/Configs.js';
import EventListenerManager from '/extlib/EventListenerManager.js';
import * as Constants from './constants.js';
export const DEVICE_SPECIFIC_CONFIG_KEYS = mapAndFilter(`
blockStartupOperations
chunkedSyncDataLocal0
chunkedSyncDataLocal1
chunkedSyncDataLocal2
chunkedSyncDataLocal3
chunkedSyncDataLocal4
chunkedSyncDataLocal5
chunkedSyncDataLocal6
chunkedSyncDataLocal7
fixDragEndCoordinates
lastConfirmedToCloseTabs
lastDragOverSidebarOwnerWindowId
lastDraggedTabs
loggingConnectionMessages
loggingQueries
migratedBookmarkUrls
requestingPermissions
requestingPermissionsNatively
syncAvailableNotified
syncDeviceInfo
syncDevicesLocalCache
syncEnabled
syncLastMessageTimestamp
syncOtherDevicesDetected
`.trim().split('\n'), key => {
key = key.trim();
return key && key.indexOf('//') != 0 && key;
});
const localKeys = DEVICE_SPECIFIC_CONFIG_KEYS.concat(mapAndFilter(`
APIEnabled
accelKey
baseIndent
cachedExternalAddons
colorScheme
debug
enableLinuxBehaviors
enableMacOSBehaviors
enableWindowsBehaviors
faviconizedTabScale
grantedExternalAddonPermissions
grantedRemovingTabIds
incognitoAllowedExternalAddons
logFor
logTimestamp
maximumDelayForBug1561879
minimumIntervalToProcessDragoverEvent
minIndent
notifiedFeaturesVersion
optionsExpandedGroups
optionsExpandedSections
outOfScreenTabsRenderingPages
rtl,
sidebarPosition
sidebarVirtuallyClosedWindows
sidebarVirtuallyOpenedWindows
sidebarWidthInWindow
startDragTimeout
style
subMenuCloseDelay
subMenuOpenDelay
testKey
userStyleRulesFieldHeight
userStyleRulesFieldTheme
runTestsParameters
`.trim().split('\n'), key => {
key = key.trim();
return key && key.indexOf('//') != 0 && key;
}));
export const obsoleteConfigs = new Set(mapAndFilter(`
sidebarScrollbarPosition // migrated to user stylesheet
scrollbarMode // migrated to user stylesheet
suppressGapFromShownOrHiddenToolbar // migrated to suppressGapFromShownOrHiddenToolbarOnFullScreen/NewTab
fakeContextMenu // migrated to emulateDefaultContextMenu
context_closeTabOptions_closeTree // migrated to context_topLevel_closeTree
context_closeTabOptions_closeDescendants // migrated to context_topLevel_closeDescendants
context_closeTabOptions_closeOthers // migrated to context_topLevel_closeOthers
collapseExpandSubtreeByDblClick // migrated to treeDoubleClickBehavior
autoExpandOnCollapsedChildActive // migrate to unfocusableCollapsedTab
inheritContextualIdentityToNewChildTab // migrated to inheritContextualIdentityToChildTabMode
inheritContextualIdentityToSameSiteOrphan // migrated to inheritContextualIdentityToSameSiteOrphanMode
inheritContextualIdentityToTabsFromExternal // migrated to inheritContextualIdentityToTabsFromExternalMode
promoteFirstChildForClosedRoot // migrated to Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_INTELLIGENTLY of closeParentBehavior
parentTabBehaviorForChanges // migrated to parentTabOperationBehaviorMode
closeParentBehaviorMode // migrated to parentTabOperationBehaviorMode
closeParentBehavior // migrated to closeParentBehavior_insideSidebar_expanded
closeParentBehavior_outsideSidebar// migrated to closeParentBehavior_outsideSidebar_expanded
closeParentBehavior_noSidebar // migrated to closeParentBehavior_noSidebar_expanded
treatTreeAsExpandedOnClosedWithNoSidebar // migrated to treatTreeAsExpandedOnClosed_noSidebar
treatTreeAsExpandedOnClosed_outsideSidebar // migrated to closeParentBehavior_noSidebar_expanded and closeParentBehavior_noSidebar_expanded
treatTreeAsExpandedOnClosed_noSidebar // migrated to closeParentBehavior_noSidebar_collapsed and moveParentBehavior_noSidebar_expanded
moveFocusInTreeForClosedActiveTab // migrated to "successorTabControlLevel"
startDragTimeout // migrated to longPressDuration
simulateCloseTabByDblclick // migrated to "treeDoubleClickBehavior=kTREE_DOUBLE_CLICK_BEHAVIOR_CLOSE"
moveDroppedTabToNewWindowForUnhandledDragEvent // see also: https://github.com/piroor/treestyletab/issues/1646 , migrated to tabDragBehavior
openAllBookmarksWithGroupAlways // migrated to suppressGroupTabForStructuredTabsFromBookmarks
// migrated to chunkedUserStyleRules0-5
userStyleRules0
userStyleRules1
userStyleRules2
userStyleRules3
userStyleRules4
userStyleRules5
userStyleRules6
userStyleRules7
autoGroupNewTabsTimeout // migrated to tabBunchesDetectionTimeout
autoGroupNewTabsDelayOnNewWindow // migrated to tabBunchesDetectionDelayOnNewWindow
autoHiddenScrollbarPlaceholderSize // migrated to shiftTabsForScrollbarDistance
`.trim().split('\n'), key => {
key = key.replace(/\/\/.*/, '').trim();
if (!key)
return undefined;
return key && key.indexOf('//') != 0 && key;
}));
const RTL_LANGUAGES = new Set([
'ar',
'he',
'fa',
'ur',
'ps',
'sd',
'ckb',
'prs',
'rhg',
]);
export function isRTL() {
const lang = (
navigator.language ||
navigator.userLanguage ||
//(new Intl.DateTimeFormat()).resolvedOptions().locale ||
''
).split('-')[0];
return RTL_LANGUAGES.has(lang);
}
export const configs = new Configs({
optionsExpandedSections: [
'section-appearance',
'section-addons',
'section-advanced',
'section-drag',
'section-treeBehavior',
'section-newTab',
'section-newTabWithOwner',
'section-contextMenu',
],
optionsExpandedGroups: [],
// appearance
sidebarPosition: Constants.kTABBAR_POSITION_AUTO,
sidebarPositionRighsideNotificationShown: false,
sidebarPositionOptionNotificationTimeout: 20 * 1000,
rtl: isRTL(),
style: /^Mac/i.test(navigator.platform) ? 'sidebar' : 'proton',
colorScheme: /^Linux/i.test(navigator.platform) ? 'system-color' : 'photon' ,
iconColor: 'auto',
indentLine: 'auto',
shiftTabsForScrollbarDistance: '0.5em',
shiftTabsForScrollbarOnlyOnHover: false,
unrepeatableBGImageAspectRatio: 4,
faviconizePinnedTabs: true,
maxFaviconizedPinnedTabsInOneRow: 0, // auto
faviconizedTabScale: 1.75,
maxPinnedTabsRowsAreaPercentage: 50,
counterRole: Constants.kCOUNTER_ROLE_CONTAINED_TABS,
baseIndent: 12,
minIndent: Constants.kDEFAULT_MIN_INDENT,
maxTreeLevel: -1,
indentAutoShrink: true,
indentAutoShrinkOnlyForVisible: true,
labelOverflowStyle: 'fade',
showContextualIdentitiesSelector: false,
showNewTabActionSelector: true,
longPressOnNewTabButton: Constants.kCONTEXTUAL_IDENTITY_SELECTOR,
zoomable: false,
tabPreviewTooltip: false,
tabPreviewTooltipRenderIn: Constants.kTAB_PREVIEW_PANEL_RENDER_IN_ANYWHERE,
tabPreviewTooltipInSidebar: null, // migrated to tabPreviewTooltipMode
tabPreviewTooltipDelayMsec: 500, // same as "ui.tooltip.delay_ms"
tabPreviewTooltipOffsetTop: 0, // See also https://github.com/piroor/treestyletab/issues/3698
showOverflowTitleByTooltip: true,
showCollapsedDescendantsByTooltip: true,
showDialogInSidebar: false,
outOfScreenTabsRenderingPages: 1,
renderHiddenTabs: false,
suppressGapFromShownOrHiddenToolbarOnlyOnMouseOperation: true,
suppressGapFromShownOrHiddenToolbarOnFullScreen: false,
suppressGapFromShownOrHiddenToolbarOnNewTab: true,
suppressGapFromShownOrHiddenToolbarInterval: 50,
suppressGapFromShownOrHiddenToolbarTimeout: 500,
cancelGapSuppresserHoverDelay: 1000, // msec
enableWorkaroundForBug1875100: true,
watchWindowStateInterval: 500,
// context menu
emulateDefaultContextMenu: true,
showTreeCommandsInTabsContextMenuGlobally: true,
context_reloadTree: true,
context_reloadDescendants: false,
context_unblockAutoplayTree: true,
context_unblockAutoplayDescendants: false,
context_toggleMuteTree: true,
context_toggleMuteDescendants: false,
context_closeTree: true,
context_closeDescendants: false,
context_closeOthers: false,
context_toggleSticky: false,
context_collapseTree: false,
context_collapseTreeRecursively: true,
context_collapseAll: true,
context_expandTree: false,
context_expandTreeRecursively: true,
context_expandAll: true,
context_bookmarkTree: true,
context_sendTreeToDevice: false,
context_topLevel_reloadTree: false,
context_topLevel_reloadDescendants: false,
context_topLevel_unblockAutoplayTree: false,
context_topLevel_unblockAutoplayDescendants: false,
context_topLevel_toggleMuteTree: false,
context_topLevel_toggleMuteDescendants: false,
context_topLevel_closeTree: false,
context_topLevel_closeDescendants: false,
context_topLevel_closeOthers: false,
context_topLevel_toggleSticky: true,
context_topLevel_collapseTree: false,
context_topLevel_collapseTreeRecursively: false,
context_topLevel_collapseAll: false,
context_topLevel_expandTree: false,
context_topLevel_expandTreeRecursively: false,
context_topLevel_expandAll: false,
context_topLevel_bookmarkTree: false,
context_topLevel_sendTreeToDevice: true,
context_collapsed: false,
context_pinnedTab: false,
context_unpinnedTab: false,
context_openAllBookmarksWithStructure: true,
context_openAllBookmarksWithStructureRecursively: false,
openAllBookmarksWithStructureDiscarded: true,
suppressGroupTabForStructuredTabsFromBookmarks: true,
// tree behavior
shouldDetectClickOnIndentSpaces: true,
autoCollapseExpandSubtreeOnAttach: true,
autoCollapseExpandSubtreeOnSelect: true,
autoCollapseExpandSubtreeOnSelectExceptActiveTabRemove: true,
treeDoubleClickBehavior: Constants.kTREE_DOUBLE_CLICK_BEHAVIOR_NONE,
autoExpandIntelligently: true,
unfocusableCollapsedTab: true,
autoExpandOnTabSwitchingShortcuts: true,
autoExpandOnTabSwitchingShortcutsDelay: 800,
autoExpandOnLongHover: true,
autoExpandOnLongHoverDelay: 500,
autoExpandOnLongHoverRestoreIniitalState: true,
autoCreateFolderForBookmarksFromTree: true,
accelKey: '',
skipCollapsedTabsForTabSwitchingShortcuts: false,
syncParentTabAndOpenerTab: true,
dropLinksOnTabBehavior: Constants.kDROPLINK_ASK,
tabDragBehavior: Constants.kDRAG_BEHAVIOR_MOVE | Constants.kDRAG_BEHAVIOR_TEAR_OFF | Constants.kDRAG_BEHAVIOR_ENTIRE_TREE,
tabDragBehaviorShift: Constants.kDRAG_BEHAVIOR_MOVE | Constants.kDRAG_BEHAVIOR_ENTIRE_TREE | Constants.kDRAG_BEHAVIOR_ALLOW_BOOKMARK,
showTabDragBehaviorNotification: true,
guessDraggedNativeTabs: true,
ignoreTabDropNearSidebarArea: true,
moveSoloTabOnDropParentToDescendant: true,
fixupTreeOnTabVisibilityChanged: false,
fixupOrderOfTabsFromOtherDevice: true,
scrollToExpandedTree: true,
syncActiveStateToBundledTabs: true,
spreadMutedStateOnlyToSoundPlayingTabs: true,
// tab bunches
tabBunchesDetectionTimeout: 100,
tabBunchesDetectionDelayOnNewWindow: 500,
autoGroupNewTabsFromBookmarks: true,
restoreTreeForTabsFromBookmarks: true,
tabsFromSameFolderMinThresholdPercentage: 50,
autoGroupNewTabsFromOthers: false,
autoGroupNewTabsFromPinned: true,
autoGroupNewTabsFromFirefoxView: false,
groupTabTemporaryStateForNewTabsFromBookmarks: Constants.kGROUP_TAB_TEMPORARY_STATE_PASSIVE,
groupTabTemporaryStateForNewTabsFromOthers: Constants.kGROUP_TAB_TEMPORARY_STATE_PASSIVE,
groupTabTemporaryStateForChildrenOfPinned: Constants.kGROUP_TAB_TEMPORARY_STATE_PASSIVE,
groupTabTemporaryStateForChildrenOfFirefoxView: Constants.kGROUP_TAB_TEMPORARY_STATE_PASSIVE,
groupTabTemporaryStateForOrphanedTabs: Constants.kGROUP_TAB_TEMPORARY_STATE_AGGRESSIVE,
groupTabTemporaryStateForAPI: Constants.kGROUP_TAB_TEMPORARY_STATE_NOTHING,
renderTreeInGroupTabs: true,
warnOnAutoGroupNewTabs: true,
warnOnAutoGroupNewTabsWithListing: true,
warnOnAutoGroupNewTabsWithListingMaxRows: 5,
showAutoGroupOptionHint: true,
showAutoGroupOptionHintWithOpener: true,
// behavior around newly opened tabs
insertNewChildAt: Constants.kINSERT_END, // basically this option affects only very edge cases not controlled with "autoAttach*" options.
insertNewTabFromPinnedTabAt: Constants.kINSERT_NEXT_TO_LAST_RELATED_TAB,
insertNewTabFromFirefoxViewAt: Constants.kINSERT_NEXT_TO_LAST_RELATED_TAB,
insertDroppedTabsAt: Constants.kINSERT_END,
scrollToNewTabMode: Constants.kSCROLL_TO_NEW_TAB_IF_POSSIBLE,
scrollLines: 3,
autoAttach: true,
autoAttachOnOpenedWithOwner: Constants.kNEWTAB_OPEN_AS_CHILD_END,
autoAttachOnNewTabCommand: Constants.kNEWTAB_DO_NOTHING,
autoAttachOnContextNewTabCommand: Constants.kNEWTAB_OPEN_AS_NEXT_SIBLING_WITH_INHERITED_CONTAINER,
autoAttachOnNewTabButtonMiddleClick: Constants.kNEWTAB_OPEN_AS_CHILD_END,
middleClickPasteURLOnNewTabButton: /^Linux/i.test(navigator.platform), // simulates "browser.tabs.searchclipboardfor.middleclick"
autoAttachOnNewTabButtonAccelClick: Constants.kNEWTAB_OPEN_AS_NEXT_SIBLING_WITH_INHERITED_CONTAINER,
autoAttachOnDuplicated: Constants.kNEWTAB_OPEN_AS_NEXT_SIBLING,
autoAttachSameSiteOrphan: Constants.kNEWTAB_OPEN_AS_CHILD_END,
autoAttachOnOpenedFromExternal: Constants.kNEWTAB_DO_NOTHING,
autoAttachOnAnyOtherTrigger: Constants.kNEWTAB_DO_NOTHING,
guessNewOrphanTabAsOpenedByNewTabCommand: true,
guessNewOrphanTabAsOpenedByNewTabCommandTitle: browser.i18n.getMessage('guessNewOrphanTabAsOpenedByNewTabCommandTitle'),
guessNewOrphanTabAsOpenedByNewTabCommandUrl: 'about:newtab|about:privatebrowsing',
inheritContextualIdentityToChildTabMode: Constants.kCONTEXTUAL_IDENTITY_DEFAULT,
inheritContextualIdentityToSameSiteOrphanMode: Constants.kCONTEXTUAL_IDENTITY_FROM_LAST_ACTIVE,
inheritContextualIdentityToTabsFromExternalMode: Constants.kCONTEXTUAL_IDENTITY_DEFAULT,
inheritContextualIdentityToTabsFromAnyOtherTriggerMode: Constants.kCONTEXTUAL_IDENTITY_DEFAULT,
inheritContextualIdentityToUnopenableURLTabs: false,
// behavior around closed tab
parentTabOperationBehaviorMode: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_MODE_PARALLEL,
//closeParentBehavior_insideSidebar_collapsed: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_ENTIRE_TREE, // permanently consistent
closeParentBehavior_insideSidebar_expanded: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_FIRST_CHILD,
closeParentBehavior_outsideSidebar_collapsed: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_FIRST_CHILD,
closeParentBehavior_outsideSidebar_expanded: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_FIRST_CHILD,
closeParentBehavior_noSidebar_collapsed: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_FIRST_CHILD,
closeParentBehavior_noSidebar_expanded: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_FIRST_CHILD,
//moveParentBehavior_insideSidebar_collapsed: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_ENTIRE_TREE, // permanently consistent
//moveParentBehavior_insideSidebar_expanded: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_ENTIRE_TREE, // permanently consistent
moveParentBehavior_outsideSidebar_collapsed: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_ENTIRE_TREE,
moveParentBehavior_outsideSidebar_expanded: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_FIRST_CHILD,
moveParentBehavior_noSidebar_collapsed: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_FIRST_CHILD,
moveParentBehavior_noSidebar_expanded: Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_FIRST_CHILD,
closeParentBehavior_replaceWithGroup_thresholdToPrevent: 1, // negative value means "never prevent"
moveTabsToBottomWhenDetachedFromClosedParent: false,
promoteAllChildrenWhenClosedParentIsLastChild: true,
successorTabControlLevel: Constants.kSUCCESSOR_TAB_CONTROL_IN_TREE,
simulateSelectOwnerOnClose: true,
simulateLockTabSizing: true,
deferScrollingToOutOfViewportSuccessor: true,
simulateTabsLoadInBackgroundInverted: false,
tabsLoadInBackgroundDiscarded: false,
supportTabsMultiselect: typeof browser.menus.overrideContext == 'function',
warnOnCloseTabs: true,
warnOnCloseTabsNotificationTimeout: 20 * 1000,
warnOnCloseTabsByClosebox: true,
warnOnCloseTabsWithListing: true,
lastConfirmedToCloseTabs: 0,
grantedRemovingTabIds: [],
sidebarVirtuallyOpenedWindows: [], // for automated tests
sidebarVirtuallyClosedWindows: [], // for automated tests
sidebarWidthInWindow: {},
// animation
animation: true,
animationForce: false,
maxAllowedImmediateRefreshCount: 1,
smoothScrollEnabled: true,
smoothScrollDuration: 150,
burstDuration: 375,
indentDuration: 200,
collapseDuration: 150,
outOfViewTabNotifyDuration: 750,
subMenuOpenDelay: 300,
subMenuCloseDelay: 300,
// subpanel
lastSelectedSubPanelProviderId: null,
lastSubPanelHeight: 0,
maxSubPanelSizeRatio: 0.66,
// misc.
showExpertOptions: false,
exposeUnblockAutoplayFeatures: false,
bookmarkTreeFolderName: browser.i18n.getMessage('bookmarkFolder_label_default', ['%TITLE%', '%YEAR%', '%MONTH%', '%DATE%']),
defaultBookmarkParentId: 'toolbar_____', // 'unfiled_____' for Firefox 83 and olders,
defaultSearchEngine: 'https://www.google.com/search?q=%s',
acceleratedTabOperations: true,
acceleratedTabCreation: false,
enableWorkaroundForBug1409262: false,
enableWorkaroundForBug1548949: true,
enableWorkaroundForBug1767165_fixDragEndCoordinates: null, // workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1767165
enableWorkaroundForBug1763420_reloadMaskImage: true, // workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1763420
maximumDelayForBug1561879: 500,
workaroundForBug1548949DroppedTabs: null,
heartbeatInterval: 5000,
connectionTimeoutDelay: 500,
maximumAcceptableDelayForTabDuplication: 10 * 1000,
maximumDelayUntilTabIsTracked: 10 * 60 * 1000,
delayToBlockUserOperationForTabsRestoration: 1000,
intervalToUpdateProgressForBlockedUserOperation: 50,
delayToShowProgressForBlockedUserOperation: 1000,
acceptableDelayForInternalFocusMoving: 150,
delayForDuplicatedTabDetection: 0, // https://github.com/piroor/treestyletab/issues/2845
delayToRetrySyncTabsOrder: 100,
notificationTimeout: 10 * 1000,
longPressDuration: 400,
minimumIntervalToProcessDragoverEvent: 50,
delayToApplyHighlightedState: 50,
acceptableFlickerToIgnoreClickOnTabAndTabbar: 10,
autoDiscardTabForUnexpectedFocus: true,
autoDiscardTabForUnexpectedFocusDelay: 500,
avoidDiscardedTabToBeActivatedIfPossible: false,
provressiveHighlightingStep: Number.MAX_SAFE_INTEGER,
progressievHighlightingInterval: 100,
generatedTabElementsPoolLifetimeMsec: 5 * 1000,
undoMultipleTabsClose: true,
allowDragNewTabButton: true,
newTabButtonDragGestureModifiers: 'shift',
migratedBookmarkUrls: [],
lastDragOverSidebarOwnerWindowId: null,
notifiedFeaturesVersion: 0,
useCachedTree: true,
persistCachedTree: true,
// This should be removed after https://bugzilla.mozilla.org/show_bug.cgi?id=1388193
// or https://bugzilla.mozilla.org/show_bug.cgi?id=1421329 become fixed.
// Otherwise you need to set "svg.context-properties.content.enabled"="true" via "about:config".
simulateSVGContextFill: true,
requestingPermissions: null,
requestingPermissionsNatively: null,
lastDraggedTabs: null,
// https://dxr.mozilla.org/mozilla-central/rev/2535bad09d720e71a982f3f70dd6925f66ab8ec7/browser/base/content/browser.css#137
newTabAnimationDuration: 100,
chunkedUserStyleRules0: '',
chunkedUserStyleRules1: '',
chunkedUserStyleRules2: '',
chunkedUserStyleRules3: '',
chunkedUserStyleRules4: '',
chunkedUserStyleRules5: '',
chunkedUserStyleRules6: '',
chunkedUserStyleRules7: '',
// obsolete, migrated to chunkedUserStyleRules0-5
userStyleRules: `
/* Show title of unread tabs with red and italic font */
/*
:root.sidebar tab-item.unread .label-content {
color: red !important;
font-style: italic !important;
}
*/
/* Add private browsing indicator per tab */
/*
:root.sidebar tab-item.private-browsing tab-label:before {
content: "🕶";
}
*/
`.trim(),
userStyleRulesFieldHeight: '10em',
userStyleRulesFieldTheme: 'auto',
syncOtherDevicesDetected: false,
syncAvailableNotified: false,
syncAvailableNotificationTimeout: 20 * 1000,
syncDeviceInfo: null,
syncDevices: {},
syncDevicesLocalCache: {},
syncDeviceExpirationDays: 14,
// Must be same to "services.sync.engine.tabs.filteredUrls"
syncUnsendableUrlPattern: '^(about:.*|resource:.*|chrome:.*|wyciwyg:.*|file:.*|blob:.*|moz-extension:.*)$',
syncLastMessageTimestamp: 0,
syncReceivedTabsNotificationTimeout: 20 * 1000,
syncSentTabsNotificationTimeout: 5 * 1000,
chunkedSyncData0: '',
chunkedSyncData1: '',
chunkedSyncData2: '',
chunkedSyncData3: '',
chunkedSyncData4: '',
chunkedSyncData5: '',
chunkedSyncData6: '',
chunkedSyncData7: '',
chunkedSyncDataLocal0: '',
chunkedSyncDataLocal1: '',
chunkedSyncDataLocal2: '',
chunkedSyncDataLocal3: '',
chunkedSyncDataLocal4: '',
chunkedSyncDataLocal5: '',
chunkedSyncDataLocal6: '',
chunkedSyncDataLocal7: '',
// Compatibility with other addons
knownExternalAddons: [
'multipletab@piro.sakura.ne.jp'
],
cachedExternalAddons: [],
grantedExternalAddonPermissions: {},
incognitoAllowedExternalAddons: [],
// This must be same to the redirect key of Container Bookmarks.
// https://addons.mozilla.org/firefox/addon/container-bookmarks/
containerRedirectKey: 'container',
debug: false,
blockStartupOperations: false, // to collect performance profile around the initialization process
runTestsParameters: '',
syncEnabled: true,
APIEnabled: true,
cacheAPITreeItems: false,
logTimestamp: true,
loggingQueries: false,
logFor: { // git grep configs.logFor | grep -v common.js | cut -d "'" -f 2 | sed -e "s/^/ '/" -e "s/$/': false,/"
'background/api-tabs-listener': false,
'background/background-cache': false,
'background/background': false,
'background/browser-action-menu': false,
'background/commands': false,
'background/context-menu': false,
'background/handle-misc': false,
'background/handle-moved-tabs': false,
'background/handle-new-tabs': false,
'background/handle-removed-tabs': false,
'background/handle-tab-bunches': false,
'background/handle-tab-focus': false,
'background/handle-tab-multiselect': false,
'background/handle-tree-changes': false,
'background/migration': false,
'background/successor-tab': false,
'background/tab-context-menu': false,
'background/tabs-group': false,
'background/tabs-move': false,
'background/tabs-open': false,
'background/tree': false,
'background/tree-structure': false,
'common/Tab': false,
'common/Window': false,
'common/api-tabs': false,
'common/bookmark': false,
'common/contextual-identities': false,
'common/dialog': false,
'common/permissions': false,
'common/retrieve-url': false,
'common/sidebar-connection': false,
'common/sync': false,
'common/tabs-internal-operation': false,
'common/tabs-update': false,
'common/tree-behavior': false,
'common/tst-api': false,
'common/unique-id': false,
'common/user-operation-blocker': false,
'sidebar/background-connection': false,
'sidebar/collapse-expand': false,
'sidebar/drag-and-drop': false,
'sidebar/event-utils': false,
'sidebar/gap-canceller': false,
'sidebar/indent': false,
'sidebar/mouse-event-listener': false,
'sidebar/pinned-tabs': false,
'sidebar/scroll': false,
'sidebar/sidebar-tabs': false,
'sidebar/sidebar': false,
'sidebar/size': false,
'sidebar/subpanel': false,
'sidebar/tab-context-menu': false,
'sidebar/tab-preview-tooltip': false,
'sidebar/tst-api-frontend': false,
},
loggingConnectionMessages: false,
enableLinuxBehaviors: false,
enableMacOSBehaviors: false,
enableWindowsBehaviors: false,
...(Object.fromEntries(Array.from(obsoleteConfigs, key => [key, null]))),
configsVersion: 0,
testKey: 0 // for tests/utils.js
}, {
localKeys
});
configs.$addLocalLoadedObserver((key, value) => {
switch (key) {
case 'syncEnabled':
configs.sync = !!value;
return;
default:
return;
}
});
// cleanup old data
browser.storage.sync.remove(localKeys);
configs.$loaded.then(() => {
EventListenerManager.debug = configs.debug;
log.forceStore = false;
if (!configs.debug)
log.logs = [];
});
export function loadUserStyleRules() {
return getChunkedConfig('chunkedUserStyleRules');
}
export function saveUserStyleRules(style) {
return setChunkedConfig('chunkedUserStyleRules', style);
}
export function getChunkedConfig(key) {
const chunks = [];
let count = 0;
while (true) {
const slotKey = `${key}${count}`;
if (!(slotKey in configs))
break;
chunks.push(configs[slotKey]);
count++;
}
return joinChunkedStrings(chunks);
}
export function setChunkedConfig(key, value) {
let slotsSize = 0;
while (`${key}${slotsSize}` in configs.$default) {
slotsSize++;
}
const chunks = chunkString(value, Constants.kSYNC_STORAGE_SAFE_QUOTA);
if (chunks.length > slotsSize)
throw new Error('too large data');
[...chunks,
...Array.from(new Uint8Array(slotsSize), _ => '')]
.slice(0, slotsSize)
.forEach((chunk, index) => {
const slotKey = `${key}${index}`;
if (slotKey in configs)
configs[slotKey] = chunk || '';
});
}
function chunkString(input, maxBytes) {
let binaryString = btoa(Array.from(new TextEncoder().encode(input), c => String.fromCharCode(c)).join(''));
const chunks = [];
while (binaryString.length > 0) {
chunks.push(binaryString.slice(0, maxBytes));
binaryString = binaryString.slice(maxBytes);
}
return chunks;
}
function joinChunkedStrings(chunks) {
try {
const buffer = Uint8Array.from(atob(chunks.join('')).split('').map(bytes => bytes.charCodeAt(0)));
return new TextDecoder().decode(buffer);
}
catch(_error) {
return '';
}
}
shouldApplyAnimation.onChanged = new EventListenerManager();
shouldApplyAnimation.prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
shouldApplyAnimation.prefersReducedMotion.addListener(_event => {
shouldApplyAnimation.onChanged.dispatch(shouldApplyAnimation());
});
configs.$addObserver(key => {
switch(key) {
case 'animation':
case 'animationForce':
shouldApplyAnimation.onChanged.dispatch(shouldApplyAnimation());
break;
case 'debug':
EventListenerManager.debug = configs[key];
break;
}
});
// Some animation effects like smooth scrolling are still active even if it matches to "prefers-reduced-motion: reduce".
// So this function provides ability to ignore the media query result.
export function shouldApplyAnimation(configOnly = false) {
if (!configs.animation)
return false;
return configOnly || configs.animationForce || !shouldApplyAnimation.prefersReducedMotion.matches;
}
export function log(module, ...args)
{
const isModuleLog = module in configs.$default.logFor;
const message = isModuleLog ? args.shift() : module ;
const useConsole = configs && configs.debug && (!isModuleLog || configs.logFor[module]);
const logging = useConsole || log.forceStore;
if (!logging)
return;
args = args.map(arg => typeof arg == 'function' ? arg() : arg);
const nest = (new Error()).stack.split('\n').length;
let indent = '';
for (let i = 0; i < nest; i++) {
indent += ' ';
}
if (isModuleLog)
module = `${module}: `
else
module = '';
const timestamp = configs.logTimestamp ? `${getTimeStamp()} ` : '';
const line = `tst<${log.context}>: ${timestamp}${module}${indent}${message}`;
if (useConsole)
console.log(line, ...args);
log.logs.push(`${line} ${args.reduce((output, arg, index) => {
output += `${index == 0 ? '' : ', '}${uneval(arg)}`;
return output;
}, '')}`);
log.logs = log.logs.slice(-log.max);
}
log.context = '?';
log.max = 2000;
log.logs = [];
log.forceStore = true;
// uneval() is no more available after https://bugzilla.mozilla.org/show_bug.cgi?id=1565170
function uneval(value) {
switch (typeof value) {
case 'undefined':
return 'undefined';
case 'function':
return value.toString();
case 'object':
if (!value)
return 'null';
default:
try {
return JSON.stringify(value);
}
catch(e) {
return `${String(value)} (couldn't be stringified due to an error: ${String(e)})`;
}
}
}
function getTimeStamp() {
const time = new Date();
const hours = `0${time.getHours()}`.slice(-2);
const minutes = `0${time.getMinutes()}`.slice(-2);
const seconds = `0${time.getSeconds()}`.slice(-2);
const milliseconds = `00${time.getMilliseconds()}`.slice(-3);
return `${hours}:${minutes}:${seconds}.${milliseconds}`;
}
configs.$logger = log;
export function dumpTab(tab) {
if (!configs || !configs.debug)
return '';
if (!tab)
return '<NULL>';
return `#${tab.id}(${!!tab.$TST ? 'tracked' : '!tracked'})`;
}
export async function wait(task = 0, timeout = 0) {
if (typeof task != 'function') {
timeout = task;
task = null;
}
return new Promise((resolve, _reject) => {
setTimeout(async () => {
if (task)
await task();
resolve();
}, timeout);
});
}
export function nextFrame() {
return new Promise((resolve, _reject) => {
window.requestAnimationFrame(resolve);
});
}
export async function asyncRunWithTimeout({ task, timeout, onTimedOut }) {
let succeeded = false;
return Promise.race([
task().then(result => {
succeeded = true;
return result;
}),
wait(timeout).then(() => {
if (!succeeded)
return onTimedOut();
}),
]);
}
const mNotificationTasks = new Map();
function destroyNotificationTask(task) {
if (!mNotificationTasks.has(task.id))
return;
mNotificationTasks.delete(task.id);
const resolve = task.resolve;
const url = task.url;
task.id = undefined;
task.url = undefined;
task.resolve = undefined;
return { resolve, url };
}
function onNotificationClicked(notificationId) {
const task = mNotificationTasks.get(notificationId);
if (!task)
return;
const { resolve, url } = destroyNotificationTask(task);
if (url) {
browser.tabs.create({
url
});
}
resolve(true);
}
browser.notifications.onClicked.addListener(onNotificationClicked);
function onNotificationClosed(notificationId) {
const task = mNotificationTasks.get(notificationId);
if (!task)
return;
const { resolve } = destroyNotificationTask(task);
resolve(false);
}
browser.notifications.onClosed.addListener(onNotificationClosed);
export async function notify({ icon, title, message, timeout, url } = {}) {
const id = await browser.notifications.create({
type: 'basic',
iconUrl: icon || Constants.kNOTIFICATION_DEFAULT_ICON,
title,
message
});
const task = { id, url };
mNotificationTasks.set(id, task);
return new Promise(async (resolve, _reject) => {
task.resolve = resolve;
if (typeof timeout != 'number')
timeout = configs.notificationTimeout;
if (timeout >= 0) {
await wait(timeout);
}
await browser.notifications.clear(id);
if (task.resolve) {
destroyNotificationTask(task);
resolve(false);
}
}).then(clicked => {
return clicked;
});
}
export function tryRevokeObjectURL(url) {
if (!url.startsWith(`blob:${browser.runtime.getURL('') }`))
return;
try {
URL.revokeObjectURL(url);
}
catch(error) {
console.log('tryRevokeObjectURL failed: ', error);
}
}
export function compareAsNumber(a, b) {
return a - b;
}
// Helper functions for optimization
// Originally implemented by @bb010g at
// https://github.com/piroor/treestyletab/pull/2368/commits/9d184c4ac6c9977d2557cd17cec8c2a0f21dd527
// For better performance the callback function must return "undefined"
// when the item should not be included. "null", "false", and other false
// values will be included to the mapped result.
export function mapAndFilter(values, mapper) {
/* This function logically equals to:
return values.reduce((mappedValues, value) => {
value = mapper(value);
if (value !== undefined)
mappedValues.push(value);
return mappedValues;
}, []);
*/
const maxi = ('length' in values ? values.length : values.size) >>> 0; // define as unsigned int
const mappedValues = new Array(maxi); // prepare with enough size at first, to avoid needless re-allocation
let count = 0,
value, // this must be defined outside of the loop, to avoid needless re-allocation
mappedValue; // this must be defined outside of the loop, to avoid needless re-allocation
for (value of values) {
mappedValue = mapper(value);
if (mappedValue !== undefined)
mappedValues[count++] = mappedValue;
}
mappedValues.length = count; // shrink the array at last
return mappedValues;
}
export function mapAndFilterUniq(values, mapper, options = {}) {
const mappedValues = new Set();
let value, // this must be defined outside of the loop, to avoid needless re-allocation
mappedValue; // this must be defined outside of the loop, to avoid needless re-allocation
for (value of values) {
mappedValue = mapper(value);
if (mappedValue !== undefined)
mappedValues.add(mappedValue);
}
return options.set ? mappedValues : Array.from(mappedValues);
}
export function countMatched(values, matcher) {
/* This function logically equals to:
return values.reduce((count, value) => {
if (matcher(value))
count++;
return count;
}, 0);
*/