Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
7.6 KB
Raw Blame
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { collectTextMatches, useInPageFind } from "./use-in-page-find";

function makeRoot(html: string): HTMLElement {
  const root = document.createElement("div");
  root.innerHTML = html;
  return root;
}

describe("collectTextMatches", () => {
  it("returns nothing for an empty query", () => {
    expect(collectTextMatches(makeRoot("<p>hello</p>"), "")).toEqual([]);
  });

  it("returns nothing when the query is not present", () => {
    expect(collectTextMatches(makeRoot("<p>hello</p>"), "zzz")).toEqual([]);
  });

  it("finds a case-insensitive match with node offsets", () => {
    const matches = collectTextMatches(makeRoot("<p>Hello World</p>"), "world");
    expect(matches).toHaveLength(1);
    expect(matches[0]!.node.nodeValue).toBe("Hello World");
    expect(matches[0]!.start).toBe(6);
    expect(matches[0]!.end).toBe(11);
  });

  it("finds every non-overlapping occurrence in one node, in order", () => {
    const matches = collectTextMatches(makeRoot("<p>ababab</p>"), "ab");
    expect(matches.map((m) => m.start)).toEqual([0, 2, 4]);
  });

  it("does not overlap on repeated characters", () => {
    const matches = collectTextMatches(makeRoot("<p>aaaa</p>"), "aa");
    expect(matches.map((m) => m.start)).toEqual([0, 2]);
  });

  it("matches inside separate text nodes but never across an element boundary", () => {
    // Text nodes: "foo ", "bar", " foobar". "foo" hits the first and third,
    // and the "bar" split across <strong> is never joined into a match.
    const root = makeRoot("<p>foo <strong>bar</strong> foobar</p>");
    const matches = collectTextMatches(root, "foo");
    expect(matches).toHaveLength(2);
    expect(collectTextMatches(root, "foobar")).toHaveLength(1);
  });

  it("skips <script> and <style> text", () => {
    const root = makeRoot(
      "<style>needle{}</style><script>needle</script><p>needle</p>",
    );
    const matches = collectTextMatches(root, "needle");
    expect(matches).toHaveLength(1);
    expect(matches[0]!.node.parentElement?.tagName).toBe("P");
  });

  it("skips subtrees marked data-find-ignore (e.g. the find bar itself)", () => {
    const root = makeRoot(
      '<div data-find-ignore><span>needle</span></div><p>needle</p>',
    );
    const matches = collectTextMatches(root, "needle");
    expect(matches).toHaveLength(1);
    expect(matches[0]!.node.parentElement?.tagName).toBe("P");
  });
});

// jsdom implements neither `CSS.highlights` nor `Highlight`, so the hook runs
// here exactly as it would on a browser without the CSS Custom Highlight API.
// This is the regression from the review: counting and prev/next navigation
// must keep working even though nothing gets painted.
describe("useInPageFind without the CSS Custom Highlight API", () => {
  let container: HTMLElement;

  beforeEach(() => {
    container = document.createElement("div");
    container.innerHTML = "<h1>Find me</h1><p>find me twice: find</p>";
    document.body.appendChild(container);
  });

  afterEach(() => {
    container.remove();
  });

  // Flush the rAF-deferred recompute(s) the open/content effects schedule.
  async function flushFrames(count = 3): Promise<void> {
    for (let i = 0; i < count; i++) {
      await act(
        () =>
          new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),
      );
    }
  }

  it("counts matches and steps through them when highlighting is unavailable", async () => {
    const { result } = renderHook(() =>
      useInPageFind({ container, contentKey: 0 }),
    );

    expect(result.current.supported).toBe(false);

    act(() => {
      result.current.openFind();
      result.current.setQuery("find");
    });
    await flushFrames();

    // "find" appears once in the heading and twice in the paragraph.
    expect(result.current.matchCount).toBe(3);
    expect(result.current.activeIndex).toBe(0);

    act(() => result.current.goNext());
    expect(result.current.activeIndex).toBe(1);

    act(() => result.current.goPrev());
    act(() => result.current.goPrev());
    expect(result.current.activeIndex).toBe(2); // wraps past the start

    act(() => result.current.setQuery("absent"));
    await flushFrames();
    expect(result.current.matchCount).toBe(0);
    expect(result.current.activeIndex).toBe(-1);
  });
});

// The virtualized timeline: units are counted from their text, and only the
// ones in the DOM are painted. Stepping to an unmounted one asks the host to
// mount it.
describe("useInPageFind with virtual content", () => {
  let container: HTMLElement;
  let virtualRoot: HTMLElement;

  beforeEach(() => {
    container = document.createElement("div");
    container.innerHTML = [
      "<h1>Find before</h1>",
      '<div id="timeline"><span>find in an activity line</span><p data-find-unit="mounted">find twice: find</p></div>',
      "<footer>find after</footer>",
    ].join("");
    document.body.appendChild(container);
    virtualRoot = container.querySelector<HTMLElement>("#timeline")!;
  });

  afterEach(() => {
    container.remove();
  });

  async function flushFrames(count = 3): Promise<void> {
    for (let i = 0; i < count; i++) {
      await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
    }
  }

  it("counts units from data in reading order and mounts the one stepped to", async () => {
    const units = [
      { key: "unmounted", text: "find me once" },
      { key: "mounted", text: "find twice: find" },
    ];
    const getUnits = () => units;
    const reveal = vi.fn((unit: { key: string }, done: () => void) => {
      const el = document.createElement("p");
      el.setAttribute("data-find-unit", unit.key);
      el.textContent = "find me once";
      virtualRoot.prepend(el);
      done();
      return () => {};
    });
    const { result } = renderHook(() =>
      useInPageFind({
        container,
        contentKey: 0,
        virtual: { root: () => virtualRoot, units: getUnits, reveal },
      }),
    );

    act(() => {
      result.current.openFind();
      result.current.setQuery("find");
    });
    await flushFrames();

    // Heading, both units' occurrences, footer. The activity line inside the
    // timeline is not a unit, so it is not counted.
    expect(result.current.matchCount).toBe(5);
    expect(result.current.activeIndex).toBe(0);
    expect(reveal).not.toHaveBeenCalled();

    act(() => result.current.goNext());
    expect(reveal).toHaveBeenCalledTimes(1);
    expect(reveal.mock.calls[0]![0]).toMatchObject({ key: "unmounted" });
    await flushFrames();
    expect(result.current.matchCount).toBe(5);
    expect(result.current.activeIndex).toBe(1);

    // Already mounted: no reveal.
    act(() => result.current.goNext());
    expect(result.current.activeIndex).toBe(2);
    expect(reveal).toHaveBeenCalledTimes(1);
  });

  it("mounts an unmounted first match once typing pauses, not per keystroke", async () => {
    const units = [{ key: "unmounted", text: "only here: needle" }];
    const getUnits = () => units;
    const reveal = vi.fn(() => () => {});
    const { result } = renderHook(() =>
      useInPageFind({
        container,
        contentKey: 0,
        virtual: { root: () => virtualRoot, units: getUnits, reveal },
      }),
    );

    act(() => result.current.openFind());
    for (const query of ["ne", "nee", "need", "needl", "needle"]) {
      act(() => result.current.setQuery(query));
      await flushFrames(1);
    }
    await flushFrames();
    expect(result.current.matchCount).toBe(1);
    expect(reveal).not.toHaveBeenCalled();

    await act(() => new Promise<void>((resolve) => setTimeout(resolve, 200)));
    expect(reveal).toHaveBeenCalledTimes(1);
  });
});