Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 18x 18x 4x 4x 4x 4x 4x 4x 4x 4x 4x 44x 4x 2x 2x 6x 6x 2x 2x 2x 4x 4x 4x 2x 2x 2x 1x 1x 1x 1x 4x 4x 4x 2x 2x 2x 1x 1x 4x 4x 4x 4x 12x | import { useEffect, useRef, useState, HTMLAttributes } from 'react';
import { Link, useHistory } from 'react-router-dom';
import { sleep, schedule, frame } from 'timing-functions';
import cn from 'classnames';
import '../styles/components/in-page-nav.scss';
const GRANULARITY = 11;
type Props = {
sections: Array<{
id: string;
label: string;
disabled?: boolean;
}>;
rootElement?: string | HTMLElement;
};
const InPageNav = ({
sections,
rootElement,
...props
}: Props & HTMLAttributes<HTMLUListElement>) => {
const history = useHistory();
const [active, setActive] = useState(sections[0].id);
const marker = useRef<HTMLDivElement>(null);
const firstMarkerRender = useRef(true);
// effect to connect user changes in scroll to browser history
useEffect(() => {
// get elements to watch from configured sections
let elements: HTMLElement[] = [];
// Intersection Observer to watch when sections appear/disappear
Iif (!('IntersectionObserver' in window)) {
// 🤷🏽♂️ too bad...
return;
}
const visibilityMap = new Map();
const io = new window.IntersectionObserver(
(entries) => {
for (const entry of entries) {
// update the visibility map
visibilityMap.set(entry.target, {
height: entry.intersectionRect.height,
ratio: entry.intersectionRatio,
});
}
let mostVisible;
let highestVisibility = 0;
for (const [element, { height, ratio }] of visibilityMap.entries()) {
// find the most visible element
if (highestVisibility < height) {
highestVisibility = height;
mostVisible = element;
}
// stop at the first element completely visible
// might happen when you have small sections
if (ratio === 1) {
break;
}
}
if (mostVisible) {
setActive(mostVisible.id);
}
},
{
threshold: Array.from({ length: GRANULARITY }).map(
(_, i) => i / (GRANULARITY - 1)
),
}
);
// sleep, to give the rest of the page a chance to start loading
// schedule, to trigger only when the page has finished doing work
// hopefully by then all the components are loaded
sleep(250)
.then(() => schedule(1000))
.then(() => {
// get elements to watch from configured sections
elements = sections
.map(({ id }) => document.querySelector<HTMLElement>(`#${id}`))
.filter((x: null | HTMLElement): x is HTMLElement => Boolean(x));
for (const element of elements) {
io.observe(element);
visibilityMap.set(element, 0);
}
});
// eslint-disable-next-line consistent-return
return () => elements.forEach((element) => io.unobserve(element));
}, [sections, history]);
// listen for changes in location hash to move corresponding element into view
useEffect(() => {
const unlisten = history.listen((location) =>
frame().then(() => {
const id = location.hash.replace('#', '');
if (id) {
document.getElementById(id)?.scrollIntoView();
} else if (rootElement) {
const element =
typeof rootElement === 'string'
? document.querySelector(rootElement)
: rootElement;
element?.scrollTo({ top: 0 });
}
})
);
return unlisten;
}, [history, rootElement]);
// move element into view on mount
useEffect(() => {
// sleep, to give the rest of the page a chance to start loading
// schedule, to trigger only when the page has finished doing work
// hopefully by then all the components are loaded and in their right space
sleep(500)
.then(() => schedule(1000))
.then(() => {
const id = history.location.hash.replace('#', '');
if (!id) {
// no id to navigate to
return;
}
document.getElementById(id)?.scrollIntoView();
});
}, [history]); // history won't change, unlike location
// move active marker
useEffect(() => {
// don't display an active marker if browser support is bad
if (
!(
marker.current &&
'animate' in marker.current &&
'IntersectionObserver' in window
)
) {
return;
}
const target = marker.current?.parentElement?.querySelector('.active');
if (!target) {
return;
}
// get measurements
const containerRect =
marker.current?.parentElement?.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const currentMarkerRec = marker.current.getBoundingClientRect();
if (!containerRect) {
return;
}
marker.current.style.display = 'block';
marker.current.animate(
{
transform: [
`translateY(${currentMarkerRec.y - containerRect.y}px) scaleY(${
currentMarkerRec.height
})`,
`translateY(${targetRect.y - containerRect.y}px) scaleY(${
targetRect.height
})`,
],
},
{
duration: firstMarkerRender.current ? 0 : 250,
// easing: 'cubic-bezier(.5,0,.35,1.25)', // overshoot
easing: 'linear',
fill: 'both',
}
);
firstMarkerRender.current = false;
}, [active]);
return (
<ul className="in-page-nav" {...props}>
<div ref={marker} className="marker" />
{sections.map(({ id, label, disabled }) => (
<li key={label} className={cn({ disabled })}>
<Link to={`#${id}`} className={cn({ active: active === id })}>
{label}
</Link>
</li>
))}
</ul>
);
};
export default InPageNav;
|