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

pullRequestDescriptionContent.ts

62 lines2.2 KB

1import { mediaReferenceFileName } from "@t3tools/client-runtime/media-reference";
2import type { PullRequestBodySegment } from "@t3tools/client-runtime/pull-request-markdown";
3import { msg } from "gt-react-native";
4import type { MarkdownNode } from "../../lib/markdownDocument";
5import { m, type MessageResolver } from "../../i18n/messages";
6​
7function isWebUrl(url: string): boolean {
8 try {
9 const parsed = new URL(url);
10 return parsed.protocol === "https:" || parsed.protocol === "http:";
11 } catch {
12 return false;
13 }
15​
16export function pullRequestDescriptionContent(
17 document: MarkdownNode,
18 media: readonly PullRequestBodySegment[] = [],
19 resolve: MessageResolver = m,
20) {
21 const attachments = new Map<
22 string,
23 { readonly uri: string; readonly caption: string; readonly kind: "image" | "video" | "unknown" }
24 >();
25 const text: string[] = [];
26 const visit = (node: MarkdownNode) => {
27 if (node.type === "image") {
28 if (node.url && isWebUrl(node.url) && !attachments.has(node.url)) {
29 attachments.set(node.url, {
30 uri: node.url,
31 caption: node.alt || node.title || resolve(msg("Image")),
32 kind: "image",
33 });
34 }
35 return;
36 }
37 if (node.type === "html") return;
38 if ("value" in node) text.push(node.value);
39 if ("children" in node) node.children.forEach(visit);
40 if (["paragraph", "heading", "listItem", "code"].includes(node.type)) text.push("\n");
41 if (node.type === "break") text.push(" ");
42 };
43 visit(document);
44 const collect = (segment: PullRequestBodySegment) => {
45 if (segment.kind === "table") {
46 segment.rows.flat().forEach((cell) => cell.segments.forEach(collect));
47 return;
48 }
49 if (segment.kind === "attachment" && !attachments.has(segment.url)) {
50 const name = mediaReferenceFileName({ kind: "url", url: segment.url });
51 attachments.set(segment.url, {
52 uri: segment.url,
53 caption:
54 segment.label ||
55 (segment.media === "video" ? resolve(msg("Video")) : name || resolve(msg("Image"))),
56 kind: segment.media,
57 });
58 }
59 };
60 media.forEach(collect);
61 return { preview: text.join("").trim(), attachments: [...attachments.values()] };