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

PullRequestMarkdown.tsx

306 lines9.7 KB

1import { T, useGT, Var } from "gt-react";
2import { ExternalLinkIcon, PaperclipIcon } from "lucide-react";
3import { useAtomValue } from "@effect/atom-react";
4import { markdownImageSourceFragment } from "@t3tools/client-runtime/markdown-images";
5import { makePullRequestMediaKindAtom } from "@t3tools/client-runtime/pull-request-markdown";
6import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
7import {
8 SOURCE_CONTROL_MEDIA_ASSET,
9 type AssetResource,
10 type EnvironmentId,
11 type ScopedThreadRef,
12} from "@t3tools/contracts";
13import { createContext, useContext, useState, type ReactNode } from "react";
14import type { MarkdownExtensions } from "~/markdown/wordsHast";
15​
16import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
17import { cn } from "~/lib/utils";
18import { PULL_REQUESTS_PANEL_REF } from "~/rightPanelStore";
19​
20import ChatMarkdown from "../ChatMarkdown";
21import { markdownImageCopy } from "../chat/ChatMarkdownMedia";
22import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
23import {
24 pullRequestFootnoteExtensions,
25 splitPullRequestBody,
26 type PullRequestBodySegment,
27} from "./pullRequestMarkdown.logic";
28​
29export const PullRequestMarkdownContext = createContext<{
30 /** Stable per repository, so comments share one renderer and its parse cache. */
31 extensions: MarkdownExtensions;
32 lineBreaks: boolean;
33 threadRef: ScopedThreadRef | null;
34 /** The change request's `owner/name`, which can differ from the checkout the body renders in. */
35 repository: string | null;
36} | null>(null);
37​
38/** The list page panel that links in thread-less markdown open in; the Issues page provides its own. */
39export const PullRequestMarkdownPanelContext =
40 createContext<ScopedThreadRef>(PULL_REQUESTS_PANEL_REF);
41​
42const pullRequestMediaKind = makePullRequestMediaKindAtom((url, options) => fetch(url, options));
43​
44function PullRequestHostMedia({
45 environmentId,
46 cwd,
47 url,
48 fetchUrl,
49 repository,
50 label,
51 image,
52 fallback,
53}: {
54 environmentId: EnvironmentId;
55 cwd: string;
56 url: string;
57 fetchUrl: string;
58 repository: string | undefined;
59 label: string | undefined;
60 image?: ReactNode;
61 fallback?: ReactNode;
62}) {
63 const gt = useGT();
64 const resource: AssetResource = {
65 _tag: SOURCE_CONTROL_MEDIA_ASSET,
66 cwd,
67 url: fetchUrl,
68 ...(repository ? { repository } : {}),
69 };
70 const assetUrl = useAssetUrlState(environmentId, resource);
71 const refreshAssetUrl = useAssetUrlRefresh(environmentId, resource);
72 const src =
73 assetUrl._tag === "Success" ? assetUrl.url : assetUrl._tag === "Failure" ? fetchUrl : null;
74 const [kind, setKind] = useState<"image" | "video" | null>(null);
75 const detected = useAtomValue(
76 pullRequestMediaKind(
77 image === undefined || kind !== null || assetUrl._tag !== "Success" ? null : src,
78 ),
79 );
80 const detectedKind = detected._tag === "Success" ? detected.value : null;
81 if (kind === null && detectedKind !== null) setKind(detectedKind);
82 if (image !== undefined) {
83 if (kind === null) return fallback;
84 if (kind === "image") return image;
85 }
86 return (
87 <MediaVideoPlayer
88 src={src === null ? null : src + markdownImageSourceFragment(url)}
89 originalUrl={url}
90 label={label ?? gt`Pull request video`}
91 className="w-full"
92 videoClassName="rounded-lg border border-border/60"
93 onRetry={refreshAssetUrl}
94 />
95 );
97​
98function PullRequestBodySegmentView({
99 segment,
100 cwd,
101 environmentId,
102 threadRef,
103 lineBreaks,
104 onTaskListChange,
105}: {
106 segment: PullRequestBodySegment;
107 cwd: string;
108 environmentId: EnvironmentId;
109 threadRef: ScopedThreadRef | undefined;
110 lineBreaks: boolean;
111 onTaskListChange: ((input: { markerOffset: number; checked: boolean }) => void) | undefined;
112}) {
113 const gt = useGT();
114 const context = useContext(PullRequestMarkdownContext);
115 const listPanelRef = useContext(PullRequestMarkdownPanelContext);
116 const repository = context?.repository ?? undefined;
117 if (segment.kind === "table") {
118 return (
119 <div className="space-y-3">
120 {segment.rows.map((cells, rowIndex) => (
121 <div
122 // oxlint-disable-next-line react/no-array-index-key -- rows have no identity besides position
123 key={rowIndex}
124 className="grid gap-3"
125 style={{ gridTemplateColumns: `repeat(${cells.length}, minmax(0, 1fr))` }}
126 >
127 {cells.map((cell, cellIndex) => (
128 <div
129 // oxlint-disable-next-line react/no-array-index-key -- cells have no identity besides position
130 key={cellIndex}
131 className={cn("min-w-0 space-y-3", cell.header && "font-medium")}
132 >
133 {cell.segments.map((cellSegment) => (
134 <PullRequestBodySegmentView
135 key={cellSegment.id}
136 segment={cellSegment}
137 cwd={cwd}
138 environmentId={environmentId}
139 threadRef={threadRef}
140 lineBreaks={lineBreaks}
141 onTaskListChange={onTaskListChange}
142 />
143 ))}
144 </div>
145 ))}
146 </div>
147 ))}
148 </div>
149 );
150 }
151 const hostMedia =
152 segment.kind === "attachment" ? sourceControlClients.mediaUrl(segment.url) : null;
153 if (segment.kind === "markdown" || segment.media !== "video") {
154 const markdown = (
155 <ChatMarkdown
156 text={
157 segment.kind === "markdown"
158 ? segment.text
159 : markdownImageCopy(segment.label ?? "", segment.url, undefined)
160 }
161 cwd={cwd}
162 threadRef={threadRef}
163 pullRequestPanelRef={threadRef ?? listPanelRef}
164 environmentId={environmentId}
165 {...(segment.kind === "markdown" && segment.footnotes
166 ? { extensions: pullRequestFootnoteExtensions(context?.extensions, segment.footnotes) }
167 : context
168 ? { extensions: context.extensions }
169 : {})}
170 lineBreaks={lineBreaks}
171 sourceControlMedia
172 sourceControlMediaRepository={repository}
173 onTaskListChange={
174 onTaskListChange && segment.kind === "markdown"
175 ? ({ markerOffset, checked }) =>
176 onTaskListChange({
177 markerOffset: segment.sourceOffset + markerOffset,
178 checked,
179 })
180 : undefined
181 }
182 />
183 );
184 if (segment.kind === "markdown" || segment.media === "image") return markdown;
185 const fallback = (
186 <PullRequestAttachmentLink
187 attachmentUrl={segment.url}
188 sourceControlHostLabel={hostMedia?.definition.label}
189 label={segment.label}
190 />
191 );
192 return hostMedia === null ? (
193 fallback
194 ) : (
195 <PullRequestHostMedia
196 key={segment.url}
197 environmentId={environmentId}
198 cwd={cwd}
199 url={segment.url}
200 fetchUrl={hostMedia.fetchUrl}
201 repository={repository}
202 label={segment.label}
203 image={markdown}
204 fallback={fallback}
205 />
206 );
207 }
208 if (hostMedia !== null) {
209 return (
210 <PullRequestHostMedia
211 key={`${segment.id}:${segment.url}`}
212 environmentId={environmentId}
213 cwd={cwd}
214 url={segment.url}
215 fetchUrl={hostMedia.fetchUrl}
216 repository={repository}
217 label={segment.label}
218 />
219 );
220 }
221 return (
222 <MediaVideoPlayer
223 key={`${segment.id}:${segment.url}`}
224 src={segment.url}
225 originalUrl={segment.url}
226 label={segment.label ?? gt`Pull request video`}
227 className="w-full"
228 videoClassName="rounded-lg border border-border/60"
229 />
230 );
232​
233function PullRequestAttachmentLink({
234 attachmentUrl,
235 sourceControlHostLabel,
236 label,
237}: {
238 attachmentUrl: string;
239 sourceControlHostLabel: string | undefined;
240 label: string | undefined;
241}) {
242 return (
243 // Desktop converts blocked _blank navigation to openExternal.
244 <a
245 href={attachmentUrl}
246 rel="noreferrer noopener"
247 target="_blank"
248 className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-3 py-2 text-sm hover:bg-muted/60"
249 >
250 <PaperclipIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
251 <span className="min-w-0 flex-1 truncate">
252 {label ?? (
253 <T>
254 Open attachment on{" "}
255 <Var>{sourceControlHostLabel ?? new URL(attachmentUrl).hostname}</Var>
256 </T>
257 )}
258 </span>
259 <ExternalLinkIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />
260 </a>
261 );
263​
264export function PullRequestMarkdown({
265 text,
266 cwd,
267 environmentId,
268 threadRef,
269 lineBreaks,
270 className,
271 onTaskListChange,
272}: {
273 text: string;
274 cwd: string;
275 environmentId: EnvironmentId;
276 threadRef?: ScopedThreadRef | null;
277 lineBreaks?: boolean;
278 className?: string;
279 /** `markerOffset` is into `text`. Checkboxes stay read-only without it. */
280 onTaskListChange?: ((input: { markerOffset: number; checked: boolean }) => void) | undefined;
281}) {
282 const segments = splitPullRequestBody(text);
283 const context = useContext(PullRequestMarkdownContext);
284 const resolvedThreadRef = threadRef ?? context?.threadRef ?? undefined;
285 return (
286 <div
287 className={cn(
288 "space-y-3 [&_[data-markdown-details]]:border-0 [&_[data-markdown-details-summary]]:text-foreground/80 [&_[data-markdown-details-summary]>svg]:text-muted-foreground/60",
289 className,
290 )}
291 data-image-gallery
292 >
293 {segments.map((segment) => (
294 <PullRequestBodySegmentView
295 key={segment.id}
296 segment={segment}
297 cwd={cwd}
298 environmentId={environmentId}
299 threadRef={resolvedThreadRef}
300 lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}
301 onTaskListChange={onTaskListChange}
302 />
303 ))}
304 </div>
305 );