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

pullRequestMarkdown.logic.ts

179 lines6.0 KB

1import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import type { Nodes } from "hast";
4​
5import {
6 splitPullRequestBody as splitBody,
7 type PullRequestBodySegment as BodySegment,
8} from "@t3tools/client-runtime/pull-request-markdown";
9import {
10 markdownFootnoteCitations,
11 markdownFootnoteLabels,
12 markdownReferenceDefinitions,
13 wordsHast,
14 type MarkdownExtensions,
15} from "~/markdown/wordsHast";
16​
17type FootnoteMode = NonNullable<MarkdownExtensions["footnotes"]>;
18​
19/** `footnotes` is how a markdown segment renders the body's footnotes. */
20export type PullRequestBodySegment = BodySegment & { readonly footnotes?: FootnoteMode };
21​
22/** How much text the footnote stubs and seeds may add across all segments. */
23const FOOTNOTE_PREFIX_MAX_ADDED_LENGTH = 256 * 1024;
24​
25/**
26 * Lifted media renders each markdown segment as its own document. A segment that cites footnotes
27 * leads with one-line stubs and the citations before it, so numbers and ids match the whole body,
28 * and one trailing segment renders the body's notes.
29 */
30export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
31 const segments = splitBody(body, markdownReferenceDefinitions);
32 if (segments.length < 2 || !body.includes("[^")) return segments;
33 const labels = markdownFootnoteLabels(body);
34 if (labels.length === 0) return segments;
35 const stubs = labels.map((label) => `[^${label}]: .`).join("\n");
36 const cited: string[] = [];
37 const withStubs: PullRequestBodySegment[] = [];
38 let added = 0;
39 for (const segment of segments) {
40 const bomLength =
41 segment.kind === "markdown" && segment.sourceOffset === 0 && segment.text.startsWith("\uFEFF")
42 ? 1
43 : 0;
44 const citations =
45 segment.kind === "markdown"
46 ? markdownFootnoteCitations(segment.text.slice(bomLength), labels)
47 : [];
48 if (segment.kind !== "markdown" || citations.length === 0) {
49 withStubs.push(segment);
50 continue;
51 }
52 // The comment closes the last stub, so a segment opening with indented code stays code.
53 const seed = cited.map((label) => `[^${label}]`).join(" ") || "<!-- -->";
54 const prefix = `${stubs}\n\n${seed}\n\n`;
55 // Seeds grow with segments times citations; past the budget the body renders as one document.
56 added += prefix.length;
57 if (added > FOOTNOTE_PREFIX_MAX_ADDED_LENGTH) {
58 const text = body.replace(/^(?:\r|\n)+/u, "");
59 return [
60 {
61 id: "markdown:0",
62 kind: "markdown",
63 text: text.trimEnd(),
64 sourceOffset: body.length - text.length,
65 },
66 ];
67 }
68 const footnotes = cited.length > 0 ? "omit-seeded" : "omit";
69 cited.push(...citations);
70 withStubs.push({
71 ...segment,
72 text: prefix + segment.text.slice(bomLength),
73 sourceOffset: segment.sourceOffset + bomLength - prefix.length,
74 footnotes,
75 });
76 }
77 if (cited.length === 0) return segments;
78 return [
79 ...withStubs,
80 { id: "footnotes", kind: "markdown", text: body, sourceOffset: 0, footnotes: "only" },
81 ];
83​
84const NO_EXTENSIONS: MarkdownExtensions = {};
85const footnoteExtensions = new WeakMap<MarkdownExtensions, Map<FootnoteMode, MarkdownExtensions>>();
86​
87/** Kept per extension object, so a segment keeps sharing its renderer's parse cache. */
88export function pullRequestFootnoteExtensions(
89 extensions: MarkdownExtensions | undefined,
90 footnotes: FootnoteMode,
91): MarkdownExtensions {
92 const base = extensions ?? NO_EXTENSIONS;
93 let byMode = footnoteExtensions.get(base);
94 if (byMode === undefined) footnoteExtensions.set(base, (byMode = new Map()));
95 let withMode = byMode.get(footnotes);
96 if (withMode === undefined) byMode.set(footnotes, (withMode = { ...base, footnotes }));
97 return withMode;
99const markdownExtensions = new Map<string, MarkdownExtensions>();
100​
101/**
102 * One extension object per repository, so every comment of a pull request shares one markdown
103 * renderer and its parse cache instead of parsing again on each render.
104 */
105export function pullRequestMarkdownExtensions(
106 changeRequest: { readonly provider: string; readonly url: string } | null,
107): MarkdownExtensions {
108 if (changeRequest === null) return NO_EXTENSIONS;
109 const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
110 .repositoryUrl;
111 if (repositoryUrl === undefined) return NO_EXTENSIONS;
112 const key = `${changeRequest.provider}\u0000${repositoryUrl}`;
113 let extensions = markdownExtensions.get(key);
114 if (extensions === undefined) {
115 extensions = {
116 changeRequest: {
117 repositoryUrl,
118 autolinks: changeRequestReferenceAutolinker(changeRequest),
119 },
120 githubEmoji: changeRequest.provider === "github",
121 };
122 markdownExtensions.set(key, extensions);
123 }
124 return extensions;
126​
127const PREVIEW_MARKDOWN = {
128 math: false,
129 breaks: false,
130 escapeHtml: false,
131 insights: false,
132 extensions: NO_EXTENSIONS,
133};
134const GITHUB_PREVIEW_MARKDOWN = {
135 ...PREVIEW_MARKDOWN,
136 extensions: { githubEmoji: true },
137};
138​
139const PREVIEW_BLOCK_TAGS = new Set([
140 "blockquote",
141 "br",
142 "dd",
143 "details",
144 "div",
145 "dl",
146 "dt",
147 "h1",
148 "h2",
149 "h3",
150 "h4",
151 "h5",
152 "h6",
153 "hr",
154 "li",
155 "ol",
156 "p",
157 "pre",
158 "summary",
159 "table",
160 "td",
161 "th",
162 "tr",
163 "ul",
164]);
165​
166function commentPreviewText(node: Nodes): string {
167 if (node.type === "text") return node.value;
168 if (node.type === "element" && node.tagName === "img") {
169 return typeof node.properties.alt === "string" ? node.properties.alt : "";
170 }
171 if (!("children" in node)) return "";
172 const text = node.children.map(commentPreviewText).join("");
173 return node.type === "element" && PREVIEW_BLOCK_TAGS.has(node.tagName) ? ` ${text} ` : text;
175​
176export function pullRequestCommentPreview(body: string, provider: string): string {
177 const options = provider === "github" ? GITHUB_PREVIEW_MARKDOWN : PREVIEW_MARKDOWN;
178 return commentPreviewText(wordsHast(body, options)).replace(/\s+/gu, " ").trim();