Open History to see the last commit
1import { CheckIcon, CopyIcon } from "lucide-react";
2import { useRef, type ComponentProps } from "react";
3
4import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
5import {
6 serializeTableElementToCsv,
7 serializeTableElementToMarkdown,
8} from "../../markdown-clipboard";
9import { Button } from "../ui/button";
10import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
11import { ScrollArea } from "../ui/scroll-area";
12import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
13import { reportMarkdownActionFailure } from "./markdownActionFailure";
14
15export function MarkdownTable({ children, ...props }: ComponentProps<"table">) {
16 const containerRef = useRef<HTMLDivElement | null>(null);
17 const { copyToClipboard, isCopied: copied } = useCopyToClipboard<"markdown" | "csv">({
18 timeout: 1200,
19 onError: (cause, format) =>
20 reportMarkdownActionFailure({ operation: "copy-table", format }, cause),
21 });
22 const copyLabel = copied ? "Copied" : "Copy table";
23
24 const handleCopy = (format: "markdown" | "csv") => {
25 const table = containerRef.current?.querySelector("table");
26 if (!table) return;
27 copyToClipboard(
28 format === "markdown"
29 ? serializeTableElementToMarkdown(table)
30 : serializeTableElementToCsv(table),
31 format,
32 );
33 };
34
35 return (
36 <div ref={containerRef} className="chat-markdown-table-container">
37 <ScrollArea radius="none" chainVerticalScroll scrollFade className="w-full max-w-full">
38 <table {...props}>{children}</table>
39 </ScrollArea>
40 {/* Stays within the row's px-1: the chat lane clips sideways overflow. */}
41 <div className="mt-0.5 -mx-1 flex items-center justify-end select-none">
42 <Menu>
43 <Tooltip>
44 <TooltipTrigger
45 render={
46 <MenuTrigger
47 render={
48 <Button
49 type="button"
50 variant="ghost-muted"
51 size="icon-xs"
52 aria-label={copyLabel}
53 />
54 }
55 />
56 }
57 >
58 {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
59 </TooltipTrigger>
60 <TooltipPopup side="top">{copyLabel}</TooltipPopup>
61 </Tooltip>
62 <MenuPopup align="end">
63 <MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
64 <MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
65 </MenuPopup>
66 </Menu>
67 </div>
68 </div>
69 );
70}