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

AssistantCitationChip.browser.test.tsx

177 lines6.2 KB

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