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

markdownDocument.ts

445 lines16.7 KB

1import type { Root, RootContent } from "mdast";
2import { unified } from "unified";
3import remarkParse from "remark-parse";
4import remarkGfm from "remark-gfm";
5​
6const parser = unified().use(remarkParse).use(remarkGfm);
7export type MarkdownNode = Root | RootContent;
8​
9interface MarkdownEdit {
10 readonly start: number;
11 readonly end: number;
12 readonly content: string;
14​
15function applyMarkdownEdits(markdown: string, edits: MarkdownEdit[]): string {
16 if (edits.length === 0) return markdown;
17 const parts: string[] = [];
18 let offset = 0;
19 // AST traversal emits disjoint edits in source order.
20 for (const edit of edits) {
21 parts.push(markdown.slice(offset, edit.start), edit.content);
22 offset = edit.end;
23 }
24 parts.push(markdown.slice(offset));
25 return parts.join("");
27​
28function decodeCodePoint(codePoint: number, entity: string): string {
29 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
30 return entity;
31 }
32 return String.fromCodePoint(codePoint);
34​
35function decodeHtmlEntities(value: string): string {
36 return value.replace(
37 /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
38 (entity, decimal: string | undefined, hexadecimal: string | undefined) => {
39 if (decimal) {
40 return decodeCodePoint(Number.parseInt(decimal, 10), entity);
41 }
42 if (hexadecimal) {
43 return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
44 }
45 switch (entity.toLowerCase()) {
46 case "&amp;":
47 return "&";
48 case "&apos;":
49 return "'";
50 case "&gt;":
51 return ">";
52 case "&lt;":
53 return "<";
54 case "&nbsp;":
55 return "\u00a0";
56 case "&quot;":
57 return '"';
58 default:
59 return entity;
60 }
61 },
62 );
64​
65const HTML_TAG = /<!--[\s\S]*?-->|<\/?[a-z](?:[^>"']|"[^"]*"|'[^']*')*>/gi;
66​
67function attribute(tag: string, name: string): string | null {
68 const attributes = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
69 for (const match of tag.matchAll(attributes)) {
70 if (match[1]?.toLowerCase() === name) {
71 return decodeHtmlEntities(match[2] ?? match[3] ?? match[4] ?? "");
72 }
73 }
74 return null;
76​
77function markdownDestination(url: string): string {
78 return `<${url.replace(/&/g, "\\&").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C").replace(/\n/g, "")}>`;
80​
81const ANCHOR_TAG = /^<\/?a[\s/>]/i;
82​
83/** Replacements for the anchor tags still ahead, and how many emitted links are open. */
84type AnchorState = { readonly pending: string[]; open: number };
85​
86// Code spans keep their text; an odd trailing backslash would escape the closing "]".
87function escapeLinkLabel(text: string): string {
88 return text
89 .replace(/(`+)[\s\S]*?\1|\\*[[\]]/g, (match) =>
90 match.startsWith("`") || match.length % 2 === 0
91 ? match
92 : `${match.slice(0, -1)}\\${match.slice(-1)}`,
93 )
94 .replace(/\\+$/, (slashes) => (slashes.length % 2 ? `${slashes}\\` : slashes));
96​
97// An unescaped "!" before the inserted "[" would turn the link into an image.
98function bangBefore(text: string, index: number): boolean {
99 if (text[index - 1] !== "!") return false;
100 let backslashes = 0;
101 while (text[index - 2 - backslashes] === "\\") backslashes += 1;
102 return backslashes % 2 === 0;
104​
105/**
106 * Pairs `<a>` tags in order. Only a closed anchor with an http(s) or mailto href becomes a
107 * Markdown link; any other anchor keeps its text unlinked.
108 */
109function anchorMarkdown(tags: readonly string[]): AnchorState {
110 const replacements = tags.map(() => "");
111 const open: Array<{ index: number; href: string | undefined }> = [];
112 tags.forEach((tag, index) => {
113 if (tag[1] !== "/") {
114 const href = attribute(tag, "href")?.trim();
115 open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined });
116 return;
117 }
118 const opening = open.pop();
119 if (!opening?.href) return;
120 replacements[opening.index] = "[";
121 replacements[index] = `](${markdownDestination(opening.href)})`;
122 });
123 return { pending: replacements, open: 0 };
125​
126function markdownHtmlTags(content: string): RegExpExecArray[] {
127 // An HTML block such as <details> can also contain Markdown fences and code spans.
128 const codeRanges: Array<{ start: number; end: number }> = [];
129 const tags = [...content.matchAll(HTML_TAG)];
130 let tagIndex = 0;
131 const delimiters = [...content.matchAll(/`+|~{3,}/g)].filter((delimiter) => {
132 while (tags[tagIndex] && tags[tagIndex]!.index + tags[tagIndex]![0].length <= delimiter.index)
133 tagIndex += 1;
134 const tag = tags[tagIndex];
135 return !tag || delimiter.index < tag.index;
136 });
137 for (let index = 0; index < delimiters.length; index += 1) {
138 const opening = delimiters[index]!;
139 const lineStart = content.lastIndexOf("\n", opening.index - 1) + 1;
140 const fenced =
141 opening[0].length >= 3 && /^ {0,3}$/.test(content.slice(lineStart, opening.index));
142 if (opening[0][0] === "~" && !fenced) continue;
143 let closingIndex = -1;
144 for (let candidate = index + 1; candidate < delimiters.length; candidate += 1) {
145 const closing = delimiters[candidate]!;
146 if (!fenced && closing[0] === opening[0]) {
147 closingIndex = candidate;
148 break;
149 }
150 if (!fenced || closing[0][0] !== opening[0][0] || closing[0].length < opening[0].length)
151 continue;
152 const start = content.lastIndexOf("\n", closing.index - 1) + 1;
153 const nextLine = content.indexOf("\n", closing.index);
154 const end = nextLine === -1 ? content.length : nextLine;
155 if (
156 /^ {0,3}$/.test(content.slice(start, closing.index)) &&
157 /^\s*$/.test(content.slice(closing.index + closing[0].length, end))
158 ) {
159 closingIndex = candidate;
160 break;
161 }
162 }
163 if (closingIndex === -1) {
164 if (fenced) codeRanges.push({ start: opening.index, end: content.length });
165 continue;
166 }
167 const closing = delimiters[closingIndex]!;
168 codeRanges.push({ start: opening.index, end: closing.index + closing[0].length });
169 index = closingIndex;
170 }
171 return tags.filter(
172 (tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end),
173 );
175​
176/**
177 * Called only for parsed HTML nodes, so Markdown code examples keep their literal tags.
178 * `anchors` is shared across sibling inline HTML nodes because each of those carries a single tag.
179 */
180export function markdownHtmlContent(
181 content: string,
182 options: { readonly anchors?: AnchorState; readonly inTableCell?: boolean } = {},
183): string {
184 const tags = markdownHtmlTags(content);
185 const anchors =
186 options.anchors ??
187 anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag)));
188 let result = "";
189 let end = 0;
190 for (const match of tags) {
191 const text = content.slice(end, match.index);
192 result += anchors.open > 0 ? escapeLinkLabel(text) : text;
193 const replacement = htmlTagMarkdown(match[0], anchors, options);
194 if (replacement === "[" && bangBefore(result, result.length))
195 result = `${result.slice(0, -1)}\\!`;
196 result +=
197 anchors.open > 0 && /[\s[]/.test(result.at(-1) ?? "")
198 ? replacement.replace(/^ /, "")
199 : replacement;
200 end = match.index + match[0].length;
201 }
202 const text = content.slice(end);
203 return result + (anchors.open > 0 ? escapeLinkLabel(text) : text);
205​
206function htmlTagMarkdown(
207 tag: string,
208 anchors: AnchorState,
209 options: { readonly inTableCell?: boolean },
210): string {
211 if (tag.startsWith("<!--")) return "";
212 if (ANCHOR_TAG.test(tag)) {
213 const replacement = anchors.pending.shift() ?? "";
214 if (replacement === "[") anchors.open += 1;
215 else if (replacement) anchors.open -= 1;
216 return replacement;
217 }
218 if (/^<img\b/i.test(tag)) {
219 const src = attribute(tag, "src");
220 if (!src) return "";
221 const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
222 return `![${alt}](${markdownDestination(src)})`;
223 }
224 // A blank line inside an open link label would end the paragraph before its "]".
225 const blockBreak = anchors.open === 0 ? "\n\n" : " ";
226 if (/^<summary\b/i.test(tag)) return `${blockBreak}**`;
227 if (/^<\/summary\s*>/i.test(tag)) return `**${blockBreak}`;
228 // A line break would end the table row, so a cell keeps its content on one line.
229 if (/^<br\b/i.test(tag)) return options.inTableCell ? " " : " \n";
230 if (/^<\/?(?:p|div|details)\b/i.test(tag)) return blockBreak;
231 return "";
233​
234export function markdownWithHtml(markdown: string): string {
235 if (!/<(?:!--|\/?[a-z])/i.test(markdown)) return markdown;
236 const edits: Array<{ start: number; end: number; content: string }> = [];
237 const visit = (node: MarkdownNode, inTableCell: boolean, inLink: boolean) => {
238 if (!("children" in node)) return;
239 inTableCell ||= node.type === "tableCell";
240 const children: readonly MarkdownNode[] = node.children;
241 // Inline HTML arrives one tag per node, so anchors pair across phrasing siblings.
242 const anchors =
243 node.type === "root" || node.type === "blockquote" || node.type === "listItem"
244 ? undefined
245 : anchorMarkdown(
246 children.flatMap((child) =>
247 child.type === "html"
248 ? markdownHtmlTags(child.value)
249 .map((tag) => tag[0])
250 .filter((tag) => ANCHOR_TAG.test(tag))
251 : [],
252 ),
253 );
254 for (const child of children) {
255 const start = child.position?.start.offset;
256 const end = child.position?.end.offset;
257 const linkLabel = inLink || (anchors?.open ?? 0) > 0;
258 if (child.type === "text") {
259 if (linkLabel && start !== undefined && end !== undefined) {
260 const content = escapeLinkLabel(markdown.slice(start, end));
261 if (content !== markdown.slice(start, end)) edits.push({ start, end, content });
262 }
263 continue;
264 }
265 if (child.type !== "html") {
266 visit(child, inTableCell, linkLabel);
267 continue;
268 }
269 const content = markdownHtmlContent(child.value, { anchors, inTableCell });
270 if (start === undefined || end === undefined) continue;
271 // Text before an outermost link is never edited, so this edit cannot overlap another.
272 if (content.startsWith("[") && !linkLabel && bangBefore(markdown, start))
273 edits.push({ start: start - 1, end: start, content: "\\!" });
274 edits.push({ start, end, content });
275 }
276 };
277 visit(parser.parse(markdown), false, false);
278 for (const edit of edits.reverse())
279 markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);
280 return markdown;
282​
283// Start only at the beginning of a backtick run to avoid retrying every suffix.
284const INLINE_CODE_SPAN = /(?<!`)`+([^`\r\n]+)`+/g;
285​
286export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
287 return transformNativeMarkdown(markdown, fileLink, false);
289​
290function transformNativeMarkdown(
291 markdown: string,
292 fileLink: RegExp | undefined,
293 tableBreaks: boolean,
294): string {
295 const breakTables = tableBreaks && mayHaveTableUnderText(markdown);
296 let linkFiles = false;
297 if (fileLink) {
298 for (const [, code] of markdown.matchAll(INLINE_CODE_SPAN)) {
299 if (fileLink.test(code!.trim())) {
300 linkFiles = true;
301 break;
302 }
303 }
304 }
305 if (!linkFiles && !breakTables) return markdown;
306 const edits: MarkdownEdit[] = [];
307 const fileEdits: MarkdownEdit[] = [];
308 let rewritesPipe = false;
309 const visit = (node: MarkdownNode) => {
310 if (linkFiles && node.type === "inlineCode") {
311 const start = node.position?.start.offset;
312 const end = node.position?.end.offset;
313 const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
314 if (
315 start !== undefined &&
316 end !== undefined &&
317 fileLink?.test(node.value) &&
318 !/[<>]/.test(node.value)
319 ) {
320 const edit = {
321 start,
322 end,
323 content: `[${escaped}](<${escaped}>)`,
324 };
325 edits.push(edit);
326 fileEdits.push(edit);
327 if (node.value.includes("|")) rewritesPipe = true;
328 }
329 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
330 node.children.forEach((child, index) => {
331 const previous = node.children[index - 1];
332 const start = child.position?.start;
333 if (
334 breakTables &&
335 child.type === "table" &&
336 previous?.type === "paragraph" &&
337 start?.offset !== undefined &&
338 previous.position?.end.line === start.line - 1
339 ) {
340 let lineStart = start.offset;
341 while (lineStart > 0 && !/[\r\n]/.test(markdown[lineStart - 1]!)) lineStart -= 1;
342 // Replace only the container prefix, leaving cell edits disjoint from the table break.
343 const [, header = "", , ending = "\n", markers = ""] =
344 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
345 edits.push({
346 start: lineStart,
347 end: lineStart + header.length,
348 content: `${markers.trimEnd()}${ending}${markers}`,
349 });
350 }
351 visit(child);
352 });
353 };
354 visit(parser.parse(markdown));
355 // Rewritten pipes can change table structure, so preserve the original pass ordering.
356 if (breakTables && rewritesPipe)
357 return markdownWithTableBreaks(applyMarkdownEdits(markdown, fileEdits));
358 return applyMarkdownEdits(markdown, edits);
360​
361// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
362function isTableDelimiterRow(line: string): boolean {
363 if (!line.includes("-")) return false;
364 const row = line.replace(/^[ \t>]+/, "").trim();
365 return row
366 .replace(/^\||\|$/g, "")
367 .split("|")
368 .every((cell) => /^:?-+:?$/.test(cell.trim()));
370​
371function mayHaveTableUnderText(markdown: string): boolean {
372 if (!markdown.includes("|")) return false;
373 const lines = markdown.split(/\r\n|\r|\n/);
374 for (let index = 2; index < lines.length; index += 1) {
375 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
376 }
377 return false;
379​
380/** md4c starts tables only at paragraph starts; insert breaks to match GFM. */
381export function markdownWithTableBreaks(markdown: string): string {
382 return transformNativeMarkdown(markdown, undefined, true);
384​
385export function parseMarkdownDocument(markdown: string): Root {
386 return parser.parse(markdownWithHtml(markdown));
388​
389export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string {
390 // HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first.
391 return transformNativeMarkdown(markdownWithHtml(markdown), fileLink, true);
393​
394/** Native media slots only cover standalone images; nested file embeds must become links. */
395export function markdownWithFileEmbeds(
396 markdown: string,
397 label: (href: string, standalone: boolean) => string | null,
398): { markdown: string; fileHrefs: ReadonlySet<string> } {
399 const fileHrefs = new Set<string>();
400 if (!markdown.includes("![")) return { markdown, fileHrefs };
401 const root = parser.parse(markdown);
402 const topLevelBlocks = new Set<MarkdownNode>(root.children);
403 const definitions = new Map<string, string>();
404 const collect = (node: MarkdownNode) => {
405 if (node.type === "definition") {
406 const identifier = node.identifier.toUpperCase();
407 if (!definitions.has(identifier)) definitions.set(identifier, node.url);
408 }
409 if ("children" in node) node.children.forEach(collect);
410 };
411 collect(root);
412 const edits: Array<{ start: number; end: number; content: string }> = [];
413 const visit = (node: MarkdownNode, standalone = false, insideLink = false) => {
414 if (node.type === "image" || node.type === "imageReference") {
415 const href =
416 node.type === "image" ? node.url : definitions.get(node.identifier.toUpperCase());
417 const name = href === undefined ? null : label(href, standalone);
418 const start = node.position?.start.offset;
419 const end = node.position?.end.offset;
420 if (href !== undefined && name !== null && start !== undefined && end !== undefined) {
421 const text = name.replace(/[\\[\]`*_~|&<>]/g, "\\$&");
422 const url = href.replace(/[\\&]/g, "\\$&").replace(/</g, "%3C").replace(/>/g, "%3E");
423 edits.push({ start, end, content: insideLink ? text : `[${text}](<${url}>)` });
424 fileHrefs.add(href);
425 }
426 }
427 if ("children" in node)
428 node.children.forEach((child) =>
429 visit(
430 child,
431 node.type === "paragraph" && node.children.length === 1 && topLevelBlocks.has(node),
432 insideLink || node.type === "link" || node.type === "linkReference",
433 ),
434 );
435 };
436 visit(root);
437 const parts: string[] = [];
438 let offset = 0;
439 for (const edit of edits) {
440 parts.push(markdown.slice(offset, edit.start), edit.content);
441 offset = edit.end;
442 }
443 parts.push(markdown.slice(offset));
444 return { markdown: parts.join(""), fileHrefs };