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

pullRequestMarkdown.logic.test.ts

272 lines9.9 KB

1import type { Element, Root } from "hast";
2import { describe, expect, it } from "vite-plus/test";
3​
4import { wordsHast } from "~/markdown/wordsHast";
5import {
6 pullRequestCommentPreview,
7 pullRequestFootnoteExtensions,
8 pullRequestMarkdownExtensions,
9 splitPullRequestBody,
10} from "./pullRequestMarkdown.logic";
11​
12function links(markdown: string) {
13 const extensions = pullRequestMarkdownExtensions({
14 provider: "github",
15 url: "https://github.com/team/repo/pull/8",
16 });
17 const tree = wordsHast(markdown, {
18 math: false,
19 breaks: false,
20 escapeHtml: false,
21 insights: false,
22 extensions,
23 });
24 const found: Array<[string, unknown, unknown]> = [];
25 const visit = (node: Root | Element) => {
26 for (const child of node.children) {
27 if (child.type !== "element") continue;
28 if (child.tagName === "a") {
29 const label = child.children[0];
30 found.push([
31 label?.type === "text" ? label.value : "",
32 child.properties.href,
33 child.properties.dataPullRequestAutolink,
34 ]);
35 }
36 visit(child);
37 }
38 };
39 visit(tree);
40 return found;
42​
43function renderFootnoteSegment(segment: ReturnType<typeof splitPullRequestBody>[number]) {
44 if (segment.kind !== "markdown") return [];
45 const tree = wordsHast(segment.text, {
46 math: false,
47 breaks: false,
48 escapeHtml: false,
49 insights: false,
50 extensions: segment.footnotes
51 ? pullRequestFootnoteExtensions(undefined, segment.footnotes)
52 : {},
53 });
54 const anchors: Array<[unknown, unknown]> = [];
55 const visit = (node: Root | Element) => {
56 for (const child of node.children) {
57 if (child.type !== "element") continue;
58 if (child.tagName === "a") anchors.push([child.properties.id, child.properties.href]);
59 visit(child);
60 }
61 };
62 visit(tree);
63 return anchors;
65​
66describe("splitPullRequestBody", () => {
67 it.each([
68 ["caret-prefixed", "^release notes"],
69 ["nonbreaking-space", "\u00a0"],
70 ])("keeps a %s reference link across lifted video", (_kind, label) => {
71 const video = "https://example.com/demo.mp4";
72 const href = "https://example.com/notes";
73 const body = `[Release notes][${label}]\n\n${video}\n\n[${label}]: ${href}`;
74 const expectedLinks = [["Release notes", href, undefined]];
75 expect(links(body).filter(([text]) => text === "Release notes")).toEqual(expectedLinks);
76​
77 const segments = splitPullRequestBody(body);
78 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "attachment", "markdown"]);
79 const first = segments[0];
80 expect(first?.kind === "markdown" ? links(first.text) : []).toEqual(expectedLinks);
81 });
82​
83 it("numbers footnotes across lifted video once, from one trailing section", () => {
84 const body = [
85 "See[^a].",
86 "https://example.com/demo.mp4",
87 " npm test",
88 "Also[^b] and[^a] [docs](https://example.com).",
89 "> [^a]: First note",
90 "- [^b]: Second note",
91 ].join("\n\n");
92 const segments = splitPullRequestBody(body);
93 expect(segments.map((segment) => [segment.kind, segment.footnotes])).toEqual([
94 ["markdown", "omit"],
95 ["attachment", undefined],
96 ["markdown", "omit-seeded"],
97 ["markdown", "only"],
98 ]);
99 const rendered = segments.map((segment) => {
100 if (segment.kind !== "markdown") return { anchors: [], text: "" };
101 const tree = wordsHast(segment.text, {
102 math: false,
103 breaks: false,
104 escapeHtml: false,
105 insights: false,
106 extensions: pullRequestFootnoteExtensions(undefined, segment.footnotes!),
107 });
108 const anchors: Array<[unknown, unknown]> = [];
109 let text = "";
110 const visit = (node: Root | Element) => {
111 for (const child of node.children) {
112 if (child.type === "text") text += child.value;
113 if (child.type !== "element") continue;
114 if (child.tagName === "a") anchors.push([child.properties.id, child.properties.href]);
115 visit(child);
116 }
117 };
118 visit(tree);
119 return { anchors, text };
120 });
121 expect(rendered[0]!.anchors).toEqual([
122 ["user-content-user-content-fnref-1", "#user-content-fn-1"],
123 ]);
124 expect(rendered[2]!.anchors).toEqual([
125 ["user-content-user-content-fnref-2", "#user-content-fn-2"],
126 ["user-content-user-content-fnref-1-2", "#user-content-fn-1"],
127 [undefined, "https://example.com"],
128 ]);
129 expect(rendered[2]!.text).toContain("npm test");
130 expect(rendered[3]!.anchors.map(([, href]) => href)).toEqual([
131 "#user-content-fnref-1",
132 "#user-content-fnref-1-2",
133 "#user-content-fnref-2",
134 ]);
135 expect(rendered[3]!.text).toContain("First note");
136 expect(rendered[3]!.text).toContain("Second note");
137​
138 const after = segments[2];
139 const offset =
140 after?.kind === "markdown" ? after.sourceOffset + after.text.indexOf("Also") : -1;
141 expect(offset).toBe(body.indexOf("Also"));
142 });
143​
144 it.each([
145 ["escaped opening bracket", "a\\[b"],
146 ["escaped closing bracket", "a\\]b"],
147 ["escaped trailing backslash", "a\\\\"],
148 ])("keeps a footnote with an %s across lifted video", (_kind, label) => {
149 const body = [
150 `See[^${label}].`,
151 "https://github.com/user-attachments/assets/a.mp4",
152 `[^${label}]: note`,
153 ].join("\n\n");
154 const segments = splitPullRequestBody(body);
155 expect(segments.map((segment) => [segment.kind, segment.footnotes])).toEqual([
156 ["markdown", "omit"],
157 ["attachment", undefined],
158 ["markdown", undefined],
159 ["markdown", "only"],
160 ]);
161 const render = (segment: (typeof segments)[number]) => {
162 if (segment.kind !== "markdown") return { refs: [], text: "" };
163 const tree = wordsHast(segment.text, {
164 math: false,
165 breaks: false,
166 escapeHtml: false,
167 insights: false,
168 extensions: segment.footnotes
169 ? pullRequestFootnoteExtensions(undefined, segment.footnotes)
170 : {},
171 });
172 const refs: Array<unknown> = [];
173 let text = "";
174 const visit = (node: Root | Element) => {
175 for (const child of node.children) {
176 if (child.type === "text") text += child.value;
177 if (child.type !== "element") continue;
178 if (child.tagName === "a" && child.properties.dataFootnoteRef !== undefined) {
179 refs.push(child.properties.href);
180 }
181 visit(child);
182 }
183 };
184 visit(tree);
185 return { refs, text };
186 };
187 expect(render(segments[0]!).refs).toEqual(["#user-content-fn-1"]);
188 expect(render(segments[3]!).text).toContain("note");
189 });
190​
191 it("ignores fenced footnote text after a leading BOM when numbering across lifted video", () => {
192 const body = [
193 "\uFEFF```\n[^b] fake\n```",
194 "https://github.com/user-attachments/assets/a.mp4",
195 "First[^a] then[^b].",
196 "[^a]: note a\n[^b]: note b",
197 ].join("\n\n");
198 const segments = splitPullRequestBody(body);
199 expect(renderFootnoteSegment(segments[2]!)).toEqual([
200 ["user-content-user-content-fnref-1", "#user-content-fn-1"],
201 ["user-content-user-content-fnref-2", "#user-content-fn-2"],
202 ]);
203 });
204​
205 it("renders a body whose footnote seeds pass the budget as one document", () => {
206 const body = Array.from({ length: 400 }, () => "x[^a][^a][^a]\n\nhttps://example.com/demo.mp4")
207 .concat("[^a]: note")
208 .join("\n\n");
209 expect(splitPullRequestBody(body).map((segment) => segment.kind)).toEqual(["markdown"]);
210 });
211});
212​
213describe("pullRequestMarkdownExtensions", () => {
214 it("links the host's references in prose and leaves links and code alone", () => {
215 expect(links("Fixes #12 in **abcdef1**. [#13](https://example.com) `#14`")).toEqual([
216 ["#12", "https://github.com/team/repo/issues/12", "reference"],
217 ["abcdef1", "https://github.com/team/repo/commit/abcdef1", "commit"],
218 ["#13", "https://example.com", undefined],
219 ]);
220 });
221 it("renders GitHub emoji shortcodes in prose and leaves code literal", () => {
222 const extensions = pullRequestMarkdownExtensions({
223 provider: "github",
224 url: "https://github.com/team/repo/pull/8",
225 });
226 const tree = wordsHast("Ship it :tada: :+1: `:tada:`", {
227 math: false,
228 breaks: false,
229 escapeHtml: false,
230 insights: false,
231 extensions,
232 });
233 const text = (node: Root | Element | Root["children"][number]): string => {
234 if (node.type === "text") return node.value;
235 if (node.type === "element" && node.tagName === "code") {
236 return `\`${node.children.map(text).join("")}\``;
237 }
238 return "children" in node ? node.children.map(text).join("") : "";
239 };
240 expect(text(tree)).toBe("Ship it πŸŽ‰ πŸ‘ `:tada:`");
241 });
242});
243​
244describe("pullRequestCommentPreview", () => {
245 it.each([
246 ["<!-- hidden -->\n> [!WARNING]\n**Guard** [this](https://example.com).", "Guard this."],
247 [
248 '<a href="https://example.com"><img src="badge.svg" /></a>\n<strong>Tasks keep the wrong computer</strong>',
249 "Tasks keep the wrong computer",
250 ],
251 [
252 "<details><summary>Review &amp; fixes</summary><p>First<br>Second</p></details>",
253 "Review & fixes First Second",
254 ],
255 ['<p title="value > limit">Keep <strong>this</strong> readable.</p>', "Keep this readable."],
256 [
257 "Use `<div>` and `Promise<void>`.\n\n```html\n<span>example</span>\n```",
258 "Use <div> and Promise<void>. <span>example</span>",
259 ],
260 ["![badge](https://example.com/badge.svg) **Review**", "badge Review"],
261 ["```md\n[!TIP]\n> [!WARNING]\n```\n\n [!NOTE]", "[!TIP] > [!WARNING] [!NOTE]"],
262 [
263 "Review :codex-file-citation{purpose='output'} safely.",
264 "Review :codex-file-citation{purpose='output'} safely.",
265 ],
266 [":codex-followup[Prepare **print** version]", ":codex-followup[Prepare **print** version]"],
267 ["Approved :thumbsup: `:warning:`", "Approved πŸ‘ :warning:"],
268 ["Approved :thumbsup:", "Approved :thumbsup:", "gitlab"],
269 ])("extracts readable text from %s", (body, expected, provider = "github") => {
270 expect(pullRequestCommentPreview(body, provider)).toBe(expected);
271 });
272});