-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1472 lines (1239 loc) · 50.1 KB
/
content.js
File metadata and controls
1472 lines (1239 loc) · 50.1 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
// Main content script for Me @ GitHub extension
(function() {
'use strict';
console.log('🚀 Me @ GitHub extension loaded!');
let username = null;
let mentions = [];
let currentMentionIndex = -1;
// Cache frequently accessed DOM elements
let cachedCounter = null;
let cachedStickyCounter = null;
let cachedDropdown = null;
// Store interval IDs for cleanup
let healthCheckInterval = null;
// Shared supported page patterns (DRY principle)
const SUPPORTED_PAGE_PATTERNS = [
/github\.com\/[^/]+\/[^/]+\/(issues|pull|discussions)\//,
/github\.com\/orgs\/[^/]+\/discussions\//
];
// Helper function to check if current page is supported
function isOnSupportedPage() {
return SUPPORTED_PAGE_PATTERNS.some(pattern => pattern.test(location.href));
}
// Get the logged-in user's username
function getUsername() {
// Check for username in the page header
const userMenu = document.querySelector('meta[name="user-login"]');
if (userMenu) {
const username = userMenu.getAttribute('content');
return validateUsername(username);
}
// Fallback: check the signed-in user menu
const signedInUser = document.querySelector('[data-login]');
if (signedInUser) {
const username = signedInUser.getAttribute('data-login');
return validateUsername(username);
}
return null;
}
// Validate username format (GitHub allows alphanumeric and hyphens only)
function validateUsername(username) {
if (!username || typeof username !== 'string') {
return null;
}
// GitHub usernames: 1-39 chars, alphanumeric or hyphens, cannot start/end with hyphen
const usernameRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/;
return usernameRegex.test(username) ? username : null;
}
// Find all mentions of the username in @<username> format
// Helper function to check if a node is in an excluded area (titles, headers, navigation)
function isInExcludedArea(node) {
let current = node;
let foundAllowedArea = false;
// Walk up the DOM tree to check for excluded areas
while (current && current !== document.body) {
const element = current.nodeType === Node.TEXT_NODE ? current.parentElement : current;
if (!element) break;
// FIRST: Check if we're inside an allowed comment body area
const classList = element.classList;
if (classList) {
const allowedClasses = [
'comment-body',
'js-comment-body',
'markdown-body',
'js-comment-update',
'edit-comment-hide',
'js-suggested-changes-contents',
'js-file-content',
'IssueCommentViewer-module__IssueCommentBody',
'DiscussionCommentViewer-module__DiscussionCommentBody',
'discussion-comment-body',
'js-discussion-comment-body',
'js-comment-container',
'js-comment-text',
'review-comment-contents',
'js-review-comment-contents',
'js-suggested-changes-blob',
'js-file-line-container',
'pull-request-review-comment',
'timeline-comment-wrapper',
// GitHub February 2025 UI refresh classes
'Layout-sc-1xcs6mc-0',
'Layout-self-start'
];
for (const allowedClass of allowedClasses) {
if (classList.contains(allowedClass)) {
// We're in a comment body - this is definitely allowed
foundAllowedArea = true;
break;
}
}
}
if (!foundAllowedArea) {
const dataTestId = element.getAttribute && element.getAttribute('data-testid');
if (dataTestId) {
const allowedTestIds = [
'comment-body',
'comment-body-inner',
'issue-comment-body',
'discussion-comment-body',
'timeline-comment-body',
'pull-request-review-comment-body',
'review-comment-body'
];
for (const allowedId of allowedTestIds) {
if (dataTestId.includes(allowedId)) {
foundAllowedArea = true;
break;
}
}
}
}
// If we found an allowed area, stop checking and allow it
if (foundAllowedArea) {
return false;
}
// Check for title areas and headers
const tagName = element.tagName?.toLowerCase();
if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'title'].includes(tagName)) {
return true;
}
// Check for GitHub-specific title and header classes
if (classList) {
const excludedClasses = [
// Issue, PR and Discussion titles
'js-issue-title',
'js-pr-title',
'js-discussion-title',
'issue-title',
'pr-title',
'discussion-title',
'js-issue-row',
'js-navigation-item-text',
'discussion-header',
'js-discussion-header',
// Activity feeds and list headers
'ActivityHeader-module',
'ActivityHeader',
'js-activity-header',
'activity-header',
'list-group-item',
'js-issue-row',
'js-recent-activity-container',
'js-navigation-item',
'js-issue-list-item',
'notification-list-item',
'issue-list-item',
// Headers and navigation
'header',
'site-header',
'js-navigation-item',
'js-repo-nav',
'subnav',
'tabnav',
'breadcrumb',
'pagehead',
'repohead',
// Commit and timeline headers
'commit-title',
'commit-message',
'timeline-comment-header',
'timeline-comment-header-text',
'timeline-comment-actions',
'js-timeline-item',
// User/author areas in headers
'hx_hit-user',
'commit-author',
'author',
'text-bold',
// File headers and code areas
'file-header',
'file-info',
'js-file-header',
'blob-code-hunk',
// Notification areas
'notification-list-item-title',
'notification-list-item-link',
// Participants and collaboration areas
'participant-avatar',
'participation-avatars',
'participants'
];
for (const excludedClass of excludedClasses) {
if (classList.contains(excludedClass)) {
return true;
}
}
// Check for role attributes that indicate navigation or headers
const role = element.getAttribute('role');
if (['navigation', 'banner', 'header', 'menubar', 'toolbar'].includes(role)) {
return true;
}
}
// Check for common header/title selectors by ID or data attributes
const id = element.id;
if (id && (id.includes('header') || id.includes('title') || id.includes('nav'))) {
return true;
}
// Additional comprehensive checks for modern GitHub CSS modules
// Handle SVG elements which have className as SVGAnimatedString object
let className = '';
if (element.className) {
if (typeof element.className === 'string') {
className = element.className;
} else if (element.className.baseVal !== undefined) {
className = element.className.baseVal;
} else {
className = String(element.className);
}
}
// Check for CSS modules (GitHub's modern styling system)
const excludedClassNamePatterns = [
'ActivityHeader',
'Header-module',
'ListItem-module',
'IssueItem-module',
'navigation',
'comment-reactions',
'social-reactions',
'reactions-container',
'js-reaction-buttons',
'participation-avatars',
'participants',
'participant-avatar',
'assignee',
'Assignee',
'd-flex',
'flex-wrap'
];
if (excludedClassNamePatterns.some(pattern => className.includes(pattern))) {
return true;
}
if (element.closest && (element.closest('[class*="ActivityHeader"]') ||
element.closest('[class*="assignee"]') ||
element.closest('[class*="Assignee"]'))) {
return true;
}
// Check data attributes that might indicate list items or headers
const dataTestId = element.getAttribute('data-testid');
if (dataTestId && (dataTestId.includes('header') || dataTestId.includes('title') || dataTestId.includes('nav'))) {
return true;
}
current = element.parentElement;
}
return false;
}
function findMentions() {
if (!username) return [];
console.log('findMentions: Searching for mentions of:', username);
const mentions = [];
// Optimize: Use combined selector instead of multiple querySelectorAll calls
// This reduces DOM traversals from 4 to 1
// Escape username to prevent CSS selector injection
const escapedUsername = CSS.escape(username);
const combinedSelector = `a.user-mention, a[href*="/${escapedUsername}"], a.mention, a[data-hovercard-type="user"]`;
const allLinks = document.querySelectorAll(combinedSelector);
console.log(`findMentions: Found ${allLinks.length} potential mention links`);
allLinks.forEach((link, idx) => {
const linkText = link.textContent.trim();
const linkHref = link.getAttribute('href') || link.href;
console.log(`findMentions: Checking link ${idx}:`, { text: linkText, href: linkHref });
// Skip if this link is in an excluded area (title, header, etc.)
const excluded = isInExcludedArea(link);
if (excluded) {
console.log(`findMentions: Link ${idx} is in excluded area, skipping`, link);
return;
}
// Check if this link mentions the current user
// GitHub's mention links have href like "/username" or "https://github.com/username"
const matchesText = linkText === `@${username}`;
const matchesHref = linkHref.endsWith(`/${username}`) || linkHref === `/${username}`;
console.log(`findMentions: Link ${idx} matching:`, { matchesText, matchesHref });
if (matchesText || matchesHref) {
// Find the text node inside the link
let textNode = Array.from(link.childNodes).find(node => node.nodeType === Node.TEXT_NODE);
if (!textNode) {
const walker = document.createTreeWalker(link, NodeFilter.SHOW_TEXT);
textNode = walker.nextNode();
}
if (textNode) {
console.log(`findMentions: Found mention in link ${idx}`);
mentions.push({
node: textNode,
text: textNode.textContent,
index: 0,
element: link
});
} else {
console.log(`findMentions: Link ${idx} matches but has no text node`);
}
}
});
// Then search in comment body containers for plain text mentions
const commentBodySelectors = [
'.comment-body',
'.js-comment-body',
'.markdown-body',
'[class*="IssueCommentViewer-module__IssueCommentBody"]',
'[class*="DiscussionCommentViewer-module__DiscussionCommentBody"]',
'.discussion-comment-body',
'.js-discussion-comment-body',
// PR-specific selectors
'.js-comment-text',
'.review-comment-contents',
'.js-review-comment-contents',
'.js-suggested-changes-blob',
'.js-file-line-container',
'[data-testid="pr-comment-body"]',
'[data-testid="review-comment-body"]',
'.js-timeline-item .comment-body',
'.js-discussion .comment-body'
];
commentBodySelectors.forEach(selector => {
const containers = document.querySelectorAll(selector);
containers.forEach((container, containerIdx) => {
const walker = document.createTreeWalker(
container,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
// Skip script, style, and our own elements
const parent = node.parentElement;
if (!parent ||
parent.tagName === 'SCRIPT' ||
parent.tagName === 'STYLE' ||
parent.classList.contains('me-at-github-counter') ||
parent.classList.contains('me-at-github-dropdown')) {
return NodeFilter.FILTER_REJECT;
}
// Skip if parent is a link that might be a mention (already processed above)
if (parent.tagName === 'A' && parent.getAttribute('href')?.includes(`/${username}`)) {
return NodeFilter.FILTER_REJECT;
}
// Skip title areas, headers, and navigation elements
if (isInExcludedArea(node)) {
return NodeFilter.FILTER_REJECT;
}
// Check if text contains the mention
const mentionPattern = `@${username}`;
if (node.textContent.includes(mentionPattern)) {
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
}
}
);
let node;
const pattern = new RegExp(`@${username}\\b`, 'gi');
while (node = walker.nextNode()) {
const text = node.textContent;
const matches = [...text.matchAll(pattern)];
for (const match of matches) {
mentions.push({
node: node,
text: text,
index: match.index,
element: node.parentElement
});
}
}
});
});
return mentions;
}
// Highlight mentions and add navigation controls
function highlightMentions() {
// Group mentions by their text node to process multiple mentions in the same node
const nodeGroups = new Map();
mentions.forEach((mention, index) => {
if (!nodeGroups.has(mention.node)) {
nodeGroups.set(mention.node, []);
}
nodeGroups.get(mention.node).push({ ...mention, originalIndex: index });
});
// Process each text node
nodeGroups.forEach((mentionList, textNode) => {
// Skip if already processed or if text node is polluted with navigation
if (!textNode.parentNode ||
textNode.parentNode.classList?.contains('me-at-github-mention-text') ||
textNode.textContent.includes('←') ||
textNode.textContent.includes('→')) {
return;
}
const parent = textNode.parentNode;
// Special handling for GitHub's native mention links
if (parent.classList && parent.classList.contains('user-mention')) {
// Wrap the entire link in our highlight span
const mentionSpan = document.createElement('span');
mentionSpan.classList.add('me-at-github-mention-text', 'me-at-github-link-wrapper');
// Get the index for this mention
const index = mentionList[0].originalIndex;
mentionSpan.setAttribute('data-mention-index', index);
// Batch DOM operations to avoid reflows
const parentNode = parent.parentNode;
parentNode.insertBefore(mentionSpan, parent);
mentionSpan.appendChild(parent);
// Update the mention reference
mentions[index].element = mentionSpan;
// Add navigation controls
addNavigationControls(mentionSpan, index);
return;
}
// Handle plain text mentions
const text = textNode.textContent;
const mentionText = `@${username}`;
const fragment = document.createDocumentFragment();
// Sort mentions by index to process them in order
mentionList.sort((a, b) => a.index - b.index);
let lastIndex = 0;
mentionList.forEach(mention => {
const index = mention.originalIndex;
// Add text before the mention
if (mention.index > lastIndex) {
fragment.appendChild(document.createTextNode(text.substring(lastIndex, mention.index)));
}
// Create mention span
const mentionSpan = document.createElement('span');
mentionSpan.classList.add('me-at-github-mention-text');
mentionSpan.textContent = mentionText;
mentionSpan.setAttribute('data-mention-index', index);
fragment.appendChild(mentionSpan);
// Update the mention reference
mention.element = mentionSpan;
mentions[index].element = mentionSpan;
lastIndex = mention.index + mentionText.length;
// Add navigation controls
addNavigationControls(mentionSpan, index);
});
// Add remaining text
if (lastIndex < text.length) {
fragment.appendChild(document.createTextNode(text.substring(lastIndex)));
}
// Replace the text node with the fragment
textNode.parentNode.replaceChild(fragment, textNode);
});
}
// Add prev/next navigation controls to a mention
function addNavigationControls(element, index) {
// Don't add navigation controls if there's only one mention
if (mentions.length <= 1) {
return;
}
// Check if navigation controls already exist
if (element.querySelector('.me-at-github-nav')) {
return;
}
// Don't add navigation to elements in excluded areas (assignees, timeline, etc.)
if (isInExcludedArea(element)) {
return;
}
const nav = document.createElement('div');
nav.classList.add('me-at-github-nav');
// Ensure nav is hidden by default with inline style as fallback
nav.style.display = 'none';
// Create navigation buttons safely without innerHTML
const prevBtn = document.createElement('button');
prevBtn.className = 'me-at-github-nav-btn me-at-github-prev';
prevBtn.title = 'Previous mention';
prevBtn.textContent = '←';
const nextBtn = document.createElement('button');
nextBtn.className = 'me-at-github-nav-btn me-at-github-next';
nextBtn.title = 'Next mention';
nextBtn.textContent = '→';
nav.appendChild(prevBtn);
nav.appendChild(nextBtn);
element.appendChild(nav);
let hideTimeout;
// Show navigation on hover or active
const showNav = () => {
clearTimeout(hideTimeout);
// Only show if we have mentions to navigate through
if (mentions.length > 1) {
nav.style.display = 'flex';
}
};
// Hide navigation with delay
const hideNav = () => {
hideTimeout = setTimeout(() => {
nav.style.display = 'none';
}, 2000); // Keep visible for 2 seconds
};
// Keep nav visible when hovering over it
nav.addEventListener('mouseenter', () => {
clearTimeout(hideTimeout);
});
nav.addEventListener('mouseleave', hideNav);
// Show nav on element hover/focus
element.addEventListener('mouseenter', showNav);
element.addEventListener('focus', showNav);
element.addEventListener('mouseleave', hideNav);
// Add event listeners
const prevBtn = nav.querySelector('.me-at-github-prev');
const nextBtn = nav.querySelector('.me-at-github-next');
prevBtn.addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
const success = navigateToMention(index - 1);
if (success) {
// Hide nav immediately after successful navigation
clearTimeout(hideTimeout);
nav.style.display = 'none';
}
});
nextBtn.addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
const success = navigateToMention(index + 1);
if (success) {
// Hide nav immediately after successful navigation
clearTimeout(hideTimeout);
nav.style.display = 'none';
}
});
}
// Navigate to a specific mention
function navigateToMention(index) {
if (mentions.length === 0) {
return false;
}
// Wrap around: if index is out of bounds, loop to the other end
if (index < 0) {
index = mentions.length - 1;
} else if (index >= mentions.length) {
index = 0;
}
currentMentionIndex = index;
const mention = mentions[index];
if (!mention || !mention.element) {
return false;
}
// Remove active class from all mentions
document.querySelectorAll('.me-at-github-mention-text').forEach(el => {
el.classList.remove('active');
});
// Add active class to current mention
mention.element.classList.add('active');
// Scroll to the mention with error handling, using RAF to avoid forced reflow
requestAnimationFrame(() => {
try {
mention.element.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
} catch (error) {
// Fallback: try without smooth behavior
mention.element.scrollIntoView({
block: 'center'
});
}
});
return true;
}
// Create and inject the counter badge
function createCounter() {
const count = mentions.length;
console.log('createCounter called with count:', count);
if (count === 0) return;
// Find the issue/PR number element first - this is our primary target
const issueSelectors = [
'[class*="HeaderViewer-module__issueNumberText"]', // Priority: New GitHub UI issue number
'.gh-header-number', // Issue/PR number in header
'span.f1-light', // Alternative number styling
'.js-issue-number', // JS issue number
'.gh-header-title .f1-light', // Number within title
'h1 .f1-light', // Generic number in h1
'[data-testid="issue-title"] .f1-light', // New GitHub UI
'h1 span.color-fg-muted', // GitHub's muted text styling
'h1 .color-fg-muted', // Alternative muted styling
'span[data-testid="issue-number"]', // Possible data attribute
'.issue-title-actions + h1 span', // Adjacent to actions
'h1 > span:first-child', // First span in h1 (often the number)
'.js-issue-title span', // Span within issue title
'bdi span', // Span within bdi element
'.gh-header-meta .color-fg-muted', // Header meta with muted color
'span[title*="#"]' // Span with # in title attribute
];
let issueNumberElement = null;
for (const selector of issueSelectors) {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
if (element && element.offsetWidth > 0 && element.offsetHeight > 0) {
// Check if it contains a # (issue/PR number)
if (element.textContent.includes('#')) {
issueNumberElement = element;
break;
}
}
}
if (issueNumberElement) break;
}
// Fallback to title element if no issue number found
if (!issueNumberElement) {
const titleSelectors = [
'h1.gh-header-title',
'h1.js-issue-title',
'h1[data-testid="issue-title"]',
'[data-testid="issue-title"]',
'h1.d-flex',
'.gh-header-title',
'bdi.js-issue-title',
'span.js-issue-title',
'main h1',
'h1'
];
for (const selector of titleSelectors) {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
if (element && element.offsetWidth > 0 && element.offsetHeight > 0) {
issueNumberElement = element;
break;
}
}
if (issueNumberElement) break;
}
}
if (!issueNumberElement) {
console.log('createCounter: No issue number element found');
return;
}
console.log('createCounter: Found issue number element:', issueNumberElement);
// Create counter badge
const counter = document.createElement('span');
counter.classList.add('me-at-github-counter');
counter.textContent = `${count} mention${count !== 1 ? 's' : ''}`;
// Set title property directly to avoid attribute injection
counter.title = count + ' mention' + (count !== 1 ? 's' : '') + ' of @' + username;
console.log('createCounter: Counter element created');
// Add click handler to toggle dropdown
counter.addEventListener('click', (e) => {
e.stopPropagation();
console.log('Counter clicked!');
toggleDropdown(counter);
});
// Store reference for body click handler to close dropdown on outside click
counter._dropdownToggleHandler = (e) => {
// Don't close if clicking on the counter itself or dropdown content
if (counter.contains(e.target) ||
document.querySelector('.me-at-github-dropdown-portal')?.contains(e.target)) {
return;
}
hideDropdown(counter);
};
// Insert the counter after the target element
issueNumberElement.parentNode.insertBefore(counter, issueNumberElement.nextSibling);
// Create dropdown
createDropdown(counter);
// Create sticky header counter
createStickyCounter(count);
}
// Create sticky header counter that appears when scrolling
function createStickyCounter(count) {
// Remove any existing sticky counter
const existingStickyCounter = document.getElementById('me-at-github-sticky-counter');
if (existingStickyCounter) {
existingStickyCounter.remove();
}
// Create sticky counter
const stickyCounter = document.createElement('div');
stickyCounter.id = 'me-at-github-sticky-counter';
stickyCounter.classList.add('me-at-github-sticky-counter');
stickyCounter.textContent = `${count} mention${count !== 1 ? 's' : ''}`;
stickyCounter.title = count + ' mention' + (count !== 1 ? 's' : '') + ' of @' + username;
// Add click handler
stickyCounter.addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
// Scroll to first mention when clicked
if (mentions.length > 0) {
navigateToMention(0);
}
});
// Insert into GitHub's sticky header if available, otherwise fallback to body
const stickyHeader = document.querySelector('[data-testid="issue-metadata-sticky"]');
// Use flexible selector strategy instead of hardcoded CSS module class
let stickyContent = null;
if (stickyHeader) {
// Try multiple selectors to find the content area (GitHub may change class names)
stickyContent = stickyHeader.querySelector('[class*="stickyContent"], [class*="sticky-content"], .sticky-content, [data-testid*="sticky-content"]');
// Fallback: use the sticky header itself if no content container found
if (!stickyContent) {
stickyContent = stickyHeader;
}
}
if (stickyContent) {
// Insert at the beginning of the sticky content
stickyContent.insertBefore(stickyCounter, stickyContent.firstChild);
} else {
// Fallback: append to body with original scroll behavior
document.body.appendChild(stickyCounter);
// Show/hide based on scroll position (only for body-appended counter)
// Throttle scroll events for better performance
let isHeaderVisible = true;
let scrollTimeout = null;
const checkScroll = () => {
// Clear any existing timeout to prevent multiple timeouts from queuing
if (scrollTimeout) {
clearTimeout(scrollTimeout);
}
scrollTimeout = setTimeout(() => {
const headerHeight = 80;
const scrolled = window.scrollY > headerHeight;
if (scrolled && isHeaderVisible) {
stickyCounter.style.display = 'flex';
stickyCounter.style.opacity = '1';
isHeaderVisible = false;
} else if (!scrolled && !isHeaderVisible) {
stickyCounter.style.opacity = '0';
setTimeout(() => {
if (window.scrollY <= headerHeight) {
stickyCounter.style.display = 'none';
}
}, 200);
isHeaderVisible = true;
}
// Timeout completed, will be cleared on next scroll if needed
}, 100); // Throttle to 100ms
};
window.addEventListener('scroll', checkScroll, { passive: true });
checkScroll(); // Initial check
}
}
// Create the dropdown menu
function createDropdown(counter) {
const dropdown = document.createElement('div');
dropdown.classList.add('me-at-github-dropdown');
dropdown.style.display = 'none';
dropdown.style.zIndex = '2147483647'; // Set maximum z-index immediately
const list = document.createElement('ul');
list.classList.add('me-at-github-dropdown-list');
mentions.forEach((mention, index) => {
const li = document.createElement('li');
li.classList.add('me-at-github-dropdown-item');
li.setAttribute('data-mention-index', index.toString());
// Create context span with safe DOM manipulation
const contextSpan = document.createElement('span');
contextSpan.classList.add('me-at-github-dropdown-context');
// Get context as DocumentFragment with proper text nodes and strong tags
const contextFragment = createContextElement(mention);
if (contextFragment && contextFragment.childNodes.length > 0) {
contextSpan.appendChild(contextFragment);
} else {
// Fallback if no context could be created
contextSpan.textContent = `Mention #${index + 1}: @${username}`;
}
li.appendChild(contextSpan);
li.addEventListener('click', (e) => {
e.stopPropagation();
navigateToMention(index);
hideDropdown(counter);
});
list.appendChild(li);
});
dropdown.appendChild(list);
counter.appendChild(dropdown);
}
// Get line content where the mention appears and create DOM nodes
function createContextElement(mention) {
let fullText = mention.text || '';
const mentionText = `@${username}`;
// Try to get better context from the element
let contextText = fullText;
if (mention.element && mention.element.closest) {
const container = mention.element.closest('.comment-body, .js-comment-body, .markdown-body, .discussion-comment-body, .js-discussion-comment-body, [class*="DiscussionCommentViewer-module__DiscussionCommentBody"]');
if (container) {
// Clone the container to safely remove navigation controls without affecting the page
const tempContainer = container.cloneNode(true);
// Remove navigation controls from the clone
tempContainer.querySelectorAll('.me-at-github-nav').forEach(nav => nav.remove());
contextText = tempContainer.textContent || fullText;
}
}
// If no meaningful text, create a simple display
if (!contextText || contextText.trim().length < 10) {
const fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(`Mentioned as `));
const strong = document.createElement('strong');
strong.textContent = mentionText;
fragment.appendChild(strong);
return fragment;
}
// If short text, show it all with highlighting
if (contextText.length < 100) {
const fragment = document.createDocumentFragment();
const displayText = contextText.trim();
// Find and highlight mentions
const mentionPattern = new RegExp(`@${username.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`, 'gi');
let lastIndex = 0;
const matches = [...displayText.matchAll(mentionPattern)];
if (matches.length === 0) {
// No matches found, just show the text
fragment.appendChild(document.createTextNode(displayText));
} else {
matches.forEach((match) => {
if (match.index > lastIndex) {
fragment.appendChild(document.createTextNode(displayText.substring(lastIndex, match.index)));
}
const strong = document.createElement('strong');
strong.textContent = match[0];
fragment.appendChild(strong);
lastIndex = match.index + match[0].length;
});
if (lastIndex < displayText.length) {
fragment.appendChild(document.createTextNode(displayText.substring(lastIndex)));
}
}
return fragment;
}
// For longer text, use the original line-based logic
fullText = contextText;
// Find the line containing the mention
const lines = fullText.split('\n');
let lineContent = '';
let lineStartIndex = 0;
let mentionLineIndex = -1;
// Find which line contains the mention
for (let i = 0; i < lines.length; i++) {
const lineEndIndex = lineStartIndex + lines[i].length;
if (mention.index >= lineStartIndex && mention.index <= lineEndIndex) {
lineContent = lines[i].trim();
mentionLineIndex = i;
break;
}
lineStartIndex = lineEndIndex + 1; // +1 for the newline character
}
// If we didn't find a line, fall back to showing context around the mention
if (lineContent === '' && mention.index >= 0) {
const start = Math.max(0, mention.index - 50);
const end = Math.min(fullText.length, mention.index + 50);
lineContent = fullText.substring(start, end).trim();
if (start > 0) lineContent = '...' + lineContent;
if (end < fullText.length) lineContent = lineContent + '...';
}
// Final fallback - just show some context from the full text
if (lineContent === '') {
lineContent = fullText.substring(0, 100).trim();
if (fullText.length > 100) lineContent += '...';
}
// If line is too long, truncate around the mention but prioritize showing full sentences
const maxLength = 120;
let displayText = lineContent;
if (lineContent.length > maxLength) {
const mentionInLine = mention.index - lineStartIndex + mentionText.length;
const start = Math.max(0, mentionInLine - maxLength / 2);
const end = Math.min(lineContent.length, start + maxLength);
displayText = lineContent.substring(start, end);
// Add ellipsis if truncated