Skip to content

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

4.8 KB
Raw Blame
import { useLayoutEffect, type RefObject } from "react";

export const BOTTOM_FOLLOW_THRESHOLD = 4;

interface BottomFollowScroller {
  scrollHeight: number;
  scrollTop?: number;
  clientHeight?: number;
  scrollTo(options?: ScrollToOptions): void;
}
type ChaseScroller = BottomFollowScroller & { scrollTop: number; clientHeight: number };

interface Chase {
  raf: number;
  /** Where the chase has got to, unrounded: a scroller that snaps scrollTop to device pixels would stall a chase that read it back. */
  pos: number;
  /** scrollTop as last read after the chase's own write; anything else moving it ends the chase. */
  seen: number;
  lastTime: number;
  frames: number;
}

const chases = new WeakMap<BottomFollowScroller, Chase>();
/** Per second: about half the gap closes in a 16 ms frame. */
const CHASE_RATE = 40;
/** A chase that has not arrived this many frames after the last growth (two seconds at 60 Hz) lands at once. */
const MAX_CHASE_FRAMES = 120;
/** Growth past this share of the view lands at once instead of a long glide. */
const SNAP_SHARE = 0.75;

const devicePixel = () => 1 / (typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1);
const bottomOf = (scroller: ChaseScroller) => Math.max(0, scroller.scrollHeight - scroller.clientHeight);

/** Ends `scroller`'s glide toward the bottom at once, where it is (the reader took over, or the view jumped). */
export function haltBottomChase(scroller: BottomFollowScroller | null | undefined): void {
  const active = scroller && chases.get(scroller);
  if (!active) return;
  cancelAnimationFrame(active.raf);
  chases.delete(scroller);
}

function canChase(scroller: BottomFollowScroller): scroller is ChaseScroller {
  return typeof requestAnimationFrame === "function" && typeof scroller.scrollTop === "number" && typeof scroller.clientHeight === "number" && scroller.clientHeight > 0;
}

function land(scroller: BottomFollowScroller): void {
  haltBottomChase(scroller);
  scroller.scrollTo({ top: scroller.scrollHeight });
}

function step(scroller: ChaseScroller, chase: Chase, now: number): void {
  const top = scroller.scrollTop;
  if (Math.abs(top - chase.seen) > 1) {
    chases.delete(scroller);
    return;
  }
  const target = bottomOf(scroller);
  const remaining = target - chase.pos;
  const pixel = devicePixel();
  if (remaining <= pixel / 2 || chase.frames >= MAX_CHASE_FRAMES || remaining > scroller.clientHeight * SNAP_SHARE) return land(scroller);
  const dt = Math.min(Math.max(now - chase.lastTime, 4), 64) / 1000;
  chase.lastTime = now;
  chase.frames += 1;
  chase.pos = Math.min(target, chase.pos + Math.max(remaining * (1 - Math.exp(-CHASE_RATE * dt)), pixel));
  scroller.scrollTop = chase.pos;
  const after = scroller.scrollTop;
  if (after === top || chase.pos >= target) return land(scroller);
  chase.seen = after;
  chase.raf = requestAnimationFrame((time) => step(scroller, chase, time));
}

/** Keeps a following transcript at its end as it grows: at once, or, with `smooth` (a reply streaming in), by a glide
 * that closes most of the gap each frame and stops when it arrives, when the scroller stops moving, or when anything
 * else moves it. Returns whether it followed. */
export function followBottomGrowth(scroller: BottomFollowScroller, following: boolean, smooth = false): boolean {
  if (!following) {
    haltBottomChase(scroller);
    return false;
  }
  if (!smooth) {
    land(scroller);
    return true;
  }
  if (!canChase(scroller)) {
    scroller.scrollTo({ top: scroller.scrollHeight, behavior: "smooth" });
    return true;
  }
  const active = chases.get(scroller);
  const gap = bottomOf(scroller) - (active?.pos ?? scroller.scrollTop);
  if (gap > scroller.clientHeight * SNAP_SHARE) {
    land(scroller);
    return true;
  }
  if (active) active.frames = 0;
  if (gap <= devicePixel() / 2 || active) return true;
  const chase: Chase = { raf: 0, pos: scroller.scrollTop, seen: scroller.scrollTop, lastTime: performance.now(), frames: 0 };
  chases.set(scroller, chase);
  chase.raf = requestAnimationFrame((time) => step(scroller, chase, time));
  return true;
}

/** Calls `onResize` whenever the transcript's content changes size: a reply growing inside its last row included. */
export function useBottomFollowResize(
  scrollRef: RefObject<HTMLElement | null>,
  transcriptRef: RefObject<HTMLElement | null>,
  observeKey: string | null,
  onResize: () => void,
): void {
  useLayoutEffect(() => {
    const scroller = scrollRef.current;
    const transcript = transcriptRef.current;
    if (!scroller || !transcript || observeKey === null) return;

    const observer = new ResizeObserver(onResize);
    observer.observe(transcript);
    return () => {
      haltBottomChase(scroller);
      observer.disconnect();
    };
  }, [observeKey, onResize, scrollRef, transcriptRef]);
}