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

markdown-clipboard.test.ts

265 lines9.6 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 readonly childNodes: Array<FakeElement | FakeText> = [];
23 readonly classList = {
24 contains: (name: string) => this.classNames.includes(name),
25 };
26​
27 constructor(
28 readonly tagName: string,
29 private readonly classNames: ReadonlyArray<string> = [],
30 private readonly attributes: Readonly<Record<string, string>> = {},
31 ) {}
32​
33 get localName(): string {
34 return this.tagName.toLowerCase();
35 }
36​
37 get textContent(): string {
38 return this.childNodes.map((child) => child.textContent).join("");
39 }
40​
41 get children(): ReadonlyArray<FakeElement> {
42 return this.childNodes.filter((child): child is FakeElement => child instanceof FakeElement);
43 }
44​
45 append(...children: Array<FakeElement | FakeText>): this {
46 this.childNodes.push(...children);
47 return this;
48 }
49​
50 getAttribute(name: string): string | null {
51 return this.attributes[name] ?? null;
52 }
53​
54 hasAttribute(name: string): boolean {
55 return Object.hasOwn(this.attributes, name);
56 }
57​
58 closest(): FakeElement | null {
59 return null;
60 }
61​
62 /** Supports only the selectors markdown-clipboard actually asks for. */
63 querySelector(selector: string): FakeElement | null {
64 const childOnly = selector.startsWith(":scope > ");
65 const target = childOnly ? selector.slice(":scope > ".length) : selector;
66 const matches = (element: FakeElement): boolean => {
67 if (target === 'input[type="checkbox"]') {
68 return element.tagName === "INPUT" && element.getAttribute("type") === "checkbox";
69 }
70 return element.tagName === target.toUpperCase();
71 };
72 const search = (parent: FakeElement): FakeElement | null => {
73 for (const child of parent.childNodes) {
74 if (!(child instanceof FakeElement)) continue;
75 if (matches(child)) return child;
76 if (!childOnly) {
77 const nested = search(child);
78 if (nested) return nested;
79 }
80 }
81 return null;
82 };
83 return search(this);
84 }
86​
87function asNode(element: FakeElement): Node {
88 return element as unknown as Node;
90​
91function shikiCodeLine(text: string): FakeElement {
92 const token = new FakeElement("SPAN").append(new FakeText(text));
93 return new FakeElement("SPAN", ["line"]).append(token);
95​
96/** Mirrors a rendered code block: select-none header chrome plus a shiki pre. */
97function renderedCodeBlock(lines: ReadonlyArray<string>): FakeElement {
98 const code = new FakeElement("CODE");
99 lines.forEach((line, index) => {
100 if (index > 0) code.append(new FakeText("\n"));
101 code.append(shikiCodeLine(line));
102 });
103 return new FakeElement("DIV", ["chat-markdown-codeblock"]).append(
104 new FakeElement("DIV", ["chat-markdown-codeblock-header", "select-none"]).append(
105 new FakeText("sh"),
106 ),
107 new FakeElement("DIV", ["chat-markdown-shiki"]).append(new FakeElement("PRE").append(code)),
108 );
110​
111describe("serializeRenderedMarkdownFragment", () => {
112 beforeEach(() => {
113 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
114 });
115​
116 afterEach(() => {
117 vi.unstubAllGlobals();
118 });
119​
120 it("wraps inline code in backticks", () => {
121 const paragraph = new FakeElement("P").append(
122 new FakeText("run "),
123 new FakeElement("CODE").append(new FakeText("git status")),
124 new FakeText(" first"),
125 );
126 const container = new FakeElement("DIV").append(paragraph);
127​
128 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("run `git status` first");
129 });
130​
131 it("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
132 const citation = {
133 version: 1 as const,
134 environmentId: EnvironmentId.make("environment-one"),
135 threadId: ThreadId.make("thread-one"),
136 messageId: MessageId.make("assistant-one"),
137 text: "A complete quote, including the part hidden by the chip preview.",
138 comment: "What does this mean?\nPlease expand on the hidden part.",
139 start: 0,
140 end: 66,
141 prefix: "",
142 suffix: "",
143 };
144 const anchor = new FakeElement("A", [], {
145 "data-markdown-copy": serializeAssistantCitation(citation),
146 href: "/environment-one/thread-one#citation",
147 }).append(new FakeText("What does this mean?…"));
148 const chip = new FakeElement("SPAN", [], {
149 "data-markdown-copy": serializeAssistantCitation(citation),
150 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
151 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
152 const copied = serializeRenderedMarkdownFragment(asNode(container));
153 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
154 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
155 });
156​
157 it("keeps a highlighted block code selection plain when its pre wrapper is outside the range", () => {
158 const code = new FakeElement("CODE").append(
159 shikiCodeLine("git show-ref --verify refs/remotes/origin/opt/deploy/dev"),
160 );
161 const container = new FakeElement("DIV").append(code);
162​
163 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
164 "git show-ref --verify refs/remotes/origin/opt/deploy/dev",
165 );
166 });
167​
168 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
169 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
170 const container = new FakeElement("DIV").append(code);
171​
172 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
173 });
174​
175 it("keeps fences when a bare list item sits alongside the code block", () => {
176 // serializeListItem emits "- " for an item with no text, so the item is
177 // content the plain-code path would drop.
178 const container = new FakeElement("DIV").append(
179 new FakeElement("UL").append(new FakeElement("LI")),
180 renderedCodeBlock(["pnpm test"]),
181 );
182​
183 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
184 });
185​
186 it("keeps fences when a checkbox-only task item sits alongside the code block", () => {
187 // The checkbox is a skipped tag, so the item renders no text of its own, but
188 // it still carries the task state.
189 const container = new FakeElement("DIV").append(
190 new FakeElement("UL").append(
191 new FakeElement("LI").append(new FakeElement("INPUT", [], { type: "checkbox" })),
192 ),
193 renderedCodeBlock(["pnpm test"]),
194 );
195​
196 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
197 "- [ ]\n\n```\npnpm test\n```",
198 );
199 });
200​
201 it("still drops fences for a code block that is the whole list item", () => {
202 // The item only wraps the block, so a selection that never left the pre
203 // would drop the marker too.
204 const container = new FakeElement("DIV").append(
205 new FakeElement("UL").append(new FakeElement("LI").append(renderedCodeBlock(["pnpm test"]))),
206 new FakeText("\n"),
207 );
208​
209 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("pnpm test");
210 });
211​
212 it("keeps fences when a file chip sits alongside the code block", () => {
213 // The chip renders as a button, a skipped tag, but its data-markdown-copy
214 // still contributes markdown, so the block is not the only visible content.
215 const container = new FakeElement("DIV").append(
216 renderedCodeBlock(["pnpm test"]),
217 new FakeText("\n"),
218 new FakeElement("BUTTON", [], { "data-markdown-copy": "`src/foo.ts`" }),
219 );
220​
221 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
222 "```\npnpm test\n```\n\n`src/foo.ts`",
223 );
224 });
225​
226 it("omits fences when a selection past the last line drags in the whole code block", () => {
227 // Dragging over the final newline ends the range after the pre, so the
228 // fragment carries the block plus the empty head of the next paragraph.
229 const container = new FakeElement("DIV").append(
230 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
231 new FakeText("\n"),
232 new FakeElement("P").append(new FakeText("")),
233 );
234​
235 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
236 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
237 );
238 });
239​
240 it("still fences a code block copied alongside prose", () => {
241 const container = new FakeElement("DIV").append(
242 new FakeElement("P").append(new FakeText("Run this:")),
243 renderedCodeBlock(["gh workflow run Deploy --ref main"]),
244 );
245​
246 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
247 "Run this:\n\n```\ngh workflow run Deploy --ref main\n```",
248 );
249 });
250​
251 it("uses a rendered card's explicit Markdown copy representation", () => {
252 const card = new FakeElement("DIV", [], {
253 "data-markdown-copy": "Hello World (Document template)\n\n",
254 }).append(
255 new FakeElement("SPAN").append(new FakeText("Hello World")),
256 new FakeElement("SPAN").append(new FakeText("Document template")),
257 new FakeElement("BUTTON").append(new FakeText("Use template")),
258 );
259 const container = new FakeElement("DIV").append(card);
260​
261 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
262 "Hello World (Document template)",
263 );
264 });
265});