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

AssistantCitationChip.browser.test.tsx

221 lines7.6 KB

1import {
2 ASSISTANT_CITATION_MAX_COMMENT_LENGTH,
3 type AssistantCitation,
4 EnvironmentId,
5 MessageId,
6 ThreadId,
7} from "@t3tools/contracts";
8import { useState, type ReactNode } from "react";
9import { describe, expect, it, vi } from "vite-plus/test";
10import { userEvent } from "vite-plus/test/browser";
11​
12import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
13import "~/index.css";
14import { act, render } from "../../../test/render";
15​
16const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() }));
17vi.mock(import("./AssistantCitationSource"), async (importOriginal) => ({
18 ...(await importOriginal()),
19 observeAssistantCitationCommentSource: mocks.observeSource,
20}));
21vi.mock(import("@tanstack/react-router"), async (importOriginal) => ({
22 ...(await importOriginal()),
23 useNavigate: () => vi.fn(),
24 Link: (({ children }: { children: ReactNode }) => <a>{children}</a>) as never,
25}));
26​
27import { AssistantCitationChip } from "./AssistantCitationChip";
28​
29const citation = {
30 version: 1 as const,
31 environmentId: EnvironmentId.make("environment"),
32 threadId: ThreadId.make("thread"),
33 messageId: MessageId.make("source"),
34 text: "hello",
35 start: 0,
36 end: 5,
37 prefix: "",
38 suffix: "",
39};
40​
41// The mocked source observer is shared, so every test starts by resetting it.
42function setup() {
43 mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
44 mocks.dispose.mockClear();
45 const source = document.createElement("p");
46 source.textContent = "hello";
47 document.body.append(source);
48 const range = document.createRange();
49 range.selectNodeContents(source);
50 const sourceAnchor = { source, range, viewport: document.body } as AssistantCitationSourceAnchor;
51 return { sourceAnchor, [Symbol.dispose]: () => source.remove() };
53​
54function mount(
55 sourceAnchor: AssistantCitationSourceAnchor | undefined,
56 onSave: () => boolean,
57 chipCitation: AssistantCitation = citation,
58) {
59 function Composer() {
60 const [open, setOpen] = useState(true);
61 return (
62 <AssistantCitationChip
63 citation={chipCitation}
64 composer
65 commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
66 />
67 );
68 }
69 return render(<Composer />);
71​
72const textarea = () =>
73 document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on selected text"]');
74​
75async function typeComment(value: string) {
76 const input = textarea()!;
77 await act(async () => {
78 Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
79 input,
80 value,
81 );
82 input.dispatchEvent(new Event("input", { bubbles: true }));
83 });
85​
86async function removeSource() {
87 const { onUnavailable } = mocks.observeSource.mock.lastCall![0];
88 await act(async () => onUnavailable());
90​
91async function clickButton(label: string) {
92 const button = [...document.querySelectorAll("button")].find(
93 (element) => element.textContent?.trim() === label,
94 );
95 expect(button, `button ${label}`).toBeDefined();
96 await act(async () => button!.click());
98​
99describe("citation comment source disappearance", () => {
100 it("preserves an over-length draft at the composer until it can be shortened and saved", async () => {
101 using source = setup();
102 const onSave = vi.fn(() => true);
103 await using _screen = await mount(source.sourceAnchor, onSave);
104 const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
105 await typeComment(draft);
106 await removeSource();
107​
108 expect(textarea()?.value).toBe(draft);
109 expect(textarea()?.getAttribute("aria-invalid")).toBe("true");
110 expect(onSave).not.toHaveBeenCalled();
111 expect(mocks.dispose).toHaveBeenCalled();
112 expect(mocks.observeSource).toHaveBeenCalledTimes(1);
113​
114 await typeComment("shortened comment");
115 await clickButton("Save");
116 expect(onSave).toHaveBeenCalledWith("shortened comment");
117 expect(textarea()).toBeNull();
118 });
119​
120 it("preserves a rejected save and allows a later retry", async () => {
121 using source = setup();
122 const onSave = vi.fn(() => false);
123 await using _screen = await mount(source.sourceAnchor, onSave);
124 await typeComment("keep this draft");
125 await removeSource();
126​
127 expect(onSave).toHaveBeenCalledWith("keep this draft");
128 expect(textarea()?.value).toBe("keep this draft");
129 onSave.mockReturnValue(true);
130 await clickButton("Save");
131 expect(onSave).toHaveBeenLastCalledWith("keep this draft");
132 expect(textarea()).toBeNull();
133 });
134});
135​
136describe("citation comment caret", () => {
137 it("opens a saved comment with the caret after its end, scrolled into view", async () => {
138 using _source = setup();
139 const comment = `${"line\n".repeat(40)}end`;
140 await using _screen = await mount(
141 undefined,
142 vi.fn(() => true),
143 { ...citation, comment },
144 );
145 await vi.waitFor(() => expect(document.activeElement).toBe(textarea()));
146 const input = textarea()!;
147​
148 expect(input.scrollHeight).toBeGreaterThan(input.clientHeight);
149 expect(input.scrollTop).toBe(input.scrollHeight - input.clientHeight);
150 await userEvent.keyboard("!");
151 expect(input.value).toBe(`${comment}!`);
152 });
153});
154​
155describe("citation comment popup position", () => {
156 it("opens at its anchor instead of sliding in from the window corner", async () => {
157 using source = setup();
158 await using _screen = await mount(
159 source.sourceAnchor,
160 vi.fn(() => true),
161 );
162 const positioner = () =>
163 document.querySelector<HTMLElement>('[data-slot="popover-positioner"]');
164 await vi.waitFor(() => expect(positioner()?.style.opacity).not.toBe("0"));
165​
166 const moves = positioner()!
167 .getAnimations()
168 .filter(
169 (animation) =>
170 animation instanceof CSSTransition &&
171 ["transform", "top", "left"].includes(animation.transitionProperty),
172 );
173 expect(moves).toEqual([]);
174 });
175​
176 it("stays on screen when the cited text ends in a code block's hidden overflow", async () => {
177 using _source = setup();
178 const message = document.createElement("div");
179 message.className = "chat-markdown";
180 message.style.width = "240px";
181 const pre = document.createElement("pre");
182 const code = document.createElement("code");
183 // Highlighted code is split into token spans, so the range's last client rect
184 // covers only the final token, wholly inside the hidden overflow.
185 for (let index = 0; index < 40; index += 1) {
186 const token = document.createElement("span");
187 token.textContent = `token${index} `;
188 code.append(token);
189 }
190 pre.append(code);
191 message.append(pre);
192 document.body.prepend(message);
193 using _message = { [Symbol.dispose]: () => message.remove() };
194 const range = document.createRange();
195 range.selectNodeContents(code);
196 const rects = range.getClientRects();
197 expect(rects.item(rects.length - 1)!.left).toBeGreaterThan(window.innerWidth);
198 const sourceAnchor = {
199 source: message,
200 range,
201 viewport: document.body,
202 } as AssistantCitationSourceAnchor;
203​
204 await using _screen = await mount(
205 sourceAnchor,
206 vi.fn(() => true),
207 );
208 const popup = () => document.querySelector<HTMLElement>('[data-slot="popover-popup"]');
209 await vi.waitFor(() => expect(popup()?.getBoundingClientRect().width).toBeGreaterThan(0));
210 // Typing scrolls ancestors to reveal the caret, which shifts the whole app
211 // sideways when the box is off screen.
212 await userEvent.keyboard("note");
213​
214 expect(textarea()?.value).toBe("note");
215 expect(document.scrollingElement?.scrollLeft).toBe(0);
216 expect(document.body.scrollLeft).toBe(0);
217 const rect = popup()!.getBoundingClientRect();
218 expect(rect.left).toBeGreaterThanOrEqual(0);
219 expect(rect.right).toBeLessThanOrEqual(window.innerWidth);
220 });
221});