Debian Codegraph @

docs/assets/js/alpinejs/data/toc.js

raw
1 var debug = 0 ? console.log.bind(console, '[toc]') : function () {};
2
3 export const toc = (Alpine) => ({
4 contentScrollSpy: null,
5 activeHeading: '',
6 justClicked: false,
7
8 setActive(id) {
9 debug('setActive', id);
10 this.activeHeading = id;
11 // Prevent the intersection observer from changing the active heading right away.
12 this.justClicked = true;
13 setTimeout(() => {
14 this.justClicked = false;
15 }, 200);
16 },
17
18 init() {
19 this.$watch('$store.nav.scroll.atTop', (value) => {
20 if (!value) return;
21 this.activeHeading = '';
22 this.$root.scrollTop = 0;
23 });
24
25 return this.$nextTick(() => {
26 let contentEl = document.getElementById('article');
27 if (contentEl) {
28 const handleIntersect = (entries) => {
29 if (this.justClicked) {
30 return;
31 }
32 for (let entry of entries) {
33 if (entry.isIntersecting) {
34 let id = entry.target.id;
35 this.activeHeading = id;
36 let liEl = this.$refs[id];
37 if (liEl) {
38 // If liEl is not in the viewport, scroll it into view.
39 let bounding = liEl.getBoundingClientRect();
40 if (bounding.top < 0 || bounding.bottom > window.innerHeight) {
41 this.$root.scrollTop = liEl.offsetTop - 100;
42 }
43 }
44 debug('intersecting', id);
45 break;
46 }
47 }
48 };
49
50 let opts = {
51 rootMargin: '0px 0px -75%',
52 threshold: 0.75,
53 };
54
55 this.contentScrollSpy = new IntersectionObserver(handleIntersect, opts);
56 // Observe all headings.
57 let headings = contentEl.querySelectorAll('h2, h3, h4, h5, h6');
58 for (let heading of headings) {
59 this.contentScrollSpy.observe(heading);
60 }
61 }
62 });
63 },
64
65 destroy() {
66 if (this.contentScrollSpy) {
67 debug('disconnecting');
68 this.contentScrollSpy.disconnect();
69 }
70 },
71 });