-
Notifications
You must be signed in to change notification settings - Fork 997
Expand file tree
/
Copy pathscript.js
More file actions
92 lines (68 loc) · 2.78 KB
/
Copy pathscript.js
File metadata and controls
92 lines (68 loc) · 2.78 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
window.onload = function() {
const toc = document.querySelector('.toc');
const tocPath = document.querySelector('.toc-marker path');
let tocItems = [];
const TOP_MARGIN = 0.1,
BOTTOM_MARGIN = 0.2;
let pathLength, lastPathStart, lastPathEnd;
window.addEventListener('resize', drawPath);
window.addEventListener('scroll', sync);
drawPath();
function drawPath() {
tocItems = Array.from(toc.querySelectorAll('li')).map(item => {
const anchor = item.querySelector('a');
const target = document.getElementById(anchor.getAttribute('href').slice(1));
return { listItem: item, anchor, target };
}).filter(item => item.target);
let path = [];
let pathIndent;
tocItems.forEach((item, i) => {
const x = item.anchor.offsetLeft - 5,
y = item.anchor.offsetTop,
height = item.anchor.offsetHeight;
if (i === 0) {
path.push(`M${x},${y}L${x},${y + height}`);
item.pathStart = 0;
} else {
if (pathIndent !== x) path.push(`L${pathIndent},${y}`);
path.push(`L${x},${y}`);
tocPath.setAttribute('d', path.join(' '));
item.pathStart = tocPath.getTotalLength() || 0;
path.push(`L${x},${y + height}`);
}
pathIndent = x;
tocPath.setAttribute('d', path.join(' '));
item.pathEnd = tocPath.getTotalLength();
});
pathLength = tocPath.getTotalLength();
sync();
}
function sync() {
const windowHeight = window.innerHeight;
let pathStart = pathLength,
pathEnd = 0,
visibleItems = 0;
tocItems.forEach(item => {
const { top, bottom } = item.target.getBoundingClientRect();
if (bottom > windowHeight * TOP_MARGIN && top < windowHeight * (1 - BOTTOM_MARGIN)) {
pathStart = Math.min(item.pathStart, pathStart);
pathEnd = Math.max(item.pathEnd, pathEnd);
visibleItems++;
item.listItem.classList.add('visible');
} else {
item.listItem.classList.remove('visible');
}
});
if (visibleItems > 0 && pathStart < pathEnd) {
if (pathStart !== lastPathStart || pathEnd !== lastPathEnd) {
tocPath.setAttribute('stroke-dashoffset', '1');
tocPath.setAttribute('stroke-dasharray', `1, ${pathStart}, ${pathEnd - pathStart}, ${pathLength}`);
tocPath.setAttribute('opacity', 1);
}
} else {
tocPath.setAttribute('opacity', 0);
}
lastPathStart = pathStart;
lastPathEnd = pathEnd;
}
};