Elffuss BraidHub

kikocis/continue public

7d19f8698b5d · 4.1 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, "text", (node, index, parent) => {
26 const { value } = node;
27
28 const tableRegex =
29 /((?:\| *[^|\r\n]+ *)+\|)(?:\r?\n)((?:\|[ :]?-+[ :]?)+\|)((?:(?:\r?\n)(?:\| *[^|\r\n]+ *)+\|)+)/g;
30 //// header // newline // |:---|----:| // new line // table rows
31
32 let match: RegExpExecArray | null;
33 let lastIndex = 0;
34 const newNodes = [];
35 let failed = false;
36 while ((match = tableRegex.exec(value)) !== null) {
37 const fullTableString = match[0];
38 const headerGroup = match[1];
39 const separatorGroup = match[2];
40 const bodyGroup = match[3];
41
42 if (!fullTableString || !headerGroup || !separatorGroup || !bodyGroup) {
43 console.error("Markdown table regex failed to yield table groups");
44 failed = true;
45 break;
46 }
47
48 const headerCells = splitRow(headerGroup);
49 const alignments = splitRow(separatorGroup).map((cell) => {
50 if (cell.startsWith(":") && cell.endsWith(":")) return "center";
51 if (cell.endsWith(":")) return "right";
52 if (cell.startsWith(":")) return "left";
53 return null;
54 });
55
56 const bodyCells = bodyGroup
57 .trim()
58 .split("\n")
59 .map((bodyRow) => splitRow(bodyRow));
60
61 try {
62 const tableNode = {
63 type: "table",
64 align: alignments,
65 children: [
66 {
67 type: "tableRow",
68 children: headerCells.map((cell, i) => ({
69 type: "element",
70 tagName: "th",
71 align: alignments[i],
72 children: [{ type: "text", value: cell }],
73 })),
74 },
75 ...bodyCells.map((row, i) => {
76 return {
77 type: "tableRow",
78 data: {
79 hProperties: {
80 class: "markdown-table",
81 key: i,
82 },
83 },
84 children: row.map((cell, i) => ({
85 type: "tableCell",
86 align: alignments[i],
87 children: [{ type: "text", value: cell.trim() }],
88 })),
89 };
90 }),
91 ],
92 };
93
94 // Add any text before the table as a text node
95 if (match.index > lastIndex) {
96 newNodes.push({
97 type: "text",
98 value: value.slice(lastIndex, match.index),
99 });
100 }
101
102 // Add table node
103 newNodes.push(tableNode);
104 } catch (e) {
105 console.error("Failed to parse markdown table after regex match", e);
106 newNodes.push({
107 type: "text",
108 value: fullTableString,
109 });
110 }
111
112 lastIndex = tableRegex.lastIndex;
113 }
114
115 if (failed) {
116 return;
117 }
118
119 // Add any remaining text after the last table
120 if (lastIndex < value.length) {
121 newNodes.push({
122 type: "text",
123 value: value.slice(lastIndex),
124 });
125 }
126
127 // Replace the original text node with the new nodes
128 if (newNodes.length > 0) {
129 parent.children.splice(index, 1, ...newNodes);
130 }
131 });
132 };
133}
134
135function splitRow(row: string) {
136 return row
137 .trim()
138 .replace(/^\||\|$/g, "") // Remove leading and trailing pipes
139 .split("|")
140 .map((cell) => cell.trim());
141}