Skip to content

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

4.0 KB
Raw Blame
// @vitest-environment happy-dom
import { act, createElement, useLayoutEffect, useRef } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { settleNearScreen, useNearScreen } from "./on-screen";

(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

class FakeObserver {
  static last: FakeObserver | undefined;
  watched = new Set<Element>();
  constructor(
    public report: (changes: { target: Element; isIntersecting: boolean }[]) => void,
    public options?: IntersectionObserverInit,
  ) {
    FakeObserver.last = this;
  }
  observe(target: Element) { this.watched.add(target); }
  unobserve(target: Element) { this.watched.delete(target); }
}

function Probe() {
  const ref = useRef<HTMLDivElement>(null);
  return createElement("div", { ref, "data-near": String(useNearScreen(ref)) });
}

let host: HTMLDivElement;
let root: Root;
const near = () => (host.firstElementChild as HTMLElement).dataset.near;

beforeEach(() => {
  vi.stubGlobal("IntersectionObserver", FakeObserver);
  host = document.createElement("div");
  document.body.append(host);
  root = createRoot(host);
});

afterEach(() => {
  act(() => root.unmount());
  host.remove();
  vi.unstubAllGlobals();
});

describe("useNearScreen", () => {
  it("is false until the element comes near, then stays true and stops watching", () => {
    act(() => root.render(createElement(Probe)));
    const watcher = FakeObserver.last!;
    const element = host.firstElementChild!;
    expect([...watcher.watched]).toEqual([element]);
    expect(watcher.options).toMatchObject({ rootMargin: "800px 0px", scrollMargin: "800px 0px" });
    act(() => watcher.report([{ target: element, isIntersecting: false }]));
    expect(near()).toBe("false");
    act(() => watcher.report([{ target: element, isIntersecting: true }]));
    expect(near()).toBe("true");
    expect(watcher.watched.size).toBe(0);
  });

  it("is true at once where the browser cannot tell", () => {
    vi.stubGlobal("IntersectionObserver", undefined);
    act(() => root.render(createElement(Probe)));
    expect(near()).toBe("true");
  });
});

/** A scroller as the chat's: it puts its scroll position in place, then answers what asked before the paint. */
function Scroller({ top, seen }: { top: number; seen: string[] }) {
  return createElement(Settles, null, createElement(Asking, { top, seen }));
}
function Settles({ children }: { children: unknown }) {
  useLayoutEffect(() => settleNearScreen());
  return createElement("div", null, children as never);
}
function Asking({ top, seen }: { top: number; seen: string[] }) {
  const ref = useRef<HTMLDivElement>(null);
  const near = useNearScreen(ref, true);
  // What each commit would paint.
  useLayoutEffect(() => { seen.push(String(near)); });
  return createElement("div", { ref, "data-near": String(near), "data-top": top });
}

describe("settleNearScreen", () => {
  beforeEach(() => {
    vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
      const top = Number(this.dataset.top ?? 0);
      return { top, bottom: top + 100, left: 0, right: 300, width: 300, height: 100, x: 0, y: top, toJSON() {} } as DOMRect;
    });
  });
  afterEach(() => vi.restoreAllMocks());

  it("tells a block that asked before paint that it is near in the commit that mounted it, with no observer report", () => {
    const seen: string[] = [];
    act(() => root.render(createElement(Scroller, { top: 200, seen })));
    // The commit that mounted it was answered before its paint: the next commit (still before the paint) draws it near.
    expect(seen).toEqual(["false", "true"]);
    expect(host.querySelector<HTMLElement>("[data-near]")!.dataset.near).toBe("true");
  });

  it("leaves a block far below the screen to the observer", () => {
    const seen: string[] = [];
    act(() => root.render(createElement(Scroller, { top: innerHeight + 2_000, seen })));
    expect(seen).toEqual(["false"]);
    expect([...FakeObserver.last!.watched]).toHaveLength(1);
  });
});