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

pullRequestMarkdown.logic.ts

170 lines5.5 KB

1import {
2 changeRequestReferenceAutolinker,
3 expandGithubEmojiAliases,
4 resolveChangeRequestMediaUrl,
5} from "@t3tools/client-runtime/pull-request-markdown";
6import {
7 sourceControlClients,
8 type ReferenceAutolink,
9} from "@t3tools/client-runtime/source-control-clients";
10import {
11 CHAT_MARKDOWN_REHYPE_PLUGINS,
12 CHAT_MARKDOWN_REMARK_PLUGINS,
13} from "@t3tools/shared/markdownPipeline";
14import type { Nodes } from "hast";
15import remarkParse from "remark-parse";
16import remarkRehype from "remark-rehype";
17import { unified, type PluggableList } from "unified";
18​
19export {
20 splitPullRequestBody,
21 type PullRequestBodySegment,
22} from "@t3tools/client-runtime/pull-request-markdown";
23​
24type MarkdownNode = {
25 type: string;
26 value?: string;
27 children?: MarkdownNode[];
28 url?: string;
29 data?: unknown;
30};
31​
32const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);
33​
34export function remarkPullRequestAutolinks(options: {
35 readonly autolinks: (text: string) => ReadonlyArray<ReferenceAutolink>;
36}) {
37 const visit = (node: MarkdownNode): void => {
38 const children = node.children;
39 if (children === undefined) return;
40 for (let index = 0; index < children.length; index += 1) {
41 const child = children[index]!;
42 if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue;
43 if (child.type !== "text" || child.value === undefined) {
44 visit(child);
45 continue;
46 }
47 const value = child.value;
48 const links = options.autolinks(value);
49 if (links.length === 0) continue;
50 const replacements: MarkdownNode[] = [];
51 let start = 0;
52 for (const link of links) {
53 if (start < link.index) {
54 replacements.push({ type: "text", value: value.slice(start, link.index) });
55 }
56 replacements.push({
57 type: "link",
58 url: link.url,
59 data: { hProperties: { dataPullRequestAutolink: link.kind } },
60 children: [{ type: "text", value: link.label }],
61 });
62 start = link.index + link.text.length;
63 }
64 if (start < value.length) replacements.push({ type: "text", value: value.slice(start) });
65 children.splice(index, 1, ...replacements);
66 index += replacements.length - 1;
67 }
68 };
69 return (tree: MarkdownNode) => visit(tree);
71​
72function remarkChangeRequestMediaUrls(options: { readonly changeRequestUrl: string }) {
73 const visit = (node: MarkdownNode): void => {
74 if ((node.type === "image" || node.type === "definition") && node.url !== undefined) {
75 node.url = resolveChangeRequestMediaUrl(node.url, options.changeRequestUrl);
76 }
77 node.children?.forEach(visit);
78 };
79 return (tree: MarkdownNode) => visit(tree);
81​
82/** GitHub renders `:alias:` emoji in prose; code keeps them, being `inlineCode`/`code`, not `text`. */
83function remarkGithubEmoji() {
84 const visit = (node: MarkdownNode): void => {
85 if (node.type === "text" && node.value !== undefined)
86 node.value = expandGithubEmojiAliases(node.value);
87 node.children?.forEach(visit);
88 };
89 return (tree: MarkdownNode) => visit(tree);
91​
92const NO_PLUGINS: PluggableList = [];
93const markdownPlugins = new Map<string, PluggableList>();
94​
95/**
96 * One plugin list per repository, so every comment of a pull request shares one markdown
97 * renderer and its parse cache instead of parsing again on each render.
98 */
99export function pullRequestMarkdownPlugins(
100 changeRequest: { readonly provider: string; readonly url: string } | null,
101): PluggableList {
102 if (changeRequest === null) return NO_PLUGINS;
103 const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
104 .repositoryUrl;
105 if (repositoryUrl === undefined) return NO_PLUGINS;
106 const key = `${changeRequest.provider}\u0000${repositoryUrl}`;
107 let plugins = markdownPlugins.get(key);
108 if (plugins === undefined) {
109 const autolinks = changeRequestReferenceAutolinker(changeRequest);
110 plugins = [[remarkChangeRequestMediaUrls, { changeRequestUrl: repositoryUrl }]];
111 if (changeRequest.provider === "github") plugins.push(remarkGithubEmoji);
112 if (autolinks) plugins.push([remarkPullRequestAutolinks, { autolinks }]);
113 markdownPlugins.set(key, plugins);
114 }
115 return plugins;
117​
118const commentPreviewProcessor = (plugins: PluggableList) =>
119 unified()
120 .use(remarkParse)
121 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
122 .use(plugins)
123 .use(remarkRehype, { allowDangerousHtml: true })
124 .use(CHAT_MARKDOWN_REHYPE_PLUGINS)
125 .freeze();
126const commentPreview = commentPreviewProcessor(NO_PLUGINS);
127const githubCommentPreview = commentPreviewProcessor([remarkGithubEmoji]);
128​
129const PREVIEW_BLOCK_TAGS = new Set([
130 "blockquote",
131 "br",
132 "dd",
133 "details",
134 "div",
135 "dl",
136 "dt",
137 "h1",
138 "h2",
139 "h3",
140 "h4",
141 "h5",
142 "h6",
143 "hr",
144 "li",
145 "ol",
146 "p",
147 "pre",
148 "summary",
149 "table",
150 "td",
151 "th",
152 "tr",
153 "ul",
154]);
155​
156function commentPreviewText(node: Nodes): string {
157 if (node.type === "text") return node.value;
158 if (node.type === "element" && node.tagName === "img") {
159 return typeof node.properties.alt === "string" ? node.properties.alt : "";
160 }
161 if (!("children" in node)) return "";
162 const text = node.children.map(commentPreviewText).join("");
163 return node.type === "element" && PREVIEW_BLOCK_TAGS.has(node.tagName) ? ` ${text} ` : text;
165​
166export function pullRequestCommentPreview(body: string, provider: string): string {
167 const processor = provider === "github" ? githubCommentPreview : commentPreview;
168 const tree = processor.runSync(processor.parse(body), body);
169 return commentPreviewText(tree).replace(/\s+/gu, " ").trim();