-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
4941 lines (4424 loc) · 194 KB
/
Copy pathcontent.js
File metadata and controls
4941 lines (4424 loc) · 194 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
// Content script for Haiilo Enhancer
//# sourceURL=haiilo-enhancer/content.js
(function() {
'use strict';
// Guard against double injection (can happen when both manifest and background inject)
if (window.__haiiloEnhancerLoaded) return;
window.__haiiloEnhancerLoaded = true;
// Browser API compatibility: browser.* is promise-based in Firefox; chrome.* in Chrome
const browserAPI = typeof browser !== 'undefined' ? browser : chrome;
const IS_FIREFOX = typeof browser !== 'undefined';
const t = (key, substitutions) => HaiiloI18n.i18nMessage(key, substitutions);
// Fetch a page-relative URL from the content script. In MV3 (both Chromium
// and Firefox) content-script fetches run in the page context, so a relative
// URL resolves against the Haiilo page. Always send an absolute URL built from
// the page origin, and include credentials in Firefox so the Haiilo session
// cookie (which the host permission grants access to) is sent.
function apiFetch(path) {
const url = new URL(path, window.location.href).href;
return IS_FIREFOX ? fetch(url, { credentials: 'include' }) : fetch(url);
}
// Global flag to track if extension context is valid
let extensionContextValid = true;
// Check if extension context is valid
function isExtensionContextValid() {
try {
// Comprehensive check for extension context
if (typeof browserAPI === 'undefined') return false;
if (typeof browserAPI.runtime === 'undefined') return false;
if (typeof browserAPI.runtime.sendMessage === 'undefined') return false;
if (!browserAPI.runtime.id) return false;
// Additional check: try to access a runtime property
try {
const id = browserAPI.runtime.id;
if (!id || id.length === 0) return false;
} catch (e) {
return false;
}
return extensionContextValid;
} catch (e) {
return false;
}
}
// Wrap chrome.runtime.sendMessage with context validation
function safeSendMessage(message) {
if (!isExtensionContextValid()) {
debugLog('Cannot send message: extension context invalid');
return Promise.reject(new Error('Extension context invalidated'));
}
try {
return browserAPI.runtime.sendMessage(message).catch(error => {
// If we get context invalidation error, mark context as invalid
if (error && error.message &&
(error.message.includes('Extension context invalidated') ||
error.message.includes('Receiving end does not exist'))) {
extensionContextValid = false;
debugLog('Extension context invalidated, marking as invalid');
}
throw error;
});
} catch (e) {
// Catch synchronous errors
if (e && e.message &&
(e.message.includes('Extension context invalidated') ||
e.message.includes('Receiving end does not exist'))) {
extensionContextValid = false;
debugLog('Extension context invalidated (sync error), marking as invalid');
}
return Promise.reject(e);
}
}
let mutedUsers = [];
let hiddenCount = 0;
let hiddenItems = [];
let lastRightClickedUser = null;
let lastRightClickedElement = null;
let observer = null;
let debugMode = false;
let extensionEnabled = true;
let domainDisabled = false;
let enhanceChannelAvatars = false;
let channelAvatarsProcessed = false;
let avatarStyle = 'ring';
let ringColor = '#502379';
let ringWidth = 2;
let squareColor = '#502379';
let squareWidth = 2;
let badgeSize = 100; // Percentage (50-150)
let badgePosition = 'bottom-left'; // 'bottom-left' or 'top-left'
let colorMode = 'random'; // 'random' or 'fixed'
let fixedColor = '#0f939d';
let customHomepageUrl = null;
let dateFormat = 'northAmerican12h'; // locale-aware preset id
let timeFormat = '12h'; // '12h' or '24h'
let dateTimeProcessed = false;
let isTyping = false;
let messengerOverlayObserver = null;
let keepMessengerExpandedActive = false;
let centerContentWithMessengerActive = false;
let collapseNavbarSpacingEnabled = false;
let navbarSpacingCollapseHandle = null; // shared domMutation handler handle
let navbarSpacingResizeBound = false; // only bind one window resize listener
let navbarSpacingCollapseTimer = null; // debounce for the domMutation handler
let navbarSpacingResizeTimer = null; // debounce for the window resize listener
let navbarSpacingNaturalWidth = 0; // cached navbar width BEFORE our width constraint
let navbarSpacingLastViewport = 0; // viewport width the natural width was measured at
let messengerReopenObserver = null;
let bodyStyleObserver = null;
let classObserver = null;
let autoExpandEnabled = false;
let autoExpandClicksPerList = 3;
let autoExpandDelayMs = 300;
let autoExpandScope = 'both';
let autoExpandMountObserver = null;
let endlessScrollEnabled = false;
let endlessScrollArmed = false;
let endlessScrollExhausted = false;
let endlessScrollCooldownUntil = 0;
let endlessScrollLoadTimeout = null;
let endlessScrollRetryTimer = null;
let endlessScrollMountObserver = null;
let endlessScrollScrollBound = false;
let autoLoadUpdatesEnabled = false;
let autoLoadUpdatesIdleSec = 5;
let autoLoadUpdatesLastActivity = Date.now();
let autoLoadUpdatesCooldownUntil = 0;
let autoLoadUpdatesTickTimer = null;
let autoLoadUpdatesActivityBound = false;
let calendarActionObserver = null;
let messengerReopenPending = false;
let mentionFormattingFixEnabled = true;
let mentionPopupFixEnabled = true;
let mentionFixStyleElement = null;
const mentionFormattingShadowStyles = new Map();
let mobileWikiBreadcrumbFixEnabled = false;
let mobileWikiBreadcrumbStyleElement = null;
let wikiModeToggleFixEnabled = false;
let floatingRichTextToolbarEnabled = true;
let floatingFormatToolbar = null;
let floatingFormatSelection = null;
let floatingFormatEditor = null;
let floatingFormatListenersBound = false;
// Markdown shortcut toolbar for the chat message editor (opt-in)
let markdownToolbarEnabled = true;
let markdownToolbarBrandEnabled = true;
let markdownToolbarEl = null;
let markdownToolbarEditor = null;
let markdownToolbarListenersBound = false;
// "Reply" action added to chat message context menus (opt-in)
let chatReplyMenuEnabled = true;
let chatReplyMenuHandle = null;
let chatReplyMenuTimer = null;
// Reaction enhancements
let sortReactionsByCount = true;
let showReactionCountTooltip = true;
let showReactionCountInline = false;
let reactionTypesCache = null; // { TYPE: { color, unicode } }
let reactionTypesPromise = null;
let reactionSenderIdCache = null; // current user ID needed by the summary API
let reactionSenderIdPromise = null;
const reactionSummaryCache = new Map();
const reactionSummaryPromises = new Map();
const reactionDetailsCache = new Map();
const reactionDetailsPromises = new Map();
const sortedReactionTargetIds = new Set();
// P7 fix: LRU eviction for reaction caches to prevent unbounded growth
const REACTION_CACHE_MAX = 500;
function evictOldestEntries(map) {
if (map.size <= REACTION_CACHE_MAX) return;
const keysToDelete = [...map.keys()].slice(0, map.size - REACTION_CACHE_MAX);
keysToDelete.forEach(k => map.delete(k));
}
let reactionEnhancerObserver = null;
// P3 fix: hiddenElements persists across hideContent() calls so already-hidden
// elements are not re-processed. WeakSet auto-releases GC'd DOM nodes.
const hiddenElements = new WeakSet();
// P8 fix: remember (element, selector-group) pairs that were scanned, had a
// fully-rendered author element, and were not muted, so a mutation burst does
// not re-walk every unchanged post. Angular re-renders replace DOM nodes
// (clearing their WeakMap entry), so a changed post is scanned again. Items
// whose author has not rendered yet are deliberately NOT cached so they keep
// being re-checked until the author appears. Keyed by selector-group so one
// group's cache never shadows another group's scan (e.g. a timeline item that
// also matches [class*="feed-item"]). Cleared in loadMutedUsers() whenever
// the mute list changes, otherwise a newly-muted user's already-scanned posts
// would never be hidden.
let scannedContentItems = new WeakMap();
// Shared messenger width constants and clamp (single source of truth in shared.js)
const MESSENGER_PANEL_WIDTH_MIN_PERCENT = HaiiloShared.MESSENGER_PANEL_WIDTH_MIN_PERCENT;
const MESSENGER_PANEL_WIDTH_MAX_PERCENT = HaiiloShared.MESSENGER_PANEL_WIDTH_MAX_PERCENT;
const MESSENGER_PANEL_WIDTH_DEFAULT_PERCENT = HaiiloShared.MESSENGER_PANEL_WIDTH_DEFAULT_PERCENT;
const clampMessengerPanelWidthPercent = HaiiloShared.clampMessengerPanelWidthPercent;
const HAIILO_DEFAULT_MESSENGER_WIDTH_PERCENT = 80;
const HAIILO_DEFAULT_MESSENGER_MAX_WIDTH_PX = 600;
// The navbar keeps a wasted gap (its left group has flex-grow: 1) whenever
// it cannot display at its full 1496px width next to the messenger. The gap
// is detected in JS rather than a media query, because the navbar only drops
// below its full width when the VIEWPORT is small, yet it can also overlap
// the open messenger panel on a wide viewport (the navbar stays 1496px and
// its right edge slides under the panel). A container query on the navbar
// is NOT usable here either: applying container-type to it makes the query
// read the containing column's capped width (~1305px) instead of the navbar
// itself, so it fires unconditionally. So the collapse is driven by an
// overlap/narrowness check in `updateNavbarSpacingCollapse()`.
const NAVBAR_COLLAPSE_MAX_VIEWPORT_PX = 1496; // the navbar's full width
function getMessengerPanelWidthCSS(widthPercent) {
const clampedPercent = clampMessengerPanelWidthPercent(widthPercent);
const scale = clampedPercent / 100;
const scaledWidthPercent = HAIILO_DEFAULT_MESSENGER_WIDTH_PERCENT * scale;
const scaledMaxWidthPx = HAIILO_DEFAULT_MESSENGER_MAX_WIDTH_PX * scale;
return `
/* Scale Haiilo's default open messenger width (80%, capped at 600px) */
coyo-messaging-sidebar aside.sidebar-container.two-columns,
coyo-messaging-sidebar aside.sidebar-container.two-c,
coyo-messaging-panel aside.sidebar-container.two-columns,
coyo-messaging-panel aside.sidebar-container.two-c {
width: ${scaledWidthPercent}% !important;
max-width: ${scaledMaxWidthPx}px !important;
}
`;
}
function getMessengerContentPositionCSS(widthPercent, centeredInRemainingSpace) {
if (!centeredInRemainingSpace) return '';
const clampedPercent = clampMessengerPanelWidthPercent(widthPercent);
const scale = clampedPercent / 100;
const scaledWidthPercent = HAIILO_DEFAULT_MESSENGER_WIDTH_PERCENT * scale;
const scaledMaxWidthPx = HAIILO_DEFAULT_MESSENGER_MAX_WIDTH_PX * scale;
// Resize the main layout to the space left beside the open panel. Haiilo
// keeps an 88px messenger rail in the normal layout, so the main content
// naturally re-centers when its container is reduced. The main navigation
// needs the same horizontal correction because Haiilo positions it
// independently of the flex container.
return `
section.container-wrapper > section.container-main {
flex: 0 0 calc(100% - min(${scaledWidthPercent}vw, ${scaledMaxWidthPx}px)) !important;
width: calc(100% - min(${scaledWidthPercent}vw, ${scaledMaxWidthPx}px)) !important;
}
section.container-wrapper > section.container-main coyo-main-navbar nav.main-navigation {
transform: translateX(calc(44px - min(${scaledWidthPercent / 2}vw, ${scaledMaxWidthPx / 2}px))) !important;
}
`;
}
// Reduces the wasted space between the left nav items (Infoboards / Hubs /
// Events) and the Search box when the reduced space beside the messenger
// can't fit the full navbar. The gap is created by Haiilo's `.nav-left`
// having flex-grow: 1, which stretches it to fill the middle. On narrow
// screens that growth is removed so the Search box hugs the nav items, while
// wide screens keep the natural spacing.
function applyCollapseNavbarSpacingCSS() {
let styleElement = document.getElementById('haiilo-enhancer-navbar-spacing-style');
if (!collapseNavbarSpacingEnabled) {
if (styleElement) styleElement.remove();
document.body.classList.remove('haiilo-enhancer-navbar-collapsed');
if (navbarSpacingCollapseHandle) {
navbarSpacingCollapseHandle.stop();
navbarSpacingCollapseHandle = null;
}
if (navbarSpacingResizeBound) {
window.removeEventListener('resize', debouncedNavbarSpacingResize);
navbarSpacingResizeBound = false;
}
return;
}
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.id = 'haiilo-enhancer-navbar-spacing-style';
document.head.appendChild(styleElement);
}
styleElement.textContent = `
body.haiilo-enhancer-navbar-collapsed section.container-wrapper > section.container-main coyo-main-navbar nav.main-navigation .nav-left {
flex-grow: 0 !important;
}
`;
if (!navbarSpacingResizeBound) {
window.addEventListener('resize', debouncedNavbarSpacingResize);
navbarSpacingResizeBound = true;
}
if (!navbarSpacingCollapseHandle) {
navbarSpacingCollapseHandle = domMutation.register({
active: () => collapseNavbarSpacingEnabled,
teardown: () => {
if (navbarSpacingCollapseTimer) clearTimeout(navbarSpacingCollapseTimer);
},
onRecords() {
if (navbarSpacingCollapseTimer) return;
navbarSpacingCollapseTimer = setTimeout(() => {
navbarSpacingCollapseTimer = null;
updateNavbarSpacingCollapse();
}, 250);
}
});
}
updateNavbarSpacingCollapse();
}
// Collapses the navbar gap when it can't fit: either the navbar is narrower
// than its full width (small viewport) or its right edge overlaps the space
// beside it (open messenger panel / viewport edge).
function updateNavbarSpacingCollapse() {
const body = document.body;
const nav = document.querySelector('section.container-main coyo-main-navbar nav.main-navigation');
const resetNavWidth = () => {
if (nav) {
nav.style.maxWidth = '';
nav.style.width = '';
}
};
if (!collapseNavbarSpacingEnabled || !extensionEnabled || !nav) {
resetNavWidth();
body.classList.remove('haiilo-enhancer-navbar-collapsed');
return;
}
const vw = window.innerWidth;
const panel = document.querySelector(
'coyo-messaging-panel aside.sidebar-container.two-c, ' +
'coyo-messaging-panel aside.sidebar-container.two-columns, ' +
'coyo-messaging-sidebar aside.sidebar-container.two-c, ' +
'coyo-messaging-sidebar aside.sidebar-container.two-columns'
);
const availableRight = panel ? panel.getBoundingClientRect().left : vw;
// Refresh the natural (unconstrained) navbar width only when the viewport
// changed. This is done synchronously (clear -> measure -> re-apply below),
// so the brief un-constrain is never painted.
if (vw !== navbarSpacingLastViewport) {
nav.style.maxWidth = '';
nav.style.width = '';
navbarSpacingNaturalWidth = nav.getBoundingClientRect().width;
navbarSpacingLastViewport = vw;
}
// Decide against the natural width (not the constrained one), with a small
// tolerance, so constraining the navbar can never flip the decision and
// cause a resize/clear feedback loop.
const navWidth = navbarSpacingNaturalWidth || nav.getBoundingClientRect().width;
const overlap = navWidth - availableRight > 2;
const narrow = navWidth < NAVBAR_COLLAPSE_MAX_VIEWPORT_PX;
const collapse = narrow || overlap;
body.classList.toggle('haiilo-enhancer-navbar-collapsed', collapse);
if (collapse && overlap) {
// Constrain to the space left of the messenger so the navbar fits beside
// it instead of sliding underneath.
const target = Math.floor(availableRight);
nav.style.maxWidth = target + 'px';
nav.style.width = target + 'px';
} else {
resetNavWidth();
}
}
// Debounced window-resize handler so the collapse follows viewport changes.
function debouncedNavbarSpacingResize() {
if (navbarSpacingResizeTimer) clearTimeout(navbarSpacingResizeTimer);
navbarSpacingResizeTimer = setTimeout(() => {
navbarSpacingResizeTimer = null;
updateNavbarSpacingCollapse();
}, 150);
}
// Per-button state. Track whether each show-more button has been
// processed in this page load, keyed by its data-test value
// ('show-more-workspace' or 'show-more-page'). Each button is
// independent - the runner can process workspace and pages at
// different times because they may appear at different moments
// as Haiilo re-renders the sidebar.
const autoExpandProcessed = new Set();
let autoExpandMountAttempts = 0; // P6 fix: max-attempt counter
const AUTO_EXPAND_SELECTORS = {
workspaces: 'button[data-test="show-more-workspace"]',
pages: 'button[data-test="show-more-page"]'
};
// Returns the list of selectors we should act on given the current scope.
function getAutoExpandSelectors() {
if (autoExpandScope === 'workspaces') return [AUTO_EXPAND_SELECTORS.workspaces];
if (autoExpandScope === 'pages') return [AUTO_EXPAND_SELECTORS.pages];
return [AUTO_EXPAND_SELECTORS.workspaces, AUTO_EXPAND_SELECTORS.pages];
}
// Normalize a stored scope value to one of the three valid strings.
function normalizeAutoExpandScope(value) {
return (value === 'workspaces' || value === 'pages') ? value : 'both';
}
// Debug logging helper
function debugLog(...args) {
if (debugMode) {
console.log(...args);
}
}
// ── Shared DOM mutation dispatcher ──────────────────────────────────────
// One document-wide MutationObserver replaces the many per-feature
// observers that each used to subscribe to the whole subtree for added
// nodes (content filter, reaction enhancer, messenger backdrop cleanup,
// auto-expand, endless scroll, calendar actions). Every Haiilo DOM change
// used to be delivered to up to 8 separate observers; now one callback
// receives the records once and forwards them only to handlers that are
// currently active. Each handler keeps its own debounce, so behavior is
// unchanged — the browser just maintains a single mutation queue instead of
// one per feature.
//
// The dispatcher only watches childList changes. Features that need
// attribute records (the messenger keep-expanded fix) keep their own tiny,
// dedicated observers that only exist while that feature is active, so
// class/style attribute records are NOT generated on pages where the
// feature is disabled.
//
// register(handler) → handle
// handler = {
// active(): boolean, // optional; handler is skipped when falsy
// onRecords(records): void, // required
// teardown(): void // optional; clears timers on stop()
// }
// handle.stop() unregisters the handler and runs its teardown.
const domMutation = {
observer: null,
handlers: [],
register(handler) {
this.handlers.push(handler);
this.ensureStarted();
let stopped = false;
return {
stop: () => {
if (stopped) return;
stopped = true;
try {
if (handler.teardown) handler.teardown();
} catch (e) {
console.error('[DomObserver] teardown error:', e);
}
const idx = this.handlers.indexOf(handler);
if (idx !== -1) this.handlers.splice(idx, 1);
}
};
},
ensureStarted() {
if (this.observer) return;
this.observer = new MutationObserver((records) => {
const handlers = this.handlers.slice();
for (const handler of handlers) {
try {
if (handler.active && !handler.active()) continue;
handler.onRecords(records);
} catch (e) {
console.error('[DomObserver] handler error:', e);
}
}
});
this.observer.observe(document.body, {
childList: true,
subtree: true
});
}
};
function parseSVG(svgString) {
if (!svgString) return null;
let xml = svgString.trim();
if (!xml.includes('xmlns=')) {
xml = xml.replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"');
}
try {
const doc = new DOMParser().parseFromString(xml, 'image/svg+xml');
const el = doc.documentElement;
if (el && el.nodeName !== 'parsererror') {
return document.importNode(el, true);
}
} catch (e) {
// ignore
}
try {
const frag = document.createRange().createContextualFragment(xml);
const el = frag.firstElementChild;
return el ? document.importNode(el, true) : null;
} catch (e) {
return null;
}
}
// Normalize Haiilo's mention trigger so editor whitespace does not create
// a large blank line around an otherwise inline mention.
function applyMentionFixStyles() {
if (!document.head) return;
if (!mentionFixStyleElement) {
mentionFixStyleElement = document.createElement('style');
mentionFixStyleElement.id = 'haiilo-enhancer-mention-style';
document.head.appendChild(mentionFixStyleElement);
}
mentionFixStyleElement.textContent = [
extensionEnabled && mentionFormattingFixEnabled
? `
.mention-peek-default > cat-dropdown > cat-button {
display: contents !important;
vertical-align: baseline !important;
}
`
: '',
extensionEnabled && mentionPopupFixEnabled
? `
.mention-peek-default {
white-space: normal !important;
}
`
: ''
].join('\n');
if (!extensionEnabled || !mentionFormattingFixEnabled) {
mentionFormattingShadowStyles.forEach(style => style.remove());
mentionFormattingShadowStyles.clear();
return;
}
const mentionButtons = document.querySelectorAll('.mention-peek-default > cat-dropdown > cat-button');
mentionButtons.forEach(button => {
const shadowRoot = button.shadowRoot;
if (!shadowRoot || mentionFormattingShadowStyles.has(shadowRoot)) return;
const style = document.createElement('style');
style.textContent = `
.cat-button-content,
.cat-button-content-inner {
display: inline !important;
white-space: normal !important;
}
::slotted(div) {
display: inline !important;
white-space: normal !important;
}
button {
height: auto !important;
min-height: 0 !important;
padding: 0 !important;
line-height: 1.2 !important;
}
`;
shadowRoot.appendChild(style);
mentionFormattingShadowStyles.set(shadowRoot, style);
});
}
function applyMobileWikiBreadcrumbFixStyles() {
if (!document.head) return;
if (!mobileWikiBreadcrumbStyleElement) {
mobileWikiBreadcrumbStyleElement = document.createElement('style');
mobileWikiBreadcrumbStyleElement.id = 'haiilo-enhancer-mobile-wiki-breadcrumb-style';
document.head.appendChild(mobileWikiBreadcrumbStyleElement);
}
mobileWikiBreadcrumbStyleElement.textContent = extensionEnabled && mobileWikiBreadcrumbFixEnabled
? `
@media (max-width: 700px) {
cat-card:has(> div > nav.breadcrumbs) {
flex-wrap: wrap !important;
}
cat-card:has(> div > nav.breadcrumbs) > div:has(> nav.breadcrumbs) {
min-width: 0 !important;
flex: 1 1 100% !important;
width: 100% !important;
max-width: 100% !important;
overflow: hidden !important;
}
cat-card:has(> div > nav.breadcrumbs) > div.edit-actions {
flex: 0 0 100% !important;
justify-content: flex-end !important;
}
nav.breadcrumbs {
display: grid !important;
grid-template-columns: max-content 20px max-content 20px max-content !important;
width: 100% !important;
min-width: 0 !important;
max-width: 100% !important;
box-sizing: border-box;
overflow-x: auto !important;
}
nav.breadcrumbs > cat-button[data-test="parent-wiki-article-btn"] {
min-width: max-content !important;
}
nav.breadcrumbs > cat-button[data-test="parent-wiki-article-btn"]::part(button) {
width: max-content !important;
min-width: 40px !important;
}
}
`
: '';
}
function setupAdvancedModeToolbarButton() {
if (!extensionEnabled || !wikiModeToggleFixEnabled) {
document.querySelectorAll('.haiilo-enhancer-mode-toggle').forEach(button => button.remove());
document.querySelectorAll('.haiilo-enhancer-mode-toggle-source').forEach(button => {
button.classList.remove('haiilo-enhancer-mode-toggle-source');
});
return;
}
const sourceButton = document.querySelector('[data-test="wiki-article-advanced-mode-toggle"]');
const toolbar = sourceButton && sourceButton.closest('coyo-wiki-edit-v2')?.querySelector('.fr-toolbar');
if (!sourceButton || !toolbar) {
document.querySelectorAll('.haiilo-enhancer-mode-toggle').forEach(button => button.remove());
return;
}
const targetGroup = toolbar.querySelector('.fr-btn-grp.fr-float-right');
if (!targetGroup) return;
targetGroup.classList.add('haiilo-enhancer-mode-toggle-group');
let toolbarButton = targetGroup.querySelector('.haiilo-enhancer-mode-toggle');
if (!toolbarButton) {
toolbarButton = document.createElement('button');
toolbarButton.type = 'button';
toolbarButton.className = 'fr-btn haiilo-enhancer-mode-toggle';
const toggleSvg = parseSVG(
'<svg class="fr-svg" viewBox="0 0 24 24" aria-hidden="true">' +
'<path fill="currentColor" d="M7 5h10.17l-2.58-2.59L16 1l5 5-5 5-1.41-1.41L17.17 7H7V5Zm10 14H6.83l2.58 2.59L8 23l-5-5 5-5 1.41 1.41L6.83 17H17v2Z"/>' +
'</svg>'
);
if (toggleSvg) toolbarButton.appendChild(toggleSvg);
targetGroup.insertBefore(toolbarButton, targetGroup.firstChild);
toolbarButton.addEventListener('click', () => {
if (isExtensionContextValid()) {
document.querySelector('[data-test="wiki-article-advanced-mode-toggle"]')?.click();
}
});
}
const label = sourceButton.getAttribute('aria-label') || sourceButton.textContent.trim();
toolbarButton.setAttribute('aria-label', label);
toolbarButton.title = label;
sourceButton.classList.add('haiilo-enhancer-mode-toggle-source');
}
function getSelectedRichTextEditor() {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null;
const range = selection.getRangeAt(0);
let node = range.commonAncestorContainer;
if (node.nodeType === Node.TEXT_NODE) node = node.parentElement;
const editor = node?.closest?.('.fr-element[contenteditable="true"]');
if (!editor || !editor.isConnected || !editor.contains(range.startContainer) || !editor.contains(range.endContainer)) {
return null;
}
return { editor, range };
}
function saveFloatingFormatSelection() {
const selected = getSelectedRichTextEditor();
if (!selected) return false;
floatingFormatEditor = selected.editor;
floatingFormatSelection = selected.range.cloneRange();
return true;
}
function restoreFloatingFormatSelection() {
if (!floatingFormatSelection || !floatingFormatEditor?.isConnected) return false;
try {
const selection = window.getSelection();
floatingFormatEditor.focus({ preventScroll: true });
selection.removeAllRanges();
selection.addRange(floatingFormatSelection);
return true;
} catch (error) {
debugLog('[Content] Could not restore floating toolbar selection:', error);
return false;
}
}
function hideFloatingFormatToolbar() {
if (!floatingFormatToolbar) return;
floatingFormatToolbar.hidden = true;
floatingFormatToolbar.classList.remove('is-below');
}
function positionFloatingFormatToolbar() {
if (!floatingFormatToolbar || floatingFormatToolbar.hidden || !floatingFormatSelection) return;
const rect = floatingFormatSelection.getBoundingClientRect();
if (!rect || (!rect.width && !rect.height)) {
hideFloatingFormatToolbar();
return;
}
const gap = 8;
const margin = 8;
const toolbarWidth = floatingFormatToolbar.offsetWidth;
const toolbarHeight = floatingFormatToolbar.offsetHeight;
const left = Math.max(margin, Math.min(
window.innerWidth - toolbarWidth - margin,
rect.left + (rect.width / 2) - (toolbarWidth / 2)
));
const hasRoomAbove = rect.top >= toolbarHeight + gap + margin;
const top = hasRoomAbove
? rect.top - toolbarHeight - gap
: Math.min(window.innerHeight - toolbarHeight - margin, rect.bottom + gap);
floatingFormatToolbar.classList.toggle('is-below', !hasRoomAbove);
floatingFormatToolbar.style.left = `${left}px`;
floatingFormatToolbar.style.top = `${Math.max(margin, top)}px`;
}
function updateFloatingFormatToolbar() {
if (!floatingRichTextToolbarEnabled || !extensionEnabled) {
hideFloatingFormatToolbar();
return;
}
const selected = getSelectedRichTextEditor();
if (!selected) {
hideFloatingFormatToolbar();
return;
}
floatingFormatEditor = selected.editor;
floatingFormatSelection = selected.range.cloneRange();
if (!floatingFormatToolbar) createFloatingFormatToolbar();
if (!floatingFormatToolbar) return;
floatingFormatToolbar.hidden = false;
floatingFormatToolbar.style.visibility = 'hidden';
positionFloatingFormatToolbar();
floatingFormatToolbar.style.visibility = 'visible';
floatingFormatToolbar.querySelectorAll('button[data-cmd]').forEach(button => {
const nativeButton = findNativeFormatButton(button.dataset.cmd, floatingFormatEditor);
let isPressed = nativeButton?.getAttribute('aria-pressed') === 'true';
if (!isPressed && ['bold', 'italic', 'underline', 'strikeThrough'].includes(button.dataset.cmd)) {
try {
isPressed = document.queryCommandState(button.dataset.cmd);
} catch (error) {
debugLog('[Content] Could not read formatting state:', error);
}
}
button.setAttribute('aria-pressed', isPressed ? 'true' : 'false');
});
}
function findNativeFormatButton(command, editor) {
const toolbar = editor?.closest('coyo-wiki-edit-v2')?.querySelector('.fr-toolbar');
return toolbar?.querySelector(`button[data-cmd="${command}"]`) ||
document.querySelector(`.fr-toolbar button[data-cmd="${command}"]`);
}
function createFloatingFormatToolbar() {
if (floatingFormatToolbar || !document.body) return;
const commands = [
['bold', 'italic', 'underline', 'strikeThrough'],
['formatUL', 'formatOL'],
['clearFormatting']
];
const toolbar = document.createElement('div');
toolbar.className = 'haiilo-enhancer-floating-format-toolbar';
toolbar.hidden = true;
toolbar.setAttribute('role', 'toolbar');
toolbar.setAttribute('aria-label', t('floatingRichTextToolbar'));
commands.forEach((group, groupIndex) => {
if (groupIndex > 0) {
const divider = document.createElement('span');
divider.className = 'haiilo-enhancer-floating-format-divider';
divider.setAttribute('aria-hidden', 'true');
toolbar.appendChild(divider);
}
group.forEach(command => {
const nativeButton = findNativeFormatButton(command, floatingFormatEditor);
if (!nativeButton) return;
const button = document.createElement('button');
button.type = 'button';
button.className = 'haiilo-enhancer-floating-format-button';
button.dataset.cmd = command;
button.setAttribute('aria-label', nativeButton.getAttribute('aria-label') || nativeButton.textContent.trim());
button.setAttribute('aria-pressed', 'false');
button.title = nativeButton.getAttribute('data-title') || nativeButton.textContent.trim();
nativeButton.childNodes.forEach(node => {
button.appendChild(node.cloneNode(true));
});
button.addEventListener('mousedown', event => {
event.preventDefault();
if (!floatingFormatSelection) saveFloatingFormatSelection();
});
button.addEventListener('click', () => {
if (!restoreFloatingFormatSelection()) return;
const commandMap = {
formatUL: 'insertUnorderedList',
formatOL: 'insertOrderedList',
clearFormatting: 'removeFormat'
};
const nativeCommand = commandMap[command] || command;
let applied = false;
try {
applied = document.execCommand(nativeCommand, false, null);
} catch (error) {
debugLog('[Content] Direct formatting command failed:', command, error);
}
if (!applied) {
const target = findNativeFormatButton(command, floatingFormatEditor);
if (!target) return;
target.click();
}
saveFloatingFormatSelection();
updateFloatingFormatToolbar();
});
toolbar.appendChild(button);
});
});
document.body.appendChild(toolbar);
floatingFormatToolbar = toolbar;
}
function removeFloatingFormatToolbar() {
floatingFormatToolbar?.remove();
floatingFormatToolbar = null;
floatingFormatSelection = null;
floatingFormatEditor = null;
}
function setupFloatingFormatToolbar() {
if (!extensionEnabled || !floatingRichTextToolbarEnabled) {
removeFloatingFormatToolbar();
return;
}
if (floatingFormatToolbar && !floatingFormatToolbar.querySelector('button[data-cmd]')) {
removeFloatingFormatToolbar();
}
createFloatingFormatToolbar();
if (floatingFormatListenersBound) return;
floatingFormatListenersBound = true;
document.addEventListener('selectionchange', updateFloatingFormatToolbar);
document.addEventListener('mouseup', () => setTimeout(updateFloatingFormatToolbar, 0));
document.addEventListener('keyup', () => setTimeout(updateFloatingFormatToolbar, 0));
window.addEventListener('scroll', positionFloatingFormatToolbar, true);
window.addEventListener('resize', positionFloatingFormatToolbar);
}
// ── Markdown shortcut toolbar for the chat message editor ───────────────
// Haiilo chats and timelines support basic Markdown but the editors are
// plain <textarea>s. When the user selects text inside one, show a small
// toolbar next to the selection that wraps/prefixes the selection with
// Markdown syntax. The command table and all DOM work are local to this
// feature; it is a no-op when disabled and safe after extension-context
// invalidation (it never touches extension APIs in its callbacks).
//
// The timeline post editor is a <textarea data-test="textarea-timeline-post">
// living inside a <cat-textarea> web component's shadow root, so focus
// detection must descend into shadow roots (see getDeepActiveElement).
// Editors where the toolbar is offered (chat message editor, timeline post
// composer, timeline comment editors).
const MARKDOWN_EDITOR_SELECTOR = [
'textarea[data-test="textarea-message-form"]',
'textarea[data-test="textarea-timeline-post"]',
'textarea[data-test="timeline-comment-message-edit-mode"]'
].join(', ');
const MARKDOWN_ICON_BOLD = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/></svg>';
const MARKDOWN_ICON_ITALIC = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M19 4h-9"/><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M14 20H5"/><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M15 4L9 20"/></svg>';
const MARKDOWN_ICON_STRIKE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M16 4H9a3 3 0 0 0-2.83 4"/><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M14 12a4 4 0 0 1 0 8H6"/><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M4 12h16"/></svg>';
const MARKDOWN_ICON_CODE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M8 7l-5 5 5 5"/><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M16 7l5 5-5 5"/></svg>';
const MARKDOWN_ICON_CODE_BLOCK = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M16 3a2 2 0 0 1 2 2v2.5a2 2 0 0 0 2 2 2 2 0 0 0-2 2V14a2 2 0 0 1-2 2"/><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M8 3a2 2 0 0 0-2 2v2.5a2 2 0 0 1-2 2 2 2 0 0 1 2 2V14a2 2 0 0 0 2 2"/></svg>';
const MARKDOWN_ICON_QUOTE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M7.17 6A4.17 4.17 0 0 0 3 10.17v5.58A2.25 2.25 0 0 0 5.25 18h3A2.25 2.25 0 0 0 10.5 15.75v-3A2.25 2.25 0 0 0 8.25 10.5H5.83A4.17 4.17 0 0 1 10 6.33 1 1 0 0 0 7.17 6zM17.17 6A4.17 4.17 0 0 0 13 10.17v5.58A2.25 2.25 0 0 0 15.25 18h3A2.25 2.25 0 0 0 20.5 15.75v-3A2.25 2.25 0 0 0 18.25 10.5h-2.42A4.17 4.17 0 0 1 20 6.33 1 1 0 0 0 17.17 6z"/></svg>';
const MARKDOWN_COMMANDS = {
bold: { prefix: '**', suffix: '**' },
italic: { prefix: '*', suffix: '*' },
strike: { prefix: '~~', suffix: '~~' },
code: { prefix: '`', suffix: '`' },
codeBlock: { prefix: '\n```\n', suffix: '\n```\n', lineWise: true },
quote: { prefix: '> ', lineWise: true }
};
const MARKDOWN_ICONS = {
bold: MARKDOWN_ICON_BOLD,
italic: MARKDOWN_ICON_ITALIC,
strike: MARKDOWN_ICON_STRIKE,
code: MARKDOWN_ICON_CODE,
codeBlock: MARKDOWN_ICON_CODE_BLOCK,
quote: MARKDOWN_ICON_QUOTE
};
const MARKDOWN_GROUPS = [
['bold', 'italic', 'strike'],
['code', 'codeBlock'],
['quote']
];
// Resolve the element that actually has focus, descending into shadow roots
// (document.activeElement only reports the shadow host, e.g. cat-textarea).
function getDeepActiveElement() {
let el = document.activeElement;
try {
while (el && el.shadowRoot && el.shadowRoot.activeElement) {
el = el.shadowRoot.activeElement;
}
} catch (e) {
// ignore malformed shadow roots
}
return el;
}
function getActiveChatEditor() {
const active = getDeepActiveElement();
if (active && active.matches && active.matches(MARKDOWN_EDITOR_SELECTOR)) {
return active;
}
return null;
}
// Measure the viewport position of the caret at `position` inside a
// <textarea> by mirroring its text into an offscreen div with identical
// fonts/padding/borders. Returns { left, top } or null when it cannot.
function getTextareaCaretPosition(ta, position) {
const taRect = ta.getBoundingClientRect();
if (!taRect.width || !taRect.height) return null;
const styles = getComputedStyle(ta);
const div = document.createElement('div');
const copyProps = [
'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariant',
'fontStretch', 'letterSpacing', 'lineHeight', 'textTransform',
'wordSpacing', 'textIndent', 'tabSize', 'paddingTop', 'paddingRight',
'paddingBottom', 'paddingLeft', 'borderTopWidth', 'borderRightWidth',
'borderBottomWidth', 'borderLeftWidth'
];
copyProps.forEach(prop => {
div.style[prop] = styles[prop];
});
// Mirror the textarea's border-box width so its content box matches the
// textarea's content box (identical borders/padding/font metrics).
div.style.boxSizing = 'border-box';
div.style.width = taRect.width + 'px';
div.style.whiteSpace = ta.wrap === 'off' ? 'pre' : 'pre-wrap';
div.style.wordWrap = 'break-word';
div.style.overflowWrap = 'break-word';
div.style.position = 'fixed';
div.style.top = '0';
div.style.left = '0';
div.style.visibility = 'hidden';
div.textContent = ta.value.substring(0, position);
const marker = document.createElement('span');
marker.textContent = '\u200b';
div.appendChild(marker);
document.body.appendChild(div);
const markerRect = marker.getBoundingClientRect();
document.body.removeChild(div);
return {
left: taRect.left + markerRect.left - ta.scrollLeft,
top: taRect.top + markerRect.top - ta.scrollTop
};
}
function hideMarkdownToolbar() {
if (!markdownToolbarEl) return;
markdownToolbarEl.hidden = true;
markdownToolbarEl.classList.remove('is-below');
}
function positionMarkdownToolbar(caret) {
if (!markdownToolbarEl || markdownToolbarEl.hidden || !caret) return;
const gap = 8;
const margin = 8;