Open History to see the last commit
1import { Check, Copy, Maximize2, Minimize2 } from "lucide";
2import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps } from "react";
3
4import { getClientSettings } from "../../hooks/useSettings";
5import { observeResize } from "../../lib/observeResize";
6import {
7 serializeTableElementToCsv,
8 serializeTableElementToMarkdown,
9} from "../../markdown-clipboard";
10import { MorphIcon } from "../MorphIcon";
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 } from "./markdownActionFailure";
16
17/**
18 * Whether any cell is clipped in the unwrapped layout. Only then does the wrap
19 * toggle change anything, so short tables hide it. Measures with the container
20 * briefly unwrapped and restores it before the browser paints.
21 */
22function tableHasClippedCells(container: HTMLElement, table: HTMLTableElement): boolean {
23 const viewport = table.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
24 const scrollLeft = viewport?.scrollLeft ?? 0;
25 const previous = container.dataset.expanded;
26 container.dataset.expanded = "false";
27 try {
28 for (const row of table.rows) {
29 for (const cell of row.cells) {
30 if (cell.scrollWidth > cell.clientWidth) return true;
31 }
32 }
33 return false;
34 } finally {
35 if (previous === undefined) delete container.dataset.expanded;
36 else container.dataset.expanded = previous;
37 // The unwrapped layout can be narrower and clamp a sideways scroll.
38 if (viewport && scrollLeft > 0) viewport.scrollLeft = scrollLeft;
39 }
40}
41
42export function MarkdownTable({ children, ...props }: ComponentProps<"table">) {
43 const containerRef = useRef<HTMLDivElement | null>(null);
44 const tableRef = useRef<HTMLTableElement | null>(null);
45 const [expanded, setExpanded] = useState(() => getClientSettings().wordWrap);
46 const [hasClippedCells, setHasClippedCells] = useState(false);
47 const [copied, setCopied] = useState(false);
48 const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
49 const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
50 const copyLabel = copied ? "Copied" : "Copy table";
51
52 const measureClippedCells = () => {
53 const container = containerRef.current;
54 const table = tableRef.current;
55 if (!container || !table) return;
56 setHasClippedCells(tableHasClippedCells(container, table));
57 };
58
59 // A streamed cell can grow until it clips while the table keeps its size,
60 // so remeasure after every render, not only on resize.
61 useLayoutEffect(measureClippedCells);
62
63 // Column width changes can clip a cell without rendering this table.
64 useLayoutEffect(() => {
65 const table = tableRef.current;
66 if (!table) return;
67 return observeResize(table, measureClippedCells);
68 }, [measureClippedCells]);
69
70 const handleCopy = (format: "markdown" | "csv") => {
71 const table = containerRef.current?.querySelector("table");
72 if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {
73 return;
74 }
75 const text =
76 format === "markdown"
77 ? serializeTableElementToMarkdown(table)
78 : serializeTableElementToCsv(table);
79 void navigator.clipboard
80 .writeText(text)
81 .then(() => {
82 if (copiedTimerRef.current != null) {
83 clearTimeout(copiedTimerRef.current);
84 }
85 setCopied(true);
86 copiedTimerRef.current = setTimeout(() => {
87 setCopied(false);
88 copiedTimerRef.current = null;
89 }, 1200);
90 })
91 .catch((cause) => {
92 reportMarkdownActionFailure({ operation: "copy-table", format }, cause);
93 });
94 };
95
96 useEffect(
97 () => () => {
98 if (copiedTimerRef.current != null) {
99 clearTimeout(copiedTimerRef.current);
100 copiedTimerRef.current = null;
101 }
102 },
103 [],
104 );
105
106 return (
107 <div
108 ref={containerRef}
109 className="chat-markdown-table-container"
110 data-expanded={expanded ? "true" : "false"}
111 >
112 <ScrollArea radius="none" chainVerticalScroll scrollFade className="w-full max-w-full">
113 <table ref={tableRef} {...props}>
114 {children}
115 </table>
116 </ScrollArea>
117 <div className="mt-0.5 flex items-center justify-between select-none">
118 {hasClippedCells ? (
119 <Tooltip>
120 <TooltipTrigger
121 render={
122 <Button
123 type="button"
124 variant={expanded ? "secondary" : "ghost-muted"}
125 size="icon-xs"
126 aria-pressed={expanded}
127 onClick={() => setExpanded((value) => !value)}
128 aria-label={expandLabel}
129 />
130 }
131 >
132 <MorphIcon className="size-3" icon={expanded ? Minimize2 : Maximize2} />
133 </TooltipTrigger>
134 <TooltipPopup side="top">{expandLabel}</TooltipPopup>
135 </Tooltip>
136 ) : (
137 <span />
138 )}
139 <Menu>
140 <Tooltip>
141 <TooltipTrigger
142 render={
143 <MenuTrigger
144 render={
145 <Button
146 type="button"
147 variant="ghost-muted"
148 size="icon-xs"
149 aria-label={copyLabel}
150 />
151 }
152 />
153 }
154 >
155 <MorphIcon className="size-3" icon={copied ? Check : Copy} />
156 </TooltipTrigger>
157 <TooltipPopup side="top">{copyLabel}</TooltipPopup>
158 </Tooltip>
159 <MenuPopup align="end">
160 <MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
161 <MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
162 </MenuPopup>
163 </Menu>
164 </div>
165 </div>
166 );
167}