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

pullRequestMarkdown.logic.ts

54 lines1.8 KB

1import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
2​
3export {
4 splitPullRequestBody,
5 type PullRequestBodySegment,
6} from "@t3tools/client-runtime/pull-request-markdown";
7​
8type MarkdownNode = {
9 type: string;
10 value?: string;
11 children?: MarkdownNode[];
12 url?: string;
13 data?: unknown;
14};
15​
16const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);
17​
18export function remarkPullRequestAutolinks(options: {
19 readonly autolinks: (text: string) => ReadonlyArray<ReferenceAutolink>;
20}) {
21 const visit = (node: MarkdownNode): void => {
22 const children = node.children;
23 if (children === undefined) return;
24 for (let index = 0; index < children.length; index += 1) {
25 const child = children[index]!;
26 if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue;
27 if (child.type !== "text" || child.value === undefined) {
28 visit(child);
29 continue;
30 }
31 const value = child.value;
32 const links = options.autolinks(value);
33 if (links.length === 0) continue;
34 const replacements: MarkdownNode[] = [];
35 let start = 0;
36 for (const link of links) {
37 if (start < link.index) {
38 replacements.push({ type: "text", value: value.slice(start, link.index) });
39 }
40 replacements.push({
41 type: "link",
42 url: link.url,
43 data: { hProperties: { dataPullRequestAutolink: link.kind } },
44 children: [{ type: "text", value: link.label }],
45 });
46 start = link.index + link.text.length;
47 }
48 if (start < value.length) replacements.push({ type: "text", value: value.slice(start) });
49 children.splice(index, 1, ...replacements);
50 index += replacements.length - 1;
51 }
52 };
53 return (tree: MarkdownNode) => visit(tree);