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

pullRequestAutolinks.ts

118 lines4.5 KB

1import { githubEmojiAliases } from "@t3tools/client-runtime/pull-request-markdown";
2import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
3import remarkGfm from "remark-gfm";
4import remarkParse from "remark-parse";
5import { unified } from "unified";
6​
7import { splitLeadingBom } from "../../lib/markdownDocument";
8​
9type MarkdownNode = {
10 readonly type: string;
11 readonly position?:
12 | {
13 readonly start: { readonly offset?: number | undefined };
14 readonly end: { readonly offset?: number | undefined };
15 }
16 | undefined;
17 readonly children?: readonly MarkdownNode[] | undefined;
18};
19​
20const parser = unified().use(remarkParse).use(remarkGfm);
21const UNLINKED_TYPES = new Set([
22 "link",
23 "linkReference",
24 "image",
25 "imageReference",
26 "code",
27 "inlineCode",
28 "html",
29 "definition",
30]);
31​
32const unchanged = (offset: number) => offset;
33​
34/**
35 * Rewrites the references `autolinks` finds in the markdown's prose as markdown links, and GitHub's
36 * `:alias:` emoji as the emoji, because the native renderer takes markdown text. Text is searched
37 * as written, escapes included. `sourceOffset` maps an offset in the result back to `markdown`.
38 */
39export function nativePullRequestMarkdown(
40 markdown: string,
41 autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null,
42 githubEmoji: boolean,
43): { readonly markdown: string; readonly sourceOffset: (offset: number) => number } {
44 if (autolinks === null && !githubEmoji) return { markdown, sourceOffset: unchanged };
45 const [bom, source] = splitLeadingBom(markdown);
46 const edits: { start: number; end: number; value: string }[] = [];
47 const visit = (node: MarkdownNode, inLink: boolean) => {
48 // Only a bracketed label is prose; an autolink's text is its destination.
49 const labelled = source[node.position?.start.offset ?? -1] === "[";
50 if (node.type === "link" && labelled && !inLink) {
51 node.children?.forEach((child) => visit(child, true));
52 return;
53 }
54 if (UNLINKED_TYPES.has(node.type)) return;
55 if (node.type === "text") {
56 const start = node.position?.start.offset;
57 const end = node.position?.end.offset;
58 if (start === undefined || end === undefined) return;
59 const text = source.slice(start, end);
60 const found: { start: number; end: number; value: string }[] = [];
61 for (const link of inLink ? [] : (autolinks?.(text) ?? [])) {
62 found.push({
63 start: start + link.index,
64 end: start + link.index + link.text.length,
65 value: `[${link.label}](${link.url})`,
66 });
67 }
68 for (const alias of githubEmoji ? githubEmojiAliases(text) : []) {
69 // Keycap emoji start with `*`, which the native parser would read as emphasis.
70 const value = alias.emoji.replaceAll("*", "\\*");
71 found.push({
72 start: start + alias.index,
73 end: start + alias.index + alias.text.length,
74 value,
75 });
76 }
77 found.sort((left, right) => left.start - right.start);
78 for (const edit of found) {
79 if (edit.start >= (edits.at(-1)?.end ?? 0)) edits.push(edit);
80 }
81 } else if (node.children !== undefined) {
82 let protectedHtmlDepth = 0;
83 for (const child of node.children) {
84 if (child.type === "html") {
85 const start = child.position?.start.offset;
86 const end = child.position?.end.offset;
87 const tag = start === undefined || end === undefined ? "" : source.slice(start, end);
88 for (const match of tag.matchAll(/<(\/)?(?:a|code|pre|script|style)(?=[\s>])[^>]*>/giu)) {
89 protectedHtmlDepth = Math.max(0, protectedHtmlDepth + (match[1] ? -1 : 1));
90 }
91 } else if (protectedHtmlDepth === 0) visit(child, inLink);
92 }
93 }
94 };
95 visit(parser.parse(markdown), false);
96 if (edits.length === 0) return { markdown, sourceOffset: unchanged };
97 let rewritten = bom;
98 let cursor = 0;
99 // Where each edit ends in the result, and how far `markdown` is ahead from there on.
100 const shifts: { end: number; delta: number }[] = [];
101 for (const edit of edits) {
102 rewritten += source.slice(cursor, edit.start) + edit.value;
103 cursor = edit.end;
104 shifts.push({ end: rewritten.length, delta: bom.length + edit.end - rewritten.length });
105 }
106 rewritten += source.slice(cursor);
107 return {
108 markdown: rewritten,
109 sourceOffset(offset) {
110 let delta = 0;
111 for (const shift of shifts) {
112 if (shift.end > offset) break;
113 delta = shift.delta;
114 }
115 return offset + delta;
116 },
117 };