Open History to see the last commit
1import { EnvironmentId, ThreadId, type AssistantCitation } from "@t3tools/contracts";
2import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations";
3import { useState } from "react";
4import { expect, it, vi } from "vite-plus/test";
5import { userEvent } from "vite-plus/test/browser";
6import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
7import { act, fakeTimers, render } from "../../../test/render";
8import "~/index.css";
9
10import { AssistantCitationChip } from "./AssistantCitationChip";
11import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
12
13const cite = () =>
14 document.querySelector<HTMLButtonElement>('button[aria-label="Cite selection in composer"]');
15const popup = () => document.querySelector<HTMLElement>('[data-slot="popover-popup"]');
16const comment = () =>
17 document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on selected text"]');
18
19function expectInside(element: Element | null, boundary: HTMLElement) {
20 expect(element).not.toBeNull();
21 const rect = element!.getBoundingClientRect();
22 const bounds = boundary.getBoundingClientRect();
23 expect(rect.width).toBeGreaterThan(0);
24 expect(rect.height).toBeGreaterThan(0);
25 expect(rect.left).toBeGreaterThanOrEqual(bounds.left);
26 expect(rect.right).toBeLessThanOrEqual(bounds.right);
27 expect(rect.top).toBeGreaterThanOrEqual(bounds.top);
28 expect(rect.bottom).toBeLessThanOrEqual(bounds.bottom);
29}
30
31async function waitForEvent(target: EventTarget, type: string, action: () => void) {
32 let received = false;
33 const listener = () => {
34 received = true;
35 };
36 target.addEventListener(type, listener);
37 try {
38 await act(action);
39 await vi.waitFor(() => expect(received).toBe(true));
40 } finally {
41 target.removeEventListener(type, listener);
42 }
43}
44
45async function scrollTo(element: HTMLElement, options: ScrollToOptions) {
46 await waitForEvent(element, "scroll", () => {
47 const previous = [element.scrollTop, element.scrollLeft];
48 element.scrollTo({ ...options, behavior: "instant" });
49 expect([element.scrollTop, element.scrollLeft]).not.toEqual(previous);
50 });
51}
52
53function mount({ viewport, boundary }: ReturnType<typeof setup>) {
54 function Chat() {
55 const [selected, setSelected] = useState<{
56 citation: AssistantCitation;
57 sourceAnchor: AssistantCitationSourceAnchor;
58 } | null>(null);
59 return (
60 <>
61 <AssistantSelectionToolbar
62 viewport={viewport}
63 boundary={boundary}
64 threadRef={{
65 environmentId: EnvironmentId.make("environment"),
66 threadId: ThreadId.make("thread"),
67 }}
68 onCite={(citation, sourceAnchor) => {
69 setSelected({ citation, sourceAnchor });
70 return true;
71 }}
72 />
73 {selected ? (
74 <AssistantCitationChip
75 citation={selected.citation}
76 composer
77 commentEditor={{
78 open: true,
79 sourceAnchor: selected.sourceAnchor,
80 onOpenChange: (open) => {
81 if (!open) setSelected(null);
82 },
83 onSave: () => true,
84 }}
85 />
86 ) : null}
87 </>
88 );
89 }
90 return render(<Chat />);
91}
92
93function setup() {
94 const host = document.createElement("div");
95 const viewport = document.createElement("div");
96 viewport.style.cssText =
97 "position: fixed; left: 20px; top: 70px; width: 360px; height: 400px; overflow: auto";
98 const boundary = document.createElement("div");
99 boundary.style.cssText =
100 "position: fixed; left: 20px; top: 70px; width: 360px; height: 260px; pointer-events: none";
101 const source = document.createElement("div");
102 source.dataset.assistantCitationSource = "message";
103 viewport.append(source);
104 host.append(viewport, boundary);
105 document.body.append(host);
106 return {
107 viewport,
108 boundary,
109 source,
110 [Symbol.dispose]() {
111 window.getSelection()?.removeAllRanges();
112 host.remove();
113 },
114 };
115}
116
117it.each([
118 { kind: "long response", direction: "backward" },
119 { kind: "wide code", direction: "forward" },
120] as const)(
121 "$kind: keeps Cite and its box in the message area for a $direction selection and scrolling",
122 async ({ kind, direction }) => {
123 using fixture = setup();
124 const { viewport, boundary, source } = fixture;
125 const paragraphs = Array.from({ length: 40 }, (_, index) => {
126 const paragraph = document.createElement("p");
127 paragraph.style.lineHeight = "24px";
128 paragraph.textContent = `Line ${index}. A silver fox waits beside the river with a notebook under the old bridge.`;
129 return paragraph;
130 });
131 let first: Node;
132 let last: Node;
133 let codeScroller: HTMLPreElement | undefined;
134 if (kind === "wide code") {
135 const pre = document.createElement("pre");
136 pre.style.cssText = "width: 300px; overflow: auto; white-space: pre";
137 for (let index = 0; index < 80; index += 1) {
138 const token = document.createElement("span");
139 token.textContent = `token${index} `;
140 pre.append(token);
141 }
142 source.append(pre, ...paragraphs);
143 codeScroller = pre;
144 first = pre.children[70]!.firstChild!;
145 last = pre.lastChild!.firstChild!;
146 } else {
147 source.append(...paragraphs);
148 first = paragraphs[0]!.firstChild!;
149 last = paragraphs.at(-1)!.firstChild!;
150 }
151 await using _screen = await mount(fixture);
152 await act(async () => {
153 if (direction === "forward")
154 window.getSelection()!.setBaseAndExtent(first, 0, last, last.textContent!.length);
155 else window.getSelection()!.setBaseAndExtent(last, last.textContent!.length, first, 0);
156 });
157 await vi.waitFor(() => expectInside(cite(), boundary));
158 if (kind === "wide code")
159 expect(window.getSelection()!.getRangeAt(0).getBoundingClientRect().left).toBeGreaterThan(
160 window.innerWidth,
161 );
162 else await scrollTo(viewport, { top: 500 });
163 expectInside(cite(), boundary);
164 await userEvent.click(cite()!);
165 await vi.waitFor(() => expectInside(popup(), boundary));
166 await userEvent.keyboard("note");
167 if (codeScroller) {
168 const pre = codeScroller;
169 await scrollTo(pre, { left: pre.scrollWidth });
170 await vi.waitFor(() => expectInside(popup(), boundary));
171 }
172
173 await scrollTo(viewport, { top: 1000 });
174 await vi.waitFor(() => expectInside(popup(), boundary));
175 await scrollTo(viewport, { top: 0 });
176 await vi.waitFor(() => expectInside(popup(), boundary));
177 await act(async () => {
178 boundary.style.height = "180px";
179 });
180 await vi.waitFor(() => expectInside(popup(), boundary));
181 expect(comment()?.value).toBe("note");
182 expect(document.scrollingElement?.scrollTop).toBe(0);
183 expect(document.scrollingElement?.scrollLeft).toBe(0);
184 },
185);
186
187it("dismisses a focused Cite when the virtualized source unmounts", async () => {
188 using fixture = setup();
189 const { source, boundary } = fixture;
190 source.textContent = "The selected assistant response.";
191 await using _screen = await mount(fixture);
192 await act(async () =>
193 window.getSelection()!.setBaseAndExtent(source.firstChild!, 0, source.firstChild!, 12),
194 );
195 await vi.waitFor(() => expectInside(cite(), boundary));
196 await userEvent.keyboard("{Tab}");
197 expect(document.activeElement).toBe(cite());
198 await act(async () => source.remove());
199 await vi.waitFor(() => expect(cite()).toBeNull());
200 expect(window.getSelection()!.isCollapsed).toBe(true);
201});
202
203it("keeps the action when an upward drag extends into the header", async () => {
204 using fixture = setup();
205 const { source, boundary, viewport } = fixture;
206 const header = document.createElement("header");
207 header.textContent = "Thread title";
208 viewport.before(header);
209 source.textContent = "The assistant response selected by the user.";
210 await using _screen = await mount(fixture);
211 await act(async () =>
212 window
213 .getSelection()!
214 .setBaseAndExtent(source.firstChild!, source.textContent!.length, header.firstChild!, 0),
215 );
216 await vi.waitFor(() => expectInside(cite(), boundary));
217 await userEvent.click(cite()!);
218 await vi.waitFor(() => expectInside(popup(), boundary));
219 const markdown = document
220 .querySelector("[data-assistant-citation-chip]")!
221 .getAttribute("data-markdown-copy")!;
222 const text = new URL(markdown.slice(markdown.indexOf("](") + 2, -1)).searchParams.get("text");
223 expect(text).toBe(source.textContent);
224});
225
226it.each([
227 { neighbor: "preceding user message", direction: "forward" },
228 { neighbor: "following timestamp", direction: "backward" },
229])(
230 "cites only assistant text when a $direction selection starts in a $neighbor",
231 async ({ neighbor, direction }) => {
232 using fixture = setup();
233 const { boundary, source } = fixture;
234 source.textContent = "The selected assistant response.";
235 const adjacent = document.createElement("p");
236 adjacent.textContent = neighbor === "following timestamp" ? "1:50 AM" : "A user message.";
237 const before = neighbor === "preceding user message";
238 if (before) source.before(adjacent);
239 else source.after(adjacent);
240 const first = before ? adjacent.firstChild! : source.firstChild!;
241 const last = before ? source.firstChild! : adjacent.firstChild!;
242 await using _screen = await mount(fixture);
243 await act(async () => {
244 if (direction === "forward")
245 window.getSelection()!.setBaseAndExtent(first, 0, last, last.textContent!.length);
246 else window.getSelection()!.setBaseAndExtent(last, last.textContent!.length, first, 0);
247 });
248
249 await vi.waitFor(() => expectInside(cite(), boundary));
250 expect(window.getSelection()!.toString()).toContain(adjacent.textContent);
251 await userEvent.click(cite()!);
252 await vi.waitFor(() => expectInside(popup(), boundary));
253 const markdown = document
254 .querySelector("[data-assistant-citation-chip]")!
255 .getAttribute("data-markdown-copy")!;
256 const citation = parseAssistantCitationHref(markdown.slice(markdown.indexOf("](") + 2, -1));
257 expect(citation).toMatchObject({
258 messageId: source.dataset.assistantCitationSource,
259 text: source.textContent,
260 });
261 },
262);
263
264it.each(["timer", "frame"])(
265 "offers Cite when scrolling interrupts the pending selection %s",
266 async (stage) => {
267 using fixture = setup();
268 const { viewport, boundary, source } = fixture;
269 source.style.height = "1500px";
270 source.textContent = "The selected assistant response.";
271 await using _screen = await mount(fixture);
272 // Consume the native event during the drag so it cannot rescue a canceled release capture.
273 await waitForEvent(document, "selectionchange", () => {
274 source.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, isPrimary: true }));
275 window.getSelection()!.setBaseAndExtent(source.firstChild!, 0, source.firstChild!, 12);
276 });
277 using _timers = fakeTimers();
278 await act(() => {
279 window.dispatchEvent(new PointerEvent("pointerup", { isPrimary: true }));
280 window.dispatchEvent(new MouseEvent("mouseup", { detail: 1 }));
281 if (stage === "frame") vi.advanceTimersByTime(0);
282 viewport.scrollTop = 500;
283 viewport.dispatchEvent(new Event("scroll"));
284 vi.runAllTimers();
285 });
286 expectInside(cite(), boundary);
287 },
288);