Skip to content
Merged
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: 3 additions & 2 deletions apps/web/src/components/ChatMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ import { createMarkdownRenderer } from "./chat/markdownRenderer";
import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks";
import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock";
import { MarkdownTable } from "./chat/MarkdownTable";
import { markdownTableMinWidth } from "./chat/markdownTableLayout";
import { MarkdownDetails } from "./chat/MarkdownDetails";
import {
authoredImageSizeStyle,
Expand Down Expand Up @@ -1660,8 +1661,8 @@ const CHAT_MARKDOWN_COMPONENTS = {
}
return <ChatMarkdownImageFallback alt={altText} copyMarkdown={copyMarkdown} kind={kind} />;
},
table: function MarkdownTableRenderer({ node: _node, ...props }) {
return <MarkdownTable {...props} />;
table: function MarkdownTableRenderer({ node, ...props }) {
return <MarkdownTable {...props} minWidth={markdownTableMinWidth(node)} />;
},
details: function MarkdownDetailsRenderer({ node: _node, children, open: detailsOpen, dir }) {
return (
Expand Down
128 changes: 102 additions & 26 deletions apps/web/src/components/chat/MarkdownTable.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import { CheckIcon, CopyIcon } from "lucide-react";
import { useRef, type ComponentProps } from "react";
import { CheckIcon, CopyIcon, Maximize2Icon } from "lucide-react";
import { useRef, useState, type ComponentProps, type CSSProperties } from "react";

import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import {
serializeTableElementToCsv,
serializeTableElementToMarkdown,
} from "../../markdown-clipboard";
import { Button } from "../ui/button";
import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { ScrollArea } from "../ui/scroll-area";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { reportMarkdownActionFailure } from "./markdownActionFailure";
import type { markdownTableMinWidth } from "./markdownTableLayout";

export function MarkdownTable({ children, ...props }: ComponentProps<"table">) {
const containerRef = useRef<HTMLDivElement | null>(null);
type MarkdownTableProps = ComponentProps<"table"> & {
minWidth?: ReturnType<typeof markdownTableMinWidth>;
};

function TableCopyMenu({
getTable,
labeled = false,
}: {
getTable: () => HTMLTableElement | null | undefined;
/** A text button instead of an icon. Inside the expanded dialog a tooltip would take one Escape press of its own. */
labeled?: boolean;
}) {
const { copyToClipboard, isCopied: copied } = useCopyToClipboard<"markdown" | "csv">({
timeout: 1200,
onError: (cause, format) =>
Expand All @@ -22,7 +34,7 @@ export function MarkdownTable({ children, ...props }: ComponentProps<"table">) {
const copyLabel = copied ? "Copied" : "Copy table";

const handleCopy = (format: "markdown" | "csv") => {
const table = containerRef.current?.querySelector("table");
const table = getTable();
if (!table) return;
copyToClipboard(
format === "markdown"
Expand All @@ -32,39 +44,103 @@ export function MarkdownTable({ children, ...props }: ComponentProps<"table">) {
);
};

const icon = copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />;
return (
<Menu>
{labeled ? (
<MenuTrigger render={<Button type="button" variant="ghost-muted" size="xs" />}>
{icon}
{copied ? "Copied" : "Copy"}
</MenuTrigger>
) : (
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger
render={
<Button
type="button"
variant="ghost-muted"
size="icon-xs"
aria-label={copyLabel}
/>
}
/>
}
>
{icon}
</TooltipTrigger>
<TooltipPopup side="top">{copyLabel}</TooltipPopup>
</Tooltip>
)}
<MenuPopup align="end">
<MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
<MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
</MenuPopup>
</Menu>
);
}

export function MarkdownTable({ children, minWidth, style, ...props }: MarkdownTableProps) {
const containerRef = useRef<HTMLDivElement | null>(null);
const expandedRef = useRef<HTMLDivElement | null>(null);
const [expanded, setExpanded] = useState(false);
const tableStyle = minWidth
? ({
...style,
"--markdown-table-floor": `calc(${minWidth.ch}ch + ${minWidth.columns - 1} * 1.5rem)`,
} as CSSProperties)
: style;

return (
<div ref={containerRef} className="chat-markdown-table-container">
<ScrollArea radius="none" chainVerticalScroll scrollFade className="w-full max-w-full">
<table {...props}>{children}</table>
</ScrollArea>
<div className="chat-markdown-table-breakout">
<ScrollArea radius="none" chainVerticalScroll scrollFade className="w-full max-w-full">
<table {...props} style={tableStyle}>
{children}
</table>
</ScrollArea>
</div>
{/* Stays within the row's px-1: the chat lane clips sideways overflow. */}
<div className="mt-0.5 -mx-1 flex items-center justify-end select-none">
<Menu>
<div className="mt-0.5 -mx-1 flex items-center justify-end gap-0.5 select-none">
<span className="chat-markdown-table-expand flex">
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger
render={
<Button
type="button"
variant="ghost-muted"
size="icon-xs"
aria-label={copyLabel}
/>
}
<Button
type="button"
variant="ghost-muted"
size="icon-xs"
aria-label="Expand table"
onClick={() => setExpanded(true)}
/>
}
>
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
<Maximize2Icon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">{copyLabel}</TooltipPopup>
<TooltipPopup side="top">Expand table</TooltipPopup>
</Tooltip>
<MenuPopup align="end">
<MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
<MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
</MenuPopup>
</Menu>
</span>
<TableCopyMenu getTable={() => containerRef.current?.querySelector("table")} />
</div>
<Dialog open={expanded} onOpenChange={setExpanded}>
<DialogPopup className="h-full max-w-none sm:max-w-[min(96vw,120rem)]">
<div className="flex items-center gap-2 border-b py-2 ps-4 pe-12">
<DialogTitle>Table</DialogTitle>
<div className="ms-auto">
<TableCopyMenu labeled getTable={() => expandedRef.current?.querySelector("table")} />
</div>
</div>
<div
ref={expandedRef}
className="chat-markdown chat-markdown-table-expanded min-h-0 flex-1 overflow-auto pb-4"
>
<table {...props} style={tableStyle}>
{children}
</table>
</div>
</DialogPopup>
</Dialog>
</div>
);
}
2 changes: 1 addition & 1 deletion apps/web/src/components/chat/TimelineAssistantRows.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind
<>
<div className="relative min-w-0 px-1 py-0.5">
<MessageAuthorHeading>T3 Code</MessageAuthorHeading>
<div data-thread-find-text="true">
<div data-thread-find-text="true" data-chat-wide-content>
<AssistantCitationSource
messageId={row.message.id}
{...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}
Expand Down
58 changes: 58 additions & 0 deletions apps/web/src/components/chat/markdownTableLayout.logic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { Element, Root } from "hast";
import remarkGfm from "remark-gfm";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import { unified } from "unified";
import { describe, expect, it } from "vite-plus/test";

import { MARKDOWN_TABLE_COLUMN_FLOOR_CH, markdownTableMinWidth } from "./markdownTableLayout";

const processor = unified().use(remarkParse).use(remarkGfm).use(remarkRehype);

function tableFrom(markdown: string): Element {
const root = processor.runSync(processor.parse(markdown)) as Root;
const table = root.children.find(
(node): node is Element => node.type === "element" && node.tagName === "table",
);
if (!table) throw new Error("no table");
return table;
}

describe("markdownTableMinWidth", () => {
it("keeps short columns at their longest cell and caps long ones at the floor", () => {
const table = tableFrom(
[
"| # | Approach | Notes |",
"| - | --- | --- |",
"| 1 | Breakout | Grows past the reading column into the free pane width |",
"| 12 | Scroll | **Keeps** the column |",
].join("\n"),
);
expect(markdownTableMinWidth(table)).toEqual({
ch: 2 + "Breakout".length + MARKDOWN_TABLE_COLUMN_FLOOR_CH,
columns: 3,
});
const spaced = tableFrom(["| A |", "| - |", "| **a** **b** **c** **d** |"].join("\n"));
expect(markdownTableMinWidth(spaced)).toEqual({ ch: "a b c d".length, columns: 1 });
});

it("sums a floor per column, so many long columns outgrow a narrow lane", () => {
const cell = "a long explanation that would otherwise wrap into a tall block";
const row = `| ${Array.from({ length: 7 }, () => cell).join(" | ")} |`;
const table = tableFrom(
[
`| ${Array.from({ length: 7 }, (_, index) => `Column ${index}`).join(" | ")} |`,
`| ${Array.from({ length: 7 }, () => "---").join(" | ")} |`,
row,
].join("\n"),
);
expect(markdownTableMinWidth(table)).toEqual({
ch: 7 * MARKDOWN_TABLE_COLUMN_FLOOR_CH,
columns: 7,
});
});

it("returns null without a table", () => {
expect(markdownTableMinWidth(undefined)).toBeNull();
});
});
47 changes: 47 additions & 0 deletions apps/web/src/components/chat/markdownTableLayout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { Element, ElementContent } from "hast";

/** Widest a column's floor gets, in characters; longer cells wrap above it. */
export const MARKDOWN_TABLE_COLUMN_FLOOR_CH = 16;

function textContent(node: ElementContent): string {
if (node.type === "text") return node.value;
if (node.type !== "element") return "";
let text = "";
for (const child of node.children) text += textContent(child);
return text;
}

function* tableRows(node: Element): Generator<Element> {
for (const child of node.children) {
if (child.type !== "element") continue;
if (child.tagName === "tr") yield child;
else if (child.tagName === "thead" || child.tagName === "tbody" || child.tagName === "tfoot") {
yield* tableRows(child);
}
}
}

/**
* The narrowest a table can get before its cells turn into tall, hard-to-scan
* blocks: each column keeps room for its longest cell, up to the floor. Narrow
* columns such as numbers keep their natural width. Returns the summed floor in
* `ch` and the column count, or null when the table has no cells.
*/
export function markdownTableMinWidth(
table: Element | undefined,
): { readonly ch: number; readonly columns: number } | null {
if (!table) return null;
const longest: number[] = [];
for (const row of tableRows(table)) {
let column = 0;
for (const cell of row.children) {
if (cell.type !== "element" || (cell.tagName !== "th" && cell.tagName !== "td")) continue;
longest[column] = Math.max(longest[column] ?? 0, textContent(cell).trim().length);
column += 1;
}
}
if (longest.length === 0) return null;
let ch = 0;
for (const length of longest) ch += Math.min(length, MARKDOWN_TABLE_COLUMN_FLOOR_CH);
return { ch, columns: longest.length };
}
Loading
Loading