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

markdown-clipboard.test.ts

322 lines11.2 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("keeps fences when a bare list item sits alongside the code block", () => {
201 const container = new FakeElement("DIV").append(
202 new FakeElement("UL").append(new FakeElement("LI")),
203 renderedCodeBlock(["pnpm test"]),
204 );
205​
206 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
207 });
208​
209 it("keeps blank lines inside a code block in a list item, quote, or longer fence", () => {
210 const code = ["import os", "", "", "def main():"];
211 const list = new FakeElement("OL").append(
212 new FakeElement("LI").append(new FakeText("Create it:\n"), renderedCodeBlock(code)),
213 );
214 const quote = new FakeElement("BLOCKQUOTE").append(
215 new FakeElement("P").append(new FakeText("Note:")),
216 renderedCodeBlock(code),
217 );
218 const nestedFence = new FakeElement("DIV").append(
219 new FakeElement("P").append(new FakeText("Example:")),
220 renderedCodeBlock(["```js", "a()", "", "", "b() ", "```"]),
221 );
222​
223 expect(serializeRenderedMarkdownFragment(asNode(nestedFence))).toBe(
224 "Example:\n\n````\n```js\na()\n\n\nb() \n```\n````",
225 );
226​
227 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
228 "1. Create it:\n ```\n import os\n\n\n def main():\n ```",
229 );
230 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(quote)))).toBe(
231 "> Note:\n>\n> ```\n> import os\n>\n>\n> def main():\n> ```",
232 );
233 });
234​
235 it("omits fences when a selection past the last line drags in the whole code block", () => {
236 const container = new FakeElement("DIV").append(
237 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
238 new FakeText("\n"),
239 new FakeElement("P").append(new FakeText("")),
240 );
241​
242 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
243 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
244 );
245 });
246});
247​
248function renderedFormula(tex: string): FakeElement {
249 // MarkdownMath's wrapper; its children stand in for KaTeX's glyphs.
250 return new FakeElement("SPAN", [], {
251 "data-markdown-math": "inline",
252 "data-markdown-copy": `\\(${tex}\\)`,
253 }).append(new FakeText(tex));
255​
256function renderedTable(...rows: Array<Array<FakeElement | FakeText>>): FakeElement {
257 const row = (tag: string, cells: Array<FakeElement | FakeText>) =>
258 new FakeElement("TR").append(...cells.map((cell) => new FakeElement(tag).append(cell)));
259 const [head = [], ...body] = rows;
260 return new FakeElement("TABLE").append(
261 new FakeElement("THEAD").append(row("TH", head)),
262 new FakeElement("TBODY").append(...body.map((cells) => row("TD", cells))),
263 );
265​
266describe("copying rendered Markdown tables", () => {
267 beforeEach(() => {
268 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
269 });
270​
271 afterEach(() => {
272 vi.unstubAllGlobals();
273 });
274​
275 it("keeps formula pipes as authored while escaping prose pipes", () => {
276 const table = renderedTable(
277 [new FakeText("Formula"), new FakeText("Note")],
278 [renderedFormula("|x|"), new FakeText("a | b")],
279 [renderedFormula("\\|x\\|"), new FakeElement("CODE").append(new FakeText("\\(c|d\\)"))],
280 [
281 new FakeElement("A", [], { href: "https://example.com/?q=a|b" }).append(
282 new FakeText("norm "),
283 renderedFormula("|y|"),
284 ),
285 new FakeText("e"),
286 ],
287 [
288 new FakeElement("UL").append(
289 new FakeElement("LI").append(renderedFormula("|z|"), new FakeText(" a | b")),
290 ),
291 new FakeElement("BLOCKQUOTE").append(new FakeElement("P").append(new FakeText("c | d"))),
292 ],
293 );
294 const markdown = serializeTableElementToMarkdown(table as unknown as Element);
295​
296 const tree = parseMarkdownWithMath(markdown);
297 const parsed = tree.children[0];
298 if (parsed?.type !== "table") throw new Error("Expected a table");
299 expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]);
300 expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([
301 "|x|",
302 "\\|x\\|",
303 "|y|",
304 "|z|",
305 ]);
306 expect(parsed.children[1]?.children[1]?.children).toMatchObject([
307 { type: "text", value: "a | b" },
308 ]);
309 expect(parsed.children[4]?.children[1]?.children).toMatchObject([
310 { type: "text", value: "> c | d" },
311 ]);
312 const [, , codeRow, linkRow] = parsed.children;
313 expect(codeRow?.children[1]?.children[0]).toMatchObject({
314 type: "inlineCode",
315 value: "\\(c|d\\)",
316 });
317 expect(linkRow?.children[0]?.children[0]).toMatchObject({
318 type: "link",
319 url: "https://example.com/?q=a|b",
320 });
321 });
322});