Open History to see the last commit
1import { observeResize } from "~/lib/observeResize";
2
3const USER_SCROLL_INTENT = ["wheel", "touchstart", "pointerdown", "keydown"] as const;
4
5/**
6 * Keeps a linked node `offset()` below the scroller's top while the content around it opens and
7 * its markdown loads, until the user scrolls, the node leaves, or the returned stop runs. Only the
8 * scroller moves; scrollIntoView would also scroll the panel's clipped ancestors.
9 */
10export function holdLinkedNodeInView(
11 node: HTMLElement,
12 scroller: HTMLElement,
13 offset: () => number,
14): () => void {
15 const controller = new AbortController();
16 const stop = () => {
17 unobserve();
18 controller.abort();
19 };
20 const align = () => {
21 if (!node.isConnected) return stop();
22 scroller.scrollTop +=
23 node.getBoundingClientRect().top - scroller.getBoundingClientRect().top - offset();
24 };
25 const unobserve = observeResize([...scroller.children], align);
26 for (const type of USER_SCROLL_INTENT) {
27 scroller.addEventListener(type, stop, { passive: true, signal: controller.signal });
28 }
29 align();
30 // Activity can load after the click; by then the user may be typing elsewhere.
31 const active = document.activeElement;
32 if (
33 !(active instanceof HTMLElement) ||
34 !(active.isContentEditable || active.matches("input, textarea, select"))
35 ) {
36 node.focus({ preventScroll: true });
37 }
38 return stop;
39}