-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1252 lines (1108 loc) · 46 KB
/
Copy pathbackground.js
File metadata and controls
1252 lines (1108 loc) · 46 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
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
// Background service worker for Haiilo Enhancer
// Compatible with both Chrome (Manifest V3) and Firefox (Manifest V3)
//# sourceURL=haiilo-enhancer/background.js
if (typeof importScripts === 'function') {
try {
importScripts('shared.js', 'i18n.js');
} catch (error) {
console.error('Failed to load shared libraries:', error);
}
}
// Browser API compatibility
const browserAPI = typeof browser !== 'undefined' ? browser : chrome;
// Firefox MV3 uses browser.action; Chrome MV3 uses chrome.action (Chrome also exposes a
// `browser` compat namespace, but only with `action`). Detect the actual API surface rather
// than the global; keep chrome.action as the final fallback so the Chromium path is never
// affected.
const badgeAPI = (typeof browser !== 'undefined' && browser.action)
? browser.action
: (browserAPI.action || chrome.action);
// Shared constants and helpers (single source of truth in shared.js).
const DATE_TIME_PRESETS = HaiiloShared.DATE_TIME_PRESETS;
const normalizeDateFormatValue = HaiiloShared.normalizeDateFormatValue;
const getDateTimePresetOptions = HaiiloShared.getDateTimePresetOptions;
const clampMessengerPanelWidthPercent = HaiiloShared.clampMessengerPanelWidthPercent;
function normalizeLocale(locale) {
return String(locale || '').replace('_', '-').trim().toLowerCase();
}
function getLocaleDateTimePresetId(locale) {
const normalized = normalizeLocale(locale);
const base = normalized.split('-')[0];
const languageFallbacks = {
de: 'centralEuropean24h',
fr: 'westernEuropean24h',
nl: 'dutch24h',
it: 'westernEuropean24h',
es: 'westernEuropean24h',
pt: 'westernEuropean24h',
pl: 'centralEuropean24h',
ru: 'centralEuropean24h',
sv: 'iso860124h',
da: 'centralEuropean24h',
nb: 'centralEuropean24h',
nn: 'centralEuropean24h',
fi: 'finnish24h',
tr: 'centralEuropean24h',
cs: 'spacedCentral24h',
sk: 'spacedCentral24h',
hu: 'hungarian24h',
ro: 'centralEuropean24h',
uk: 'centralEuropean24h',
el: 'westernEuropean24h',
he: 'middleEastern24h',
ar: 'middleEastern24h',
hi: 'southAsian12h',
ja: 'eastAsian24h',
ko: 'korean24h',
zh: 'eastAsian24h',
th: 'southeastAsian24h',
vi: 'southeastAsian24h',
id: 'southeastAsian24h',
ms: 'southeastAsian24h',
fa: 'iso860124h',
ca: 'westernEuropean24h',
eu: 'iso860124h',
gl: 'westernEuropean24h',
af: 'iso860124h'
};
if (['en-ca', 'en-au', 'en-nz', 'en-ie', 'en-mt', 'en-cy'].includes(normalized)) return 'westernEuropean12h';
if (['en-gb', 'en-sg', 'en-hk', 'en-my'].includes(normalized)) return 'westernEuropean24h';
if (normalized === 'en-in' || normalized === 'hi-in' || normalized === 'bn-bd' || normalized === 'bn-in' || normalized === 'ur-pk' || normalized === 'pa-in' || normalized === 'ta-in') return 'southAsian12h';
if (normalized === 'en-za') return 'iso860124h';
if (normalized === 'en-us' || normalized === 'en-ph' || normalized === 'tl-ph' || normalized === 'en') return 'northAmerican12h';
if (normalized === 'nl-nl' || normalized === 'nl') return 'dutch24h';
if (normalized === 'nl-be') return 'westernEuropean24h';
if (normalized === 'fr-ca' || normalized === 'sv-se' || normalized === 'lt-lt' || normalized === 'af-za' || normalized === 'en-za' || normalized === 'eu-es') {
return 'iso860124h';
}
if (['de-de', 'de-at', 'de-ch', 'de-li', 'de-lu', 'fr-ch', 'it-ch', 'pl-pl', 'ro-ro', 'bg-bg', 'tr-tr', 'tr-cy', 'ka-ge', 'hy-am', 'az-az', 'uk-ua', 'be-by', 'ru-ru', 'ru-by', 'ru-kz', 'lb-lu', 'mk-mk', 'da-dk', 'nb-no', 'nn-no', 'et-ee', 'lv-lv', 'sv-fi', 'is-is'].includes(normalized)) {
return 'centralEuropean24h';
}
if (['fr-fr', 'fr-be', 'fr-lu', 'fr-mc', 'fr-ma', 'fr-tn', 'fr-sn', 'fr-ci', 'fr-cm', 'fr-mg', 'it-it', 'es-es', 'pt-pt', 'ca-es', 'gl-es', 'el-gr', 'el-cy', 'mt-mt', 'fo-fo'].includes(normalized)) {
return 'westernEuropean24h';
}
if (normalized === 'fi-fi') return 'finnish24h';
if (['cs-cz', 'sk-sk', 'sl-si'].includes(normalized)) return 'spacedCentral24h';
if (['hr-hr', 'bs-ba', 'sr-rs', 'sr-ba'].includes(normalized)) return 'dottedSlavic24h';
if (normalized === 'hu-hu') return 'hungarian24h';
if (normalized === 'ko-kr') return 'korean24h';
if (['ja-jp', 'zh-cn'].includes(normalized)) return 'eastAsian24h';
if (normalized === 'zh-tw') return 'eastAsian12h';
if (normalized === 'zh-hk' || normalized === 'zh-mo') return 'westernEuropean12h';
if (normalized === 'fa-ir' || normalized.startsWith('ar-') || normalized === 'he-il') return 'middleEastern24h';
if (['hi-in', 'bn-bd', 'bn-in', 'ur-pk', 'pa-in', 'ta-in'].includes(normalized)) return 'southAsian12h';
if (['ms-my', 'ms-bn', 'th-th', 'vi-vn', 'id-id', 'km-kh', 'lo-la', 'my-mm'].includes(normalized)) return 'southeastAsian24h';
if (['sw-ke', 'am-et'].includes(normalized)) return 'southeastAsian12h';
if (['es-mx', 'es-co', 'es-cr', 'es-gt', 'es-sv', 'es-hn', 'es-ni', 'es-pa', 'es-do'].includes(normalized)) return 'latinAmerican12h';
if (['es-ar', 'es-cl', 'es-pe', 'es-ve', 'es-ec', 'es-bo', 'es-py', 'es-uy', 'es-cu'].includes(normalized)) return 'latinAmerican24h';
if (normalized === 'en-sg' || normalized === 'en-hk' || normalized === 'en-my') return 'southeastAsian24h';
if (languageFallbacks[base]) return languageFallbacks[base];
if (base === 'en') return 'northAmerican12h';
return 'northAmerican12h';
}
function getLocaleDateTimeDefaults(locale) {
return DATE_TIME_PRESETS[getLocaleDateTimePresetId(locale)] || DATE_TIME_PRESETS.northAmerican12h;
}
function getRequestedLocale(preferredLocale) {
return normalizeLocale(preferredLocale || (browserAPI.i18n && typeof browserAPI.i18n.getUILanguage === 'function' ? browserAPI.i18n.getUILanguage() : '') || (typeof navigator !== 'undefined' ? navigator.language : '') || 'en-US');
}
// Debug logging helper — P1 fix: cache debugMode in memory to avoid
// hitting storage on every call (60+ call sites in this file alone).
let _debugMode = false;
browserAPI.storage.local.get('settings').then(data => {
_debugMode = !!(data.settings && data.settings.debugMode);
}).catch(() => {});
browserAPI.storage.onChanged.addListener((changes) => {
if (changes.settings && changes.settings.newValue) {
_debugMode = !!changes.settings.newValue.debugMode;
}
});
function debugLog(...args) {
if (_debugMode) console.log(...args);
}
// Default settings
const DEFAULT_SETTINGS = {
language: 'browser', // 'browser' or one of the bundled locale codes
extensionEnabled: true,
defaultMuteDays: 7,
showMutedIndicator: true,
debugMode: false,
enhanceChannelAvatars: true,
channelAvatarStyle: 'ring', // 'ring', 'square', or 'badge'
channelAvatarRingColor: '#502379', // Brand purple
channelAvatarRingWidth: 2, // Ring border width in pixels (0-5)
channelAvatarSquareColor: '#502379', // Brand purple for square border
channelAvatarSquareWidth: 2, // Square border width in pixels (0-5)
channelAvatarBadgeSize: 100, // Badge size as percentage (50-150, 100 = default)
channelAvatarBadgePosition: 'bottom-left', // 'bottom-left' or 'top-left'
channelAvatarColorMode: 'random', // 'random' or 'fixed'
channelAvatarFixedColor: '#0f939d', // Haiilo teal color when colorMode is 'fixed'
dateFormat: 'northAmerican12h', // locale-aware preset id
timeFormat: '12h', // '12h' or '24h'
keepMessengerExpanded: false, // Keep messenger panel permanently expanded
messengerPanelWidthPercent: 100, // Messenger width scale (50-125, 100 = Haiilo default)
centerContentWithMessenger: false, // Center page content in the space left beside the messenger
collapseNavbarSpacing: false, // Collapse the wasted navbar gap when the reduced space can't fit all items
autoExpandEnabled: false, // Auto-click "Show more" buttons in sidebar lists
autoExpandClicksPerList: 3, // Max number of "Show more" clicks per list (0-10)
autoExpandDelayMs: 300, // Delay between clicks in ms (100-1000)
autoExpandScope: 'both', // Which lists to expand: 'both', 'workspaces', or 'pages'
endlessScrollEnabled: false, // Auto-click the timeline "Load more" button when scrolled to the bottom
autoLoadUpdatesEnabled: false, // Auto-click the timeline "Load new updates" button when the page is idle
autoLoadUpdatesIdleSec: 5, // Idle time in seconds (0-600) without user activity before new updates are loaded automatically
cloudSync: false, // Sync settings and muted users via browser account (opt-in)
theme: 'system', // 'system' (follow browser), 'light', or 'dark'
sortReactionsByCount: true, // Sort reaction emojis by count (most used first)
showReactionCountTooltip: true, // Show reaction count breakdown on hover
showReactionCountInline: false, // Show counts next to reaction emojis
fixMentionFormatting: true, // Fix oversized whitespace around inline mentions
fixMentionPopup: true, // Fix oversized profile popups opened from rich content
fixMobileWikiBreadcrumbs: false, // Fix collapsed wiki breadcrumbs on narrow screens
fixWikiModeToggle: false, // Keep the wiki simple/advanced mode toggle in the toolbar
floatingRichTextToolbar: true, // Show formatting controls next to selected editor text
markdownToolbar: true, // Show a Markdown shortcut toolbar when selecting text in the chat message editor
markdownToolbarBrand: true, // Show the Haiilo Enhancer mark at the end of the Markdown toolbar
chatReplyMenu: true // Add a "Reply" action to chat message context menus that quotes the message
};
function normalizeSettings(settings = {}) {
const normalized = { ...DEFAULT_SETTINGS };
Object.keys(DEFAULT_SETTINGS).forEach(key => {
if (Object.prototype.hasOwnProperty.call(settings, key)) {
normalized[key] = settings[key];
}
});
normalized.messengerPanelWidthPercent = clampMessengerPanelWidthPercent(normalized.messengerPanelWidthPercent);
if (normalized.keepMessengerExpanded !== true) {
normalized.centerContentWithMessenger = false;
}
normalized.language = ['browser', 'en', 'de', 'cs', 'es', 'fr', 'hu', 'it', 'nl', 'pl'].includes(normalized.language)
? normalized.language
: DEFAULT_SETTINGS.language;
normalized.dateFormat = normalizeDateFormatValue(normalized.dateFormat);
const preset = DATE_TIME_PRESETS[normalized.dateFormat] || DATE_TIME_PRESETS.northAmerican12h;
normalized.timeFormat = normalized.timeFormat === '24h' ? '24h' : preset.timeFormat;
normalized.theme = ['system', 'light', 'dark'].includes(normalized.theme)
? normalized.theme
: DEFAULT_SETTINGS.theme;
return normalized;
}
function buildLocaleAwareSettings() {
const locale = getRequestedLocale();
const localeDefaults = getLocaleDateTimeDefaults(locale);
return normalizeSettings({
...DEFAULT_SETTINGS,
dateFormat: localeDefaults ? getLocaleDateTimePresetId(locale) : DEFAULT_SETTINGS.dateFormat,
timeFormat: localeDefaults ? localeDefaults.timeFormat : DEFAULT_SETTINGS.timeFormat
});
}
// Default domains
const DEFAULT_DOMAINS = ['haiilo.app', 'haiilo.com'];
const CLOUD_SYNC_USER_LIMIT = 50;
// Write settings + mutedUsers to storage.sync if cloudSync is enabled.
// If mutedUsers exceeds the limit, disable cloudSync and broadcast a warning.
async function syncToCloud() {
try {
const data = await browserAPI.storage.local.get(['settings', 'mutedUsers']);
const settings = data.settings || DEFAULT_SETTINGS;
if (!settings.cloudSync) return;
const mutedUsers = data.mutedUsers || [];
if (mutedUsers.length > CLOUD_SYNC_USER_LIMIT) {
// Disable cloud sync and persist the change
settings.cloudSync = false;
await browserAPI.storage.local.set({ settings });
await broadcastMessageToAllHaiiloTabs({ action: 'settingsUpdated' });
await broadcastMessageToAllHaiiloTabs({
action: 'cloudSyncDisabled',
reason: `Cloud sync disabled: muted user list exceeds the ${CLOUD_SYNC_USER_LIMIT}-user limit.`
});
debugLog('[CloudSync] Disabled — user limit exceeded');
return;
}
await browserAPI.storage.sync.set({ settings, mutedUsers });
debugLog('[CloudSync] Synced to cloud:', mutedUsers.length, 'users');
} catch (e) {
console.error('[CloudSync] Failed to sync to cloud:', e);
}
}
// Pull settings + mutedUsers from storage.sync and merge into local storage.
// Only runs if cloudSync is enabled in either local or sync settings.
async function pullFromCloud() {
try {
const syncData = await browserAPI.storage.sync.get(['settings', 'mutedUsers']);
if (!syncData.settings || !syncData.settings.cloudSync) return;
const localData = await browserAPI.storage.local.get(['settings', 'mutedUsers']);
const localSettings = localData.settings || DEFAULT_SETTINGS;
// Merge: prefer sync data (it's the "canonical" cloud copy)
const mergedSettings = normalizeSettings({ ...localSettings, ...syncData.settings });
const mergedUsers = syncData.mutedUsers || localData.mutedUsers || [];
await browserAPI.storage.local.set({ settings: mergedSettings, mutedUsers: mergedUsers });
debugLog('[CloudSync] Pulled from cloud:', mergedUsers.length, 'users');
} catch (e) {
console.error('[CloudSync] Failed to pull from cloud:', e);
}
}
// Initialize extension on install
browserAPI.runtime.onInstalled.addListener(async () => {
try {
// Initialize storage with defaults if not set
// A7 fix: only query top-level storage keys (sub-keys like 'language',
// 'extensionEnabled' etc. live inside 'settings', not at the root).
const data = await browserAPI.storage.local.get([
'mutedUsers',
'settings',
'customDomains',
'customHomepages',
'disabledDomains'
]);
if (!data.mutedUsers) {
await browserAPI.storage.local.set({ mutedUsers: [] });
}
if (!data.settings) {
await browserAPI.storage.local.set({ settings: buildLocaleAwareSettings() });
} else {
await browserAPI.storage.local.set({ settings: normalizeSettings(data.settings) });
}
if (!data.customDomains) {
await browserAPI.storage.local.set({ customDomains: [] });
}
if (!data.customHomepages) {
await browserAPI.storage.local.set({ customHomepages: {} });
}
if (!data.disabledDomains) {
await browserAPI.storage.local.set({ disabledDomains: [] });
}
// Create context menu
try {
await createContextMenu();
} catch (e) {
console.error('Error creating context menu on install:', e);
}
// Register dynamic content scripts for custom domains
try {
await registerDynamicContentScripts();
} catch (e) {
console.error('Error registering dynamic content scripts on install:', e);
}
// Inject content scripts into existing tabs
try {
await injectContentScripts();
} catch (e) {
console.error('Error injecting content scripts on install:', e);
}
} catch (err) {
console.error('Error in onInstalled listener:', err);
}
});
// Create context menu on startup and re-register content scripts
browserAPI.runtime.onStartup.addListener(async () => {
await pullFromCloud();
await createContextMenu();
// Re-register dynamic content scripts (they don't persist across browser restarts)
await registerDynamicContentScripts();
});
// Inject content script when navigating to Haiilo pages
// Note: Dynamic content scripts handle automatic injection for custom domains
// This listener serves as a fallback and handles default domains
browserAPI.webNavigation.onCompleted.addListener(async (details) => {
if (await isHaiiloTab({ url: details.url })) {
try {
await browserAPI.scripting.executeScript({
target: { tabId: details.tabId },
files: ['shared.js', 'i18n.js', 'content.js']
});
await browserAPI.scripting.insertCSS({
target: { tabId: details.tabId },
files: ['colors.css', 'content.css']
});
debugLog('Content script injected on navigation to:', details.url);
} catch (e) {
debugLog('Could not inject content script on navigation:', e.message);
}
}
});
async function createContextMenu() {
const settings = normalizeSettings((await browserAPI.storage.local.get('settings')).settings || DEFAULT_SETTINGS);
await initializeI18n(settings.language);
if (settings.extensionEnabled === false) {
browserAPI.contextMenus.removeAll();
return;
}
// Get all domains (default + custom) for targetUrlPatterns
const allDomains = await getAllDomains();
// Build targetUrlPatterns for all domains
const targetUrlPatterns = [];
allDomains.forEach(domain => {
targetUrlPatterns.push(
`https://*.${domain}/home/*`,
`https://${domain}/home/*`,
`https://*.${domain}/pages/*`,
`https://${domain}/pages/*`,
`https://*.${domain}/workspaces/*`,
`https://${domain}/workspaces/*`,
`http://*.${domain}/home/*`,
`http://${domain}/home/*`,
`http://*.${domain}/pages/*`,
`http://${domain}/pages/*`,
`http://*.${domain}/workspaces/*`,
`http://${domain}/workspaces/*`
);
});
// Build documentUrlPatterns for all domains
const documentUrlPatterns = [];
allDomains.forEach(domain => {
documentUrlPatterns.push(
`https://*.${domain}/*`,
`https://${domain}/*`,
`http://*.${domain}/*`,
`http://${domain}/*`
);
});
// Remove existing menu items first
browserAPI.contextMenus.removeAll(() => {
// Create parent menu
browserAPI.contextMenus.create({
id: 'hush-parent',
title: i18nMessage('extensionName'),
contexts: ['link', 'selection']
});
// Mute permanently
browserAPI.contextMenus.create({
id: 'mute-permanent',
parentId: 'hush-parent',
title: i18nMessage('muteUserPermanently'),
contexts: ['link', 'selection']
});
// Mute for default days
browserAPI.contextMenus.create({
id: 'mute-default',
parentId: 'hush-parent',
title: i18nMessage('muteDefaultPeriod'),
contexts: ['link', 'selection']
});
// Separator
browserAPI.contextMenus.create({
id: 'separator-1',
parentId: 'hush-parent',
type: 'separator',
contexts: ['link', 'selection']
});
// Mute for specific durations
const durations = [1, 3, 7, 14, 30, 90];
durations.forEach(days => {
browserAPI.contextMenus.create({
id: `mute-${days}`,
parentId: 'hush-parent',
title: i18nMessage('muteForDays', days),
contexts: ['link', 'selection']
});
});
// Separator
browserAPI.contextMenus.create({
id: 'separator-2',
parentId: 'hush-parent',
type: 'separator',
contexts: ['link', 'selection']
});
// Set as default homepage (only shown for valid homepage links)
browserAPI.contextMenus.create({
id: 'set-homepage',
parentId: 'hush-parent',
title: i18nMessage('setDefaultHomepage'),
contexts: ['link'],
documentUrlPatterns: documentUrlPatterns,
targetUrlPatterns: targetUrlPatterns
});
});
}
// Handle context menu clicks
browserAPI.contextMenus.onClicked.addListener(async (info, tab) => {
const settings = (await browserAPI.storage.local.get('settings')).settings || DEFAULT_SETTINGS;
if (!settings.extensionEnabled) {
debugLog('Extension is disabled, ignoring context menu click');
return;
}
debugLog('Context menu clicked:', info);
// Handle setting custom homepage
if (info.menuItemId === 'set-homepage') {
handleSetHomepage(info, tab);
return;
}
// Get user name from selection or try to extract from link
let userName = null;
// First, ensure content script is injected
if (await isHaiiloTab(tab)) {
try {
// Check if content script is already injected by trying to send a ping
try {
await browserAPI.tabs.sendMessage(tab.id, { action: 'ping' }).catch(() => null);
debugLog('Content script already present');
} catch (pingError) {
// Content script not present, inject it
await browserAPI.scripting.executeScript({
target: { tabId: tab.id },
files: ['shared.js', 'i18n.js', 'content.js']
});
debugLog('Content script injected successfully');
// Wait a moment for content script to initialize
await new Promise(resolve => setTimeout(resolve, 200));
}
} catch (e) {
debugLog('Could not inject content script:', e.message);
}
} else {
debugLog('Not a Haiilo tab, skipping content script injection');
}
if (info.selectionText) {
userName = info.selectionText.trim();
debugLog('Username from selection:', userName);
} else if (info.linkUrl) {
// Try to extract username from the page via content script
try {
const response = await browserAPI.tabs.sendMessage(tab.id, {
action: 'getUserNameFromElement'
}).catch(() => null);
if (response && response.userName) {
userName = response.userName;
debugLog('Username from element:', userName);
}
} catch (e) {
// This catch block should not be reached due to the .catch() above
console.error('Could not get username from element:', e);
}
}
if (!userName) {
// Ask content script for the last right-clicked username
try {
const response = await browserAPI.tabs.sendMessage(tab.id, {
action: 'getLastRightClickedUser'
}).catch(() => null);
if (response && response.userName) {
userName = response.userName;
debugLog('Username from last right-click:', userName);
}
} catch (e) {
// This catch block should not be reached due to the .catch() above
console.error('Could not get last right-clicked user:', e);
}
}
if (!userName) {
debugLog('No username found to mute');
return;
}
// Determine mute duration
let muteDays = null; // null = permanent
if (info.menuItemId === 'mute-permanent') {
muteDays = null;
} else if (info.menuItemId === 'mute-default') {
muteDays = settings.defaultMuteDays;
} else if (info.menuItemId.startsWith('mute-')) {
muteDays = parseInt(info.menuItemId.replace('mute-', ''), 10);
}
// Add user to muted list
await muteUser(userName, muteDays);
// Notify content script to update
try {
await browserAPI.tabs.sendMessage(tab.id, { action: 'refreshFilter' });
debugLog('Sent refreshFilter message to tab', tab.id);
} catch (e) {
console.error('Failed to send refreshFilter message:', e);
// Try to inject content script and send message again
try {
await browserAPI.scripting.executeScript({
target: { tabId: tab.id },
files: ['shared.js', 'i18n.js', 'content.js']
});
debugLog('Re-injected content script, trying refresh again');
await browserAPI.tabs.sendMessage(tab.id, { action: 'refreshFilter' });
} catch (retryError) {
console.error('Failed to refresh after re-injection:', retryError);
}
}
// Show an undo toast in the tab so the mute can be reverted from the page.
// Best effort — the tab may not have the content script loaded yet.
try {
await browserAPI.tabs.sendMessage(tab.id, { action: 'showUndoToast', userName });
debugLog('Sent showUndoToast message to tab', tab.id);
} catch (e) {
debugLog('Could not send undo toast to tab', tab.id);
}
});
// Mute a user
async function muteUser(userName, days) {
debugLog('Muting user:', userName, 'for', days ? `${days} days` : 'permanently');
const data = await browserAPI.storage.local.get('mutedUsers');
const mutedUsers = data.mutedUsers || [];
// Check if user already exists
const existingIndex = mutedUsers.findIndex(u => u.name.toLowerCase() === userName.toLowerCase());
const muteEntry = {
name: userName,
mutedAt: Date.now(),
expiresAt: days ? Date.now() + (days * 24 * 60 * 60 * 1000) : null,
permanent: !days
};
if (existingIndex >= 0) {
mutedUsers[existingIndex] = muteEntry;
} else {
mutedUsers.push(muteEntry);
}
await browserAPI.storage.local.set({ mutedUsers });
await syncToCloud();
debugLog(`Muted user: ${userName}`, days ? `for ${days} days` : 'permanently');
debugLog('Updated muted users list:', mutedUsers);
}
// Listen for messages from content script or popup
browserAPI.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'getMutedUsers') {
getMutedUsers().then(sendResponse);
return true; // Keep channel open for async response
}
if (message.action === 'unmuteUser') {
unmuteUser(message.userName).then(() => {
sendResponse({ success: true });
// Notify all Haiilo tabs to refresh
notifyAllHaiiloTabs();
});
return true;
}
if (message.action === 'muteUser') {
muteUser(message.userName, message.days).then(() => {
sendResponse({ success: true });
notifyAllHaiiloTabs();
});
return true;
}
if (message.action === 'getSettings') {
browserAPI.storage.local.get('settings').then(data => {
sendResponse(normalizeSettings(data.settings));
});
return true;
}
if (message.action === 'saveSettings') {
// Merge with existing stored settings so keys not present in the incoming
// object are preserved.
browserAPI.storage.local.get('settings').then(async (data) => {
const previousSettings = normalizeSettings(data.settings || DEFAULT_SETTINGS);
const merged = { ...previousSettings, ...message.settings };
const settings = normalizeSettings(merged);
await browserAPI.storage.local.set({ settings });
// If cloudSync was just turned off, clear data from storage.sync
if (!settings.cloudSync) {
browserAPI.storage.sync.remove(['settings', 'mutedUsers']).catch(e => {
console.error('[CloudSync] Failed to clear sync storage:', e);
});
} else {
await syncToCloud();
}
await createContextMenu();
await updateAllBadges();
await broadcastMessageToAllHaiiloTabs({ action: 'settingsUpdated' });
if (settings.language !== previousSettings.language) {
await broadcastMessageToAllHaiiloTabs({ action: 'languageChanged' });
}
sendResponse({ success: true });
}).catch(e => {
console.error('Failed to save settings:', e);
sendResponse({ success: false, error: e.message });
});
return true;
}
if (message.action === 'resetSettings') {
browserAPI.storage.local.set({ settings: buildLocaleAwareSettings() }).then(async () => {
await createContextMenu();
await updateAllBadges();
await broadcastMessageToAllHaiiloTabs({ action: 'settingsUpdated' });
await broadcastMessageToAllHaiiloTabs({ action: 'languageChanged' });
sendResponse({ success: true });
});
return true;
}
if (message.action === 'applyLocaleDefaults') {
browserAPI.storage.local.get('settings').then(async data => {
const settings = normalizeSettings(data.settings || DEFAULT_SETTINGS);
const locale = getRequestedLocale(message.locale);
const localeDefaults = getLocaleDateTimeDefaults(locale);
settings.dateFormat = getLocaleDateTimePresetId(locale);
settings.timeFormat = localeDefaults.timeFormat;
await browserAPI.storage.local.set({ settings });
await createContextMenu();
await updateAllBadges();
await broadcastMessageToAllHaiiloTabs({ action: 'settingsUpdated' });
sendResponse({ success: true, settings });
}).catch(error => {
sendResponse({ success: false, error: error.message });
});
return true;
}
if (message.action === 'updateHiddenCount') {
debugLog('Updating badge for tab', sender.tab.id, 'with count', message.count);
if (!badgeAPI || typeof badgeAPI.setBadgeText !== 'function') {
debugLog('Badge API not available, skipping update');
sendResponse({ success: false, error: 'Badge API unavailable' });
return true;
}
// Update badge with hidden count or OFF status
browserAPI.storage.local.get('settings').then(data => {
const settings = data.settings || DEFAULT_SETTINGS;
if (settings.extensionEnabled === false || message.domainDisabled === true) {
badgeAPI.setBadgeText({ text: 'OFF', tabId: sender.tab.id });
badgeAPI.setBadgeBackgroundColor({ color: '#888888', tabId: sender.tab.id });
debugLog('Badge updated with OFF status');
} else if (message.count > 0) {
badgeAPI.setBadgeText({ text: message.count.toString(), tabId: sender.tab.id });
badgeAPI.setBadgeBackgroundColor({ color: '#6366f1', tabId: sender.tab.id });
debugLog('Badge updated with count:', message.count);
} else {
badgeAPI.setBadgeText({ text: '', tabId: sender.tab.id });
debugLog('Badge cleared');
}
sendResponse({ success: true });
}).catch(error => {
console.error('Error in updateHiddenCount badge update:', error);
sendResponse({ success: false, error: error.message });
});
return true;
}
if (message.action === 'getCustomDomains') {
browserAPI.storage.local.get('customDomains').then(data => {
sendResponse(data.customDomains || []);
});
return true;
}
if (message.action === 'getDisabledDomains') {
browserAPI.storage.local.get('disabledDomains').then(data => {
sendResponse(data.disabledDomains || []);
});
return true;
}
if (message.action === 'setDomainEnabled') {
setDomainEnabled(message.domain, message.enabled).then(() => {
sendResponse({ success: true });
broadcastMessageToAllHaiiloTabs({ action: 'settingsUpdated' });
updateAllBadges();
});
return true;
}
if (message.action === 'addCustomDomain') {
addCustomDomain(message.domain)
.then(() => {
sendResponse({ success: true });
})
.catch((error) => {
sendResponse({ success: false, error: error.message });
});
return true;
}
if (message.action === 'removeCustomDomain') {
removeCustomDomain(message.domain).then(() => {
sendResponse({ success: true });
});
return true;
}
if (message.action === 'isHaiiloTab') {
isHaiiloTab(sender.tab).then(result => {
sendResponse({ isHaiilo: result });
});
return true;
}
if (message.action === 'getCustomHomepages') {
browserAPI.storage.local.get('customHomepages').then(data => {
sendResponse(data.customHomepages || {});
});
return true;
}
if (message.action === 'setCustomHomepage') {
setCustomHomepage(message.baseUrl, message.homepageUrl).then(() => {
sendResponse({ success: true });
}).catch(error => {
sendResponse({ success: false, error: error.message });
});
return true;
}
if (message.action === 'removeCustomHomepage') {
removeCustomHomepage(message.baseUrl).then(() => {
sendResponse({ success: true });
});
return true;
}
});
// Get active muted users (filter out expired)
async function getMutedUsers() {
const data = await browserAPI.storage.local.get('mutedUsers');
let mutedUsers = data.mutedUsers || [];
const now = Date.now();
debugLog('Retrieved muted users from storage:', mutedUsers);
// Filter out expired users
const activeUsers = mutedUsers.filter(user => {
if (user.permanent || !user.expiresAt) return true;
return user.expiresAt > now;
});
debugLog('Active muted users after filtering:', activeUsers);
// Save if we filtered any out
if (activeUsers.length !== mutedUsers.length) {
await browserAPI.storage.local.set({ mutedUsers: activeUsers });
debugLog('Saved filtered muted users list');
}
return activeUsers;
}
// Unmute a user
async function unmuteUser(userName) {
const data = await browserAPI.storage.local.get('mutedUsers');
const mutedUsers = data.mutedUsers || [];
const filtered = mutedUsers.filter(u => u.name.toLowerCase() !== userName.toLowerCase());
await browserAPI.storage.local.set({ mutedUsers: filtered });
await syncToCloud();
debugLog(`Unmuted user: ${userName}`);
}
// P2 fix: sync hostname helpers that accept pre-fetched domain lists,
// avoiding per-tab async storage reads inside loops.
function isHaiiloHostname(hostname, allDomains) {
return allDomains.some(domain => hostname === domain || hostname.endsWith('.' + domain));
}
function isHostnameDisabled(hostname, disabledDomains) {
return disabledDomains.some(domain => hostname === domain || hostname.endsWith('.' + domain));
}
// Notify all Haiilo tabs to refresh their filter
async function notifyAllHaiiloTabs() {
const allDomains = await getAllDomains();
const tabs = await browserAPI.tabs.query({});
for (const tab of tabs) {
if (!tab.url) continue;
try {
const hostname = new URL(tab.url).hostname;
if (isHaiiloHostname(hostname, allDomains)) {
browserAPI.tabs.sendMessage(tab.id, { action: 'refreshFilter' }).catch(() => {});
}
} catch (e) { /* skip malformed URLs */ }
}
}
// Broadcast a message to all Haiilo tabs
async function broadcastMessageToAllHaiiloTabs(message) {
const allDomains = await getAllDomains();
const tabs = await browserAPI.tabs.query({});
for (const tab of tabs) {
if (!tab.url) continue;
try {
const hostname = new URL(tab.url).hostname;
if (isHaiiloHostname(hostname, allDomains)) {
browserAPI.tabs.sendMessage(tab.id, message).catch(() => {});
}
} catch (e) { /* skip malformed URLs */ }
}
}
// Update badges for all Haiilo tabs based on extensionEnabled setting
async function updateAllBadges() {
if (!badgeAPI || typeof badgeAPI.setBadgeText !== 'function') return;
const settings = (await browserAPI.storage.local.get('settings')).settings || DEFAULT_SETTINGS;
const allDomains = await getAllDomains();
const disabledData = await browserAPI.storage.local.get('disabledDomains');
const disabledDomains = disabledData.disabledDomains || [];
const tabs = await browserAPI.tabs.query({});
for (const tab of tabs) {
if (!tab.url) { badgeAPI.setBadgeText({ text: '', tabId: tab.id }); continue; }
try {
const hostname = new URL(tab.url).hostname;
if (isHaiiloHostname(hostname, allDomains)) {
if (settings.extensionEnabled === false || isHostnameDisabled(hostname, disabledDomains)) {
badgeAPI.setBadgeText({ text: 'OFF', tabId: tab.id });
badgeAPI.setBadgeBackgroundColor({ color: '#888888', tabId: tab.id });
} else {
// Query tab for hidden count, if not available, clear badge
try {
const response = await browserAPI.tabs.sendMessage(tab.id, { action: 'getHiddenCount' }).catch(() => null);
if (response && typeof response.count === 'number' && response.count > 0) {
badgeAPI.setBadgeText({ text: response.count.toString(), tabId: tab.id });
badgeAPI.setBadgeBackgroundColor({ color: '#6366f1', tabId: tab.id });
} else {
badgeAPI.setBadgeText({ text: '', tabId: tab.id });
}
} catch (e) {
badgeAPI.setBadgeText({ text: '', tabId: tab.id });
}
}
} else {
badgeAPI.setBadgeText({ text: '', tabId: tab.id });
}
} catch (e) {
badgeAPI.setBadgeText({ text: '', tabId: tab.id });
}
}
}
// Get all domains (default + custom)
async function getAllDomains() {
const data = await browserAPI.storage.local.get('customDomains');
const customDomains = data.customDomains || [];
return [...DEFAULT_DOMAINS, ...customDomains];
}
// Check if a tab is a Haiilo tab
async function isHaiiloTab(tab) {
if (!tab || !tab.url) return false;
try {
const allDomains = await getAllDomains();
const url = new URL(tab.url);
return allDomains.some(domain => {
return url.hostname === domain || url.hostname.endsWith('.' + domain);
});
} catch (e) {
debugLog('Error parsing URL in isHaiiloTab:', tab.url, e);
return false;
}
}
// Add a custom domain (permission must be granted before calling this)
async function addCustomDomain(domain) {
// S3 fix: validate domain is a proper hostname before storing
if (!domain || typeof domain !== 'string') {
throw new Error('Invalid domain');
}
domain = domain.trim().toLowerCase();
if (!/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(domain)) {
throw new Error('Invalid domain format');
}
const data = await browserAPI.storage.local.get('customDomains');
const customDomains = data.customDomains || [];
if (customDomains.includes(domain)) {
throw new Error('Domain already exists');
}
try {
customDomains.push(domain);
await browserAPI.storage.local.set({ customDomains });
debugLog(`Added custom domain: ${domain}`);
// Rebuild context menu to include new domain in targetUrlPatterns
await createContextMenu();
// Register dynamic content scripts for the new domain
await registerDynamicContentScripts();
// Inject content scripts into existing tabs with this domain
await injectContentScripts();
} catch (error) {
console.error(`Error adding domain ${domain}:`, error);
throw error;
}
}
// Remove a custom domain (permissions should be removed by the options page before calling this)
async function removeCustomDomain(domain) {
const data = await browserAPI.storage.local.get(['customDomains', 'disabledDomains']);
const customDomains = data.customDomains || [];
const disabledDomains = data.disabledDomains || [];
const filtered = customDomains.filter(d => d !== domain);
const remainingDisabled = disabledDomains.filter(d => d !== domain);
await browserAPI.storage.local.set({ customDomains: filtered, disabledDomains: remainingDisabled });
// Rebuild context menu to remove domain from targetUrlPatterns