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

markdown-clipboard.test.ts

200 lines6.8 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 checked = false;
23 readonly childNodes: Array<FakeElement | FakeText> = [];
24 readonly classList = {
25 contains: (name: string) => this.classNames.includes(name),
26 };
27​
28 constructor(
29 readonly tagName: string,
30 private readonly classNames: ReadonlyArray<string> = [],
31 private readonly attributes: Readonly<Record<string, string>> = {},
32 ) {}
33​
34 get localName(): string {
35 return this.tagName.toLowerCase();
36 }
37​
38 get textContent(): string {
39 return this.childNodes.map((child) => child.textContent).join("");
40 }
41​
42 get children(): ReadonlyArray<FakeElement> {
43 return this.childNodes.filter((child): child is FakeElement => child instanceof FakeElement);
44 }
45​
46 append(...children: Array<FakeElement | FakeText>): this {
47 this.childNodes.push(...children);
48 return this;
49 }
50​
51 getAttribute(name: string): string | null {
52 return this.attributes[name] ?? null;
53 }
54​
55 hasAttribute(name: string): boolean {
56 return Object.hasOwn(this.attributes, name);
57 }
58​
59 closest(): FakeElement | null {
60 return null;
61 }
62​
63 querySelector(selector: string): FakeElement | null {
64 if (selector.includes(", ")) {
65 for (const part of selector.split(", ")) {
66 const match = this.querySelector(part);
67 if (match) return match;
68 }
69 return null;
70 }
71 const childOnly = selector.startsWith(":scope > ");
72 const [target, ...rest] = (childOnly ? selector.slice(":scope > ".length) : selector).split(
73 " > ",
74 );
75 const matches = (element: FakeElement): boolean => {
76 if (target === 'input[type="checkbox"]') {
77 return element.tagName === "INPUT" && element.getAttribute("type") === "checkbox";
78 }
79 return element.tagName === target?.toUpperCase();
80 };
81 const search = (parent: FakeElement): FakeElement | null => {
82 for (const child of parent.childNodes) {
83 if (!(child instanceof FakeElement)) continue;
84 if (matches(child)) {
85 if (rest.length === 0) return child;
86 const nested = child.querySelector(`:scope > ${rest.join(" > ")}`);
87 if (nested) return nested;
88 }
89 if (!childOnly) {
90 const nested = search(child);
91 if (nested) return nested;
92 }
93 }
94 return null;
95 };
96 return search(this);
97 }
99​
100function asNode(element: FakeElement): Node {
101 return element as unknown as Node;
103​
104function shikiCodeLine(text: string): FakeElement {
105 const token = new FakeElement("SPAN").append(new FakeText(text));
106 return new FakeElement("SPAN", ["line"]).append(token);
108​
109function renderedCodeBlock(lines: ReadonlyArray<string>): FakeElement {
110 const code = new FakeElement("CODE");
111 lines.forEach((line, index) => {
112 if (index > 0) code.append(new FakeText("\n"));
113 code.append(shikiCodeLine(line));
114 });
115 return new FakeElement("DIV", ["chat-markdown-codeblock"]).append(
116 new FakeElement("DIV", ["chat-markdown-codeblock-header", "select-none"]).append(
117 new FakeText("sh"),
118 ),
119 new FakeElement("DIV", ["chat-markdown-shiki"]).append(new FakeElement("PRE").append(code)),
120 );
122​
123describe("serializeRenderedMarkdownFragment", () => {
124 it("copies a popover context reference once, without its details or nested label", () => {
125 const reference = "[Review comment](t3-context://v1/review-comment/review-1)";
126 const container = new FakeElement("DIV").append(
127 new FakeText("Fix "),
128 new FakeElement("BUTTON", [], { "data-markdown-copy": reference }).append(
129 new FakeElement("SPAN", [], { "data-markdown-copy": reference }).append(
130 new FakeText("Review comment"),
131 ),
132 ),
133 new FakeText(" please"),
134 );
135​
136 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(`Fix ${reference} please`);
137 });
138​
139 beforeEach(() => {
140 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
141 });
142​
143 afterEach(() => {
144 vi.unstubAllGlobals();
145 });
146​
147 it("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
148 const citation = {
149 version: 1 as const,
150 environmentId: EnvironmentId.make("environment-one"),
151 threadId: ThreadId.make("thread-one"),
152 messageId: MessageId.make("assistant-one"),
153 text: "A complete quote, including the part hidden by the chip preview.",
154 comment: "What does this mean?\nPlease expand on the hidden part.",
155 start: 0,
156 end: 66,
157 prefix: "",
158 suffix: "",
159 };
160 const anchor = new FakeElement("A", [], {
161 "data-markdown-copy": serializeAssistantCitation(citation),
162 href: "/environment-one/thread-one#citation",
163 }).append(new FakeText("What does this mean?…"));
164 const chip = new FakeElement("SPAN", [], {
165 "data-markdown-copy": serializeAssistantCitation(citation),
166 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
167 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
168 const copied = serializeRenderedMarkdownFragment(asNode(container));
169 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
170 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
171 });
172​
173 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
174 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
175 const container = new FakeElement("DIV").append(code);
176​
177 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
178 });
179​
180 it("keeps fences when a bare list item sits alongside the code block", () => {
181 const container = new FakeElement("DIV").append(
182 new FakeElement("UL").append(new FakeElement("LI")),
183 renderedCodeBlock(["pnpm test"]),
184 );
185​
186 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
187 });
188​
189 it("omits fences when a selection past the last line drags in the whole code block", () => {
190 const container = new FakeElement("DIV").append(
191 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
192 new FakeText("\n"),
193 new FakeElement("P").append(new FakeText("")),
194 );
195​
196 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
197 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
198 );
199 });
200});