Skip to content

Commit 42a8fd5

Browse files
authored
feat(pull-requests): link GitHub references in markdown (pingdotgg#8812)
Co-authored-by: maria-rcks <[email protected]>
1 parent c78ae50 commit 42a8fd5

5 files changed

Lines changed: 179 additions & 7 deletions

File tree

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ interface ChatMarkdownProps {
179179
onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
180180
imageBaseDir?: string | undefined;
181181
onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
182+
extraRemarkPlugins?: NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
182183
}
183184

184185
export function canUseMarkdownFileShellActions(
@@ -211,6 +212,7 @@ export function shouldUseMarkdownFileBrowserPrimaryAction(input: {
211212
}
212213

213214
const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
215+
const EMPTY_REMARK_PLUGINS: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = [];
214216

215217
const ARTIFACT_TEMPLATE_ICON_BY_KIND = {
216218
document: FileTextIcon,
@@ -360,6 +362,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
360362
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
361363
blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
362364
div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
365+
a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
363366
img: [...(defaultSchema.attributes?.img ?? []), "dataLocalSrc", "dataMarkdownTitle"],
364367
},
365368
protocols: {
@@ -1807,6 +1810,7 @@ function ChatMarkdown({
18071810
onUseArtifactTemplate,
18081811
imageBaseDir,
18091812
onImageExpand,
1813+
extraRemarkPlugins = EMPTY_REMARK_PLUGINS,
18101814
}: ChatMarkdownProps) {
18111815
const { resolvedTheme } = useTheme();
18121816
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
@@ -2203,13 +2207,25 @@ function ChatMarkdown({
22032207
: null;
22042208
if (!fileLinkMeta) {
22052209
const faviconHost = resolveExternalWebLinkHost(href);
2210+
const pullRequestAutolink = String(
2211+
(props as Record<string, unknown>)["data-pull-request-autolink"] ?? "",
2212+
);
2213+
const pullRequestCopy =
2214+
pullRequestAutolink === "commit"
2215+
? /\/commit\/([0-9a-f]{40})$/iu.exec(href ?? "")?.[1]
2216+
: pullRequestAutolink === "reference"
2217+
? plainHastText(node)
2218+
: undefined;
2219+
const isPullRequestAutolink = pullRequestCopy !== undefined;
22062220
const isSameDocumentLink = href?.startsWith("#") ?? false;
22072221
const onClick = props.onClick;
22082222
const canOpenInPreview = Boolean(threadRef) && isPreviewSupportedInRuntime();
22092223
const linkChildren = <MarkdownLinkContext value>{children}</MarkdownLinkContext>;
22102224
const link = (
22112225
<a
22122226
{...props}
2227+
className={cn(props.className, pullRequestAutolink === "commit" && "font-mono")}
2228+
data-markdown-copy={pullRequestCopy}
22132229
href={href}
22142230
target={isSameDocumentLink ? undefined : "_blank"}
22152231
rel={isSameDocumentLink ? undefined : "noopener noreferrer"}
@@ -2281,7 +2297,7 @@ function ChatMarkdown({
22812297
});
22822298
}}
22832299
>
2284-
{faviconHost && hastHasText(node) ? (
2300+
{faviconHost && hastHasText(node) && !isPullRequestAutolink ? (
22852301
<MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}>
22862302
{linkChildren}
22872303
</MarkdownExternalLinkContent>
@@ -2438,6 +2454,14 @@ function ChatMarkdown({
24382454
]);
24392455
/* eslint-enable react/no-unstable-nested-components */
24402456

2457+
const remarkPlugins = useMemo(
2458+
() => [
2459+
...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),
2460+
...extraRemarkPlugins,
2461+
],
2462+
[extraRemarkPlugins, lineBreaks],
2463+
);
2464+
24412465
// react-markdown converts unparsed HTML nodes to text when skipHtml is false.
24422466
// Keep that behavior explicit because literal mode depends on escaping the
24432467
// complete source token instead of dropping it from the rendered message.
@@ -2450,9 +2474,7 @@ function ChatMarkdown({
24502474
onCopy={handleCopy}
24512475
>
24522476
<ReactMarkdown
2453-
remarkPlugins={
2454-
lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS
2455-
}
2477+
remarkPlugins={remarkPlugins}
24562478
rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : undefined}
24572479
skipHtml={false}
24582480
components={markdownComponents}

‎apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ import { DiffPanelLoadingState } from "../DiffPanelShell";
9797
import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
9898
import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab";
9999
import { openOnHostLabel, showPullRequestLinkContextMenu } from "./pullRequestLinkContextMenu";
100+
import { PullRequestMarkdownContext } from "./PullRequestMarkdown";
100101
import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
101102
import { PullRequestTimelineTab } from "./PullRequestTimelineTab";
102103
import {
@@ -1921,7 +1922,7 @@ export function PullRequestDetailPanel({
19211922
{...(unavailableGitHubUrl ? { gitHubUrl: unavailableGitHubUrl } : {})}
19221923
/>
19231924
) : detail ? (
1924-
<>
1925+
<PullRequestMarkdownContext value={detail.provider === "github" ? repositoryUrl : null}>
19251926
{mountedTabs.has("summary") ? (
19261927
<div className={cn("absolute inset-0", tab !== "summary" && "invisible")}>
19271928
<PullRequestSummaryTab
@@ -1978,7 +1979,7 @@ export function PullRequestDetailPanel({
19781979
</Suspense>
19791980
</div>
19801981
) : null}
1981-
</>
1982+
</PullRequestMarkdownContext>
19821983
) : null}
19831984
</div>
19841985

‎apps/web/src/components/pullRequest/PullRequestMarkdown.tsx‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
import { ExternalLinkIcon, PaperclipIcon, PlayIcon } from "lucide-react";
22
import type { EnvironmentId } from "@t3tools/contracts";
3+
import { createContext, useContext, useMemo } from "react";
4+
import type { Options as ReactMarkdownOptions } from "react-markdown";
35

46
import { cn } from "~/lib/utils";
57

68
import ChatMarkdown from "../ChatMarkdown";
7-
import { splitPullRequestBody } from "./pullRequestMarkdown.logic";
9+
import { remarkPullRequestAutolinks, splitPullRequestBody } from "./pullRequestMarkdown.logic";
10+
11+
export const PullRequestMarkdownContext = createContext<string | null>(null);
812

913
/**
1014
* A pull request body, rendered with the app's markdown renderer plus a card for each upload
@@ -27,6 +31,11 @@ export function PullRequestMarkdown({
2731
className?: string;
2832
}) {
2933
const segments = splitPullRequestBody(text);
34+
const repositoryUrl = useContext(PullRequestMarkdownContext);
35+
const extraRemarkPlugins = useMemo<NonNullable<ReactMarkdownOptions["remarkPlugins"]>>(
36+
() => (repositoryUrl ? [[remarkPullRequestAutolinks, { repositoryUrl }]] : []),
37+
[repositoryUrl],
38+
);
3039
return (
3140
<div className={cn("space-y-3", className)}>
3241
{segments.map((segment) => {
@@ -37,6 +46,7 @@ export function PullRequestMarkdown({
3746
text={segment.text}
3847
cwd={cwd}
3948
environmentId={environmentId}
49+
extraRemarkPlugins={extraRemarkPlugins}
4050
/>
4151
);
4252
}

‎apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
import {
2+
findAndReplaceText,
3+
type MarkdownNode,
4+
type TextMatch,
5+
} from "~/vendor/mdast-find-and-replace";
6+
17
/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
28
export type PullRequestBodySegment =
39
| { readonly id: string; readonly kind: "markdown"; readonly text: string }
@@ -141,3 +147,46 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
141147
flushMarkdown();
142148
return segments;
143149
}
150+
151+
const AUTOLINK_CANDIDATE_PATTERN = /#[1-9]\d*|[0-9a-f]{40}/giu;
152+
const AUTOLINK_WORD_CHARACTER_PATTERN = /[A-Za-z0-9_]/u;
153+
const AUTOLINK_COMMIT_PREFIX_PATTERN = /[\s([{]/u;
154+
const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);
155+
156+
/** GitHub-style same-repository references for pull request prose, never code or authored links. */
157+
export function remarkPullRequestAutolinks(options: { readonly repositoryUrl: string }) {
158+
const repositoryUrl = options.repositoryUrl.replace(/\/+$/u, "");
159+
return (tree: MarkdownNode) => {
160+
findAndReplaceText(
161+
tree,
162+
AUTOLINK_CANDIDATE_PATTERN,
163+
(matched: string, match: TextMatch) => {
164+
const reference = matched.startsWith("#");
165+
const before = match.input[match.index - 1];
166+
const after = match.input[match.index + matched.length];
167+
if (
168+
(before !== undefined &&
169+
(reference
170+
? AUTOLINK_WORD_CHARACTER_PATTERN.test(before)
171+
: !AUTOLINK_COMMIT_PREFIX_PATTERN.test(before))) ||
172+
(after !== undefined && AUTOLINK_WORD_CHARACTER_PATTERN.test(after))
173+
) {
174+
return false;
175+
}
176+
return {
177+
type: "link",
178+
url: reference
179+
? `${repositoryUrl}/issues/${matched.slice(1)}`
180+
: `${repositoryUrl}/commit/${matched}`,
181+
data: {
182+
hProperties: {
183+
dataPullRequestAutolink: reference ? "reference" : "commit",
184+
},
185+
},
186+
children: [{ type: "text", value: reference ? matched : matched.slice(0, 7) }],
187+
};
188+
},
189+
AUTOLINK_IGNORED_TYPES,
190+
);
191+
};
192+
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Adapted from mdast-util-find-and-replace:
3+
* https://github.com/syntax-tree/mdast-util-find-and-replace/blob/main/lib/index.js
4+
*
5+
* The MIT License
6+
*
7+
* Copyright (c) Titus Wormer <[email protected]>
8+
*
9+
* Permission is hereby granted, free of charge, to any person obtaining a copy
10+
* of this software and associated documentation files (the "Software"), to deal
11+
* in the Software without restriction, including without limitation the rights
12+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
* copies of the Software, and to permit persons to whom the Software is
14+
* furnished to do so, subject to the following conditions:
15+
*
16+
* The above copyright notice and this permission notice shall be included in
17+
* all copies or substantial portions of the Software.
18+
*
19+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25+
* SOFTWARE.
26+
*/
27+
28+
export type MarkdownNode = {
29+
type: string;
30+
value?: string;
31+
children?: MarkdownNode[];
32+
url?: string;
33+
data?: unknown;
34+
};
35+
36+
export type TextMatch = {
37+
index: number;
38+
input: string;
39+
};
40+
41+
/** The dependency-free subset of mdast-util-find-and-replace used by PR autolinks. */
42+
export function findAndReplaceText(
43+
tree: MarkdownNode,
44+
find: RegExp,
45+
replace: (matched: string, match: TextMatch) => MarkdownNode | false,
46+
ignoredTypes: ReadonlySet<string>,
47+
): void {
48+
visit(tree);
49+
50+
function visit(node: MarkdownNode): void {
51+
if (node.children === undefined) return;
52+
for (let childIndex = 0; childIndex < node.children.length; childIndex += 1) {
53+
const child = node.children[childIndex]!;
54+
if (ignoredTypes.has(child.type)) continue;
55+
if (child.type !== "text" || child.value === undefined) {
56+
visit(child);
57+
continue;
58+
}
59+
60+
const replacements: MarkdownNode[] = [];
61+
let start = 0;
62+
let changed = false;
63+
find.lastIndex = 0;
64+
let match = find.exec(child.value);
65+
while (match !== null) {
66+
const position = match.index;
67+
const replacement = replace(match[0], { index: position, input: match.input });
68+
if (replacement === false) {
69+
find.lastIndex = position + 1;
70+
} else {
71+
if (start < position) {
72+
replacements.push({ type: "text", value: child.value.slice(start, position) });
73+
}
74+
replacements.push(replacement);
75+
start = position + match[0].length;
76+
changed = true;
77+
}
78+
if (!find.global) break;
79+
match = find.exec(child.value);
80+
}
81+
82+
if (!changed) continue;
83+
if (start < child.value.length) {
84+
replacements.push({ type: "text", value: child.value.slice(start) });
85+
}
86+
node.children.splice(childIndex, 1, ...replacements);
87+
childIndex += replacements.length - 1;
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)