The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 03:15 UTC
fix(web): PR bodies keep before/after video tables intact (#25988)
Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>
Bartłomiej Błoniarz committed
Nov 6, 2026 at 21:35 UTC
32a0531748c44b25072d7495ce0b9bd7e9450a87
7 files changed
+473
-128
apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
+90
-45
@@ -1,4 +1,7 @@
1
-import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown";
1
+import {
2
+ splitPullRequestBody,
3
+ type PullRequestBodySegment,
4
+} from "@t3tools/client-runtime/pull-request-markdown";
5
import { markdownTaskMarkerOffset } from "@t3tools/shared/markdownTaskList";
6
import type { ReactNode } from "react";
7
import { View } from "react-native";
@@ -116,49 +119,101 @@ export function PullRequestMarkdown(props: {
119
readonly checked: boolean;
120
}) => boolean;
121
}) {
119
- const { onTaskListChange } = props;
122
+ const mediaContext = useContext(PullRequestMediaContext);
123
+ const changeRequestUrl = useContext(ChangeRequestUrlContext);
124
const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]);
125
const [undoneTicks, setUndoneTicks] = useState(0);
126
+ const gallery: FilePreviewItem[] = markdownImageSources(
127
+ props.imageGroupMarkdown ?? props.markdown,
128
+ )
129
+ .map((href) => (changeRequestUrl ? resolveChangeRequestMediaUrl(href, changeRequestUrl) : href))
130
+ .filter(
131
+ (uri) =>
132
+ /^https?:\/\//i.test(uri) &&
133
+ videoMimeType({ name: uri.split(/[?#]/)[0] ?? uri, mimeType: "" }) === null,
134
+ )
135
+ .map((uri) => pullRequestImageSource(uri, mediaContext));
136
+ const segmentProps = {
137
+ gallery,
138
+ lineBreaks: props.lineBreaks,
139
+ undoneTicks,
140
+ onTaskListChange: props.onTaskListChange,
141
+ onTaskListUndone: () => setUndoneTicks((count) => count + 1),
142
+ };
143
+ return (
144
+ <View style={{ gap: 12 }}>
145
+ {segments.map((segment) => (
146
+ <PullRequestBodySegmentView key={segment.id} segment={segment} {...segmentProps} />
147
+ ))}
148
+ </View>
149
+ );
150
+}
151
+
152
+function PullRequestBodySegmentView(props: {
153
+ readonly segment: PullRequestBodySegment;
154
+ readonly gallery: FilePreviewItem[];
155
+ readonly lineBreaks: boolean | undefined;
156
+ readonly undoneTicks: number;
157
+ readonly onTaskListChange:
158
+ | ((input: { readonly markerOffset: number; readonly checked: boolean }) => boolean)
159
+ | undefined;
160
+ readonly onTaskListUndone: () => void;
161
+}) {
162
+ const { segment, onTaskListChange } = props;
163
+ if (segment.kind === "markdown") {
164
+ return (
165
+ <PullRequestMarkdownContent
166
+ key={props.undoneTicks}
167
+ markdown={segment.text}
168
+ gallery={props.gallery}
169
+ lineBreaks={props.lineBreaks}
170
+ onTaskListItemPress={
171
+ onTaskListChange
172
+ ? (event) => {
173
+ const offset = markdownTaskMarkerOffset(
174
+ segment.text,
175
+ event.index,
176
+ event.text,
177
+ event.checked,
178
+ );
179
+ const kept =
180
+ offset !== null &&
181
+ onTaskListChange({
182
+ markerOffset: segment.sourceOffset + offset,
183
+ checked: event.checked,
184
+ });
185
+ if (!kept) props.onTaskListUndone();
186
+ }
187
+ : undefined
188
+ }
189
+ />
190
+ );
191
+ }
192
+ if (segment.kind === "attachment") {
193
+ return <PullRequestMedia url={segment.url} kind={segment.media} />;
194
+ }
195
return (
196
<View style={{ gap: 12 }}>
124
- {segments.map((segment) =>
125
- segment.kind === "markdown" ? (
126
- <PullRequestMarkdownContent
127
- key={`${segment.id}:${undoneTicks}`}
128
- markdown={segment.text}
129
- imageGroupMarkdown={props.imageGroupMarkdown ?? props.markdown}
130
- lineBreaks={props.lineBreaks}
131
- onTaskListItemPress={
132
- onTaskListChange
133
- ? (event) => {
134
- const offset = markdownTaskMarkerOffset(
135
- segment.text,
136
- event.index,
137
- event.text,
138
- event.checked,
139
- );
140
- const kept =
141
- offset !== null &&
142
- onTaskListChange({
143
- markerOffset: segment.sourceOffset + offset,
144
- checked: event.checked,
145
- });
146
- if (!kept) setUndoneTicks((count) => count + 1);
147
- }
148
- : undefined
149
- }
150
- />
151
- ) : (
152
- <PullRequestMedia key={segment.id} url={segment.url} kind={segment.media} />
153
- ),
154
- )}
197
+ {segment.rows.map((cells, rowIndex) => (
198
+ // oxlint-disable-next-line react/no-array-index-key -- rows have no identity besides position
199
+ <View key={rowIndex} style={{ flexDirection: "row", gap: 12 }}>
200
+ {cells.map((cell, cellIndex) => (
201
+ // oxlint-disable-next-line react/no-array-index-key -- cells have no identity besides position
202
+ <View key={cellIndex} style={{ flex: 1, minWidth: 0, gap: 12 }}>
203
+ {cell.segments.map((cellSegment) => (
204
+ <PullRequestBodySegmentView key={cellSegment.id} {...props} segment={cellSegment} />
205
+ ))}
206
+ </View>
207
+ ))}
208
+ </View>
209
+ ))}
210
</View>
211
);
212
}
213
214
function PullRequestMarkdownContent(props: {
215
readonly markdown: string;
161
- readonly imageGroupMarkdown?: string;
216
+ readonly gallery: FilePreviewItem[];
217
readonly lineBreaks: boolean | undefined;
218
readonly onTaskListItemPress?: SelectableMarkdownTextProps["onTaskListItemPress"];
219
}) {
@@ -173,23 +228,13 @@ function PullRequestMarkdownContent(props: {
228
const openLink = (href: string) => {
229
void openPullRequest(href);
230
};
176
- const gallery: FilePreviewItem[] = markdownImageSources(
177
- props.imageGroupMarkdown ?? props.markdown,
178
- )
179
- .map(resolveMediaUrl)
180
- .filter(
181
- (uri) =>
182
- /^https?:\/\//i.test(uri) &&
183
- videoMimeType({ name: uri.split(/[?#]/)[0] ?? uri, mimeType: "" }) === null,
184
- )
185
- .map((uri) => pullRequestImageSource(uri, mediaContext));
231
const [preview, setPreview] = useState<FilePreviewSource | null>(null);
232
const renderImage: MarkdownImageRenderer = (image) => (
233
<MarkdownImage href={resolveMediaUrl(image.href)} alt={image.alt} onPreview={setPreview} />
234
);
235
const styles = useMarkdownPreviewStyles();
236
return (
192
- <FilePreviewGallery value={gallery}>
237
+ <FilePreviewGallery value={props.gallery}>
238
<SelectableMarkdownText
239
markdown={markdown}
240
preserveSoftBreaks={props.lineBreaks ?? hostLineBreaks}
apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts
+12
@@ -26,4 +26,16 @@ describe("PR attachments", () => {
26
},
27
]);
28
});
29
+
30
+ it("collects videos from a before/after table", () => {
31
+ const media = splitPullRequestBody(
32
+ "<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>",
33
+ );
34
+ expect(
35
+ pullRequestDescriptionContent({ type: "root" } as MarkdownNode, media).attachments,
36
+ ).toEqual([
37
+ { uri: "https://drop.example.com/before.mp4", caption: "Video", kind: "video" },
38
+ { uri: "https://drop.example.com/after.mp4", caption: "Video", kind: "video" },
39
+ ]);
40
+ });
41
});
apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts
+7
-2
@@ -37,7 +37,11 @@ export function pullRequestDescriptionContent(
37
if (node.type === "break") text.push(" ");
38
};
39
visit(document);
40
- for (const segment of media) {
40
+ const collect = (segment: PullRequestBodySegment) => {
41
+ if (segment.kind === "table") {
42
+ segment.rows.flat().forEach((cell) => cell.segments.forEach(collect));
43
+ return;
44
+ }
45
if (segment.kind === "attachment" && !attachments.has(segment.url)) {
46
const name = new URL(segment.url).pathname.split("/").pop();
47
attachments.set(segment.url, {
@@ -46,6 +50,7 @@ export function pullRequestDescriptionContent(
50
kind: segment.media,
51
});
52
}
49
- }
53
+ };
54
+ media.forEach(collect);
55
return { preview: text.join("").trim(), attachments: [...attachments.values()] };
56
}
apps/web/src/components/media/MediaVideoPlayer.tsx
+1
-1
@@ -132,7 +132,7 @@ export function MediaVideoPlayer({
132
<span
133
role="alert"
134
className={cn(
135
- "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",
135
+ "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",
136
stateClassName,
137
)}
138
>
apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+129
-70
@@ -16,7 +16,7 @@ import { PULL_REQUESTS_PANEL_REF } from "~/rightPanelStore";
16
17
import ChatMarkdown from "../ChatMarkdown";
18
import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
19
-import { splitPullRequestBody } from "./pullRequestMarkdown.logic";
19
+import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.logic";
20
21
export const PullRequestMarkdownContext = createContext<{
22
/** Stable per repository, so comments share one renderer and its parse cache. */
@@ -62,6 +62,123 @@ function PullRequestHostVideo({
62
);
63
}
64
65
+function PullRequestBodySegmentView({
66
+ segment,
67
+ cwd,
68
+ environmentId,
69
+ threadRef,
70
+ lineBreaks,
71
+ onTaskListChange,
72
+}: {
73
+ segment: PullRequestBodySegment;
74
+ cwd: string;
75
+ environmentId: EnvironmentId;
76
+ threadRef: ScopedThreadRef | undefined;
77
+ lineBreaks: boolean;
78
+ onTaskListChange: ((input: { markerOffset: number; checked: boolean }) => void) | undefined;
79
+}) {
80
+ const context = useContext(PullRequestMarkdownContext);
81
+ const repository = context?.repository ?? undefined;
82
+ if (segment.kind === "table") {
83
+ return (
84
+ <div className="space-y-3">
85
+ {segment.rows.map((cells, rowIndex) => (
86
+ <div
87
+ // oxlint-disable-next-line react/no-array-index-key -- rows have no identity besides position
88
+ key={rowIndex}
89
+ className="grid gap-3"
90
+ style={{ gridTemplateColumns: `repeat(${cells.length}, minmax(0, 1fr))` }}
91
+ >
92
+ {cells.map((cell, cellIndex) => (
93
+ <div
94
+ // oxlint-disable-next-line react/no-array-index-key -- cells have no identity besides position
95
+ key={cellIndex}
96
+ className={cn("min-w-0 space-y-3", cell.header && "font-medium")}
97
+ >
98
+ {cell.segments.map((cellSegment) => (
99
+ <PullRequestBodySegmentView
100
+ key={cellSegment.id}
101
+ segment={cellSegment}
102
+ cwd={cwd}
103
+ environmentId={environmentId}
104
+ threadRef={threadRef}
105
+ lineBreaks={lineBreaks}
106
+ onTaskListChange={onTaskListChange}
107
+ />
108
+ ))}
109
+ </div>
110
+ ))}
111
+ </div>
112
+ ))}
113
+ </div>
114
+ );
115
+ }
116
+ if (segment.kind === "markdown" || segment.media === "image") {
117
+ return (
118
+ <ChatMarkdown
119
+ text={segment.kind === "markdown" ? segment.text : ``}
120
+ cwd={cwd}
121
+ threadRef={threadRef}
122
+ pullRequestPanelRef={threadRef ?? PULL_REQUESTS_PANEL_REF}
123
+ environmentId={environmentId}
124
+ {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})}
125
+ lineBreaks={lineBreaks}
126
+ sourceControlMedia
127
+ sourceControlMediaRepository={repository}
128
+ onTaskListChange={
129
+ onTaskListChange && segment.kind === "markdown"
130
+ ? ({ markerOffset, checked }) =>
131
+ onTaskListChange({
132
+ markerOffset: segment.sourceOffset + markerOffset,
133
+ checked,
134
+ })
135
+ : undefined
136
+ }
137
+ />
138
+ );
139
+ }
140
+ const hostMedia = sourceControlClients.mediaUrl(segment.url);
141
+ if (segment.media === "video" && hostMedia !== null) {
142
+ return (
143
+ <PullRequestHostVideo
144
+ key={`${segment.id}:${segment.url}`}
145
+ environmentId={environmentId}
146
+ cwd={cwd}
147
+ url={segment.url}
148
+ fetchUrl={hostMedia.fetchUrl}
149
+ repository={repository}
150
+ />
151
+ );
152
+ }
153
+ if (segment.media === "video") {
154
+ return (
155
+ <MediaVideoPlayer
156
+ key={`${segment.id}:${segment.url}`}
157
+ src={segment.url}
158
+ originalUrl={segment.url}
159
+ label="Pull request video"
160
+ className="w-full"
161
+ videoClassName="rounded-lg border border-border/60"
162
+ />
163
+ );
164
+ }
165
+ return (
166
+ // Desktop converts blocked _blank navigation to openExternal.
167
+ <a
168
+ href={segment.url}
169
+ rel="noreferrer noopener"
170
+ target="_blank"
171
+ 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"
172
+ >
173
+ <PaperclipIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
174
+ <span className="min-w-0 flex-1 truncate">
175
+ Open attachment on {hostMedia?.definition.label ?? new URL(segment.url).hostname}
176
+ </span>
177
+ <ExternalLinkIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />
178
+ </a>
179
+ );
180
+}
181
+
182
export function PullRequestMarkdown({
183
text,
184
cwd,
@@ -82,7 +199,6 @@ export function PullRequestMarkdown({
199
}) {
200
const segments = splitPullRequestBody(text);
201
const context = useContext(PullRequestMarkdownContext);
85
- const repository = context?.repository ?? undefined;
202
const resolvedThreadRef = threadRef ?? context?.threadRef ?? undefined;
203
return (
204
<div
@@ -92,74 +208,17 @@ export function PullRequestMarkdown({
208
)}
209
data-image-gallery
210
>
95
- {segments.map((segment) => {
96
- if (segment.kind === "markdown" || segment.media === "image") {
97
- return (
98
- <ChatMarkdown
99
- key={segment.id}
100
- text={segment.kind === "markdown" ? segment.text : ``}
101
- cwd={cwd}
102
- threadRef={resolvedThreadRef}
103
- pullRequestPanelRef={resolvedThreadRef ?? PULL_REQUESTS_PANEL_REF}
104
- environmentId={environmentId}
105
- {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})}
106
- lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}
107
- sourceControlMedia
108
- sourceControlMediaRepository={repository}
109
- onTaskListChange={
110
- onTaskListChange && segment.kind === "markdown"
111
- ? ({ markerOffset, checked }) =>
112
- onTaskListChange({
113
- markerOffset: segment.sourceOffset + markerOffset,
114
- checked,
115
- })
116
- : undefined
117
- }
118
- />
119
- );
120
- }
121
- const hostMedia = sourceControlClients.mediaUrl(segment.url);
122
- if (segment.media === "video" && hostMedia !== null) {
123
- return (
124
- <PullRequestHostVideo
125
- key={`${segment.id}:${segment.url}`}
126
- environmentId={environmentId}
127
- cwd={cwd}
128
- url={segment.url}
129
- fetchUrl={hostMedia.fetchUrl}
130
- repository={repository}
131
- />
132
- );
133
- }
134
- if (segment.media === "video") {
135
- return (
136
- <MediaVideoPlayer
137
- key={`${segment.id}:${segment.url}`}
138
- src={segment.url}
139
- originalUrl={segment.url}
140
- label="Pull request video"
141
- className="w-full"
142
- videoClassName="rounded-lg border border-border/60"
143
- />
144
- );
145
- }
146
- return (
147
- // Desktop converts blocked _blank navigation to openExternal.
148
- <a
149
- key={segment.id}
150
- href={segment.url}
151
- rel="noreferrer noopener"
152
- target="_blank"
153
- 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"
154
- >
155
- <PaperclipIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
156
- <span className="min-w-0 flex-1 truncate">
157
- Open attachment on {hostMedia?.definition.label ?? new URL(segment.url).hostname}
158
- </span>
159
- <ExternalLinkIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />
160
- </a>
161
- );
162
- })}
211
+ {segments.map((segment) => (
212
+ <PullRequestBodySegmentView
213
+ key={segment.id}
214
+ segment={segment}
215
+ cwd={cwd}
216
+ environmentId={environmentId}
217
+ threadRef={resolvedThreadRef}
218
+ lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}
219
+ onTaskListChange={onTaskListChange}
220
+ />
221
+ ))}
222
</div>
223
);
224
}
packages/client-runtime/src/pullRequestMarkdown.test.ts
+109
-7
@@ -4,6 +4,7 @@ import {
4
changeRequestReferenceAutolinker,
5
resolveChangeRequestMediaUrl,
6
splitPullRequestBody,
7
+ type PullRequestBodySegment,
8
} from "./pullRequestMarkdown.ts";
9
10
describe("pull request body segmentation", () => {
@@ -26,17 +27,26 @@ describe("pull request body segmentation", () => {
27
]);
28
});
29
29
- it("places each prose run at its offset in the body", () => {
30
+ it("places each prose run at its offset in the body, including inside a media table", () => {
31
const body =
31
- '\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';
32
- const prose = splitPullRequestBody(body).flatMap((segment) =>
33
- segment.kind === "markdown" ? [segment] : [],
34
- );
35
- expect(prose.map((segment) => segment.text)).toEqual([
32
+ '\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';
33
+ type Prose = Extract<PullRequestBodySegment, { kind: "markdown" }>;
34
+ const prose = (segments: ReadonlyArray<PullRequestBodySegment>): Prose[] =>
35
+ segments.flatMap((segment) =>
36
+ segment.kind === "markdown"
37
+ ? [segment]
38
+ : segment.kind === "table"
39
+ ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
40
+ : [],
41
+ );
42
+ const runs = prose(splitPullRequestBody(body));
43
+ expect(runs.map((segment) => segment.text)).toEqual([
44
"- [ ] Before",
45
" - [ ] code\n- [x] After",
46
+ "- [ ] In a cell",
47
+ "- [ ] Last",
48
]);
39
- for (const segment of prose) {
49
+ for (const segment of runs) {
50
expect(body.slice(segment.sourceOffset, segment.sourceOffset + segment.text.length)).toBe(
51
segment.text,
52
);
@@ -166,6 +176,98 @@ describe("media on custom hosts", () => {
176
});
177
});
178
179
+describe("media tables", () => {
180
+ const before = "https://github.com/user-attachments/assets/c69c7c1c-ef2f-47dd-97e8-fe42e40712eb";
181
+ const after = "https://github.com/user-attachments/assets/1867b6ec-4f88-4248-b2df-6b0f9808105b";
182
+ const video = "https://example.com/a.mp4";
183
+
184
+ it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
185
+ const segments = splitPullRequestBody(
186
+ `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`,
187
+ );
188
+ expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
189
+ expect(segments[0]).toMatchObject({ text: "Intro" });
190
+ expect(segments[2]).toMatchObject({ text: "Outro" });
191
+ const table = segments[1]!;
192
+ if (table.kind !== "table") throw new Error("expected a table segment");
193
+ expect(
194
+ table.rows.map((row) =>
195
+ row.map((cell) =>
196
+ cell.segments.map((segment) =>
197
+ segment.kind === "attachment" ? `attachment:${segment.url}` : segment,
198
+ ),
199
+ ),
200
+ ),
201
+ ).toEqual([
202
+ [
203
+ [{ id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 23 }],
204
+ [{ id: "markdown:0", kind: "markdown", text: "After", sourceOffset: 38 }],
205
+ ],
206
+ [[`attachment:${before}`], [`attachment:${after}`]],
207
+ ]);
208
+ });
209
+
210
+ it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
211
+ const [table] = splitPullRequestBody(
212
+ `<table>\n<tr><td title="Before > after">Caption</td><td>\n\n${video}\n\n</td></tr>\n</table>`,
213
+ );
214
+ expect(table).toMatchObject({
215
+ kind: "table",
216
+ rows: [[{ segments: [{ kind: "markdown", text: "Caption" }] }, {}]],
217
+ });
218
+ });
219
+
220
+ it("leaves a table without media links as markdown", () => {
221
+ const body = "<table>\n<tr><td>a</td><td>b</td></tr>\n</table>";
222
+ expect(splitPullRequestBody(body)).toEqual([
223
+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
224
+ ]);
225
+ });
226
+
227
+ it.each([
228
+ ["a caption", "<table>\n<caption>Before upgrading</caption>\n<tr><td>", "</td></tr>\n</table>"],
229
+ ["text outside cells", "<table>\nBefore upgrading\n<tr><td>", "</td></tr>\n</table>"],
230
+ [
231
+ "text inside a row but outside cells",
232
+ "<table>\n<tr>Before upgrading<td>",
233
+ "</td></tr>\n</table>",
234
+ ],
235
+ [
236
+ "a table nested in another",
237
+ "<table>\n<tr><td>\n<table>\n<tr><td>",
238
+ "</td></tr>\n</table>\n</td></tr>\n</table>",
239
+ ],
240
+ ["an unclosed table", "<table>\n<tr><td>", ""],
241
+ ["a spanning cell", '<table>\n<tr><td colspan="2">', "</td></tr>\n</table>"],
242
+ [
243
+ "an indented cell",
244
+ "<table>\n <tr>\n <th>\n Before\n </th>\n </tr>\n <tr><td>",
245
+ "</td></tr>\n</table>",
246
+ ],
247
+ [
248
+ "a cell indented by a space and a tab",
249
+ "<table>\n<tr><td>\n \tBefore\n</td><td>",
250
+ "</td></tr>\n</table>",
251
+ ],
252
+ ])("splits a media table with %s line by line, as before", (_name, open, close) => {
253
+ const body = `${open}\n\n${video}\n\n${close}`;
254
+ expect(splitPullRequestBody(body)).toEqual([
255
+ { id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
256
+ { id: "attachment:1", kind: "attachment", url: video, media: "video" },
257
+ ...(close
258
+ ? [
259
+ {
260
+ id: "markdown:2",
261
+ kind: "markdown",
262
+ text: close,
263
+ sourceOffset: body.length - close.length,
264
+ },
265
+ ]
266
+ : []),
267
+ ]);
268
+ });
269
+});
270
+
271
describe("change request reference autolinks", () => {
272
const urls = (provider: string, url: string, text: string) =>
273
changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
packages/client-runtime/src/pullRequestMarkdown.ts
+125
-3
@@ -14,8 +14,18 @@ export type PullRequestBodySegment =
14
readonly kind: "attachment";
15
readonly url: string;
16
readonly media: "video" | "image" | "unknown";
17
+ }
18
+ | {
19
+ readonly id: string;
20
+ readonly kind: "table";
21
+ readonly rows: ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
22
};
23
24
+type PullRequestBodyTableCell = {
25
+ readonly header: boolean;
26
+ readonly segments: ReadonlyArray<PullRequestBodySegment>;
27
+};
28
+
29
// `.` stops at the `\r` of a CRLF body, which is how GitHub stores one written in its web editor.
30
const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)\r?$/u;
31
/**
@@ -24,7 +34,8 @@ const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)\r?$/u;
34
*/
35
const VIDEO_TAG_MAX_LINES = 8;
36
27
-const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/u;
37
+// A tab after up to three spaces still reaches the fourth column.
38
+const INDENTED_CODE_PATTERN = /^(?: {4}| {0,3}\t)/u;
39
const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
40
const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)(?:$|[?#])/iu;
41
const MARKDOWN_LINK_PATTERN = /^\[[^\]]*\]\((https?:\/\/[^\s)]+)\)$/u;
@@ -35,6 +46,21 @@ const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)[
46
const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
47
const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
48
49
+/** Bounded like `VIDEO_TAG_MAX_LINES`; room for a before/after table with several rows. */
50
+const TABLE_MAX_LINES = 64;
51
+const TABLE_START_PATTERN = /^\s*<table\b/iu;
52
+const TABLE_END_PATTERN = /<\/table>\s*$/iu;
53
+const TABLE_OPEN_PATTERN = /<table\b/giu;
54
+const TABLE_CLOSE_PATTERN = /<\/table\s*>/giu;
55
+/**
56
+ * Quoted attribute values may hold `>`. The alternatives start on disjoint characters and an
57
+ * unquoted run stops at the next `<`, so a run of unterminated tags stays linear.
58
+ */
59
+const TABLE_STRUCTURE_TAG_PATTERN =
60
+ /<(\/?)(table|thead|tbody|tfoot|tr|td|th)\b((?:[^<>"']|"[^"]*"|'[^']*')*)>/giu;
61
+/** Rows are laid out independently, so a spanning cell would shift the cells after it. */
62
+const CELL_SPAN_PATTERN = /\b(?:col|row)span\b/iu;
63
+
64
function isWebUrl(url: string): boolean {
65
try {
66
const parsed = new URL(url);
@@ -57,7 +83,91 @@ function attachmentFromLine(
83
return null;
84
}
85
86
+type TableRows = ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
87
+
88
+/**
89
+ * Cells of a table made only of rows and cells, or null when anything else is in it: a caption,
90
+ * text between cells, a nested table. Cell contents are split on their own, so tables never nest.
91
+ */
92
+function tableRows(html: string, htmlOffset: number): TableRows | null {
93
+ const rows: PullRequestBodyTableCell[][] = [];
94
+ let row: PullRequestBodyTableCell[] | null = null;
95
+ let cell: { tag: string; contentStart: number } | null = null;
96
+ let opened = false;
97
+ let closed = false;
98
+ let cursor = 0;
99
+ for (const match of html.matchAll(TABLE_STRUCTURE_TAG_PATTERN)) {
100
+ const closing = match[1] === "/";
101
+ const tag = match[2]!.toLowerCase();
102
+ if (cell !== null) {
103
+ if (!closing || tag !== cell.tag) return null;
104
+ const content = html.slice(cell.contentStart, match.index);
105
+ // Indented HTML would render as a code block once the cell is markdown on its own.
106
+ if (content.split("\n").some((line) => INDENTED_CODE_PATTERN.test(line) && line.trim()))
107
+ return null;
108
+ row!.push({
109
+ header: tag === "th",
110
+ segments: splitBodyAt(content, htmlOffset + cell.contentStart),
111
+ });
112
+ cell = null;
113
+ } else {
114
+ if (html.slice(cursor, match.index).trim().length > 0) return null;
115
+ const tableOpen = opened && !closed;
116
+ if (tag === "table") {
117
+ if (closing ? !tableOpen || row !== null : opened) return null;
118
+ opened = true;
119
+ closed = closing;
120
+ } else if (tag === "tr") {
121
+ if (!tableOpen || closing === (row === null)) return null;
122
+ if (closing) rows.push(row!);
123
+ row = closing ? null : [];
124
+ } else if (tag === "td" || tag === "th") {
125
+ if (closing || row === null || CELL_SPAN_PATTERN.test(match[3]!)) return null;
126
+ cell = { tag, contentStart: match.index + match[0].length };
127
+ } else if (!tableOpen || row !== null) {
128
+ return null;
129
+ }
130
+ }
131
+ cursor = match.index + match[0].length;
132
+ }
133
+ if (!closed || html.slice(cursor).trim().length > 0) return null;
134
+ return rows.filter((cells) => cells.length > 0);
135
+}
136
+
137
+/**
138
+ * The table opening at `start`, through its matching close. `end` is the last line looked at
139
+ * even when the table is not usable, so the caller never re-reads an inner table on its own.
140
+ */
141
+function mediaTableAt(
142
+ lines: ReadonlyArray<string>,
143
+ start: number,
144
+ startOffset: number,
145
+): { end: number; rows: TableRows | null } {
146
+ const lastCandidate = Math.min(start + TABLE_MAX_LINES, lines.length) - 1;
147
+ let depth = 0;
148
+ let end = start;
149
+ for (; ; end += 1) {
150
+ const line = lines[end]!;
151
+ depth +=
152
+ (line.match(TABLE_OPEN_PATTERN)?.length ?? 0) -
153
+ (line.match(TABLE_CLOSE_PATTERN)?.length ?? 0);
154
+ if (depth <= 0 || end === lastCandidate) break;
155
+ }
156
+ if (depth !== 0 || !TABLE_END_PATTERN.test(lines[end]!)) return { end, rows: null };
157
+ // Lifting attachment links out of a table's cells would tear the table apart.
158
+ const rows = tableRows(lines.slice(start, end + 1).join("\n"), startOffset);
159
+ const hasMedia = rows?.some((cells) =>
160
+ cells.some((cell) => cell.segments.some((segment) => segment.kind === "attachment")),
161
+ );
162
+ return { end, rows: hasMedia ? rows : null };
163
+}
164
+
165
export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
166
+ return splitBodyAt(body, 0);
167
+}
168
+
169
+/** `baseOffset` is where `body` starts in the whole body, so a table cell's edits write back. */
170
+function splitBodyAt(body: string, baseOffset: number): ReadonlyArray<PullRequestBodySegment> {
171
const segments: PullRequestBodySegment[] = [];
172
const markdown: string[] = [];
173
let markdownStart = 0;
@@ -67,7 +177,7 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
177
// indented code block, so trimming a run would silently turn code into prose.
178
const flushMarkdown = () => {
179
const joined = markdown.join("\n");
70
- const text = joined.replace(/^\n+/u, "");
180
+ const text = joined.replace(/^(?:\r?\n)+/u, "");
181
const sourceOffset = markdownStart + joined.length - text.length;
182
markdown.length = 0;
183
if (text.trim().length > 0) {
@@ -81,7 +191,8 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
191
};
192
193
const lines = body.split("\n");
84
- let lineStart = 0;
194
+ let tableScannedThrough = -1;
195
+ let lineStart = baseOffset;
196
for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {
197
const line = lines[index]!;
198
if (markdown.length === 0) markdownStart = lineStart;
@@ -109,6 +220,17 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
220
continue;
221
}
222
223
+ if (index > tableScannedThrough && TABLE_START_PATTERN.test(line)) {
224
+ const table = mediaTableAt(lines, index, lineStart);
225
+ tableScannedThrough = table.end;
226
+ if (table.rows !== null) {
227
+ flushMarkdown();
228
+ segments.push({ id: `table:${segments.length}`, kind: "table", rows: table.rows });
229
+ for (; index < table.end; index += 1) lineStart += lines[index]!.length + 1;
230
+ continue;
231
+ }
232
+ }
233
+
234
const bareAttachment = attachmentFromLine(line);
235
if (bareAttachment !== null) {
236
flushMarkdown();