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