All files / src/hooks useDocumentTop.ts

94.44% Statements 17/18
83.33% Branches 5/6
100% Functions 4/4
100% Lines 14/14

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                                    246x 246x   246x 65x 65x 49x 52x 52x   49x 49x 49x 49x 49x     246x    
import { useLayoutEffect, useRef, useState } from "react";
 
/**
 * How far below the top of the document an element starts, kept current.
 *
 * For a pane that runs from where it starts down to the bottom of the
 * window (`calc(100dvh - top)`): the chat sits under a page title whose
 * height depends on how it wraps, so no fixed offset fits every page.
 * Measured in a layout effect, so the first paint already uses it, then
 * again whenever the element resizes — the title above rewraps only when
 * the width changes, which resizes the element too. A change in the
 * window's height needs no measuring: `dvh` follows it. 0 until measured,
 * and wherever nothing lays out (jsdom).
 */
export function useDocumentTop<T extends HTMLElement>(): [
  React.RefObject<T>,
  number,
] {
  const ref = useRef<T>(null);
  const [top, setTop] = useState(0);
 
  useLayoutEffect(() => {
    const element = ref.current;
    if (!element) return;
    const measure = () => {
      const next = element.getBoundingClientRect().top + window.scrollY;
      if (Number.isFinite(next)) setTop(Math.round(next));
    };
    measure();
    Iif (typeof ResizeObserver !== "function") return;
    const observer = new ResizeObserver(measure);
    observer.observe(element);
    return () => observer.disconnect();
  }, []);
 
  return [ref, top];
}