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

markdown-clipboard.test.ts

333 lines12.0 KB

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) {}
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 }
99​
100function asNode(element: FakeElement): Node {
101 return element as unknown as Node;
103​
104function shikiCodeLine(text: string): FakeElement {
105 const token = new FakeElement("SPAN").append(new FakeText(text));
106 return new FakeElement("SPAN", ["line"]).append(token);
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 );
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("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
210 const citation = {
211 version: 1 as const,
212 environmentId: EnvironmentId.make("environment-one"),
213 threadId: ThreadId.make("thread-one"),
214 messageId: MessageId.make("assistant-one"),
215 text: "A complete quote, including the part hidden by the chip preview.",
216 comment: "What does this mean?\nPlease expand on the hidden part.",
217 start: 0,
218 end: 66,
219 prefix: "",
220 suffix: "",
221 };
222 const anchor = new FakeElement("A", [], {
223 "data-markdown-copy": serializeAssistantCitation(citation),
224 href: "/environment-one/thread-one#citation",
225 }).append(new FakeText("What does this mean?…"));
226 const chip = new FakeElement("SPAN", [], {
227 "data-markdown-copy": serializeAssistantCitation(citation),
228 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
229 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
230 const copied = serializeRenderedMarkdownFragment(asNode(container));
231 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
232 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
233 });
234​
235 it("keeps a highlighted block code selection plain when its pre wrapper is outside the range", () => {
236 const code = new FakeElement("CODE").append(
237 shikiCodeLine("git show-ref --verify refs/remotes/origin/opt/deploy/dev"),
238 );
239 const container = new FakeElement("DIV").append(code);
240​
241 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
242 "git show-ref --verify refs/remotes/origin/opt/deploy/dev",
243 );
244 });
245​
246 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
247 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
248 const container = new FakeElement("DIV").append(code);
249​
250 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
251 });
252​
253 it("keeps fences when a bare list item sits alongside the code block", () => {
254 const container = new FakeElement("DIV").append(
255 new FakeElement("UL").append(new FakeElement("LI")),
256 renderedCodeBlock(["pnpm test"]),
257 );
258​
259 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
260 });
261​
262 it("keeps fences when a checkbox-only task item sits alongside the code block", () => {
263 const container = new FakeElement("DIV").append(
264 new FakeElement("UL").append(
265 new FakeElement("LI").append(new FakeElement("INPUT", [], { type: "checkbox" })),
266 ),
267 renderedCodeBlock(["pnpm test"]),
268 );
269​
270 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
271 "- [ ]\n\n```\npnpm test\n```",
272 );
273 });
274​
275 it("still drops fences for a code block that is the whole list item", () => {
276 const container = new FakeElement("DIV").append(
277 new FakeElement("UL").append(new FakeElement("LI").append(renderedCodeBlock(["pnpm test"]))),
278 new FakeText("\n"),
279 );
280​
281 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("pnpm test");
282 });
283​
284 it("keeps fences when a file chip sits alongside the code block", () => {
285 const container = new FakeElement("DIV").append(
286 renderedCodeBlock(["pnpm test"]),
287 new FakeText("\n"),
288 new FakeElement("BUTTON", [], { "data-markdown-copy": "`src/foo.ts`" }),
289 );
290​
291 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
292 "```\npnpm test\n```\n\n`src/foo.ts`",
293 );
294 });
295​
296 it("omits fences when a selection past the last line drags in the whole code block", () => {
297 const container = new FakeElement("DIV").append(
298 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
299 new FakeText("\n"),
300 new FakeElement("P").append(new FakeText("")),
301 );
302​
303 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
304 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
305 );
306 });
307​
308 it("still fences a code block copied alongside prose", () => {
309 const container = new FakeElement("DIV").append(
310 new FakeElement("P").append(new FakeText("Run this:")),
311 renderedCodeBlock(["gh workflow run Deploy --ref main"]),
312 );
313​
314 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
315 "Run this:\n\n```\ngh workflow run Deploy --ref main\n```",
316 );
317 });
318​
319 it("uses a rendered card's explicit Markdown copy representation", () => {
320 const card = new FakeElement("DIV", [], {
321 "data-markdown-copy": "Hello World (Document template)\n\n",
322 }).append(
323 new FakeElement("SPAN").append(new FakeText("Hello World")),
324 new FakeElement("SPAN").append(new FakeText("Document template")),
325 new FakeElement("BUTTON").append(new FakeText("Use template")),
326 );
327 const container = new FakeElement("DIV").append(card);
328​
329 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
330 "Hello World (Document template)",
331 );
332 });
333});