Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { serializeRenderedMarkdownFragment } from "./markdown-clipboard";
4import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
5import {
6 collectAssistantCitations,
7 serializeAssistantCitation,
8} from "@t3tools/shared/assistantCitations";
9
10const TEXT_NODE = 3;
11const ELEMENT_NODE = 1;
12
13class FakeText {
14 readonly nodeType = TEXT_NODE;
15 readonly childNodes: ReadonlyArray<never> = [];
16
17 constructor(readonly textContent: string) {}
18}
19
20class FakeElement {
21 readonly nodeType = ELEMENT_NODE;
22 checked = false;
23 readonly childNodes: Array<FakeElement | FakeText> = [];
24 readonly classList = {
25 contains: (name: string) => this.classNames.includes(name),
26 };
27
28 constructor(
29 readonly tagName: string,
30 private readonly classNames: ReadonlyArray<string> = [],
31 private readonly attributes: Readonly<Record<string, string>> = {},
32 ) {}
33
34 get localName(): string {
35 return this.tagName.toLowerCase();
36 }
37
38 get textContent(): string {
39 return this.childNodes.map((child) => child.textContent).join("");
40 }
41
42 get children(): ReadonlyArray<FakeElement> {
43 return this.childNodes.filter((child): child is FakeElement => child instanceof FakeElement);
44 }
45
46 append(...children: Array<FakeElement | FakeText>): this {
47 this.childNodes.push(...children);
48 return this;
49 }
50
51 getAttribute(name: string): string | null {
52 return this.attributes[name] ?? null;
53 }
54
55 hasAttribute(name: string): boolean {
56 return Object.hasOwn(this.attributes, name);
57 }
58
59 closest(): FakeElement | null {
60 return null;
61 }
62
63 querySelector(selector: string): FakeElement | null {
64 if (selector.includes(", ")) {
65 for (const part of selector.split(", ")) {
66 const match = this.querySelector(part);
67 if (match) return match;
68 }
69 return null;
70 }
71 const childOnly = selector.startsWith(":scope > ");
72 const [target, ...rest] = (childOnly ? selector.slice(":scope > ".length) : selector).split(
73 " > ",
74 );
75 const matches = (element: FakeElement): boolean => {
76 if (target === 'input[type="checkbox"]') {
77 return element.tagName === "INPUT" && element.getAttribute("type") === "checkbox";
78 }
79 return element.tagName === target?.toUpperCase();
80 };
81 const search = (parent: FakeElement): FakeElement | null => {
82 for (const child of parent.childNodes) {
83 if (!(child instanceof FakeElement)) continue;
84 if (matches(child)) {
85 if (rest.length === 0) return child;
86 const nested = child.querySelector(`:scope > ${rest.join(" > ")}`);
87 if (nested) return nested;
88 }
89 if (!childOnly) {
90 const nested = search(child);
91 if (nested) return nested;
92 }
93 }
94 return null;
95 };
96 return search(this);
97 }
98}
99
100function asNode(element: FakeElement): Node {
101 return element as unknown as Node;
102}
103
104function shikiCodeLine(text: string): FakeElement {
105 const token = new FakeElement("SPAN").append(new FakeText(text));
106 return new FakeElement("SPAN", ["line"]).append(token);
107}
108
109function renderedCodeBlock(lines: ReadonlyArray<string>): FakeElement {
110 const code = new FakeElement("CODE");
111 lines.forEach((line, index) => {
112 if (index > 0) code.append(new FakeText("\n"));
113 code.append(shikiCodeLine(line));
114 });
115 return new FakeElement("DIV", ["chat-markdown-codeblock"]).append(
116 new FakeElement("DIV", ["chat-markdown-codeblock-header", "select-none"]).append(
117 new FakeText("sh"),
118 ),
119 new FakeElement("DIV", ["chat-markdown-shiki"]).append(new FakeElement("PRE").append(code)),
120 );
121}
122
123describe("serializeRenderedMarkdownFragment", () => {
124 it("copies a popover context reference once, without its details or nested label", () => {
125 const reference = "[Review comment](t3-context://v1/review-comment/review-1)";
126 const container = new FakeElement("DIV").append(
127 new FakeText("Fix "),
128 new FakeElement("BUTTON", [], { "data-markdown-copy": reference }).append(
129 new FakeElement("SPAN", [], { "data-markdown-copy": reference }).append(
130 new FakeText("Review comment"),
131 ),
132 ),
133 new FakeText(" please"),
134 );
135
136 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(`Fix ${reference} please`);
137 });
138
139 beforeEach(() => {
140 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
141 });
142
143 afterEach(() => {
144 vi.unstubAllGlobals();
145 });
146
147 it("wraps inline code in backticks", () => {
148 const paragraph = new FakeElement("P").append(
149 new FakeText("run "),
150 new FakeElement("CODE").append(new FakeText("git status")),
151 new FakeText(" first"),
152 );
153 const container = new FakeElement("DIV").append(paragraph);
154
155 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("run `git status` first");
156 });
157
158 describe.each([
159 { parentLayout: "tight", childLayout: "tight" },
160 { parentLayout: "tight", childLayout: "loose" },
161 { parentLayout: "loose", childLayout: "tight" },
162 { parentLayout: "loose", childLayout: "loose" },
163 ])("$parentLayout parent with $childLayout child", ({ parentLayout, childLayout }) => {
164 it.each([
165 { parentChecked: null, childChecked: true, parent: "- Parent", child: " - [x] Child" },
166 {
167 parentChecked: false,
168 childChecked: true,
169 parent: "- [ ] Parent",
170 child: " - [x] Child",
171 },
172 {
173 parentChecked: true,
174 childChecked: false,
175 parent: "- [x] Parent",
176 child: " - [ ] Child",
177 },
178 ])("copies $parent with $child", ({ parentChecked, childChecked, parent, child }) => {
179 const parentContent = parentLayout === "loose" ? new FakeElement("P") : new FakeElement("LI");
180 if (parentChecked !== null) {
181 const checkbox = new FakeElement("INPUT", [], { type: "checkbox" });
182 checkbox.checked = parentChecked;
183 parentContent.append(checkbox, new FakeText(" "));
184 }
185 parentContent.append(new FakeText("Parent"));
186 const parentItem =
187 parentLayout === "loose" ? new FakeElement("LI").append(parentContent) : parentContent;
188 const checkbox = new FakeElement("INPUT", [], { type: "checkbox" });
189 checkbox.checked = childChecked;
190 const childContent = new FakeElement(childLayout === "loose" ? "P" : "LI").append(
191 checkbox,
192 new FakeText(" Child"),
193 );
194 const childItem =
195 childLayout === "loose" ? new FakeElement("LI").append(childContent) : childContent;
196 parentItem.append(new FakeText("\n"), new FakeElement("UL").append(childItem));
197 const container = new FakeElement("DIV").append(
198 new FakeElement("P").append(new FakeText("Before")),
199 new FakeElement("UL").append(parentItem),
200 new FakeElement("P").append(new FakeText("After")),
201 );
202
203 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
204 `Before\n\n${parent}${parentLayout === "loose" ? "\n\n" : "\n"}${child}\n\nAfter`,
205 );
206 });
207 });
208
209 it("indents a code block under a numbered task item by the number width only", () => {
210 const checkbox = new FakeElement("INPUT", [], { type: "checkbox" });
211 checkbox.checked = true;
212 const item = new FakeElement("LI").append(
213 new FakeElement("P").append(checkbox, new FakeText(" Run the tests")),
214 renderedCodeBlock(["pnpm test"]),
215 );
216 const container = new FakeElement("DIV").append(new FakeElement("OL").append(item));
217
218 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
219 "1. [x] Run the tests\n\n ```\n pnpm test\n ```",
220 );
221 });
222
223 it("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
224 const citation = {
225 version: 1 as const,
226 environmentId: EnvironmentId.make("environment-one"),
227 threadId: ThreadId.make("thread-one"),
228 messageId: MessageId.make("assistant-one"),
229 text: "A complete quote, including the part hidden by the chip preview.",
230 comment: "What does this mean?\nPlease expand on the hidden part.",
231 start: 0,
232 end: 66,
233 prefix: "",
234 suffix: "",
235 };
236 const anchor = new FakeElement("A", [], {
237 "data-markdown-copy": serializeAssistantCitation(citation),
238 href: "/environment-one/thread-one#citation",
239 }).append(new FakeText("What does this mean?…"));
240 const chip = new FakeElement("SPAN", [], {
241 "data-markdown-copy": serializeAssistantCitation(citation),
242 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
243 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
244 const copied = serializeRenderedMarkdownFragment(asNode(container));
245 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
246 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
247 });
248
249 it("keeps a highlighted block code selection plain when its pre wrapper is outside the range", () => {
250 const code = new FakeElement("CODE").append(
251 shikiCodeLine("git show-ref --verify refs/remotes/origin/opt/deploy/dev"),
252 );
253 const container = new FakeElement("DIV").append(code);
254
255 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
256 "git show-ref --verify refs/remotes/origin/opt/deploy/dev",
257 );
258 });
259
260 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
261 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
262 const container = new FakeElement("DIV").append(code);
263
264 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
265 });
266
267 it("keeps fences when a bare list item sits alongside the code block", () => {
268 const container = new FakeElement("DIV").append(
269 new FakeElement("UL").append(new FakeElement("LI")),
270 renderedCodeBlock(["pnpm test"]),
271 );
272
273 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
274 });
275
276 it("keeps fences when a checkbox-only task item sits alongside the code block", () => {
277 const container = new FakeElement("DIV").append(
278 new FakeElement("UL").append(
279 new FakeElement("LI").append(new FakeElement("INPUT", [], { type: "checkbox" })),
280 ),
281 renderedCodeBlock(["pnpm test"]),
282 );
283
284 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
285 "- [ ]\n\n```\npnpm test\n```",
286 );
287 });
288
289 it("still drops fences for a code block that is the whole list item", () => {
290 const container = new FakeElement("DIV").append(
291 new FakeElement("UL").append(new FakeElement("LI").append(renderedCodeBlock(["pnpm test"]))),
292 new FakeText("\n"),
293 );
294
295 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("pnpm test");
296 });
297
298 it("keeps fences when a file chip sits alongside the code block", () => {
299 const container = new FakeElement("DIV").append(
300 renderedCodeBlock(["pnpm test"]),
301 new FakeText("\n"),
302 new FakeElement("BUTTON", [], { "data-markdown-copy": "`src/foo.ts`" }),
303 );
304
305 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
306 "```\npnpm test\n```\n\n`src/foo.ts`",
307 );
308 });
309
310 it("omits fences when a selection past the last line drags in the whole code block", () => {
311 const container = new FakeElement("DIV").append(
312 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
313 new FakeText("\n"),
314 new FakeElement("P").append(new FakeText("")),
315 );
316
317 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
318 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
319 );
320 });
321
322 it("still fences a code block copied alongside prose", () => {
323 const container = new FakeElement("DIV").append(
324 new FakeElement("P").append(new FakeText("Run this:")),
325 renderedCodeBlock(["gh workflow run Deploy --ref main"]),
326 );
327
328 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
329 "Run this:\n\n```\ngh workflow run Deploy --ref main\n```",
330 );
331 });
332
333 it("uses a rendered card's explicit Markdown copy representation", () => {
334 const card = new FakeElement("DIV", [], {
335 "data-markdown-copy": "Hello World (Document template)\n\n",
336 }).append(
337 new FakeElement("SPAN").append(new FakeText("Hello World")),
338 new FakeElement("SPAN").append(new FakeText("Document template")),
339 new FakeElement("BUTTON").append(new FakeText("Use template")),
340 );
341 const container = new FakeElement("DIV").append(card);
342
343 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
344 "Hello World (Document template)",
345 );
346 });
347});