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

markdownInlineFileLinks.test.ts

193 lines7.7 KB

1import { describe, expect, it } from "vite-plus/test";
2import { unified } from "unified";
3import remarkParse from "remark-parse";
4import remarkGfm from "remark-gfm";
5import type { Root, RootContent } from "mdast";
6import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation";
7import {
8 markdownForNativeRendering,
9 markdownWithInlineFileLinks,
10 markdownWithHtml,
11} from "./markdownDocument";
12​
13const rewrite = (markdown: string) =>
14 markdownWithInlineFileLinks(markdown, ENRICHED_INLINE_FILE_LINK_REGEX);
15​
16describe("inline code that names a file", () => {
17 it.each([
18 [
19 "file links",
20 "See `src/math.ts:2`, `C:\\repo\\a.ts`, `./src/a©.ts`, and [`./README.md`](readme).",
21 ],
22 [
23 "tables",
24 "Intro `src/math.ts:2`\n| `./README.md` | Fit |\n|---|---|\n| `./a.ts` | A |\n\nMore\n| a |\n|---|\n| b |",
25 ],
26 ["escaped pipe in file header", "Intro text\n| `./a\\|b.ts` | c |\n|---|---|\n| a | b |"],
27 ["escaped pipe in file body", "Intro text\n| a | c |\n|---|---|\n| `./a\\|b.ts` | b |"],
28 [
29 "escaped pipe after a normal file span",
30 "Intro `./normal.ts`\n| `./a\\|b.ts` | c |\n|---|---|\n| a | b |",
31 ],
32 [
33 "unmatched delimiter before escaped pipe in header",
34 "Intro `./normal.ts`\n| `x``./a\\|b.ts`` | c |\n|---|---|\n|a|b|",
35 ],
36 [
37 "unmatched delimiter before escaped pipe in body",
38 "Intro `./normal.ts`\n| a | c |\n|---|---|\n| `x``./a\\|b.ts`` | b |",
39 ],
40 ["tabbed quote header", ">\tIntro `./a.ts`\n>\t| `./b.ts` | c |\n>\t|---|---|\n>\t| a | b |"],
41 ["lazy quote header", "> Intro\n`./README.md` | file\n> | - | - |\n> | ok | yes |"],
42 ["lazy list header", "- Intro\n`./README.md` | file\n | - | - |\n | ok | yes |"],
43 [
44 "HTML",
45 '<details>\n<summary>Files</summary>\n\nSee `src/math.ts:2`\n| `./README.md` |\n|---|\n| ok |\n<img alt="A &amp; B" src="https://example.com/a.png?a=1&amp;b=2">\n</details>',
46 ],
47 [
48 "nested fences",
49 '> - Example\n> ````md\n> ```ts\n> `src/math.ts:2`\n> <img src="literal.png">\n> | a |\n> |---|\n> ```\n> ````\n\nSee `./README.md`.',
50 ],
51 [
52 "HTML fences",
53 '<details>\n<summary>Example</summary>\n\n````md\n```html\n<img src="literal.png">\n```\n`src/math.ts`\n````\n\nSee `./README.md`\n</details>',
54 ],
55 ])("preserves the two-pass output for every streamed prefix: %s", (_name, fixture) => {
56 for (const ending of ["\n", "\r\n", "\r"]) {
57 const document = fixture.replaceAll("\n", ending);
58 for (let length = 0; length <= document.length; length++) {
59 const prefix = document.slice(0, length);
60 const expected = previousTableBreaks(
61 previousFileLinks(markdownWithHtml(prefix), ENRICHED_INLINE_FILE_LINK_REGEX),
62 );
63 expect(
64 markdownForNativeRendering(prefix, ENRICHED_INLINE_FILE_LINK_REGEX),
65 JSON.stringify(prefix),
66 ).toBe(expected);
67 }
68 }
69 });
70​
71 it("becomes a link to the same path", () => {
72 expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe(
73 "See [src/math.ts:2](<src/math.ts:2>) and [./README.md](<./README.md>).",
74 );
75 });
76​
77 it("keeps commands, identifiers and URLs as code", () => {
78 const markdown = "Run `vp test run`, call `useMemo`, open `https://example.com/a.ts`.";
79 expect(rewrite(markdown)).toBe(markdown);
80 });
81​
82 it("leaves fenced code blocks and code already inside a link alone", () => {
83 const markdown = "```\nsrc/math.ts:2\n```\n\n[`src/math.ts`](src/math.ts)";
84 expect(rewrite(markdown)).toBe(markdown);
85 });
86​
87 it("links to the exact path when it holds backslashes or ampersands", () => {
88 for (const path of ["C:\\repo\\_private\\file.ts", "./src/a&copy;.ts", "./src/[id].ts"]) {
89 const paragraph = parser.parse(rewrite(`\`${path}\``)).children[0];
90 const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
91 expect(link?.type === "link" && link.url).toBe(path);
92 expect(
93 link?.type === "link" && link.children[0]?.type === "text" && link.children[0].value,
94 ).toBe(path);
95 }
96 });
97});
98​
99// Freeze the pre-optimization passes so shared transform regressions cannot change the oracle.
100const parser = unified().use(remarkParse).use(remarkGfm);
101type MarkdownNode = Root | RootContent;
102const INLINE_CODE_SPAN = /`+([^`\r\n]+)`+/g;
103​
104function previousFileLinks(markdown: string, fileLink: RegExp): string {
105 if (![...markdown.matchAll(INLINE_CODE_SPAN)].some(([, code]) => fileLink.test(code!.trim())))
106 return markdown;
107 const edits: Array<{ start: number; end: number; content: string }> = [];
108 const visit = (node: MarkdownNode) => {
109 if (node.type === "inlineCode") {
110 const start = node.position?.start.offset;
111 const end = node.position?.end.offset;
112 const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
113 if (
114 start !== undefined &&
115 end !== undefined &&
116 fileLink.test(node.value) &&
117 !/[<>]/.test(node.value)
118 )
119 edits.push({
120 start,
121 end,
122 content: `[${escaped}](<${escaped}>)`,
123 });
124 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
125 node.children.forEach(visit);
126 };
127 visit(parser.parse(markdown));
128 for (const edit of edits.toReversed())
129 markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);
130 return markdown;
132​
133// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
134function isTableDelimiterRow(line: string): boolean {
135 if (!line.includes("-")) return false;
136 const row = line.replace(/^[ \t>]+/, "").trim();
137 return row
138 .replace(/^\||\|$/g, "")
139 .split("|")
140 .every((cell) => /^:?-+:?$/.test(cell.trim()));
142​
143// Cheap pre-check for a delimiter row two lines below text, so most messages skip the parse.
144function mayHaveTableUnderText(markdown: string): boolean {
145 if (!markdown.includes("|")) return false;
146 const lines = markdown.split(/\r\n|\r|\n/);
147 for (let index = 2; index < lines.length; index += 1) {
148 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
149 }
150 return false;
152​
153/**
154 * GFM lets a table interrupt a paragraph, but the native parser (md4c) only starts a table
155 * on a paragraph's first line, so a table right under a line of text renders as one
156 * run-on paragraph. Insert the blank line md4c needs before each such table.
157 */
158function previousTableBreaks(markdown: string): string {
159 if (!mayHaveTableUnderText(markdown)) return markdown;
160 const lineStarts: number[] = [];
161 const visit = (node: MarkdownNode) => {
162 if (!("children" in node)) return;
163 node.children.forEach((child, index) => {
164 const previous = node.children[index - 1];
165 const start = child.position?.start;
166 if (
167 child.type === "table" &&
168 previous?.type === "paragraph" &&
169 start?.offset !== undefined &&
170 previous.position?.end.line === start.line - 1
171 )
172 lineStarts.push(
173 Math.max(
174 markdown.lastIndexOf("\n", start.offset - 1),
175 markdown.lastIndexOf("\r", start.offset - 1),
176 ) + 1,
177 );
178 visit(child);
179 });
180 };
181 visit(parser.parse(markdown));
182 for (const lineStart of lineStarts.toReversed()) {
183 // The header row may be a lazy line without its container markers (`>` or list indent),
184 // so copy the delimiter row's markers onto the blank line and the header row.
185 const [, header = "", cells = "", ending = "\n", markers = ""] =
186 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
187 markdown =
188 markdown.slice(0, lineStart) +
189 `${markers.trimEnd()}${ending}${markers}${cells}` +
190 markdown.slice(lineStart + header.length + cells.length);
191 }
192 return markdown;