Elffuss BraidHub

kikocis/continue public

c977fe2591e2 · 4.5 KiBRawPermalink
1import { visit } from "unist-util-visit";
2
3/*
4 Remark plugin for github-flavor markdown tables
5 Given a table such as this exists in a text node:
6
7 | Fruit | Color | Taste |
8 |----------|---------|-------------|
9 | Apple | Red | Sweet |
10 | Banana | Yellow | Sweet |
11 | Lemon | Yellow | Sour |
12 | Orange | Orange | Citrus |
13 | Grape | Purple | Sweet/Tart |
14
15 1. Find it and split it into groups using regex
16 - header
17 - alignment row
18 - body
19 2. Parse the groups to get table cell values and text alignment
20 3. Build an MDAST table node
21 4. Do this for each table found, until no tables are found
22*/
23export function remarkTables() {
24 return (tree: any) => {
25 visit(tree, "paragraph", (paragraphNode, index, parentOfParagraphNode) => {
26 let buffer = "";
27 visit(paragraphNode, "text", (textNode) => {
28 buffer += textNode.value;
29 });
30
31 const tableRegex =
32 /((?:\| *[^|\r\n]+ *)+\|)(?:\r?\n)((?:\|[ :]?-+[ :]?)+\|)((?:(?:\r?\n)(?:\| *[^|\r\n]+ *)+\|)+)/g;
33 //// header // newline // |:---|----:| // new line // table rows
34
35 // prevent modifying if no markdown tables are present
36 if (!buffer.match(tableRegex)) {
37 return;
38 }
39
40 let match: RegExpExecArray | null;
41 let lastIndex = 0;
42 const newNodes = [];
43 let failed = false;
44
45 while ((match = tableRegex.exec(buffer)) !== null) {
46 const fullTableString = match[0];
47 const headerGroup = match[1];
48 const separatorGroup = match[2];
49 const bodyGroup = match[3];
50
51 if (!fullTableString || !headerGroup || !separatorGroup || !bodyGroup) {
52 console.error("Markdown table regex failed to yield table groups");
53 failed = true;
54 break;
55 }
56
57 const headerCells = splitRow(headerGroup);
58 const alignments = splitRow(separatorGroup).map((cell) => {
59 if (cell.startsWith(":") && cell.endsWith(":")) return "center";
60 if (cell.endsWith(":")) return "right";
61 if (cell.startsWith(":")) return "left";
62 return null;
63 });
64
65 const bodyCells = bodyGroup
66 .trim()
67 .split("\n")
68 .map((bodyRow) => splitRow(bodyRow));
69
70 try {
71 const tableNode = {
72 type: "table",
73 align: alignments,
74 data: {
75 hProperties: {
76 class: "markdown-table",
77 },
78 },
79 children: [
80 {
81 type: "tableRow",
82 children: headerCells.map((cell, i) => ({
83 type: "element",
84 tagName: "th",
85 align: alignments[i],
86 children: [{ type: "text", value: cell }],
87 })),
88 },
89 ...bodyCells.map((row, i) => {
90 return {
91 type: "tableRow",
92 data: {
93 hProperties: {
94 key: i,
95 },
96 },
97 children: row.map((cell, i) => ({
98 type: "tableCell",
99 align: alignments[i],
100 children: [{ type: "text", value: cell.trim() }],
101 })),
102 };
103 }),
104 ],
105 };
106
107 // Add any text before the table as a text node
108 if (match.index > lastIndex) {
109 newNodes.push({
110 type: "text",
111 value: buffer.slice(lastIndex, match.index),
112 });
113 }
114
115 // Add table node
116 newNodes.push(tableNode);
117 } catch (e) {
118 console.error("Failed to parse markdown table after regex match", e);
119 newNodes.push({
120 type: "text",
121 value: fullTableString,
122 });
123 }
124
125 lastIndex = tableRegex.lastIndex;
126 }
127
128 if (failed) {
129 return;
130 }
131
132 // Add any remaining text after the last table
133 if (lastIndex < buffer.length) {
134 newNodes.push({
135 type: "text",
136 value: buffer.slice(lastIndex),
137 });
138 }
139
140 // Replace the original paragraph node with the new nodes
141 if (newNodes.length > 0) {
142 parentOfParagraphNode.children.splice(index, 1, ...newNodes);
143 }
144 });
145 };
146}
147
148function splitRow(row: string) {
149 return row
150 .trim()
151 .replace(/^\||\|$/g, "") // Remove leading and trailing pipes
152 .split("|")
153 .map((cell) => cell.trim());
154}