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

MarkdownTable.tsx

145 lines5.5 KB

1import { Check, Copy, Maximize2, Minimize2 } from "lucide";
2import { useRef, useState, type ComponentProps } from "react";
3​
4import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
5import { getClientSettings } from "../../hooks/useSettings";
6import { observeResize } from "../../lib/observeResize";
7import {
8 serializeTableElementToCsv,
9 serializeTableElementToMarkdown,
10} from "../../markdown-clipboard";
11import { MorphIcon } from "../MorphIcon";
12import { Button } from "../ui/button";
13import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
14import { ScrollArea } from "../ui/scroll-area";
15import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
16import { reportMarkdownActionFailure } from "./markdownActionFailure";
17​
18/**
19 * Whether any cell is clipped in the unwrapped layout. Only then does the wrap
20 * toggle change anything, so short tables hide it. Measures with the container
21 * briefly unwrapped and restores it before the browser paints.
22 */
23function tableHasClippedCells(container: HTMLElement, table: HTMLTableElement): boolean {
24 const viewport = table.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
25 const scrollLeft = viewport?.scrollLeft ?? 0;
26 const previous = container.dataset.expanded;
27 container.dataset.expanded = "false";
28 try {
29 for (const row of table.rows) {
30 for (const cell of row.cells) {
31 if (cell.scrollWidth > cell.clientWidth) return true;
32 }
33 }
34 return false;
35 } finally {
36 if (previous === undefined) delete container.dataset.expanded;
37 else container.dataset.expanded = previous;
38 // The unwrapped layout can be narrower and clamp a sideways scroll.
39 if (viewport && scrollLeft > 0) viewport.scrollLeft = scrollLeft;
40 }
42​
43export function MarkdownTable({ children, ...props }: ComponentProps<"table">) {
44 const containerRef = useRef<HTMLDivElement | null>(null);
45 const [expanded, setExpanded] = useState(() => getClientSettings().wordWrap);
46 const [hasClippedCells, setHasClippedCells] = useState(false);
47 const { copyToClipboard, isCopied: copied } = useCopyToClipboard<"markdown" | "csv">({
48 timeout: 1200,
49 onError: (cause, format) =>
50 reportMarkdownActionFailure({ operation: "copy-table", format }, cause),
51 });
52 const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
53 const copyLabel = copied ? "Copied" : "Copy table";
54​
55 // React calls this with null when a previous attach returned no cleanup.
56 const attachContainer = (container: HTMLDivElement | null) => {
57 containerRef.current = container;
58 const table = container?.querySelector("table");
59 if (!container || !table) return;
60 const measure = () => setHasClippedCells(tableHasClippedCells(container, table));
61 measure();
62 // A streamed cell can grow until it clips while the table keeps its size, and a
63 // narrower column can clip a cell without this component rendering.
64 const mutations = new MutationObserver(measure);
65 mutations.observe(table, { childList: true, characterData: true, subtree: true });
66 const stopResize = observeResize(table, measure);
67 return () => {
68 mutations.disconnect();
69 stopResize();
70 containerRef.current = null;
71 };
72 };
73​
74 const handleCopy = (format: "markdown" | "csv") => {
75 const table = containerRef.current?.querySelector("table");
76 if (!table) return;
77 copyToClipboard(
78 format === "markdown"
79 ? serializeTableElementToMarkdown(table)
80 : serializeTableElementToCsv(table),
81 format,
82 );
83 };
84​
85 return (
86 <div
87 ref={attachContainer}
88 className="chat-markdown-table-container"
89 data-expanded={expanded ? "true" : "false"}
90 >
91 <ScrollArea radius="none" chainVerticalScroll scrollFade className="w-full max-w-full">
92 <table {...props}>{children}</table>
93 </ScrollArea>
94 {/* Stays within the row's px-1: the chat lane clips sideways overflow. */}
95 <div className="mt-0.5 -mx-1 flex items-center justify-between select-none">
96 {hasClippedCells ? (
97 <Tooltip>
98 <TooltipTrigger
99 render={
100 <Button
101 type="button"
102 variant={expanded ? "secondary" : "ghost-muted"}
103 size="icon-xs"
104 aria-pressed={expanded}
105 onClick={() => setExpanded((value) => !value)}
106 aria-label={expandLabel}
107 />
108 }
109 >
110 <MorphIcon className="size-3" icon={expanded ? Minimize2 : Maximize2} />
111 </TooltipTrigger>
112 <TooltipPopup side="top">{expandLabel}</TooltipPopup>
113 </Tooltip>
114 ) : (
115 <span />
116 )}
117 <Menu>
118 <Tooltip>
119 <TooltipTrigger
120 render={
121 <MenuTrigger
122 render={
123 <Button
124 type="button"
125 variant="ghost-muted"
126 size="icon-xs"
127 aria-label={copyLabel}
128 />
129 }
130 />
131 }
132 >
133 <MorphIcon className="size-3" icon={copied ? Check : Copy} />
134 </TooltipTrigger>
135 <TooltipPopup side="top">{copyLabel}</TooltipPopup>
136 </Tooltip>
137 <MenuPopup align="end">
138 <MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
139 <MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
140 </MenuPopup>
141 </Menu>
142 </div>
143 </div>
144 );