({
children,
className,
onCopy,
onError,
timeout = 2000,
}: TableCopyDropdownProps)
| 19 | } |
| 20 | |
| 21 | export const TableCopyDropdown = ({ |
| 22 | children, |
| 23 | className, |
| 24 | onCopy, |
| 25 | onError, |
| 26 | timeout = 2000, |
| 27 | }: TableCopyDropdownProps) => { |
| 28 | const cn = useCn(); |
| 29 | const [isOpen, setIsOpen] = useState(false); |
| 30 | const [isCopied, setIsCopied] = useState(false); |
| 31 | const dropdownRef = useRef<HTMLDivElement>(null); |
| 32 | const timeoutRef = useRef(0); |
| 33 | const { isAnimating } = useContext(StreamdownContext); |
| 34 | const t = useTranslations(); |
| 35 | |
| 36 | const copyTableData = async (format: "csv" | "tsv" | "md") => { |
| 37 | if (typeof window === "undefined" || !navigator?.clipboard?.write) { |
| 38 | onError?.(new Error("Clipboard API not available")); |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | try { |
| 43 | const tableWrapper = dropdownRef.current?.closest( |
| 44 | '[data-streamdown="table-wrapper"]' |
| 45 | ); |
| 46 | const tableElement = tableWrapper?.querySelector( |
| 47 | "table" |
| 48 | ) as HTMLTableElement; |
| 49 | |
| 50 | if (!tableElement) { |
| 51 | onError?.(new Error("Table not found")); |
| 52 | return; |
| 53 | } |
| 54 | |
| 55 | const tableData = extractTableDataFromElement(tableElement); |
| 56 | |
| 57 | const formatters = { |
| 58 | csv: tableDataToCSV, |
| 59 | tsv: tableDataToTSV, |
| 60 | md: tableDataToMarkdown, |
| 61 | }; |
| 62 | const formatter = formatters[format] || tableDataToMarkdown; |
| 63 | const content = formatter(tableData); |
| 64 | |
| 65 | const clipboardItemData = new ClipboardItem({ |
| 66 | "text/plain": new Blob([content], { type: "text/plain" }), |
| 67 | "text/html": new Blob([tableElement.outerHTML], { |
| 68 | type: "text/html", |
| 69 | }), |
| 70 | }); |
| 71 | |
| 72 | await navigator.clipboard.write([clipboardItemData]); |
| 73 | setIsCopied(true); |
| 74 | setIsOpen(false); |
| 75 | onCopy?.(format); |
| 76 | timeoutRef.current = window.setTimeout(() => setIsCopied(false), timeout); |
| 77 | } catch (error) { |
| 78 | onError?.(error as Error); |
nothing calls this directly
no test coverage detected