Skip to content
TypeScript

fix(web): PR bodies keep before/after video tables intact (#25988)

Bartłomiej Błoniarz32a0531748c4
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
index d829f6f649b..41b93f96666 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
@@ -1,4 +1,7 @@
-import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown";
+import {
+ splitPullRequestBody,
+ type PullRequestBodySegment,
+} from "@t3tools/client-runtime/pull-request-markdown";
import { markdownTaskMarkerOffset } from "@t3tools/shared/markdownTaskList";
import type { ReactNode } from "react";
import { View } from "react-native";
@@ -116,49 +119,101 @@ export function PullRequestMarkdown(props: {
readonly checked: boolean;
}) => boolean;
}) {
- const { onTaskListChange } = props;
+ const mediaContext = useContext(PullRequestMediaContext);
+ const changeRequestUrl = useContext(ChangeRequestUrlContext);
const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]);
const [undoneTicks, setUndoneTicks] = useState(0);
+ const gallery: FilePreviewItem[] = markdownImageSources(
+ props.imageGroupMarkdown ?? props.markdown,
+ )
+ .map((href) => (changeRequestUrl ? resolveChangeRequestMediaUrl(href, changeRequestUrl) : href))
+ .filter(
+ (uri) =>
+ /^https?:\/\//i.test(uri) &&
+ videoMimeType({ name: uri.split(/[?#]/)[0] ?? uri, mimeType: "" }) === null,
+ )
+ .map((uri) => pullRequestImageSource(uri, mediaContext));
+ const segmentProps = {
+ gallery,
+ lineBreaks: props.lineBreaks,
+ undoneTicks,
+ onTaskListChange: props.onTaskListChange,
+ onTaskListUndone: () => setUndoneTicks((count) => count + 1),
+ };
+ return (
+ <View style={{ gap: 12 }}>
+ {segments.map((segment) => (
+ <PullRequestBodySegmentView key={segment.id} segment={segment} {...segmentProps} />
+ ))}
+ </View>
+ );
+}
+
+function PullRequestBodySegmentView(props: {
+ readonly segment: PullRequestBodySegment;
+ readonly gallery: FilePreviewItem[];
+ readonly lineBreaks: boolean | undefined;
+ readonly undoneTicks: number;
+ readonly onTaskListChange:
+ | ((input: { readonly markerOffset: number; readonly checked: boolean }) => boolean)
+ | undefined;
+ readonly onTaskListUndone: () => void;
+}) {
+ const { segment, onTaskListChange } = props;
+ if (segment.kind === "markdown") {
+ return (
+ <PullRequestMarkdownContent
+ key={props.undoneTicks}
+ markdown={segment.text}
+ gallery={props.gallery}
+ lineBreaks={props.lineBreaks}
+ onTaskListItemPress={
+ onTaskListChange
+ ? (event) => {
+ const offset = markdownTaskMarkerOffset(
+ segment.text,
+ event.index,
+ event.text,
+ event.checked,
+ );
+ const kept =
+ offset !== null &&
+ onTaskListChange({
+ markerOffset: segment.sourceOffset + offset,
+ checked: event.checked,
+ });
+ if (!kept) props.onTaskListUndone();
+ }
+ : undefined
+ }
+ />
+ );
+ }
+ if (segment.kind === "attachment") {
+ return <PullRequestMedia url={segment.url} kind={segment.media} />;
+ }
return (
<View style={{ gap: 12 }}>
- {segments.map((segment) =>
- segment.kind === "markdown" ? (
- <PullRequestMarkdownContent
- key={`${segment.id}:${undoneTicks}`}
- markdown={segment.text}
- imageGroupMarkdown={props.imageGroupMarkdown ?? props.markdown}
- lineBreaks={props.lineBreaks}
- onTaskListItemPress={
- onTaskListChange
- ? (event) => {
- const offset = markdownTaskMarkerOffset(
- segment.text,
- event.index,
- event.text,
- event.checked,
- );
- const kept =
- offset !== null &&
- onTaskListChange({
- markerOffset: segment.sourceOffset + offset,
- checked: event.checked,
- });
- if (!kept) setUndoneTicks((count) => count + 1);
- }
- : undefined
- }
- />
- ) : (
- <PullRequestMedia key={segment.id} url={segment.url} kind={segment.media} />
- ),
- )}
+ {segment.rows.map((cells, rowIndex) => (
+ // oxlint-disable-next-line react/no-array-index-key -- rows have no identity besides position
+ <View key={rowIndex} style={{ flexDirection: "row", gap: 12 }}>
+ {cells.map((cell, cellIndex) => (
+ // oxlint-disable-next-line react/no-array-index-key -- cells have no identity besides position
+ <View key={cellIndex} style={{ flex: 1, minWidth: 0, gap: 12 }}>
+ {cell.segments.map((cellSegment) => (
+ <PullRequestBodySegmentView key={cellSegment.id} {...props} segment={cellSegment} />
+ ))}
+ </View>
+ ))}
+ </View>
+ ))}
</View>
);
}
function PullRequestMarkdownContent(props: {
readonly markdown: string;
- readonly imageGroupMarkdown?: string;
+ readonly gallery: FilePreviewItem[];
readonly lineBreaks: boolean | undefined;
readonly onTaskListItemPress?: SelectableMarkdownTextProps["onTaskListItemPress"];
}) {
@@ -173,23 +228,13 @@ function PullRequestMarkdownContent(props: {
const openLink = (href: string) => {
void openPullRequest(href);
};
- const gallery: FilePreviewItem[] = markdownImageSources(
- props.imageGroupMarkdown ?? props.markdown,
- )
- .map(resolveMediaUrl)
- .filter(
- (uri) =>
- /^https?:\/\//i.test(uri) &&
- videoMimeType({ name: uri.split(/[?#]/)[0] ?? uri, mimeType: "" }) === null,
- )
- .map((uri) => pullRequestImageSource(uri, mediaContext));
const [preview, setPreview] = useState<FilePreviewSource | null>(null);
const renderImage: MarkdownImageRenderer = (image) => (
<MarkdownImage href={resolveMediaUrl(image.href)} alt={image.alt} onPreview={setPreview} />
);
const styles = useMarkdownPreviewStyles();
return (
- <FilePreviewGallery value={gallery}>
+ <FilePreviewGallery value={props.gallery}>
<SelectableMarkdownText
markdown={markdown}
preserveSoftBreaks={props.lineBreaks ?? hostLineBreaks}
diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts
index 3ce98c4870a..6d6a1bfe4b6 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts
@@ -26,4 +26,16 @@ describe("PR attachments", () => {
},
]);
});
+
+ it("collects videos from a before/after table", () => {
+ const media = splitPullRequestBody(
+ "<table>\n<tr><th>Before</th><th>After</th></tr>\n<tr><td>\n\nhttps://drop.example.com/before.mp4\n\n</td><td>\n\nhttps://drop.example.com/after.mp4\n\n</td></tr>\n</table>",
+ );
+ expect(
+ pullRequestDescriptionContent({ type: "root" } as MarkdownNode, media).attachments,
+ ).toEqual([
+ { uri: "https://drop.example.com/before.mp4", caption: "Video", kind: "video" },
+ { uri: "https://drop.example.com/after.mp4", caption: "Video", kind: "video" },
+ ]);
+ });
});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts
index 8d0d3c93edd..242d1207fd0 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts
@@ -37,7 +37,11 @@ export function pullRequestDescriptionContent(
if (node.type === "break") text.push(" ");
};
visit(document);
- for (const segment of media) {
+ const collect = (segment: PullRequestBodySegment) => {
+ if (segment.kind === "table") {
+ segment.rows.flat().forEach((cell) => cell.segments.forEach(collect));
+ return;
+ }
if (segment.kind === "attachment" && !attachments.has(segment.url)) {
const name = new URL(segment.url).pathname.split("/").pop();
attachments.set(segment.url, {
@@ -46,6 +50,7 @@ export function pullRequestDescriptionContent(
kind: segment.media,
});
}
- }
+ };
+ media.forEach(collect);
return { preview: text.join("").trim(), attachments: [...attachments.values()] };
}
diff --git a/apps/web/src/components/media/MediaVideoPlayer.tsx b/apps/web/src/components/media/MediaVideoPlayer.tsx
index 9c8dde95f44..6faae7da234 100644
--- a/apps/web/src/components/media/MediaVideoPlayer.tsx
+++ b/apps/web/src/components/media/MediaVideoPlayer.tsx
@@ -132,7 +132,7 @@ export function MediaVideoPlayer({
<span
role="alert"
className={cn(
- "flex aspect-video max-h-full min-h-28 w-full flex-col items-center justify-center gap-3 rounded-lg border border-border/40 bg-muted/40 p-4 text-center text-sm text-muted-foreground",
+ "flex aspect-video max-h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-border/40 bg-muted/40 p-4 text-center text-sm text-muted-foreground",
stateClassName,
)}
>
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
index 00f7a5d0bd1..449e901d0f0 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
@@ -16,7 +16,7 @@ import { PULL_REQUESTS_PANEL_REF } from "~/rightPanelStore";
import ChatMarkdown from "../ChatMarkdown";
import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
-import { splitPullRequestBody } from "./pullRequestMarkdown.logic";
+import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.logic";
export const PullRequestMarkdownContext = createContext<{
/** Stable per repository, so comments share one renderer and its parse cache. */
@@ -62,6 +62,123 @@ function PullRequestHostVideo({
);
}
+function PullRequestBodySegmentView({
+ segment,
+ cwd,
+ environmentId,
+ threadRef,
+ lineBreaks,
+ onTaskListChange,
+}: {
+ segment: PullRequestBodySegment;
+ cwd: string;
+ environmentId: EnvironmentId;
+ threadRef: ScopedThreadRef | undefined;
+ lineBreaks: boolean;
+ onTaskListChange: ((input: { markerOffset: number; checked: boolean }) => void) | undefined;
+}) {
+ const context = useContext(PullRequestMarkdownContext);
+ const repository = context?.repository ?? undefined;
+ if (segment.kind === "table") {
+ return (
+ <div className="space-y-3">
+ {segment.rows.map((cells, rowIndex) => (
+ <div
+ // oxlint-disable-next-line react/no-array-index-key -- rows have no identity besides position
+ key={rowIndex}
+ className="grid gap-3"
+ style={{ gridTemplateColumns: `repeat(${cells.length}, minmax(0, 1fr))` }}
+ >
+ {cells.map((cell, cellIndex) => (
+ <div
+ // oxlint-disable-next-line react/no-array-index-key -- cells have no identity besides position
+ key={cellIndex}
+ className={cn("min-w-0 space-y-3", cell.header && "font-medium")}
+ >
+ {cell.segments.map((cellSegment) => (
+ <PullRequestBodySegmentView
+ key={cellSegment.id}
+ segment={cellSegment}
+ cwd={cwd}
+ environmentId={environmentId}
+ threadRef={threadRef}
+ lineBreaks={lineBreaks}
+ onTaskListChange={onTaskListChange}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ );
+ }
+ if (segment.kind === "markdown" || segment.media === "image") {
+ return (
+ <ChatMarkdown
+ text={segment.kind === "markdown" ? segment.text : `![](<${segment.url}>)`}
+ cwd={cwd}
+ threadRef={threadRef}
+ pullRequestPanelRef={threadRef ?? PULL_REQUESTS_PANEL_REF}
+ environmentId={environmentId}
+ {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})}
+ lineBreaks={lineBreaks}
+ sourceControlMedia
+ sourceControlMediaRepository={repository}
+ onTaskListChange={
+ onTaskListChange && segment.kind === "markdown"
+ ? ({ markerOffset, checked }) =>
+ onTaskListChange({
+ markerOffset: segment.sourceOffset + markerOffset,
+ checked,
+ })
+ : undefined
+ }
+ />
+ );
+ }
+ const hostMedia = sourceControlClients.mediaUrl(segment.url);
+ if (segment.media === "video" && hostMedia !== null) {
+ return (
+ <PullRequestHostVideo
+ key={`${segment.id}:${segment.url}`}
+ environmentId={environmentId}
+ cwd={cwd}
+ url={segment.url}
+ fetchUrl={hostMedia.fetchUrl}
+ repository={repository}
+ />
+ );
+ }
+ if (segment.media === "video") {
+ return (
+ <MediaVideoPlayer
+ key={`${segment.id}:${segment.url}`}
+ src={segment.url}
+ originalUrl={segment.url}
+ label="Pull request video"
+ className="w-full"
+ videoClassName="rounded-lg border border-border/60"
+ />
+ );
+ }
+ return (
+ // Desktop converts blocked _blank navigation to openExternal.
+ <a
+ href={segment.url}
+ rel="noreferrer noopener"
+ target="_blank"
+ 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"
+ >
+ <PaperclipIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">
+ Open attachment on {hostMedia?.definition.label ?? new URL(segment.url).hostname}
+ </span>
+ <ExternalLinkIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />
+ </a>
+ );
+}
+
export function PullRequestMarkdown({
text,
cwd,
@@ -82,7 +199,6 @@ export function PullRequestMarkdown({
}) {
const segments = splitPullRequestBody(text);
const context = useContext(PullRequestMarkdownContext);
- const repository = context?.repository ?? undefined;
const resolvedThreadRef = threadRef ?? context?.threadRef ?? undefined;
return (
<div
@@ -92,74 +208,17 @@ export function PullRequestMarkdown({
)}
data-image-gallery
>
- {segments.map((segment) => {
- if (segment.kind === "markdown" || segment.media === "image") {
- return (
- <ChatMarkdown
- key={segment.id}
- text={segment.kind === "markdown" ? segment.text : `![](<${segment.url}>)`}
- cwd={cwd}
- threadRef={resolvedThreadRef}
- pullRequestPanelRef={resolvedThreadRef ?? PULL_REQUESTS_PANEL_REF}
- environmentId={environmentId}
- {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})}
- lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}
- sourceControlMedia
- sourceControlMediaRepository={repository}
- onTaskListChange={
- onTaskListChange && segment.kind === "markdown"
- ? ({ markerOffset, checked }) =>
- onTaskListChange({
- markerOffset: segment.sourceOffset + markerOffset,
- checked,
- })
- : undefined
- }
- />
- );
- }
- const hostMedia = sourceControlClients.mediaUrl(segment.url);
- if (segment.media === "video" && hostMedia !== null) {
- return (
- <PullRequestHostVideo
- key={`${segment.id}:${segment.url}`}
- environmentId={environmentId}
- cwd={cwd}
- url={segment.url}
- fetchUrl={hostMedia.fetchUrl}
- repository={repository}
- />
- );
- }
- if (segment.media === "video") {
- return (
- <MediaVideoPlayer
- key={`${segment.id}:${segment.url}`}
- src={segment.url}
- originalUrl={segment.url}
- label="Pull request video"
- className="w-full"
- videoClassName="rounded-lg border border-border/60"
- />
- );
- }
- return (
- // Desktop converts blocked _blank navigation to openExternal.
- <a
- key={segment.id}
- href={segment.url}
- rel="noreferrer noopener"
- target="_blank"
- 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"
- >
- <PaperclipIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
- <span className="min-w-0 flex-1 truncate">
- Open attachment on {hostMedia?.definition.label ?? new URL(segment.url).hostname}
- </span>
- <ExternalLinkIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />
- </a>
- );
- })}
+ {segments.map((segment) => (
+ <PullRequestBodySegmentView
+ key={segment.id}
+ segment={segment}
+ cwd={cwd}
+ environmentId={environmentId}
+ threadRef={resolvedThreadRef}
+ lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}
+ onTaskListChange={onTaskListChange}
+ />
+ ))}
</div>
);
}
diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts
index a5508e81974..13327d8480a 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.test.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts
@@ -4,6 +4,7 @@ import {
changeRequestReferenceAutolinker,
resolveChangeRequestMediaUrl,
splitPullRequestBody,
+ type PullRequestBodySegment,
} from "./pullRequestMarkdown.ts";
describe("pull request body segmentation", () => {
@@ -26,17 +27,26 @@ describe("pull request body segmentation", () => {
]);
});
- it("places each prose run at its offset in the body", () => {
+ it("places each prose run at its offset in the body, including inside a media table", () => {
const body =
- '\n\n- [ ] Before\r\n\nhttps://example.com/shot.png\n\n\n<video controls>\n <source src="https://example.com/a.mp4">\n</video>\n - [ ] code\n- [x] After\n';
- const prose = splitPullRequestBody(body).flatMap((segment) =>
- segment.kind === "markdown" ? [segment] : [],
- );
- expect(prose.map((segment) => segment.text)).toEqual([
+ '\n\n- [ ] Before\r\n\nhttps://example.com/shot.png\n\n\n<video controls>\n <source src="https://example.com/a.mp4">\n</video>\n - [ ] code\n- [x] After\n\r\n<table>\r\n<tr><td>\r\n\r\n- [ ] In a cell\r\n\r\n</td><td>\r\n\r\nhttps://example.com/b.mp4\r\n\r\n</td></tr>\r\n</table>\r\n- [ ] Last\n';
+ type Prose = Extract<PullRequestBodySegment, { kind: "markdown" }>;
+ const prose = (segments: ReadonlyArray<PullRequestBodySegment>): Prose[] =>
+ segments.flatMap((segment) =>
+ segment.kind === "markdown"
+ ? [segment]
+ : segment.kind === "table"
+ ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
+ : [],
+ );
+ const runs = prose(splitPullRequestBody(body));
+ expect(runs.map((segment) => segment.text)).toEqual([
"- [ ] Before",
" - [ ] code\n- [x] After",
+ "- [ ] In a cell",
+ "- [ ] Last",
]);
- for (const segment of prose) {
+ for (const segment of runs) {
expect(body.slice(segment.sourceOffset, segment.sourceOffset + segment.text.length)).toBe(
segment.text,
);
@@ -166,6 +176,98 @@ describe("media on custom hosts", () => {
});
});
+describe("media tables", () => {
+ const before = "https://github.com/user-attachments/assets/c69c7c1c-ef2f-47dd-97e8-fe42e40712eb";
+ const after = "https://github.com/user-attachments/assets/1867b6ec-4f88-4248-b2df-6b0f9808105b";
+ const video = "https://example.com/a.mp4";
+
+ it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
+ const segments = splitPullRequestBody(
+ `Intro\n\n<table>\n<tr><th>Before</th><th>After</th></tr>\n<tr>\n<td>\n\n${before}\n\n</td>\n<td>\n\n${after}\n\n</td>\n</tr>\n</table>\n\nOutro`,
+ );
+ expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
+ expect(segments[0]).toMatchObject({ text: "Intro" });
+ expect(segments[2]).toMatchObject({ text: "Outro" });
+ const table = segments[1]!;
+ if (table.kind !== "table") throw new Error("expected a table segment");
+ expect(
+ table.rows.map((row) =>
+ row.map((cell) =>
+ cell.segments.map((segment) =>
+ segment.kind === "attachment" ? `attachment:${segment.url}` : segment,
+ ),
+ ),
+ ),
+ ).toEqual([
+ [
+ [{ id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 23 }],
+ [{ id: "markdown:0", kind: "markdown", text: "After", sourceOffset: 38 }],
+ ],
+ [[`attachment:${before}`], [`attachment:${after}`]],
+ ]);
+ });
+
+ it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
+ const [table] = splitPullRequestBody(
+ `<table>\n<tr><td title="Before > after">Caption</td><td>\n\n${video}\n\n</td></tr>\n</table>`,
+ );
+ expect(table).toMatchObject({
+ kind: "table",
+ rows: [[{ segments: [{ kind: "markdown", text: "Caption" }] }, {}]],
+ });
+ });
+
+ it("leaves a table without media links as markdown", () => {
+ const body = "<table>\n<tr><td>a</td><td>b</td></tr>\n</table>";
+ expect(splitPullRequestBody(body)).toEqual([
+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
+ ]);
+ });
+
+ it.each([
+ ["a caption", "<table>\n<caption>Before upgrading</caption>\n<tr><td>", "</td></tr>\n</table>"],
+ ["text outside cells", "<table>\nBefore upgrading\n<tr><td>", "</td></tr>\n</table>"],
+ [
+ "text inside a row but outside cells",
+ "<table>\n<tr>Before upgrading<td>",
+ "</td></tr>\n</table>",
+ ],
+ [
+ "a table nested in another",
+ "<table>\n<tr><td>\n<table>\n<tr><td>",
+ "</td></tr>\n</table>\n</td></tr>\n</table>",
+ ],
+ ["an unclosed table", "<table>\n<tr><td>", ""],
+ ["a spanning cell", '<table>\n<tr><td colspan="2">', "</td></tr>\n</table>"],
+ [
+ "an indented cell",
+ "<table>\n <tr>\n <th>\n Before\n </th>\n </tr>\n <tr><td>",
+ "</td></tr>\n</table>",
+ ],
+ [
+ "a cell indented by a space and a tab",
+ "<table>\n<tr><td>\n \tBefore\n</td><td>",
+ "</td></tr>\n</table>",
+ ],
+ ])("splits a media table with %s line by line, as before", (_name, open, close) => {
+ const body = `${open}\n\n${video}\n\n${close}`;
+ expect(splitPullRequestBody(body)).toEqual([
+ { id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
+ { id: "attachment:1", kind: "attachment", url: video, media: "video" },
+ ...(close
+ ? [
+ {
+ id: "markdown:2",
+ kind: "markdown",
+ text: close,
+ sourceOffset: body.length - close.length,
+ },
+ ]
+ : []),
+ ]);
+ });
+});
+
describe("change request reference autolinks", () => {
const urls = (provider: string, url: string, text: string) =>
changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.ts
index 92c7d6de70c..2ca59143ad2 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.ts
@@ -14,8 +14,18 @@ export type PullRequestBodySegment =
readonly kind: "attachment";
readonly url: string;
readonly media: "video" | "image" | "unknown";
+ }
+ | {
+ readonly id: string;
+ readonly kind: "table";
+ readonly rows: ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
};
+type PullRequestBodyTableCell = {
+ readonly header: boolean;
+ readonly segments: ReadonlyArray<PullRequestBodySegment>;
+};
+
// `.` stops at the `\r` of a CRLF body, which is how GitHub stores one written in its web editor.
const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)\r?$/u;
/**
@@ -24,7 +34,8 @@ const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)\r?$/u;
*/
const VIDEO_TAG_MAX_LINES = 8;
-const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/u;
+// A tab after up to three spaces still reaches the fourth column.
+const INDENTED_CODE_PATTERN = /^(?: {4}| {0,3}\t)/u;
const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)(?:$|[?#])/iu;
const MARKDOWN_LINK_PATTERN = /^\[[^\]]*\]\((https?:\/\/[^\s)]+)\)$/u;
@@ -35,6 +46,21 @@ const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)[
const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
+/** Bounded like `VIDEO_TAG_MAX_LINES`; room for a before/after table with several rows. */
+const TABLE_MAX_LINES = 64;
+const TABLE_START_PATTERN = /^\s*<table\b/iu;
+const TABLE_END_PATTERN = /<\/table>\s*$/iu;
+const TABLE_OPEN_PATTERN = /<table\b/giu;
+const TABLE_CLOSE_PATTERN = /<\/table\s*>/giu;
+/**
+ * Quoted attribute values may hold `>`. The alternatives start on disjoint characters and an
+ * unquoted run stops at the next `<`, so a run of unterminated tags stays linear.
+ */
+const TABLE_STRUCTURE_TAG_PATTERN =
+ /<(\/?)(table|thead|tbody|tfoot|tr|td|th)\b((?:[^<>"']|"[^"]*"|'[^']*')*)>/giu;
+/** Rows are laid out independently, so a spanning cell would shift the cells after it. */
+const CELL_SPAN_PATTERN = /\b(?:col|row)span\b/iu;
+
function isWebUrl(url: string): boolean {
try {
const parsed = new URL(url);
@@ -57,7 +83,91 @@ function attachmentFromLine(
return null;
}
+type TableRows = ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
+
+/**
+ * Cells of a table made only of rows and cells, or null when anything else is in it: a caption,
+ * text between cells, a nested table. Cell contents are split on their own, so tables never nest.
+ */
+function tableRows(html: string, htmlOffset: number): TableRows | null {
+ const rows: PullRequestBodyTableCell[][] = [];
+ let row: PullRequestBodyTableCell[] | null = null;
+ let cell: { tag: string; contentStart: number } | null = null;
+ let opened = false;
+ let closed = false;
+ let cursor = 0;
+ for (const match of html.matchAll(TABLE_STRUCTURE_TAG_PATTERN)) {
+ const closing = match[1] === "/";
+ const tag = match[2]!.toLowerCase();
+ if (cell !== null) {
+ if (!closing || tag !== cell.tag) return null;
+ const content = html.slice(cell.contentStart, match.index);
+ // Indented HTML would render as a code block once the cell is markdown on its own.
+ if (content.split("\n").some((line) => INDENTED_CODE_PATTERN.test(line) && line.trim()))
+ return null;
+ row!.push({
+ header: tag === "th",
+ segments: splitBodyAt(content, htmlOffset + cell.contentStart),
+ });
+ cell = null;
+ } else {
+ if (html.slice(cursor, match.index).trim().length > 0) return null;
+ const tableOpen = opened && !closed;
+ if (tag === "table") {
+ if (closing ? !tableOpen || row !== null : opened) return null;
+ opened = true;
+ closed = closing;
+ } else if (tag === "tr") {
+ if (!tableOpen || closing === (row === null)) return null;
+ if (closing) rows.push(row!);
+ row = closing ? null : [];
+ } else if (tag === "td" || tag === "th") {
+ if (closing || row === null || CELL_SPAN_PATTERN.test(match[3]!)) return null;
+ cell = { tag, contentStart: match.index + match[0].length };
+ } else if (!tableOpen || row !== null) {
+ return null;
+ }
+ }
+ cursor = match.index + match[0].length;
+ }
+ if (!closed || html.slice(cursor).trim().length > 0) return null;
+ return rows.filter((cells) => cells.length > 0);
+}
+
+/**
+ * The table opening at `start`, through its matching close. `end` is the last line looked at
+ * even when the table is not usable, so the caller never re-reads an inner table on its own.
+ */
+function mediaTableAt(
+ lines: ReadonlyArray<string>,
+ start: number,
+ startOffset: number,
+): { end: number; rows: TableRows | null } {
+ const lastCandidate = Math.min(start + TABLE_MAX_LINES, lines.length) - 1;
+ let depth = 0;
+ let end = start;
+ for (; ; end += 1) {
+ const line = lines[end]!;
+ depth +=
+ (line.match(TABLE_OPEN_PATTERN)?.length ?? 0) -
+ (line.match(TABLE_CLOSE_PATTERN)?.length ?? 0);
+ if (depth <= 0 || end === lastCandidate) break;
+ }
+ if (depth !== 0 || !TABLE_END_PATTERN.test(lines[end]!)) return { end, rows: null };
+ // Lifting attachment links out of a table's cells would tear the table apart.
+ const rows = tableRows(lines.slice(start, end + 1).join("\n"), startOffset);
+ const hasMedia = rows?.some((cells) =>
+ cells.some((cell) => cell.segments.some((segment) => segment.kind === "attachment")),
+ );
+ return { end, rows: hasMedia ? rows : null };
+}
+
export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
+ return splitBodyAt(body, 0);
+}
+
+/** `baseOffset` is where `body` starts in the whole body, so a table cell's edits write back. */
+function splitBodyAt(body: string, baseOffset: number): ReadonlyArray<PullRequestBodySegment> {
const segments: PullRequestBodySegment[] = [];
const markdown: string[] = [];
let markdownStart = 0;
@@ -67,7 +177,7 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
// indented code block, so trimming a run would silently turn code into prose.
const flushMarkdown = () => {
const joined = markdown.join("\n");
- const text = joined.replace(/^\n+/u, "");
+ const text = joined.replace(/^(?:\r?\n)+/u, "");
const sourceOffset = markdownStart + joined.length - text.length;
markdown.length = 0;
if (text.trim().length > 0) {
@@ -81,7 +191,8 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
};
const lines = body.split("\n");
- let lineStart = 0;
+ let tableScannedThrough = -1;
+ let lineStart = baseOffset;
for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {
const line = lines[index]!;
if (markdown.length === 0) markdownStart = lineStart;
@@ -109,6 +220,17 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
continue;
}
+ if (index > tableScannedThrough && TABLE_START_PATTERN.test(line)) {
+ const table = mediaTableAt(lines, index, lineStart);
+ tableScannedThrough = table.end;
+ if (table.rows !== null) {
+ flushMarkdown();
+ segments.push({ id: `table:${segments.length}`, kind: "table", rows: table.rows });
+ for (; index < table.end; index += 1) lineStart += lines[index]!.length + 1;
+ continue;
+ }
+ }
+
const bareAttachment = attachmentFromLine(line);
if (bareAttachment !== null) {
flushMarkdown();