Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/preserve-markdown-table-literals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"streamdown": patch
---

Preserve literal HTML tags and character entities when copying or downloading tables as Markdown.
21 changes: 21 additions & 0 deletions packages/streamdown/__tests__/table-utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { marked } from "marked";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
escapeMarkdownTableCell,
Expand Down Expand Up @@ -481,6 +482,26 @@ describe("Table Utils", () => {
});

describe("tableDataToMarkdown", () => {
it("should preserve literal HTML and entities when rendered again", () => {
const table = document.createElement("table");
table.innerHTML = `
<thead><tr><th>Type &lt;T&gt;</th><th>Entities</th></tr></thead>
<tbody><tr>
<td><code>Array&lt;string&gt;</code></td>
<td>&amp;copy; and &amp;#124;</td>
</tr></tbody>
`;
const data = extractTableDataFromElement(table);
const markdown = tableDataToMarkdown(data);
const container = document.createElement("div");
container.innerHTML = marked.parse(markdown, { async: false });
const restoredTable = container.querySelector(
"table"
) as HTMLTableElement;

expect(extractTableDataFromElement(restoredTable)).toEqual(data);
});

it("should convert simple table data to Markdown", () => {
const data: TableData = {
headers: ["Name", "Age", "City"],
Expand Down
15 changes: 14 additions & 1 deletion packages/streamdown/lib/table/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,14 @@ export const escapeMarkdownTableCell = (cell: string): string => {
// OPTIMIZATION: Fast path for cells that don't need escaping - check chars directly
let needsEscaping = false;
for (const char of cell) {
if (char === "\\" || char === "|" || char === "\n") {
if (
char === "\\" ||
char === "|" ||
char === "\n" ||
char === "&" ||
char === "<" ||
char === ">"
) {
needsEscaping = true;
break;
}
Expand All @@ -202,6 +209,12 @@ export const escapeMarkdownTableCell = (cell: string): string => {
parts.push("\\|");
} else if (char === "\n") {
parts.push("<br>");
} else if (char === "&") {
parts.push("&amp;");
} else if (char === "<") {
parts.push("&lt;");
} else if (char === ">") {
parts.push("&gt;");
} else {
parts.push(char);
}
Expand Down