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
8 changes: 8 additions & 0 deletions .changeset/three-squids-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"streamdown": minor
---

- Fixed table copy losing line breaks inside cells containing `<br>` elements.
- Preserved multiline content during table data extraction.
- Improved copied Markdown, CSV, and TSV output consistency for multiline cells.
- Added coverage for `<br>` handling in table extraction.
214 changes: 214 additions & 0 deletions packages/streamdown/__tests__/copy-dropdown.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -615,4 +615,218 @@ describe("TableCopyDropdown", () => {
expect.any(Function)
);
});

describe("line breaks inside table cells", () => {
const OriginalBlob = globalThis.Blob;
let blobPartsByType: Record<string, BlobPart[]>;
let blobSpy: ReturnType<typeof vi.spyOn>;

const getClipboardPlainText = (): string => {
const plainTextParts = blobPartsByType["text/plain"];
return String(plainTextParts?.[0] ?? "");
};

beforeEach(() => {
blobPartsByType = {};
blobSpy = vi.spyOn(globalThis, "Blob").mockImplementation(function (
this: Blob,
parts?: BlobPart[],
opts?: BlobPropertyBag
) {
const type = opts?.type ?? "";
if (parts) {
blobPartsByType[type] = parts;
}
return new OriginalBlob(parts, opts);
} as unknown as typeof Blob);

mockTable.innerHTML = `
<thead>
<tr>
<th>Description</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Paragraph one.<br>Paragraph two.</td>
<td>Line A<br>Line B<br>Line C</td>
</tr>
</tbody>
`;
});

afterEach(() => {
blobSpy.mockRestore();
});

it("should preserve <br> as newlines when copying as Markdown", async () => {
const dropdownContainer = document.createElement("div");
mockWrapper.appendChild(dropdownContainer);

const { container, getByText } = render(
<StreamdownContext.Provider
value={{
isAnimating: false,
mode: "streaming",
shikiTheme: ["github-light", "github-dark"],
controls: true,
}}
>
<TableCopyDropdown />
</StreamdownContext.Provider>,
{ container: dropdownContainer }
);

const button = container.querySelector('button[title="Copy table"]');
expect(button).toBeTruthy();
if (button) {
fireEvent.click(button);
}

fireEvent.click(getByText("Markdown"));

await waitFor(() => {
expect(navigator.clipboard.write).toHaveBeenCalled();
});

expect(blobPartsByType["text/plain"]).toBeDefined();

expect(getClipboardPlainText()).toBe(
"| Description | Notes |\n| --- | --- |\n| Paragraph one.<br>Paragraph two. | Line A<br>Line B<br>Line C |"
);

mockWrapper.removeChild(dropdownContainer);
});

it("should preserve <br> as newlines when copying as CSV", async () => {
const dropdownContainer = document.createElement("div");
mockWrapper.appendChild(dropdownContainer);

const { container, getByText } = render(
<StreamdownContext.Provider
value={{
isAnimating: false,
mode: "streaming",
shikiTheme: ["github-light", "github-dark"],
controls: true,
}}
>
<TableCopyDropdown />
</StreamdownContext.Provider>,
{ container: dropdownContainer }
);

const button = container.querySelector('button[title="Copy table"]');
expect(button).toBeTruthy();
if (button) {
fireEvent.click(button);
}

fireEvent.click(getByText("CSV"));

await waitFor(() => {
expect(navigator.clipboard.write).toHaveBeenCalled();
});

expect(blobPartsByType["text/plain"]).toBeDefined();

expect(getClipboardPlainText()).toBe(
'Description,Notes\n"Paragraph one.\nParagraph two.","Line A\nLine B\nLine C"'
);

mockWrapper.removeChild(dropdownContainer);
});

it("should preserve <br> as escaped newlines when copying as TSV", async () => {
const dropdownContainer = document.createElement("div");
mockWrapper.appendChild(dropdownContainer);

const { container, getByText } = render(
<StreamdownContext.Provider
value={{
isAnimating: false,
mode: "streaming",
shikiTheme: ["github-light", "github-dark"],
controls: true,
}}
>
<TableCopyDropdown />
</StreamdownContext.Provider>,
{ container: dropdownContainer }
);

const button = container.querySelector('button[title="Copy table"]');
expect(button).toBeTruthy();
if (button) {
fireEvent.click(button);
}

fireEvent.click(getByText("TSV"));

await waitFor(() => {
expect(navigator.clipboard.write).toHaveBeenCalled();
});

expect(blobPartsByType["text/plain"]).toBeDefined();

expect(getClipboardPlainText()).toBe(
"Description\tNotes\nParagraph one.\\nParagraph two.\tLine A\\nLine B\\nLine C"
);

mockWrapper.removeChild(dropdownContainer);
});

it("should not merge cell text across <br> tags", async () => {
mockTable.innerHTML = `
<thead>
<tr>
<th>Cell</th>
</tr>
</thead>
<tbody>
<tr>
<td>Paragraph one.<br>Paragraph two.</td>
</tr>
</tbody>
`;

const dropdownContainer = document.createElement("div");
mockWrapper.appendChild(dropdownContainer);

const { container, getByText } = render(
<StreamdownContext.Provider
value={{
isAnimating: false,
mode: "streaming",
shikiTheme: ["github-light", "github-dark"],
controls: true,
}}
>
<TableCopyDropdown />
</StreamdownContext.Provider>,
{ container: dropdownContainer }
);

const button = container.querySelector('button[title="Copy table"]');
expect(button).toBeTruthy();
if (button) {
fireEvent.click(button);
}

fireEvent.click(getByText("CSV"));
await waitFor(() => {
expect(navigator.clipboard.write).toHaveBeenCalled();
});

expect(blobPartsByType["text/plain"]).toBeDefined();

const plainText = getClipboardPlainText();

expect(plainText).not.toContain("Paragraph one.Paragraph two.");
expect(plainText).toContain("Paragraph one.\nParagraph two.");

mockWrapper.removeChild(dropdownContainer);
});
});
});
76 changes: 76 additions & 0 deletions packages/streamdown/__tests__/table-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,64 @@ describe("Table Utils", () => {
expect(result.headers).toEqual([]);
expect(result.rows).toEqual([["Data"]]);
});

