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

markdown-clipboard.test.ts

296 lines10.1 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("omits fences when a selection past the last line drags in the whole code block", () => {
210 const container = new FakeElement("DIV").append(
211 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
212 new FakeText("\n"),
213 new FakeElement("P").append(new FakeText("")),
214 );
215​
216 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
217 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
218 );
219 });
220});
221​
222function renderedFormula(tex: string): FakeElement {
223 // MarkdownMath's wrapper; its children stand in for KaTeX's glyphs.
224 return new FakeElement("SPAN", [], {
225 "data-markdown-math": "inline",
226 "data-markdown-copy": `\\(${tex}\\)`,
227 }).append(new FakeText(tex));
229​
230function renderedTable(...rows: Array<Array<FakeElement | FakeText>>): FakeElement {
231 const row = (tag: string, cells: Array<FakeElement | FakeText>) =>
232 new FakeElement("TR").append(...cells.map((cell) => new FakeElement(tag).append(cell)));
233 const [head = [], ...body] = rows;
234 return new FakeElement("TABLE").append(
235 new FakeElement("THEAD").append(row("TH", head)),
236 new FakeElement("TBODY").append(...body.map((cells) => row("TD", cells))),
237 );
239​
240describe("copying rendered Markdown tables", () => {
241 beforeEach(() => {
242 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
243 });
244​
245 afterEach(() => {
246 vi.unstubAllGlobals();
247 });
248​
249 it("keeps formula pipes as authored while escaping prose pipes", () => {
250 const table = renderedTable(
251 [new FakeText("Formula"), new FakeText("Note")],
252 [renderedFormula("|x|"), new FakeText("a | b")],
253 [renderedFormula("\\|x\\|"), new FakeElement("CODE").append(new FakeText("\\(c|d\\)"))],
254 [
255 new FakeElement("A", [], { href: "https://example.com/?q=a|b" }).append(
256 new FakeText("norm "),
257 renderedFormula("|y|"),
258 ),
259 new FakeText("e"),
260 ],
261 [
262 new FakeElement("UL").append(
263 new FakeElement("LI").append(renderedFormula("|z|"), new FakeText(" a | b")),
264 ),
265 new FakeElement("BLOCKQUOTE").append(new FakeElement("P").append(new FakeText("c | d"))),
266 ],
267 );
268 const markdown = serializeTableElementToMarkdown(table as unknown as Element);
269​
270 const tree = parseMarkdownWithMath(markdown);
271 const parsed = tree.children[0];
272 if (parsed?.type !== "table") throw new Error("Expected a table");
273 expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]);
274 expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([
275 "|x|",
276 "\\|x\\|",
277 "|y|",
278 "|z|",
279 ]);
280 expect(parsed.children[1]?.children[1]?.children).toMatchObject([
281 { type: "text", value: "a | b" },
282 ]);
283 expect(parsed.children[4]?.children[1]?.children).toMatchObject([
284 { type: "text", value: "> c | d" },
285 ]);
286 const [, , codeRow, linkRow] = parsed.children;
287 expect(codeRow?.children[1]?.children[0]).toMatchObject({
288 type: "inlineCode",
289 value: "\\(c|d\\)",
290 });
291 expect(linkRow?.children[0]?.children[0]).toMatchObject({
292 type: "link",
293 url: "https://example.com/?q=a|b",
294 });
295 });
296});