-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
925 lines (779 loc) · 30.4 KB
/
content.js
File metadata and controls
925 lines (779 loc) · 30.4 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
(() => {
'use strict';
const SIDEBAR_ID = 'gmtoc-sidebar';
const WRAPPER_ID = 'gmtoc-wrapper';
const MARKDOWN_SELECTORS = [
'#readme .markdown-body',
'.wiki-body .markdown-body',
'.markdown-body',
];
const STORAGE_KEY_POSITION = 'gmtoc_position';
const STORAGE_KEY_COLLAPSED = 'gmtoc_collapsed';
const STORAGE_KEY_MAX_LEVEL = 'gmtoc_max_level';
const DEBOUNCE_MS = 200;
let sidebarEl = null;
let wrapperEl = null;
let bodyEl = null;
let modalEl = null;
let overlayEl = null;
let modalBodyEl = null;
let currentHeaders = [];
let currentMdBody = null;
let mountHost = null; // element wrapper is appended to (may differ from currentMdBody)
let resizeObserver = null;
let stickyHeaderObserver = null;
let baseZIndex = 32;
let activeId = null;
let settings = { position: 'right', collapsed: false, maxLevel: 4 };
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
function parseZIndex(value) {
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) ? parsed : null;
}
function computeSidebarZIndex() {
let target = baseZIndex;
const backdrop = document.querySelector('.dark-backdrop');
if (backdrop) {
const backdropZ = parseZIndex(window.getComputedStyle(backdrop).zIndex);
if (backdropZ !== null) {
target = Math.min(baseZIndex, backdropZ - 1);
if (!Number.isFinite(target)) target = baseZIndex;
if (target < 0) target = 0;
}
}
return target;
}
function applySidebarZIndex() {
if (!wrapperEl || !sidebarEl) return;
const target = computeSidebarZIndex();
wrapperEl.style.zIndex = String(target);
sidebarEl.style.zIndex = String(target);
}
function buildHeaderSelector() {
return Array.from({ length: settings.maxLevel }, (_, i) => `h${i + 1}`).join(', ');
}
function getPathSegments() {
return window.location.pathname.replace(/\/+$/, '').split('/').filter(Boolean);
}
function findMarkdownBody() {
for (const sel of MARKDOWN_SELECTORS) {
const el = document.querySelector(sel);
if (el) return el;
}
return null;
}
/**
* URL-based page filter: only show sidebar on pages where a TOC
* makes sense. Allowed pages:
* - /owner/repo (repo root README)
* - /owner/repo/tree/xxx (branch/tag root README)
* - /owner/repo/blob/branch/path/file.md (.md file viewer)
* - /owner/repo/wiki/** (wiki pages)
*/
function isAllowedPage() {
const path = window.location.pathname;
const segments = getPathSegments();
console.log('[GMTOC DEBUG] isAllowedPage:', { path, segments, len: segments.length });
if (segments.length < 2) { console.log('[GMTOC DEBUG] rejected: < 2 segments'); return false; }
// Exactly 2 segments = repo root
if (segments.length === 2) return true;
const action = segments[2];
// .md file viewer
if (action === 'blob' && /\.md$/i.test(path)) return true;
// Branch/tag root (shows README)
if (action === 'tree') return true;
// Wiki pages
if (action === 'wiki') return true;
return false;
}
function isBlobMarkdownPage() {
const segments = getPathSegments();
if (segments.length < 3) return false;
if (segments[2] !== 'blob') return false;
return /\.md$/i.test(window.location.pathname);
}
/**
* Walk up from mdBody to find the best mount point for the wrapper.
* If any ancestor between mdBody and <body> clips overflow, mount the
* wrapper on that ancestor's parent so the sidebar is not clipped.
* Falls back to mdBody itself when no clipping ancestor exists.
*/
function findMountHost(mdBody) {
// Find stable mount point: prefer markdown-body's direct parent container
// This avoids relying on class names that might change with GitHub's UI updates
let el = mdBody.parentElement;
while (el && el !== document.body) {
const cs = window.getComputedStyle(el);
const isClipping = cs.overflow !== 'visible' ||
cs.overflowX !== 'visible' ||
cs.overflowY !== 'visible';
if (isClipping && el.parentElement) {
return el.parentElement;
}
if (el.tagName === 'DIV' && el.children.length > 0) {
return el;
}
el = el.parentElement;
}
return mdBody;
}
function findReadmeContainer(mdBody, host) {
let el = mdBody.parentElement;
while (el && el !== host) {
if (parseFloat(window.getComputedStyle(el).borderTopWidth) > 0) {
return el;
}
el = el.parentElement;
}
return null;
}
function extractHeaders(mdBody) {
const headers = [];
if (!mdBody) return headers;
const selector = buildHeaderSelector();
mdBody.querySelectorAll(selector).forEach((el) => {
const level = parseInt(el.tagName.charAt(1), 10);
const text = el.textContent.trim();
if (!text) return;
let id = el.id;
if (!id) {
const anchor = el.querySelector('a.anchor');
if (anchor) {
const href = anchor.getAttribute('href');
if (href && href.startsWith('#')) {
id = href.slice(1);
}
}
}
if (!id) {
id = 'gmtoc-' + text.toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g, '-').replace(/(^-|-$)/g, '');
el.id = id;
}
headers.push({ level, text, id, el });
});
return headers;
}
/**
* When the top-level heading only appears once, skip it and promote the
* next level as the display root. E.g. a single H1 + multiple H2s →
* H2 becomes display-level-1. Applies recursively (single H2 → check H3…).
* Returns a new array with a `displayLevel` property on each item.
*/
function normalizeHeaders(headers) {
if (headers.length === 0) return [];
const minLevel = Math.min(...headers.map((h) => h.level));
const topLevelCount = headers.filter((h) => h.level === minLevel).length;
let skipLevel = minLevel;
if (topLevelCount === 1) {
const remaining = headers.filter((h) => h.level !== minLevel);
if (remaining.length > 0) {
return normalizeHeaders(remaining);
}
}
const effectiveMin = Math.min(...headers.map((h) => h.level));
return headers.map((h) => ({
...h,
displayLevel: h.level - effectiveMin + 1,
}));
}
const ICONS = {
toc: `<svg viewBox="0 0 16 16" fill="currentColor"><path d="M2 3.5h12v1H2zm0 4h8v1H2zm0 4h10v1H2zm12-4h-1.5v1H14zm0 4h-1.5v1H14z"/></svg>`,
collapse: `<svg viewBox="0 0 16 16" fill="currentColor"><path d="M12 8.5H4v-1h8z"/></svg>`,
expand: `<svg viewBox="0 0 16 16" fill="currentColor"><path d="M8.5 4v3.5H12v1H8.5V12h-1V8.5H4v-1h3.5V4z"/></svg>`,
close: `<svg viewBox="0 0 16 16" fill="currentColor"><path d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"/></svg>`,
panelLeft: `<svg viewBox="0 0 16 16" fill="currentColor"><path fill-rule="evenodd" d="M2 3.75C2 2.784 2.784 2 3.75 2h8.5c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0112.25 14h-8.5A1.75 1.75 0 012 12.25zM3.75 3.5a.25.25 0 00-.25.25v8.5c0 .138.112.25.25.25H5.5v-9zm3.25 0v9h5.25a.25.25 0 00.25-.25v-8.5a.25.25 0 00-.25-.25z"/></svg>`,
panelRight: `<svg viewBox="0 0 16 16" fill="currentColor"><path fill-rule="evenodd" d="M14 3.75A1.75 1.75 0 0012.25 2h-8.5A1.75 1.75 0 002 3.75v8.5c0 .966.784 1.75 1.75 1.75h8.5A1.75 1.75 0 0014 12.25zM12.25 3.5a.25.25 0 01.25.25v8.5a.25.25 0 01-.25.25H10.5v-9zm-3.25 0v9H3.75a.25.25 0 01-.25-.25v-8.5a.25.25 0 01.25-.25z"/></svg>`,
};
/* ------------------------------------------------------------------ */
/* Sidebar positioning relative to .markdown-body */
/* ------------------------------------------------------------------ */
const FALLBACK_STICKY_HEIGHT = 224; // Fallback: 224 + gap(26) = 250px from top
const STICKY_TOP_GAP = 17;
const OVERVIEW_BOX_SELECTOR = '[class^="OverviewRepoFiles-module__Box"], [class*=" OverviewRepoFiles-module__Box"]';
function getOverviewStickyBox() {
const candidates = Array.from(document.querySelectorAll(OVERVIEW_BOX_SELECTOR));
if (candidates.length === 0) return null;
const metrics = candidates.map((el) => {
const rect = el.getBoundingClientRect();
const cs = window.getComputedStyle(el);
return { el, height: rect.height, position: cs.position };
});
const sticky = metrics.find((item) => item.position === 'sticky' || item.position === 'fixed');
if (sticky) return sticky.el;
const reasonable = metrics.filter((item) => item.height >= 24 && item.height <= 200);
if (reasonable.length > 0) {
reasonable.sort((a, b) => a.height - b.height);
return reasonable[0].el;
}
const nonZero = metrics.filter((item) => item.height > 0);
if (nonZero.length > 0) {
nonZero.sort((a, b) => a.height - b.height);
return nonZero[0].el;
}
return candidates[0];
}
function getStickyOffsetElement() {
if (isBlobMarkdownPage()) {
return document.querySelector('#repos-sticky-header > div');
}
return getOverviewStickyBox();
}
function getStickyTopOffset() {
const stickyEl = getStickyOffsetElement();
if (stickyEl) return stickyEl.getBoundingClientRect().height + STICKY_TOP_GAP;
let maxBottom = 0;
document.querySelectorAll('header, nav').forEach((el) => {
const cs = window.getComputedStyle(el);
if (cs.position === 'fixed' || cs.position === 'sticky') {
const bottom = el.getBoundingClientRect().bottom;
if (bottom > 0 && bottom < 200) {
maxBottom = Math.max(maxBottom, bottom);
}
}
});
return maxBottom + STICKY_TOP_GAP;
}
function observeStickyTargets(observer) {
if (!observer) return false;
const stickyEl = getStickyOffsetElement();
if (!stickyEl) return false;
observer.observe(stickyEl);
if (stickyEl.parentElement) observer.observe(stickyEl.parentElement);
return true;
}
const TIER_FULL = 260;
const TIER_NARROW = 160;
function applyResponsiveTier(sidebar, availableWidth) {
sidebar.classList.remove('gmtoc-narrow', 'gmtoc-mini-fab');
if (availableWidth < TIER_NARROW) {
sidebar.classList.add('gmtoc-mini-fab');
return;
}
if (availableWidth < TIER_FULL) {
sidebar.classList.add('gmtoc-narrow');
sidebar.style.width = Math.max(160, Math.min(availableWidth, 259)) + 'px';
} else {
sidebar.style.width = Math.max(200, Math.min(availableWidth, 320)) + 'px';
}
const btn = sidebar.querySelector('.gmtoc-btn-collapse');
if (btn) btn.innerHTML = settings.collapsed ? ICONS.expand : ICONS.collapse;
}
function positionSidebar() {
if (!sidebarEl || !wrapperEl || !currentMdBody || !mountHost) {
console.log('[GMTOC] positionSidebar skip:', { s: !!sidebarEl, w: !!wrapperEl, m: !!currentMdBody, h: !!mountHost });
return;
}
console.log('[GMTOC] positionSidebar called, mdBody connected:', currentMdBody.isConnected, 'mountHost connected:', mountHost.isConnected);
const defaultGap = 26;
const stickyTop = getStickyTopOffset();
sidebarEl.style.top = stickyTop + 'px';
// For .md file pages, use markdown-body directly as container
// For repo home pages, use markdown-body's parent container
const isBlobPage = isBlobMarkdownPage();
const containerEl = isBlobPage ? currentMdBody : currentMdBody.parentElement;
if (!containerEl) {
console.log('[GMTOC] No container element found');
return;
}
const containerRect = containerEl.getBoundingClientRect();
const hostRect = mountHost.getBoundingClientRect();
const containerOffsetLeft = containerRect.left - hostRect.left;
const containerWidth = containerEl.offsetWidth;
if (mountHost !== currentMdBody) {
const anchor = findReadmeContainer(currentMdBody, mountHost) || currentMdBody;
const anchorRect = anchor.getBoundingClientRect();
const anchorHeight = anchor.offsetHeight;
console.log('[GMTOC] anchor:', anchor.tagName, anchor.className.substring(0, 60), 'h:', anchorHeight, 'top:', Math.round(anchorRect.top), 'hostTop:', Math.round(hostRect.top));
// Defense: Don't write invalid values when anchor hasn't finished layout, let ResizeObserver fix it later
if (anchorHeight > 0) {
wrapperEl.style.top = (anchorRect.top - hostRect.top) + 'px';
wrapperEl.style.height = anchorHeight + 'px';
wrapperEl.style.visibility = '';
} else {
return;
}
} else {
wrapperEl.style.visibility = '';
}
// Use fixed gap - sidebar positioned outside container
const effectiveGap = defaultGap;
// Calculate available width based on container edges
const availableWidth = settings.position === 'right'
? window.innerWidth - containerRect.right - effectiveGap * 2
: containerRect.left - effectiveGap * 2;
console.log('[GMTOC] availableWidth:', Math.round(availableWidth), 'vpWidth:', window.innerWidth, 'containerRight:', Math.round(containerRect.right), 'containerLeft:', Math.round(containerRect.left), 'gap:', effectiveGap, 'isBlobPage:', isBlobPage);
const isCollapsed = sidebarEl.classList.contains('gmtoc-collapsed');
if (isCollapsed) {
sidebarEl.classList.remove('gmtoc-narrow', 'gmtoc-mini-fab');
sidebarEl.style.width = '32px';
} else {
applyResponsiveTier(sidebarEl, availableWidth);
}
if (sidebarEl.classList.contains('gmtoc-mini-fab')) {
wrapperEl.style.left = 'auto';
wrapperEl.style.right = '12px';
} else {
wrapperEl.style.right = 'auto';
if (settings.position === 'right') {
sidebarEl.style.transform = '';
// Position sidebar outside container's right edge
wrapperEl.style.left = (containerOffsetLeft + containerWidth + effectiveGap) + 'px';
} else {
sidebarEl.style.transform = 'translateX(-100%)';
// Position sidebar outside container's left edge
wrapperEl.style.left = (containerOffsetLeft - effectiveGap) + 'px';
}
}
}
const debouncedPosition = debounce(positionSidebar, 100);
function setupPositionTracking() {
destroyPositionTracking();
if (currentMdBody) {
resizeObserver = new ResizeObserver(() => {
console.log('[GMTOC] ResizeObserver fired, mdBody connected:', currentMdBody.isConnected);
debouncedPosition();
});
resizeObserver.observe(currentMdBody);
resizeObserver.observe(document.documentElement);
if (mountHost && mountHost !== currentMdBody) {
resizeObserver.observe(mountHost);
const anchor = findReadmeContainer(currentMdBody, mountHost);
if (anchor && anchor !== mountHost && anchor !== currentMdBody) {
resizeObserver.observe(anchor);
}
}
const hasStickyTarget = observeStickyTargets(resizeObserver);
if (!hasStickyTarget) {
console.log('[GMTOC] sticky target not found yet, waiting for DOM update');
}
}
// Watch for sticky element appearance (GitHub may render this element lazily)
if (!getStickyOffsetElement()) {
stickyHeaderObserver = new MutationObserver(() => {
const didObserve = observeStickyTargets(resizeObserver);
if (didObserve) {
debouncedPosition();
if (stickyHeaderObserver) {
stickyHeaderObserver.disconnect();
stickyHeaderObserver = null;
}
}
});
stickyHeaderObserver.observe(document.body, { childList: true, subtree: true });
}
window.addEventListener('resize', debouncedPosition, { passive: true });
}
function destroyPositionTracking() {
if (resizeObserver) {
resizeObserver.disconnect();
resizeObserver = null;
}
if (stickyHeaderObserver) {
stickyHeaderObserver.disconnect();
stickyHeaderObserver = null;
}
window.removeEventListener('resize', debouncedPosition);
}
/* ------------------------------------------------------------------ */
/* Sidebar DOM */
/* ------------------------------------------------------------------ */
function createSidebar() {
if (sidebarEl) return sidebarEl;
if (!currentMdBody) return null;
mountHost = findMountHost(currentMdBody);
const hostStyle = window.getComputedStyle(mountHost);
if (hostStyle.position === 'static') {
mountHost.style.position = 'relative';
}
const wrapper = document.createElement('div');
wrapper.id = WRAPPER_ID;
wrapper.style.visibility = 'hidden';
const sidebar = document.createElement('div');
sidebar.id = SIDEBAR_ID;
if (settings.collapsed) sidebar.classList.add('gmtoc-collapsed');
const positionIcon = settings.position === 'right' ? ICONS.panelLeft : ICONS.panelRight;
const positionTitle = settings.position === 'right'
? chrome.i18n.getMessage('move_to_left')
: chrome.i18n.getMessage('move_to_right');
sidebar.innerHTML = `
<div class="gmtoc-header">
<div class="gmtoc-header-left">
<span class="gmtoc-icon">${ICONS.toc}</span>
<span class="gmtoc-title-text">${chrome.i18n.getMessage('navigation')}</span>
</div>
<div class="gmtoc-header-right">
<button class="gmtoc-btn gmtoc-btn-position" title="${positionTitle}">
${positionIcon}
</button>
<button class="gmtoc-btn gmtoc-btn-collapse" title="${chrome.i18n.getMessage('collapse_expand')}">
${settings.collapsed ? ICONS.expand : ICONS.collapse}
</button>
</div>
</div>
<div class="gmtoc-body"></div>
`;
sidebar.querySelector('.gmtoc-btn-position').addEventListener('click', (e) => {
e.stopPropagation();
togglePosition();
});
sidebar.querySelector('.gmtoc-btn-collapse').addEventListener('click', (e) => {
e.stopPropagation();
toggleCollapse();
});
sidebar.querySelector('.gmtoc-header').addEventListener('click', (e) => {
if (sidebarEl.classList.contains('gmtoc-mini-fab') || sidebarEl.classList.contains('gmtoc-collapsed')) {
e.stopPropagation();
toggleCollapse();
}
});
wrapper.appendChild(sidebar);
mountHost.appendChild(wrapper);
wrapperEl = wrapper;
sidebarEl = sidebar;
bodyEl = sidebar.querySelector('.gmtoc-body');
baseZIndex = parseZIndex(window.getComputedStyle(wrapperEl).zIndex) ?? 32;
applySidebarZIndex();
return sidebar;
}
function removeSidebar() {
if (wrapperEl) {
wrapperEl.remove();
wrapperEl = null;
}
sidebarEl = null;
bodyEl = null;
currentMdBody = null;
mountHost = null;
baseZIndex = 32;
destroyModal();
destroyObserver();
destroyPositionTracking();
}
function hideSidebar() {
removeSidebar();
}
function togglePosition() {
settings.position = settings.position === 'right' ? 'left' : 'right';
chrome.storage.sync.set({ [STORAGE_KEY_POSITION]: settings.position });
removeSidebar();
update();
}
function toggleCollapse() {
if (!sidebarEl) return;
if (sidebarEl.classList.contains('gmtoc-mini-fab')) {
openModal();
return;
}
settings.collapsed = !settings.collapsed;
sidebarEl.classList.toggle('gmtoc-collapsed', settings.collapsed);
const btn = sidebarEl.querySelector('.gmtoc-btn-collapse');
if (btn) btn.innerHTML = settings.collapsed ? ICONS.expand : ICONS.collapse;
chrome.storage.sync.set({ [STORAGE_KEY_COLLAPSED]: settings.collapsed });
// Recalculate position after CSS layout update (width changes from full to 32px when collapsed)
requestAnimationFrame(() => positionSidebar());
}
function createModal() {
if (modalEl) return;
overlayEl = document.createElement('div');
overlayEl.className = 'gmtoc-overlay';
overlayEl.addEventListener('click', closeModal);
modalEl = document.createElement('div');
modalEl.className = 'gmtoc-modal';
modalEl.innerHTML = `
<div class="gmtoc-modal-header">
<div class="gmtoc-modal-header-left">
<span class="gmtoc-icon">${ICONS.toc}</span>
<span class="gmtoc-title-text">${chrome.i18n.getMessage('navigation')}</span>
</div>
<button class="gmtoc-btn gmtoc-btn-collapse" title="${chrome.i18n.getMessage('close')}">
${ICONS.close}
</button>
</div>
<div class="gmtoc-modal-body"></div>
`;
modalEl.querySelector('.gmtoc-btn-collapse').addEventListener('click', (e) => {
e.stopPropagation();
closeModal();
});
modalBodyEl = modalEl.querySelector('.gmtoc-modal-body');
document.body.appendChild(overlayEl);
document.body.appendChild(modalEl);
}
function openModal() {
createModal();
renderModalTOC();
overlayEl.classList.add('gmtoc-overlay-visible');
modalEl.classList.add('gmtoc-modal-visible');
const activeItem = modalBodyEl && modalBodyEl.querySelector('.gmtoc-active');
if (activeItem) {
requestAnimationFrame(() => activeItem.scrollIntoView({ block: 'nearest' }));
}
}
function closeModal() {
if (overlayEl) overlayEl.classList.remove('gmtoc-overlay-visible');
if (modalEl) modalEl.classList.remove('gmtoc-modal-visible');
}
function destroyModal() {
if (overlayEl) { overlayEl.remove(); overlayEl = null; }
if (modalEl) { modalEl.remove(); modalEl = null; }
modalBodyEl = null;
}
function renderModalTOC() {
if (!modalBodyEl) return;
modalBodyEl.innerHTML = '';
const normalized = normalizeHeaders(currentHeaders);
if (normalized.length === 0) {
modalBodyEl.innerHTML = `<div class="gmtoc-empty">${chrome.i18n.getMessage('no_headers_found')}</div>`;
return;
}
normalized.forEach((h) => {
const item = document.createElement('a');
item.className = `gmtoc-item gmtoc-level-${h.displayLevel}`;
if (h.id === activeId) item.classList.add('gmtoc-active');
item.textContent = h.text;
item.title = h.text;
item.dataset.id = h.id;
item.addEventListener('click', (e) => {
e.preventDefault();
const target = document.getElementById(h.id);
if (target) {
target.scrollIntoView({ behavior: 'instant', block: 'start' });
const offset = getStickyTopOffset();
if (offset) {
window.scrollBy({ top: -offset, behavior: 'instant' });
}
history.replaceState(null, '', `#${h.id}`);
setActive(h.id);
}
});
modalBodyEl.appendChild(item);
});
}
/* ------------------------------------------------------------------ */
/* Render TOC items */
/* ------------------------------------------------------------------ */
function renderTOC(headers) {
if (!bodyEl) return;
bodyEl.innerHTML = '';
const normalized = normalizeHeaders(headers);
if (normalized.length === 0) {
bodyEl.innerHTML = `<div class="gmtoc-empty">${chrome.i18n.getMessage('no_headers_found')}</div>`;
return;
}
normalized.forEach((h) => {
const item = document.createElement('a');
item.className = `gmtoc-item gmtoc-level-${h.displayLevel}`;
item.textContent = h.text;
item.title = h.text;
item.dataset.id = h.id;
item.addEventListener('click', (e) => {
e.preventDefault();
const target = document.getElementById(h.id);
if (target) {
target.scrollIntoView({ behavior: 'instant', block: 'start' });
const offset = getStickyTopOffset();
if (offset) {
window.scrollBy({ top: -offset, behavior: 'instant' });
}
history.replaceState(null, '', `#${h.id}`);
setActive(h.id);
}
});
bodyEl.appendChild(item);
});
}
function setActive(id) {
if (activeId === id) return;
activeId = id;
[bodyEl, modalBodyEl].forEach((container) => {
if (!container) return;
container.querySelectorAll('.gmtoc-item').forEach((item) => {
item.classList.toggle('gmtoc-active', item.dataset.id === id);
});
const activeItem = container.querySelector('.gmtoc-active');
if (activeItem) {
activeItem.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
});
}
/* ------------------------------------------------------------------ */
/* Scroll tracking */
/* ------------------------------------------------------------------ */
let scrollRafId = null;
function setupObserver(headers) {
destroyObserver();
if (headers.length === 0) return;
const onScroll = () => {
if (scrollRafId) return;
scrollRafId = requestAnimationFrame(() => {
scrollRafId = null;
updateActiveHeader();
});
};
window.addEventListener('scroll', onScroll, { passive: true });
updateActiveHeader();
}
function updateActiveHeader() {
if (currentHeaders.length === 0) return;
// Add 2px tolerance for floating-point precision issues
// (scrollIntoView + scrollBy may result in rect.top being slightly > offset)
const offset = Math.max(20, getStickyTopOffset()) + 2;
let active = currentHeaders[0];
for (const h of currentHeaders) {
const rect = h.el.getBoundingClientRect();
if (rect.top <= offset) {
active = h;
} else {
break;
}
}
if (active) setActive(active.id);
}
function destroyObserver() {
if (scrollRafId) {
cancelAnimationFrame(scrollRafId);
scrollRafId = null;
}
}
/* ------------------------------------------------------------------ */
/* Main flow */
/* ------------------------------------------------------------------ */
function update() {
console.log('[GMTOC] update() called');
// Detect stale DOM reference: old sidebar no longer in DOM after SPA navigation
if (sidebarEl && !sidebarEl.isConnected) {
removeSidebar();
}
if (!isAllowedPage()) {
console.log('[GMTOC DEBUG] update() -> page not allowed, removing sidebar');
removeSidebar();
return;
}
const mdBody = findMarkdownBody();
if (!mdBody) {
removeSidebar();
return;
}
const headers = extractHeaders(mdBody);
// After normalization, a single-item TOC has no navigation value
const normalized = normalizeHeaders(headers);
if (normalized.length <= 1) {
removeSidebar();
return;
}
currentHeaders = headers;
currentMdBody = mdBody;
createSidebar();
renderTOC(headers);
applySidebarZIndex();
setupObserver(headers);
positionSidebar();
setupPositionTracking();
}
const debouncedUpdate = debounce(update, DEBOUNCE_MS);
/* ------------------------------------------------------------------ */
/* SPA navigation detection (GitHub Turbo) */
/* ------------------------------------------------------------------ */
function setupNavigationListener() {
document.addEventListener('turbo:load', debouncedUpdate);
document.addEventListener('turbo:render', debouncedUpdate);
document.addEventListener('soft-nav:end', debouncedUpdate);
window.addEventListener('popstate', debouncedUpdate);
const mo = new MutationObserver(
debounce(() => {
const mdBody = findMarkdownBody();
if (mdBody && isAllowedPage()) {
if (sidebarEl) applySidebarZIndex();
if (!sidebarEl) {
console.log('[GMTOC] MO: no sidebar, triggering update');
debouncedUpdate();
return;
}
const newHeaders = extractHeaders(mdBody);
const newSig = newHeaders.map((h) => `${h.level}:${h.id}`).join('|');
const oldSig = currentHeaders.map((h) => `${h.level}:${h.id}`).join('|');
const mdBodyChanged = mdBody !== currentMdBody;
const sigChanged = newSig !== oldSig;
console.log('[GMTOC] MO: mdBodyChanged:', mdBodyChanged, 'sigChanged:', sigChanged);
if (sigChanged || mdBodyChanged) {
debouncedUpdate();
}
} else if (sidebarEl) {
removeSidebar();
}
}, 500)
);
mo.observe(document.body, {
childList: true,
subtree: true,
});
}
/* ------------------------------------------------------------------ */
/* Settings */
/* ------------------------------------------------------------------ */
function loadSettings() {
return new Promise((resolve) => {
chrome.storage.sync.get(
{
[STORAGE_KEY_POSITION]: 'right',
[STORAGE_KEY_COLLAPSED]: false,
[STORAGE_KEY_MAX_LEVEL]: 4,
},
(result) => {
settings.position = result[STORAGE_KEY_POSITION] || 'right';
settings.collapsed = result[STORAGE_KEY_COLLAPSED] || false;
settings.maxLevel = result[STORAGE_KEY_MAX_LEVEL] || 3;
resolve();
}
);
});
}
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== 'sync') return;
let needsRebuild = false;
if (changes[STORAGE_KEY_POSITION]) {
settings.position = changes[STORAGE_KEY_POSITION].newValue;
needsRebuild = true;
}
if (changes[STORAGE_KEY_MAX_LEVEL]) {
settings.maxLevel = changes[STORAGE_KEY_MAX_LEVEL].newValue;
needsRebuild = true;
}
if (changes[STORAGE_KEY_COLLAPSED]) {
settings.collapsed = changes[STORAGE_KEY_COLLAPSED].newValue;
if (sidebarEl) {
sidebarEl.classList.toggle('gmtoc-collapsed', settings.collapsed);
const btn = sidebarEl.querySelector('.gmtoc-btn-collapse');
if (btn) btn.innerHTML = settings.collapsed ? ICONS.expand : ICONS.collapse;
}
}
if (needsRebuild) {
removeSidebar();
update();
}
});
/* ------------------------------------------------------------------ */
/* Init */
/* ------------------------------------------------------------------ */
async function init() {
await loadSettings();
update();
setupNavigationListener();
// Fallback: Wait for browser to complete initial layout then re-correct sidebar position
requestAnimationFrame(() => {
requestAnimationFrame(() => {
positionSidebar();
});
});
}
if (!window.__gmtocInitialized) {
window.__gmtocInitialized = true;
init();
}
})();