Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

4.1 KB
Raw Blame
import { useEffect, useLayoutEffect, useState, type RefObject } from "react";

// One observer per margin, each with its own elements, so an element can be watched at two margins at once.
const observers = new Map<number, { observer: IntersectionObserver; watchers: Map<Element, (onScreen: boolean) => void> }>();

function watch(element: Element, onChange: (onScreen: boolean) => void, margin = 0): () => void {
  let watching = observers.get(margin);
  if (!watching) {
    const watchers = new Map<Element, (onScreen: boolean) => void>();
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) watchers.get(entry.target)?.(entry.isIntersecting);
      },
      // scrollMargin carries the margin into scrolling boxes (like the chat's), not only the window.
      margin ? ({ rootMargin: `${margin}px 0px`, scrollMargin: `${margin}px 0px` } as IntersectionObserverInit) : undefined,
    );
    watching = { observer, watchers };
    observers.set(margin, watching);
  }
  const { observer, watchers } = watching;
  watchers.set(element, onChange);
  observer.observe(element);
  return () => {
    watchers.delete(element);
    observer.unobserve(element);
  };
}

/** Whether the element is on screen: false until the browser says so, true where it cannot tell. */
export function useOnScreen(ref: RefObject<Element | null>): boolean {
  const [onScreen, setOnScreen] = useState(false);
  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    if (typeof IntersectionObserver === "undefined") return setOnScreen(true);
    return watch(element, setOnScreen);
  }, [ref]);
  return onScreen;
}

const NEAR_SCREEN_MARGIN = 800;

/** Elements waiting to be told, before the paint, whether they mount near the screen (see `settleNearScreen`). */
const askedBeforePaint = new Map<Element, () => void>();

/** Whether `element` is within `margin` of the screen now, clipped by the boxes it scrolls in, as the observer counts. */
function nearScreenNow(element: Element, margin: number): boolean {
  const box = element.getBoundingClientRect();
  if (box.width === 0 && box.height === 0) return false;
  let top = -margin, bottom = window.innerHeight + margin;
  for (let parent = element.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
    const overflow = getComputedStyle(parent).overflowY;
    if (overflow !== "auto" && overflow !== "scroll") continue;
    const frame = parent.getBoundingClientRect();
    top = Math.max(top, frame.top - margin);
    bottom = Math.min(bottom, frame.bottom + margin);
  }
  return box.bottom >= top && box.top <= bottom;
}

/**
 * Answers, in the commit that mounted them, the elements that asked before paint whether they are near the screen.
 * Called by a scroller from a layout effect once it has put its scroll position in place, so a block drawn in a chat's
 * first frame is coloured in that frame instead of one frame later, when the observer would report.
 */
export function settleNearScreen(): void {
  if (askedBeforePaint.size === 0) return;
  const asked = [...askedBeforePaint];
  askedBeforePaint.clear();
  for (const [element, near] of asked) if (nearScreenNow(element, NEAR_SCREEN_MARGIN)) near();
}

/**
 * Stays true once the element has come near the screen; true at once where the browser has no IntersectionObserver.
 * `beforePaint`: the element has something ready to draw once near (a cached colouring), so it also asks the scroller
 * that mounts it (`settleNearScreen`) before the first paint.
 */
export function useNearScreen(ref: RefObject<Element | null>, beforePaint = false): boolean {
  const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined");
  useLayoutEffect(() => {
    const element = ref.current;
    if (near || !beforePaint || !element) return;
    askedBeforePaint.set(element, () => setNear(true));
    return () => {
      askedBeforePaint.delete(element);
    };
  }, [ref, near, beforePaint]);
  useEffect(() => {
    const element = ref.current;
    if (near || !element) return;
    return watch(element, (nearNow) => nearNow && setNear(true), NEAR_SCREEN_MARGIN);
  }, [ref, near]);
  return near;
}