Open History to see the last commit
1import {
2 ASSISTANT_CITATION_MAX_COMMENT_LENGTH,
3 EnvironmentId,
4 MessageId,
5 ThreadId,
6} from "@t3tools/contracts";
7import { act, useState, type ReactNode } from "react";
8import { createRoot, type Root } from "react-dom/client";
9import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10
11import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
12
13const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() }));
14vi.mock(import("./AssistantCitationSource"), async (importOriginal) => ({
15 ...(await importOriginal()),
16 observeAssistantCitationCommentSource: mocks.observeSource,
17}));
18vi.mock(import("@tanstack/react-router"), async (importOriginal) => ({
19 ...(await importOriginal()),
20 useNavigate: () => vi.fn(),
21 Link: (({ children }: { children: ReactNode }) => <a>{children}</a>) as never,
22}));
23
24import { AssistantCitationChip } from "./AssistantCitationChip";
25
26const citation = {
27 version: 1 as const,
28 environmentId: EnvironmentId.make("environment"),
29 threadId: ThreadId.make("thread"),
30 messageId: MessageId.make("source"),
31 text: "hello",
32 start: 0,
33 end: 5,
34 prefix: "",
35 suffix: "",
36};
37
38let root: Root;
39let container: HTMLDivElement;
40let sourceAnchor: AssistantCitationSourceAnchor;
41
42async function mount(onSave = vi.fn(() => true)) {
43 function Composer() {
44 const [open, setOpen] = useState(true);
45 return (
46 <AssistantCitationChip
47 citation={citation}
48 composer
49 commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
50 />
51 );
52 }
53 await act(async () => root.render(<Composer />));
54 return onSave;
55}
56
57const textarea = () =>
58 document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on selected text"]');
59
60async function typeComment(value: string) {
61 const input = textarea()!;
62 await act(async () => {
63 Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
64 input,
65 value,
66 );
67 input.dispatchEvent(new Event("input", { bubbles: true }));
68 });
69}
70
71async function removeSource() {
72 const { onUnavailable } = mocks.observeSource.mock.lastCall![0];
73 await act(async () => onUnavailable());
74}
75
76async function clickButton(label: string) {
77 const button = [...document.querySelectorAll("button")].find(
78 (element) => element.textContent?.trim() === label,
79 );
80 expect(button, `button ${label}`).toBeDefined();
81 await act(async () => button!.click());
82}
83
84beforeEach(() => {
85 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
86 mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
87 mocks.dispose.mockClear();
88 const source = document.createElement("p");
89 source.textContent = "hello";
90 document.body.append(source);
91 const range = document.createRange();
92 range.selectNodeContents(source);
93 sourceAnchor = { source, range, viewport: document.body } as AssistantCitationSourceAnchor;
94 container = document.createElement("div");
95 document.body.append(container);
96 root = createRoot(container);
97});
98
99afterEach(async () => {
100 await act(async () => root.unmount());
101 document.body.replaceChildren();
102 vi.unstubAllGlobals();
103});
104
105describe("citation comment source disappearance", () => {
106 it("preserves an over-length draft at the composer until it can be shortened and saved", async () => {
107 const onSave = await mount();
108 const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
109 await typeComment(draft);
110 await removeSource();
111
112 expect(textarea()?.value).toBe(draft);
113 expect(textarea()?.getAttribute("aria-invalid")).toBe("true");
114 expect(onSave).not.toHaveBeenCalled();
115 expect(mocks.dispose).toHaveBeenCalled();
116 expect(mocks.observeSource).toHaveBeenCalledTimes(1);
117
118 await typeComment("shortened comment");
119 await clickButton("Save");
120 expect(onSave).toHaveBeenCalledWith("shortened comment");
121 expect(textarea()).toBeNull();
122 });
123
124 it("preserves a rejected save and allows a later retry", async () => {
125 const onSave = await mount(vi.fn(() => false));
126 await typeComment("keep this draft");
127 await removeSource();
128
129 expect(onSave).toHaveBeenCalledWith("keep this draft");
130 expect(textarea()?.value).toBe("keep this draft");
131 onSave.mockReturnValue(true);
132 await clickButton("Save");
133 expect(onSave).toHaveBeenLastCalledWith("keep this draft");
134 expect(textarea()).toBeNull();
135 });
136
137 it("still allows explicit cancellation after source disappearance", async () => {
138 const onSave = await mount(vi.fn(() => false));
139 await typeComment("discard this draft");
140 await removeSource();
141 onSave.mockClear();
142 await clickButton("Cancel");
143 expect(onSave).not.toHaveBeenCalled();
144 expect(textarea()).toBeNull();
145 });
146
147 it("saves and closes when the source disappears with a valid draft", async () => {
148 const onSave = await mount();
149 await typeComment("saved comment");
150 await removeSource();
151 expect(onSave).toHaveBeenCalledWith("saved comment");
152 expect(textarea()).toBeNull();
153 });
154});
155
156describe("citation comment popup placement", () => {
157 it("opens inside the window when the cited line ends in a code block's horizontal overflow", async () => {
158 const pre = document.createElement("pre");
159 pre.style.cssText = "width: 120px; overflow-x: auto; white-space: pre; margin: 0";
160 pre.textContent = `${"x".repeat(400)}\ny`;
161 document.body.append(pre);
162 const range = document.createRange();
163 range.setStart(pre.firstChild!, 0);
164 range.setEnd(pre.firstChild!, 401);
165 sourceAnchor = { source: pre, range, viewport: document.body } as AssistantCitationSourceAnchor;
166 // The anchor is the selection's last rect: a narrow line-end rect past the window edge.
167 const rects = range.getClientRects();
168 expect(rects.item(rects.length - 1)!.left).toBeGreaterThan(window.innerWidth);
169
170 await mount();
171
172 const popup = document.querySelector('[data-slot="popover-popup"]')!.getBoundingClientRect();
173 expect(popup.left).toBeGreaterThanOrEqual(0);
174 expect(popup.right).toBeLessThanOrEqual(window.innerWidth);
175 });
176});