Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MarkdownTable.tsx

71 lines2.6 KB

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