Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

htmlRenderCitationSource.browser.test.ts

231 lines7.9 KB

1import type { LegendListRef } from "@legendapp/list/react";
2import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
3import { describe, expect, it, vi } from "vite-plus/test";
4import { fakeTimers } from "../../../test/render";
5import { observeHtmlRenderCitationSource } from "./htmlRenderCitationSource";
6import type { AssistantCitationTarget } from "./AssistantCitationSource";
7import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
8​
9const toast = vi.hoisted(() => vi.fn());
10vi.mock("../ui/toast", () => ({ toastManager: { add: toast } }));
11function environment() {
12 const disposers: Array<() => void> = [];
13 toast.mockClear();
14 vi.stubGlobal(
15 "ResizeObserver",
16 class {
17 observe() {}
18 disconnect() {}
19 },
20 );
21 vi.stubGlobal("matchMedia", () => ({ matches: false }));
22 return {
23 disposers,
24 [Symbol.dispose]() {
25 for (const dispose of disposers.splice(0)) dispose();
26 document.body.replaceChildren();
27 vi.restoreAllMocks();
28 vi.unstubAllGlobals();
29 },
30 };
32​
33function setup(disposers: Array<() => void>, ready = true) {
34 const root = document.createElement("div");
35 const frame = document.createElement("iframe");
36 frame.style.cssText = "width: 400px; height: 300px; border: 0";
37 if (ready) frame.dataset.htmlSelectionReady = "true";
38 const scrollNode = document.createElement("div");
39 root.append(frame);
40 scrollNode.append(root);
41 document.body.append(scrollNode);
42 Object.defineProperties(scrollNode, {
43 clientHeight: { value: 400 },
44 scrollHeight: { value: 2000 },
45 });
46 let scroll = 0;
47 vi.spyOn(frame, "getBoundingClientRect").mockImplementation(
48 () => new DOMRect(100, 800 - scroll, 400, 300),
49 );
50 vi.spyOn(scrollNode, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 600, 400));
51 const stopPosition = vi.fn();
52 const state = {
53 get scroll() {
54 return scroll;
55 },
56 indexByKey: () => 1,
57 sizeAtIndex: () => 300,
58 listenToPosition: () => stopPosition,
59 };
60 const scrollToOffset = vi.fn(async ({ offset }: { offset: number }) => {
61 scroll = offset;
62 });
63 const list = {
64 getScrollableNode: () => scrollNode,
65 getState: () => state,
66 scrollToOffset,
67 } as unknown as LegendListRef;
68 const request: AssistantCitationTarget = {
69 citation: {
70 version: 1,
71 environmentId: EnvironmentId.make("env"),
72 threadId: ThreadId.make("thread"),
73 messageId: MessageId.make("render"),
74 text: "quote",
75 start: 0,
76 end: 5,
77 prefix: "",
78 suffix: "",
79 },
80 key: "activation",
81 activationRef: { current: { scrolled: false, dismissed: false } },
82 onComplete: vi.fn(),
83 };
84 const post = vi.spyOn(frame.contentWindow!, "postMessage");
85 const dispose = observeHtmlRenderCitationSource({ root, itemKey: "render", request, list })!;
86 disposers.push(dispose);
87 const send = (selector = request.citation, source: Window | null = frame.contentWindow) =>
88 window.dispatchEvent(
89 new MessageEvent("message", {
90 source,
91 data: {
92 jsonrpc: "2.0",
93 method: "t3/selection",
94 params: { target: { left: 0, top: 20, width: 80, height: 15 }, selector },
95 },
96 }),
97 );
98 return { root, frame, request, post, send, scrollToOffset, stopPosition, dispose };
100​
101describe("HTML citation source navigation", () => {
102 it.each([true, false])(
103 "finishes with a recovery message when readiness is %s and the frame does not reply",
104 (ready) => {
105 using _timers = fakeTimers();
106 using fixture = environment();
107 const disposers = fixture.disposers;
108 const p = setup(disposers, ready);
109 vi.advanceTimersByTime(5000);
110 expect(p.request.onComplete).toHaveBeenCalledOnce();
111 expect(p.request.activationRef.current.dismissed).toBe(true);
112 expect(toast).toHaveBeenCalledWith(
113 expect.objectContaining({ title: "Could not open the cited HTML" }),
114 );
115 },
116 );
117​
118 it("updates a comment anchor and releases it when the quote disappears", () => {
119 using fixture = environment();
120 const disposers = fixture.disposers;
121 const p = setup(disposers);
122 p.dispose();
123 disposers.pop();
124 const onUnavailable = vi.fn();
125 const onPositionChange = vi.fn();
126 const updateRange = vi.fn(() => true);
127 const dispose = observeAssistantCitationCommentSource({
128 anchor: {
129 source: p.root,
130 viewport: p.root.parentElement!,
131 htmlRender: p.frame,
132 range: {
133 getBoundingClientRect: () => new DOMRect(),
134 getClientRects: () => Object.assign([], { item: () => null }),
135 },
136 updateRange,
137 },
138 citation: p.request.citation,
139 onUnavailable,
140 onPositionChange,
141 });
142 disposers.push(dispose);
143 const reply = (
144 target: unknown,
145 source: Window | null = p.frame.contentWindow,
146 selector = p.request.citation,
147 ) =>
148 window.dispatchEvent(
149 new MessageEvent("message", {
150 source,
151 data: {
152 jsonrpc: "2.0",
153 method: "t3/selection",
154 params: { action: "mark", target, selector },
155 },
156 }),
157 );
158 const rect = { left: 12, top: 24, width: 60, height: 20 };
159 reply(rect, window);
160 reply(rect, p.frame.contentWindow, { ...p.request.citation, text: "another quote" });
161 expect(updateRange).not.toHaveBeenCalled();
162 reply(rect);
163 expect(updateRange).toHaveBeenCalledWith(rect);
164 expect(onPositionChange).toHaveBeenCalledOnce();
165 expect(onUnavailable).not.toHaveBeenCalled();
166 reply(null);
167 expect(onUnavailable).toHaveBeenCalledOnce();
168 expect(p.post).toHaveBeenLastCalledWith(
169 { method: "t3/selection-command", params: { action: "unmark", selector: undefined } },
170 "*",
171 );
172 });
173​
174 it("waits for iframe readiness, then resolves and scrolls to the saved quote", async () => {
175 using fixture = environment();
176 const disposers = fixture.disposers;
177 const p = setup(disposers, false);
178 expect(p.post).not.toHaveBeenCalled();
179 p.frame.dataset.htmlSelectionReady = "true";
180 p.frame.dispatchEvent(new Event("t3-html-selection-ready", { bubbles: true }));
181 expect(p.post).toHaveBeenLastCalledWith(
182 {
183 method: "t3/selection-command",
184 params: {
185 action: "target",
186 selector: { text: "quote", start: 0, end: 5, prefix: "", suffix: "" },
187 },
188 },
189 "*",
190 );
191 p.send();
192 expect(p.scrollToOffset).toHaveBeenCalledWith({ offset: 700, animated: true });
193 expect(p.request.onComplete).not.toHaveBeenCalled();
194 await Promise.resolve();
195 p.send();
196 expect(p.request.activationRef.current.scrolled).toBe(true);
197 expect(p.request.onComplete).toHaveBeenCalledOnce();
198 p.dispose();
199 expect(p.stopPosition).toHaveBeenCalledOnce();
200 expect(p.post).toHaveBeenLastCalledWith(
201 { method: "t3/selection-command", params: { action: "untarget", selector: undefined } },
202 "*",
203 );
204 disposers.pop();
205 });
206​
207 it("ignores unrelated frames and stale replies for a different quote", () => {
208 using fixture = environment();
209 const disposers = fixture.disposers;
210 const p = setup(disposers);
211 p.send(p.request.citation, window);
212 p.send({ ...p.request.citation, text: "other" });
213 expect(p.scrollToOffset).not.toHaveBeenCalled();
214 expect(p.request.onComplete).not.toHaveBeenCalled();
215 });
216​
217 it("finishes navigation with an actionable error when the page cannot load", async () => {
218 using fixture = environment();
219 const disposers = fixture.disposers;
220 const p = setup(disposers, false);
221 const error = document.createElement("p");
222 error.dataset.htmlRenderError = "true";
223 p.root.append(error);
224 await Promise.resolve();
225 expect(p.request.onComplete).toHaveBeenCalledOnce();
226 expect(p.request.activationRef.current.dismissed).toBe(true);
227 expect(toast).toHaveBeenCalledWith(
228 expect.objectContaining({ title: "Could not load the cited HTML" }),
229 );
230 });
231});