Skip to content

Commit 36abf76

Browse files
Merge pull request #5560 from uinstinct/md-table
prevent markdown table from breaking on formatted nodes
2 parents d43f5c1 + 699e3b6 commit 36abf76

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,27 @@ import { visit } from "unist-util-visit";
2222
*/
2323
export function remarkTables() {
2424
return (tree: any) => {
25-
visit(tree, "text", (node, index, parent) => {
26-
const { value } = node;
25+
visit(tree, "paragraph", (paragraphNode, index, parentOfParagraphNode) => {
26+
let buffer = "";
27+
visit(paragraphNode, "text", (textNode) => {
28+
buffer += textNode.value;
29+
});
2730

2831
const tableRegex =
2932
/((?:\| *[^|\r\n]+ *)+\|)(?:\r?\n)((?:\|[ :]?-+[ :]?)+\|)((?:(?:\r?\n)(?:\| *[^|\r\n]+ *)+\|)+)/g;
3033
//// header // newline // |:---|----:| // new line // table rows
3134

35+
// prevent modifying if no markdown tables are present
36+
if(!buffer.match(tableRegex)) {
37+
return;
38+
}
39+
3240
let match: RegExpExecArray | null;
3341
let lastIndex = 0;
3442
const newNodes = [];
3543
let failed = false;
36-
while ((match = tableRegex.exec(value)) !== null) {
44+
45+
while ((match = tableRegex.exec(buffer)) !== null) {
3746
const fullTableString = match[0];
3847
const headerGroup = match[1];
3948
const separatorGroup = match[2];
@@ -62,6 +71,11 @@ export function remarkTables() {
6271
const tableNode = {
6372
type: "table",
6473
align: alignments,
74+
data: {
75+
hProperties: {
76+
class: "markdown-table",
77+
},
78+
},
6579
children: [
6680
{
6781
type: "tableRow",
@@ -77,7 +91,6 @@ export function remarkTables() {
7791
type: "tableRow",
7892
data: {
7993
hProperties: {
80-
class: "markdown-table",
8194
key: i,
8295
},
8396
},
@@ -95,7 +108,7 @@ export function remarkTables() {
95108
if (match.index > lastIndex) {
96109
newNodes.push({
97110
type: "text",
98-
value: value.slice(lastIndex, match.index),
111+
value: buffer.slice(lastIndex, match.index),
99112
});
100113
}
101114

@@ -117,16 +130,16 @@ export function remarkTables() {
117130
}
118131

119132
// Add any remaining text after the last table
120-
if (lastIndex < value.length) {
133+
if (lastIndex < buffer.length) {
121134
newNodes.push({
122135
type: "text",
123-
value: value.slice(lastIndex),
136+
value: buffer.slice(lastIndex),
124137
});
125138
}
126139

127-
// Replace the original text node with the new nodes
140+
// Replace the original paragraph node with the new nodes
128141
if (newNodes.length > 0) {
129-
parent.children.splice(index, 1, ...newNodes);
142+
parentOfParagraphNode.children.splice(index, 1, ...newNodes);
130143
}
131144
});
132145
};

0 commit comments

Comments
 (0)