Open History to see the last commit
1import { act } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4import { collectThreadFindRanges, useThreadFindHighlights } from "./threadFindHighlights";
5
6function Probe(props: Parameters<typeof useThreadFindHighlights>[0]) {
7 useThreadFindHighlights(props);
8 return null;
9}
10
11let root: Root;
12let host: HTMLElement;
13let container: HTMLElement;
14const onActiveRange = vi.fn();
15const activeRanges = () => [
16 ...(CSS.highlights.get("t3-thread-find-active") as unknown as Set<Range>),
17];
18
19beforeEach(() => {
20 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
21 vi.stubGlobal("CSS", { highlights: new Map() });
22 vi.stubGlobal(
23 "Highlight",
24 class extends Set<Range> {
25 constructor(...ranges: Range[]) {
26 super(ranges);
27 }
28 },
29 );
30 host = document.createElement("div");
31 container = document.createElement("div");
32 container.innerHTML =
33 '<div data-timeline-row-id="first"><p data-thread-find-text>COD4 and COD4</p></div>' +
34 '<div data-timeline-row-id="second"><p data-thread-find-text>COD4</p></div>';
35 document.body.append(host, container);
36 root = createRoot(host);
37});
38afterEach(async () => {
39 await act(async () => root.unmount());
40 host.remove();
41 container.remove();
42 vi.restoreAllMocks();
43 vi.clearAllMocks();
44 vi.unstubAllGlobals();
45});
46
47describe("find highlight caching", () => {
48 it("checks only the old and new occurrence when cycling a message with many clipped matches", async () => {
49 container.innerHTML =
50 '<div data-timeline-row-id="first"><div data-thread-find-fold><p data-thread-find-text>' +
51 "COD4 ".repeat(1500) +
52 "</p></div></div>";
53 const bounds = vi.fn(() => new DOMRect(0, 0, 40, 20));
54 Object.defineProperty(Range.prototype, "getBoundingClientRect", {
55 configurable: true,
56 value: bounds,
57 });
58 container.querySelector<HTMLElement>("[data-thread-find-fold]")!.getBoundingClientRect = () =>
59 new DOMRect(0, 0, 800, 100);
60 const props = {
61 container,
62 query: "COD4",
63 activeRowId: "first",
64 activeOccurrence: 0,
65 onActiveRange,
66 };
67 try {
68 await act(async () => root.render(<Probe {...props} />));
69 const inactive = CSS.highlights.get("t3-thread-find");
70 const first = activeRanges()[0];
71 bounds.mockClear();
72 await act(async () => root.render(<Probe {...props} activeOccurrence={1} />));
73 expect(bounds).toHaveBeenCalledTimes(2);
74 expect(CSS.highlights.get("t3-thread-find")).toBe(inactive);
75 expect(inactive?.size).toBe(1499);
76 expect(inactive?.has(first!)).toBe(true);
77 expect(activeRanges()[0]?.startOffset).toBe(5);
78 expect(inactive?.has(activeRanges()[0]!)).toBe(false);
79 } finally {
80 Reflect.deleteProperty(Range.prototype, "getBoundingClientRect");
81 }
82 });
83
84 it("repaints for searchable text changes but not for timers outside it", async () => {
85 const timer = document.createElement("span");
86 container.firstElementChild!.append(timer);
87 await act(async () =>
88 root.render(
89 <Probe
90 container={container}
91 query="COD4"
92 activeRowId="first"
93 activeOccurrence={0}
94 onActiveRange={onActiveRange}
95 />,
96 ),
97 );
98 onActiveRange.mockClear();
99 await act(async () => {
100 timer.textContent = "0:01";
101 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
102 });
103 expect(onActiveRange).not.toHaveBeenCalled();
104 await act(async () => {
105 container.querySelector("p")!.append(" COD4");
106 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
107 });
108 expect(onActiveRange).toHaveBeenCalled();
109 });
110
111 it("opens only the selected fold while reusing its cached text", async () => {
112 container.innerHTML =
113 '<div data-timeline-row-id="first"><div hidden><p data-thread-find-text>COD4 COD4</p></div></div>' +
114 '<div data-timeline-row-id="second"><div hidden><p data-thread-find-text>COD4</p></div></div>';
115 const folds = [...container.querySelectorAll<HTMLElement>("[hidden]")];
116 for (const fold of folds)
117 fold.addEventListener("beforematch", () => fold.removeAttribute("hidden"));
118 const createRange = vi.spyOn(document, "createRange");
119 await act(async () =>
120 root.render(
121 <Probe
122 container={container}
123 query="COD4"
124 activeRowId="first"
125 activeOccurrence={0}
126 onActiveRange={onActiveRange}
127 />,
128 ),
129 );
130 await act(async () => {
131 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
132 });
133 expect(folds[0]?.hasAttribute("hidden")).toBe(false);
134 expect(folds[1]?.hasAttribute("hidden")).toBe(true);
135 expect(activeRanges()[0]?.toString()).toBe("COD4");
136 expect(CSS.highlights.get("t3-thread-find")?.size).toBe(1);
137 const scanned = createRange.mock.calls.length;
138 await act(async () =>
139 root.render(
140 <Probe
141 container={container}
142 query="COD4"
143 activeRowId="first"
144 activeOccurrence={1}
145 onActiveRange={onActiveRange}
146 />,
147 ),
148 );
149 expect(createRange).toHaveBeenCalledTimes(scanned);
150 expect(activeRanges()[0]?.startOffset).toBe(5);
151 });
152
153 it("observes rows mounted synchronously while revealing the first match", async () => {
154 container.replaceChildren();
155 onActiveRange.mockImplementationOnce(() => {
156 container.innerHTML =
157 '<div data-timeline-row-id="first"><p data-thread-find-text>COD4</p></div>';
158 });
159 await act(async () => {
160 root.render(
161 <Probe
162 container={container}
163 query="COD4"
164 activeRowId="first"
165 activeOccurrence={0}
166 onActiveRange={onActiveRange}
167 />,
168 );
169 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
170 });
171 await act(async () => {
172 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
173 });
174 expect(activeRanges()[0]?.toString()).toBe("COD4");
175 });
176
177 it("rebuilds ranges when the list moves or recycles an existing row", async () => {
178 const props = {
179 container,
180 query: "COD4",
181 activeRowId: "first",
182 activeOccurrence: 0,
183 onActiveRange,
184 };
185 await act(async () => root.render(<Probe {...props} />));
186 const initial = activeRanges()[0];
187 const row = container.querySelector<HTMLElement>('[data-timeline-row-id="first"]')!;
188 await act(async () => {
189 row.remove();
190 container.append(row);
191 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
192 });
193 expect(activeRanges()[0]).not.toBe(initial);
194 expect(activeRanges()[0]?.toString()).toBe("COD4");
195 await act(async () => {
196 row.dataset.timelineRowId = "recycled";
197 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
198 });
199 expect(activeRanges()).toHaveLength(0);
200 await act(async () => root.render(<Probe {...props} activeRowId="recycled" />));
201 expect(activeRanges()[0]?.toString()).toBe("COD4");
202 });
203
204 it("reuses unchanged text ranges on navigation and scans only the streaming row", async () => {
205 const createRange = vi.spyOn(document, "createRange");
206 const props = {
207 container,
208 query: "COD4",
209 activeRowId: "first",
210 activeOccurrence: 0,
211 onActiveRange,
212 };
213 await act(async () => root.render(<Probe {...props} />));
214 expect(createRange).toHaveBeenCalledTimes(3);
215 const initial = activeRanges()[0];
216 await act(async () => root.render(<Probe {...props} activeOccurrence={1} />));
217 expect(createRange).toHaveBeenCalledTimes(3);
218 expect(activeRanges()[0]?.startOffset).toBe(9);
219 await act(async () => root.render(<Probe {...props} />));
220 expect(activeRanges()[0]).toBe(initial);
221 await act(async () => {
222 container.querySelector('[data-timeline-row-id="second"] p')!.firstChild!.nodeValue =
223 "COD4 COD4";
224 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
225 });
226 expect(createRange).toHaveBeenCalledTimes(5);
227 expect(activeRanges()[0]).toBe(initial);
228 await act(async () =>
229 root.render(<Probe {...props} activeRowId="second" activeOccurrence={1} />),
230 );
231 expect(createRange).toHaveBeenCalledTimes(5);
232 expect(activeRanges()[0]?.toString()).toBe("COD4");
233 expect(activeRanges()[0]?.startOffset).toBe(5);
234 await act(async () => {
235 container.querySelector('[data-timeline-row-id="second"]')!.remove();
236 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
237 });
238 expect(activeRanges()).toHaveLength(0);
239 expect(onActiveRange).toHaveBeenLastCalledWith(null);
240 expect(CSS.highlights.get("t3-thread-find")?.size).toBe(2);
241 await act(async () => root.render(<Probe {...props} query="missing" />));
242 expect(CSS.highlights.get("t3-thread-find")?.size).toBe(0);
243 });
244});
245
246function row(html: string) {
247 const container = document.createElement("div");
248 container.innerHTML = `<div data-timeline-row-id="row"><div data-thread-find-text>${html}</div></div>`;
249 return container;
250}
251
252describe("collectThreadFindRanges", () => {
253 it("finds matches split across inline token spans, in order", () => {
254 // Shiki-style tokens split one identifier over several text nodes.
255 const container = row(
256 "<pre><code><span>con</span><span>st</span> a = <span>c</span>onst; const</code></pre>",
257 );
258 const ranges = collectThreadFindRanges(container, "const");
259 expect(ranges.map((match) => [match.occurrence, match.range.toString()])).toEqual([
260 [0, "const"],
261 [1, "const"],
262 [2, "const"],
263 ]);
264 });
265
266 it("finds every match across thousands of token nodes", () => {
267 const tokens = Array.from({ length: 4000 }, (_, i) => `<span>id</span><span>${i} </span>`);
268 const container = row(`<pre><code>${tokens.join("")}</code></pre>`);
269 const ranges = collectThreadFindRanges(container, "id");
270 expect(ranges).toHaveLength(4000);
271 expect(ranges.map((match) => match.occurrence)).toEqual([...ranges.keys()]);
272 expect(ranges.every((match) => match.range.toString() === "id")).toBe(true);
273 });
274});