it("should convert <br> elements to newlines in cells", () => {
tableElement.innerHTML = `
<thead>
<tr>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Paragraph one.<br>Paragraph two.</td>
</tr>
</tbody>
`;

const result = extractTableDataFromElement(tableElement);

expect(result.rows).toEqual([["Paragraph one.\nParagraph two."]]);
});

it("should convert multiple <br> elements to newlines", () => {
tableElement.innerHTML = `
<thead>
<tr>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Line A<br>Line B<br>Line C</td>
</tr>
</tbody>
`;

const result = extractTableDataFromElement(tableElement);

expect(result.rows).toEqual([["Line A\nLine B\nLine C"]]);
});

it("should convert <br> inside nested elements to newlines", () => {
tableElement.innerHTML = `
<thead>
<tr>
<th>Header<br>with break</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Bold</strong><br><em>Italic</em></td>
</tr>
</tbody>
`;

const result = extractTableDataFromElement(tableElement);

expect(result.headers).toEqual(["Header\nwith break"]);
expect(result.rows).toEqual([["Bold\nItalic"]]);
});
});

describe("tableDataToCSV", () => {
Expand Down Expand Up @@ -290,6 +348,11 @@ describe("Table Utils", () => {
const result = escapeMarkdownTableCell("");
expect(result).toBe("");
});

it("should convert newlines to <br>", () => {
const result = escapeMarkdownTableCell("Paragraph one.\nParagraph two.");
expect(result).toBe("Paragraph one.<br>Paragraph two.");
});
});

describe("tableDataToMarkdown", () => {
Expand Down Expand Up @@ -378,5 +441,18 @@ describe("Table Utils", () => {
// Extra cells are ignored during the mapping
expect(result).toBe("| Col1 | Col2 |\n| --- | --- |\n| A | B | C | D |");
});

it("should convert cell newlines to <br> for single-line table rows", () => {
const data: TableData = {
headers: ["Description"],
rows: [["Paragraph one.\nParagraph two."]],
};

const result = tableDataToMarkdown(data);

expect(result).toBe(
"| Description |\n| --- |\n| Paragraph one.<br>Paragraph two. |"
);
});
});
});
27 changes: 23 additions & 4 deletions packages/streamdown/lib/table/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,24 @@ export interface TableData {
rows: string[][];
}

function extractCellText(node: Node): string {
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent ?? "";
}

if (node.nodeType !== Node.ELEMENT_NODE) {
return "";
}

const element = node as HTMLElement;

if (element.tagName === "BR") {
return "\n";
}

return Array.from(element.childNodes).map(extractCellText).join("");
}

export const extractTableDataFromElement = (
tableElement: HTMLElement
): TableData => {
Expand All @@ -12,7 +30,7 @@ export const extractTableDataFromElement = (
// Extract headers
const headerCells = tableElement.querySelectorAll("thead th");
for (const cell of headerCells) {
headers.push(cell.textContent?.trim() || "");
headers.push(extractCellText(cell).trim());
}

// Extract rows
Expand All @@ -21,7 +39,7 @@ export const extractTableDataFromElement = (
const rowData: string[] = [];
const cells = row.querySelectorAll("td");
for (const cell of cells) {
rowData.push(cell.textContent?.trim() || "");
rowData.push(extractCellText(cell).trim());
}
rows.push(rowData);
}
Expand Down Expand Up @@ -139,7 +157,7 @@ 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 === "|") {
if (char === "\\" || char === "|" || char === "\n") {
needsEscaping = true;
break;
}
Expand All @@ -149,13 +167,14 @@ export const escapeMarkdownTableCell = (cell: string): string => {
return cell;
}

// OPTIMIZATION: Use array building instead of string concatenation for better performance
const parts: string[] = [];
for (const char of cell) {
if (char === "\\") {
parts.push("\\\\");
} else if (char === "|") {
parts.push("\\|");
} else if (char === "\n") {
parts.push("<br>");
} else {
parts.push(char);
}
Expand Down
Loading