Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(markdown): render safe table line breaks and copy them faithfully

Afloat3617a8798100
diff --git a/src/components/ChatMarkdown.table-breaks.test.ts b/src/components/ChatMarkdown.table-breaks.test.ts
new file mode 100644
index 0000000000..ce1267c354
--- /dev/null
+++ b/src/components/ChatMarkdown.table-breaks.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { renderToStaticMarkup } from "react-dom/server";
+import { afterEach, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import { ChatMarkdown } from "./ChatMarkdown";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => vi.restoreAllMocks());
+
+const table = (value: string) => `| Result |\n| --- |\n| ${value} |`;
+const render = (text: string) => {
+ const host = document.createElement("div");
+ host.innerHTML = renderToStaticMarkup(createElement(ChatMarkdown, { text }));
+ return host;
+};
+
+it.each(["<br>", "<br/>", "<br />", "<BR>"])("renders %s as a line break inside a table cell", (tag) => {
+ const cell = render(table(`Score: 8.8 / 10${tag}Details`)).querySelector("td")!;
+ expect(cell.querySelectorAll("br")).toHaveLength(1);
+ expect(cell.textContent).not.toContain(tag);
+ expect(cell.textContent).toContain("Score: 8.8 / 10");
+ expect(cell.textContent).toContain("Details");
+});
+
+it("also breaks a table heading without losing its emphasis", () => {
+ const cell = render("| **Score**<br>out of ten |\n| --- |\n| 8.8 |").querySelector("th")!;
+ expect(cell.querySelectorAll("br")).toHaveLength(1);
+ expect(cell.querySelector("strong")?.textContent).toBe("Score");
+ expect(cell.textContent).toContain("out of ten");
+});
+
+it("breaks inside emphasis while keeping that emphasis in the cell", () => {
+ const strong = render(table("**First<br>Second**")).querySelector("td strong")!;
+ expect(strong.querySelectorAll("br")).toHaveLength(1);
+ expect(strong.textContent).toContain("Second");
+});
+
+it("keeps code, escaped tags, attributes, and other HTML inert", () => {
+ const value = '`<br>` &lt;br&gt; \\<br> <br onclick="bad()"> <img src=x onerror="bad()"> <script>bad()</script>';
+ const cell = render(table(value)).querySelector("td")!;
+ expect(cell.querySelector("br, img, script, [onclick], [onerror]")).toBeNull();
+ expect(cell.querySelector("code")?.textContent).toBe("<br>");
+ expect(cell.textContent).toContain('<br onclick="bad()">');
+ expect(render('```html\n<br>\n```').querySelector("pre")?.textContent).toContain("<br>");
+});
+
+it("keeps HTML outside table cells as source text", () => {
+ const host = render("Before<br>After");
+ expect(host.querySelector("br")).toBeNull();
+ expect(host.textContent).toBe("Before<br>After");
+});
+
+it.each([
+ ["First<br>Second", "First\nSecond"],
+ ["First<br/><br/>Second", "First\n\nSecond"],
+ ["**First**<br />[Second](https://example.test)", "First\nSecond"],
+ ["**First<br />Second**", "First\nSecond"],
+])("copies the visible line breaks from %s without extra blank lines", async (source, copied) => {
+ setLocale("en");
+ const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ try {
+ await act(async () => root.render(createElement(ChatMarkdown, { text: table(source) })));
+ const button = host.querySelector<HTMLButtonElement>('button[aria-label="Copy table"]');
+ expect(button).not.toBeNull();
+ await act(async () => button!.click());
+ expect(writeText).toHaveBeenCalledWith(`Result\r\n"${copied}"`);
+ } finally {
+ await act(async () => root.unmount());
+ host.remove();
+ }
+});
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index b7c042ac37..3db4b0dea8 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -105,14 +105,16 @@ const normalizationParseOptions: MarkdownParseOptions = {
mdastExtensions: [...(gfmParseData.fromMarkdownExtensions ?? []), windowsPathDestinations],
};
-/** A single line break in a reply is a line break, as chat apps show it, not a space. */
+/** A reply's newlines and a table cell's attribute-free <br> tags become Markdown breaks, without parsing raw HTML. */
function remarkSoftBreaks() {
return (tree: { children?: any[] }) => {
- const visit = (node: { children?: any[] }) => {
+ const visit = (node: { type?: string; children?: any[] }, inTableCell = false) => {
if (!node.children) return;
+ const tableCell = inTableCell || node.type === "tableCell";
node.children = node.children.flatMap((child) => {
+ if (tableCell && child?.type === "html" && /^<br\s*\/?>$/i.test(child.value)) return [{ type: "break" }];
if (child?.type !== "text" || !child.value.includes("\n")) {
- visit(child);
+ visit(child, tableCell);
return [child];
}
return (child.value as string).split("\n").flatMap((value, index) => [
diff --git a/src/components/MarkdownTable.tsx b/src/components/MarkdownTable.tsx
index 574c7cc323..9333c0f5ad 100644
--- a/src/components/MarkdownTable.tsx
+++ b/src/components/MarkdownTable.tsx
@@ -5,7 +5,11 @@ type Element = ReactElement<{ children?: ReactNode; align?: string; alt?: string
const elements = (children: ReactNode): Element[] => Children.toArray(children).filter(isValidElement) as Element[];
function plain(node: ReactNode): string {
if (typeof node === "string" || typeof node === "number") return String(node);
- if (Array.isArray(node)) return node.map(plain).join("");
+ if (Array.isArray(node)) return node.map((child, index) => {
+ const previous = node[index - 1];
+ // A Markdown break emits both <br> and a formatting newline; only the break belongs in copied cell text.
+ return typeof child === "string" && isValidElement(previous) && previous.type === "br" ? child.replace(/^\n/, "") : plain(child);
+ }).join("");
if (!isValidElement(node)) return "";
const element = node as Element;
if (element.type === "br") return "\n";