Open History to see the last commit
1interface MarkdownAstNode {
2 type?: string;
3 value?: unknown;
4 data?: {
5 hProperties?: Record<string, unknown>;
6 };
7 children?: MarkdownAstNode[];
8}
9
10const GITHUB_ALERT_MARKER = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:\r?\n|$)/i;
11
12function readGithubAlert(node: MarkdownAstNode): void {
13 if (node.type !== "blockquote") return;
14 const paragraph = node.children?.[0];
15 const text = paragraph?.children?.[0];
16 if (paragraph?.type !== "paragraph" || text?.type !== "text" || typeof text.value !== "string") {
17 return;
18 }
19 const match = GITHUB_ALERT_MARKER.exec(text.value);
20 if (!match?.[1]) return;
21
22 const remainder = text.value.slice(match[0].length);
23 // Whether the marker's own line ended inside this text node. Without it, an empty remainder
24 // is ambiguous: `[!NOTE]\n**bold**` parses as [text "[!NOTE]\n", strong] — next-line content
25 // in a sibling — while `[!NOTE]*aside*` parses the same way minus the newline.
26 const markerEndsItsLine = match[0].endsWith("\n");
27 if (remainder.length > 0) {
28 text.value = remainder;
29 } else if (markerEndsItsLine || paragraph.children?.length === 1) {
30 paragraph.children?.shift();
31 if (paragraph.children?.length === 0) {
32 node.children?.shift();
33 }
34 } else {
35 return;
36 }
37
38 node.data = {
39 ...node.data,
40 hProperties: {
41 ...node.data?.hProperties,
42 dataAlert: match[1].toLowerCase(),
43 },
44 };
45}
46
47export function remarkGithubAlerts() {
48 return (tree: MarkdownAstNode) => {
49 const visit = (node: MarkdownAstNode) => {
50 node.children?.forEach(visit);
51 readGithubAlert(node);
52 };
53 visit(tree);
54 };
55}