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

markdown-clipboard.test.ts

334 lines11.8 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import {
4 serializeRenderedMarkdownFragment,
5 serializeTableElementToMarkdown,
6} from "./markdown-clipboard";
7import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
8import {
9 collectAssistantCitations,
10 serializeAssistantCitation,
11} from "@t3tools/shared/assistantCitations";
12import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
13​
14const TEXT_NODE = 3;
15const ELEMENT_NODE = 1;
16​
17class FakeText {
18 readonly nodeType = TEXT_NODE;
19 readonly childNodes: ReadonlyArray<never> = [];
20​
21 constructor(readonly textContent: string) {}
23​
24class FakeElement {
25 readonly nodeType = ELEMENT_NODE;
26 checked = false;
27 readonly childNodes: Array<FakeElement | FakeText> = [];
28 readonly classList = {
29 contains: (name: string) => this.classNames.includes(name),
30 };
31​
32 constructor(
33 readonly tagName: string,
34 private readonly classNames: ReadonlyArray<string> = [],
35 private readonly attributes: Readonly<Record<string, string>> = {},
36 ) {}
37​
38 get localName(): string {
39 return this.tagName.toLowerCase();
40 }
41​
42 get textContent(): string {
43 return this.childNodes.map((child) => child.textContent).join("");
44 }
45​
46 get children(): ReadonlyArray<FakeElement> {
47 return this.childNodes.filter((child): child is FakeElement => child instanceof FakeElement);
48 }
49​
50 append(...children: Array<FakeElement | FakeText>): this {
51 this.childNodes.push(...children);
52 return this;
53 }
54​
55 getAttribute(name: string): string | null {
56 return this.attributes[name] ?? null;
57 }
58​
59 hasAttribute(name: string): boolean {
60 return Object.hasOwn(this.attributes, name);
61 }
62​
63 closest(): FakeElement | null {
64 return null;
65 }
66​
67 querySelector(selector: string): FakeElement | null {
68 if (selector.includes(", ")) {
69 for (const part of selector.split(", ")) {
70 const match = this.querySelector(part);
71 if (match) return match;
72 }
73 return null;
74 }
75 const childOnly = selector.startsWith(":scope > ");
76 const [target, ...rest] = (childOnly ? selector.slice(":scope > ".length) : selector).split(
77 " > ",
78 );
79 const matches = (element: FakeElement): boolean => {
80 if (target === 'input[type="checkbox"]') {
81 return element.tagName === "INPUT" && element.getAttribute("type") === "checkbox";
82 }
83 return element.tagName === target?.toUpperCase();
84 };
85 const search = (parent: FakeElement): FakeElement | null => {
86 for (const child of parent.childNodes) {
87 if (!(child instanceof FakeElement)) continue;
88 if (matches(child)) {
89 if (rest.length === 0) return child;
90 const nested = child.querySelector(`:scope > ${rest.join(" > ")}`);
91 if (nested) return nested;
92 }
93 if (!childOnly) {
94 const nested = search(child);
95 if (nested) return nested;
96 }
97 }
98 return null;
99 };
100 return search(this);
101 }
102​
103 /** Supports the `:scope > a > b` child paths the table serializer queries. */
104 querySelectorAll(selector: string): FakeElement[] {
105 return selector.split(", ").flatMap((part) =>
106 part
107 .replace(/^:scope > /, "")
108 .split(" > ")
109 .reduce<FakeElement[]>(
110 (level, tag) =>
111 level.flatMap((element) =>
112 element.children.filter((child) => child.tagName === tag.toUpperCase()),
113 ),
114 [this],
115 ),
116 );
117 }
119​
120function asNode(element: FakeElement): Node {
121 return element as unknown as Node;
123​
124function shikiCodeLine(text: string): FakeElement {
125 const token = new FakeElement("SPAN").append(new FakeText(text));
126 return new FakeElement("SPAN", ["line"]).append(token);
128​
129function renderedCodeBlock(lines: ReadonlyArray<string>): FakeElement {
130 const code = new FakeElement("CODE");
131 lines.forEach((line, index) => {
132 if (index > 0) code.append(new FakeText("\n"));
133 code.append(shikiCodeLine(line));
134 });
135 return new FakeElement("DIV", ["chat-markdown-codeblock"]).append(
136 new FakeElement("DIV", ["chat-markdown-codeblock-header", "select-none"]).append(
137 new FakeText("sh"),
138 ),
139 new FakeElement("DIV", ["chat-markdown-shiki"]).append(new FakeElement("PRE").append(code)),
140 );
142​
143describe("serializeRenderedMarkdownFragment", () => {
144 it("copies a popover context reference once, without its details or nested label", () => {
145 const reference = "[Review comment](t3-context://v1/review-comment/review-1)";
146 const container = new FakeElement("DIV").append(
147 new FakeText("Fix "),
148 new FakeElement("BUTTON", [], { "data-markdown-copy": reference }).append(
149 new FakeElement("SPAN", [], { "data-markdown-copy": reference }).append(
150 new FakeText("Review comment"),
151 ),
152 ),
153 new FakeText(" please"),
154 );
155​
156 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(`Fix ${reference} please`);
157 });
158​
159 beforeEach(() => {
160 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
161 });
162​
163 afterEach(() => {
164 vi.unstubAllGlobals();
165 });
166​
167 it("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
168 const citation = {
169 version: 1 as const,
170 environmentId: EnvironmentId.make("environment-one"),
171 threadId: ThreadId.make("thread-one"),
172 messageId: MessageId.make("assistant-one"),
173 text: "A complete quote, including the part hidden by the chip preview.",
174 comment: "What does this mean?\nPlease expand on the hidden part.",
175 start: 0,
176 end: 66,
177 prefix: "",
178 suffix: "",
179 };
180 const anchor = new FakeElement("A", [], {
181 "data-markdown-copy": serializeAssistantCitation(citation),
182 href: "/environment-one/thread-one#citation",
183 }).append(new FakeText("What does this mean?…"));
184 const chip = new FakeElement("SPAN", [], {
185 "data-markdown-copy": serializeAssistantCitation(citation),
186 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
187 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
188 const copied = serializeRenderedMarkdownFragment(asNode(container));
189 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
190 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
191 });
192​
193 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
194 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
195 const container = new FakeElement("DIV").append(code);
196​
197 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
198 });
199​
200 it("preserves explicit ordered-list values and continues from resets when copying", () => {
201 const list = new FakeElement("OL", [], { start: "0" }).append(
202 new FakeElement("LI").append(new FakeText("A")),
203 new FakeElement("LI", [], { value: "5" }).append(new FakeText("B")),
204 new FakeElement("LI").append(new FakeText("C")),
205 new FakeElement("LI", [], { value: "0" }).append(new FakeText("D")),
206 );
207 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
208 "0. A\n5. B\n6. C\n0. D",
209 );
210 });
211​
212 it("keeps fences when a bare list item sits alongside the code block", () => {
213 const container = new FakeElement("DIV").append(
214 new FakeElement("UL").append(new FakeElement("LI")),
215 renderedCodeBlock(["pnpm test"]),
216 );
217​
218 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
219 });
220​
221 it("keeps blank lines inside a code block in a list item, quote, or longer fence", () => {
222 const code = ["import os", "", "", "def main():"];
223 const list = new FakeElement("OL").append(
224 new FakeElement("LI").append(new FakeText("Create it:\n"), renderedCodeBlock(code)),
225 );
226 const quote = new FakeElement("BLOCKQUOTE").append(
227 new FakeElement("P").append(new FakeText("Note:")),
228 renderedCodeBlock(code),
229 );
230 const nestedFence = new FakeElement("DIV").append(
231 new FakeElement("P").append(new FakeText("Example:")),
232 renderedCodeBlock(["```js", "a()", "", "", "b() ", "```"]),
233 );
234​
235 expect(serializeRenderedMarkdownFragment(asNode(nestedFence))).toBe(
236 "Example:\n\n````\n```js\na()\n\n\nb() \n```\n````",
237 );
238​
239 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
240 "1. Create it:\n ```\n import os\n\n\n def main():\n ```",
241 );
242 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(quote)))).toBe(
243 "> Note:\n>\n> ```\n> import os\n>\n>\n> def main():\n> ```",
244 );
245 });
246​
247 it("omits fences when a selection past the last line drags in the whole code block", () => {
248 const container = new FakeElement("DIV").append(
249 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
250 new FakeText("\n"),
251 new FakeElement("P").append(new FakeText("")),
252 );
253​
254 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
255 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
256 );
257 });
258});
259​
260function renderedFormula(tex: string): FakeElement {
261 // MarkdownMath's wrapper; its children stand in for KaTeX's glyphs.
262 return new FakeElement("SPAN", [], {
263 "data-markdown-math": "inline",
264 "data-markdown-copy": `\\(${tex}\\)`,
265 }).append(new FakeText(tex));
267​
268function renderedTable(...rows: Array<Array<FakeElement | FakeText>>): FakeElement {
269 const row = (tag: string, cells: Array<FakeElement | FakeText>) =>
270 new FakeElement("TR").append(...cells.map((cell) => new FakeElement(tag).append(cell)));
271 const [head = [], ...body] = rows;
272 return new FakeElement("TABLE").append(
273 new FakeElement("THEAD").append(row("TH", head)),
274 new FakeElement("TBODY").append(...body.map((cells) => row("TD", cells))),
275 );
277​
278describe("copying rendered Markdown tables", () => {
279 beforeEach(() => {
280 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
281 });
282​
283 afterEach(() => {
284 vi.unstubAllGlobals();
285 });
286​
287 it("keeps formula pipes as authored while escaping prose pipes", () => {
288 const table = renderedTable(
289 [new FakeText("Formula"), new FakeText("Note")],
290 [renderedFormula("|x|"), new FakeText("a | b")],
291 [renderedFormula("\\|x\\|"), new FakeElement("CODE").append(new FakeText("\\(c|d\\)"))],
292 [
293 new FakeElement("A", [], { href: "https://example.com/?q=a|b" }).append(
294 new FakeText("norm "),
295 renderedFormula("|y|"),
296 ),
297 new FakeText("e"),
298 ],
299 [
300 new FakeElement("UL").append(
301 new FakeElement("LI").append(renderedFormula("|z|"), new FakeText(" a | b")),
302 ),
303 new FakeElement("BLOCKQUOTE").append(new FakeElement("P").append(new FakeText("c | d"))),
304 ],
305 );
306 const markdown = serializeTableElementToMarkdown(table as unknown as Element);
307​
308 const tree = parseMarkdownWithMath(markdown);
309 const parsed = tree.children[0];
310 if (parsed?.type !== "table") throw new Error("Expected a table");
311 expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]);
312 expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([
313 "|x|",
314 "\\|x\\|",
315 "|y|",
316 "|z|",
317 ]);
318 expect(parsed.children[1]?.children[1]?.children).toMatchObject([
319 { type: "text", value: "a | b" },
320 ]);
321 expect(parsed.children[4]?.children[1]?.children).toMatchObject([
322 { type: "text", value: "> c | d" },
323 ]);
324 const [, , codeRow, linkRow] = parsed.children;
325 expect(codeRow?.children[1]?.children[0]).toMatchObject({
326 type: "inlineCode",
327 value: "\\(c|d\\)",
328 });
329 expect(linkRow?.children[0]?.children[0]).toMatchObject({
330 type: "link",
331 url: "https://example.com/?q=a|b",
332 });
333 });
334});