Open History to see the last commit
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() };
52}
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 commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
65 />
66 );
67 }
68 return render(<Composer />);
69}
70
71const textarea = () =>
72 document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on selected text"]');
73
74async function typeComment(value: string) {
75 const input = textarea()!;
76 await act(async () => {
77 Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
78 input,
79 value,
80 );
81 input.dispatchEvent(new Event("input", { bubbles: true }));
82 });
83}
84
85async function removeSource() {
86 const { onUnavailable } = mocks.observeSource.mock.lastCall![0];
87 await act(async () => onUnavailable());
88}
89
90async function clickButton(label: string) {
91 const button = [...document.querySelectorAll("button")].find(
92 (element) => element.textContent?.trim() === label,
93 );
94 expect(button, `button ${label}`).toBeDefined();
95 await act(async () => button!.click());
96}
97
98describe("citation comment source disappearance", () => {
99 it("preserves an over-length draft at the composer until it can be shortened and saved", async () => {
100 using source = setup();
101 const onSave = vi.fn(() => true);
102 await using _screen = await mount(source.sourceAnchor, onSave);
103 const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
104 await typeComment(draft);
105 await removeSource();
106
107 expect(textarea()?.value).toBe(draft);
108 expect(textarea()?.getAttribute("aria-invalid")).toBe("true");
109 expect(onSave).not.toHaveBeenCalled();
110 expect(mocks.dispose).toHaveBeenCalled();
111 expect(mocks.observeSource).toHaveBeenCalledTimes(1);
112
113 await typeComment("shortened comment");
114 await clickButton("Save");
115 expect(onSave).toHaveBeenCalledWith("shortened comment");
116 expect(textarea()).toBeNull();
117 });
118
119 it("preserves a rejected save and allows a later retry", async () => {
120 using source = setup();
121 const onSave = vi.fn(() => false);
122 await using _screen = await mount(source.sourceAnchor, onSave);
123 await typeComment("keep this draft");
124 await removeSource();
125
126 expect(onSave).toHaveBeenCalledWith("keep this draft");
127 expect(textarea()?.value).toBe("keep this draft");
128 onSave.mockReturnValue(true);
129 await clickButton("Save");
130 expect(onSave).toHaveBeenLastCalledWith("keep this draft");
131 expect(textarea()).toBeNull();
132 });
133});
134
135describe("citation comment caret", () => {
136 it("opens a saved comment with the caret after its end, scrolled into view", async () => {
137 using _source = setup();
138 const comment = `${"line\n".repeat(40)}end`;
139 await using _screen = await mount(
140 undefined,
141 vi.fn(() => true),
142 { ...citation, comment },
143 );
144 await vi.waitFor(() => expect(document.activeElement).toBe(textarea()));
145 const input = textarea()!;
146
147 expect(input.scrollHeight).toBeGreaterThan(input.clientHeight);
148 expect(input.scrollTop).toBe(input.scrollHeight - input.clientHeight);
149 await userEvent.keyboard("!");
150 expect(input.value).toBe(`${comment}!`);
151 });
152});
153
154describe("citation comment popup position", () => {
155 it("opens at its anchor instead of sliding in from the window corner", async () => {
156 using source = setup();
157 await using _screen = await mount(
158 source.sourceAnchor,
159 vi.fn(() => true),
160 );
161 const positioner = () =>
162 document.querySelector<HTMLElement>('[data-slot="popover-positioner"]');
163 await vi.waitFor(() => expect(positioner()?.style.opacity).not.toBe("0"));
164
165 const moves = positioner()!
166 .getAnimations()
167 .filter(
168 (animation) =>
169 animation instanceof CSSTransition &&
170 ["transform", "top", "left"].includes(animation.transitionProperty),
171 );
172 expect(moves).toEqual([]);
173 });
174
175 it("stays on screen when the cited text ends in a code block's hidden overflow", async () => {
176 using _source = setup();
177 const message = document.createElement("div");
178 message.className = "chat-markdown";
179 message.style.width = "240px";
180 const pre = document.createElement("pre");
181 const code = document.createElement("code");
182 // Highlighted code is split into token spans, so the range's last client rect
183 // covers only the final token, wholly inside the hidden overflow.
184 for (let index = 0; index < 40; index += 1) {
185 const token = document.createElement("span");
186 token.textContent = `token${index} `;
187 code.append(token);
188 }
189 pre.append(code);
190 message.append(pre);
191 document.body.prepend(message);
192 using _message = { [Symbol.dispose]: () => message.remove() };
193 const range = document.createRange();
194 range.selectNodeContents(code);
195 const rects = range.getClientRects();
196 expect(rects.item(rects.length - 1)!.left).toBeGreaterThan(window.innerWidth);
197 const sourceAnchor = {
198 source: message,
199 range,
200 viewport: document.body,
201 } as AssistantCitationSourceAnchor;
202
203 await using _screen = await mount(
204 sourceAnchor,
205 vi.fn(() => true),
206 );
207 const popup = () => document.querySelector<HTMLElement>('[data-slot="popover-popup"]');
208 await vi.waitFor(() => expect(popup()?.getBoundingClientRect().width).toBeGreaterThan(0));
209 // Typing scrolls ancestors to reveal the caret, which shifts the whole app
210 // sideways when the box is off screen.
211 await userEvent.keyboard("note");
212
213 expect(textarea()?.value).toBe("note");
214 expect(document.scrollingElement?.scrollLeft).toBe(0);
215 expect(document.body.scrollLeft).toBe(0);
216 const rect = popup()!.getBoundingClientRect();
217 expect(rect.left).toBeGreaterThanOrEqual(0);
218 expect(rect.right).toBeLessThanOrEqual(window.innerWidth);
219 });
220});