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