a tool for shared writing and social publishing
1export function scrollIntoViewIfNeeded(
2 el: Element | null,
3 centerIfNeeded: boolean = true,
4 behavior?: ScrollBehavior,
5 threshold: number = 1,
6) {
7 if (!el) {
8 return;
9 }
10 let observer = new IntersectionObserver(
11 function ([entry]) {
12 const ratio = entry.intersectionRatio;
13
14 if (ratio < threshold) {
15 let place =
16 ratio <= 0 && centerIfNeeded
17 ? ("center" as const)
18 : ("nearest" as const);
19 el.scrollIntoView({
20 block: place,
21 inline: place,
22 behavior: behavior ? behavior : "auto",
23 });
24 }
25 observer.disconnect();
26 },
27 { threshold: [0, threshold] },
28 );
29 observer.observe(el);
30}