Open History to see the last commit
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) {}
18}
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 }
85}
86
87function asNode(element: FakeElement): Node {
88 return element as unknown as Node;
89}
90
91function shikiCodeLine(text: string): FakeElement {
92 const token = new FakeElement("SPAN").append(new FakeText(text));
93 return new FakeElement("SPAN", ["line"]).append(token);
94}
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 );
109}
110
111describe("serializeRenderedMarkdownFragment", () => {
112 it("copies a popover context reference once, without its details or nested label", () => {
113 const reference = "[Review comment](t3-context://v1/review-comment/review-1)";
114 const container = new FakeElement("DIV").append(
115 new FakeText("Fix "),
116 new FakeElement("BUTTON", [], { "data-markdown-copy": reference }).append(
117 new FakeElement("SPAN", [], { "data-markdown-copy": reference }).append(
118 new FakeText("Review comment"),
119 ),
120 ),
121 new FakeText(" please"),
122 );
123
124 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(`Fix ${reference} please`);
125 });
126
127 beforeEach(() => {
128 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
129 });
130
131 afterEach(() => {
132 vi.unstubAllGlobals();
133 });
134
135 it("wraps inline code in backticks", () => {
136 const paragraph = new FakeElement("P").append(
137 new FakeText("run "),
138 new FakeElement("CODE").append(new FakeText("git status")),
139 new FakeText(" first"),
140 );
141 const container = new FakeElement("DIV").append(paragraph);
142
143 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("run `git status` first");
144 });
145
146 it("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
147 const citation = {
148 version: 1 as const,
149 environmentId: EnvironmentId.make("environment-one"),
150 threadId: ThreadId.make("thread-one"),
151 messageId: MessageId.make("assistant-one"),
152 text: "A complete quote, including the part hidden by the chip preview.",
153 comment: "What does this mean?\nPlease expand on the hidden part.",
154 start: 0,
155 end: 66,
156 prefix: "",
157 suffix: "",
158 };
159 const anchor = new FakeElement("A", [], {
160 "data-markdown-copy": serializeAssistantCitation(citation),
161 href: "/environment-one/thread-one#citation",
162 }).append(new FakeText("What does this mean?…"));
163 const chip = new FakeElement("SPAN", [], {
164 "data-markdown-copy": serializeAssistantCitation(citation),
165 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
166 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
167 const copied = serializeRenderedMarkdownFragment(asNode(container));
168 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
169 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
170 });
171
172 it("keeps a highlighted block code selection plain when its pre wrapper is outside the range", () => {
173 const code = new FakeElement("CODE").append(
174 shikiCodeLine("git show-ref --verify refs/remotes/origin/opt/deploy/dev"),
175 );
176 const container = new FakeElement("DIV").append(code);
177
178 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
179 "git show-ref --verify refs/remotes/origin/opt/deploy/dev",
180 );
181 });
182
183 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
184 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
185 const container = new FakeElement("DIV").append(code);
186
187 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
188 });
189
190 it("keeps fences when a bare list item sits alongside the code block", () => {
191 // serializeListItem emits "- " for an item with no text, so the item is
192 // content the plain-code path would drop.
193 const container = new FakeElement("DIV").append(
194 new FakeElement("UL").append(new FakeElement("LI")),
195 renderedCodeBlock(["pnpm test"]),
196 );
197
198 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
199 });
200
201 it("keeps fences when a checkbox-only task item sits alongside the code block", () => {
202 // The checkbox is a skipped tag, so the item renders no text of its own, but
203 // it still carries the task state.
204 const container = new FakeElement("DIV").append(
205 new FakeElement("UL").append(
206 new FakeElement("LI").append(new FakeElement("INPUT", [], { type: "checkbox" })),
207 ),
208 renderedCodeBlock(["pnpm test"]),
209 );
210
211 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
212 "- [ ]\n\n```\npnpm test\n```",
213 );
214 });
215
216 it("still drops fences for a code block that is the whole list item", () => {
217 // The item only wraps the block, so a selection that never left the pre
218 // would drop the marker too.
219 const container = new FakeElement("DIV").append(
220 new FakeElement("UL").append(new FakeElement("LI").append(renderedCodeBlock(["pnpm test"]))),
221 new FakeText("\n"),
222 );
223
224 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("pnpm test");
225 });
226
227 it("keeps fences when a file chip sits alongside the code block", () => {
228 // The chip renders as a button, a skipped tag, but its data-markdown-copy
229 // still contributes markdown, so the block is not the only visible content.
230 const container = new FakeElement("DIV").append(
231 renderedCodeBlock(["pnpm test"]),
232 new FakeText("\n"),
233 new FakeElement("BUTTON", [], { "data-markdown-copy": "`src/foo.ts`" }),
234 );
235
236 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
237 "```\npnpm test\n```\n\n`src/foo.ts`",
238 );
239 });
240
241 it("omits fences when a selection past the last line drags in the whole code block", () => {
242 // Dragging over the final newline ends the range after the pre, so the
243 // fragment carries the block plus the empty head of the next paragraph.
244 const container = new FakeElement("DIV").append(
245 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
246 new FakeText("\n"),
247 new FakeElement("P").append(new FakeText("")),
248 );
249
250 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
251 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
252 );
253 });
254
255 it("still fences a code block copied alongside prose", () => {
256 const container = new FakeElement("DIV").append(
257 new FakeElement("P").append(new FakeText("Run this:")),
258 renderedCodeBlock(["gh workflow run Deploy --ref main"]),
259 );
260
261 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
262 "Run this:\n\n```\ngh workflow run Deploy --ref main\n```",
263 );
264 });
265
266 it("uses a rendered card's explicit Markdown copy representation", () => {
267 const card = new FakeElement("DIV", [], {
268 "data-markdown-copy": "Hello World (Document template)\n\n",
269 }).append(
270 new FakeElement("SPAN").append(new FakeText("Hello World")),
271 new FakeElement("SPAN").append(new FakeText("Document template")),
272 new FakeElement("BUTTON").append(new FakeText("Use template")),
273 );
274 const container = new FakeElement("DIV").append(card);
275
276 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
277 "Hello World (Document template)",
278 );
279 });
280});