A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: copy table values to clipboard, for Excel/Sheets (#4995)
Myles Scolnick135446613a4e
diff --git a/frontend/src/components/data-table/download-actions.tsx b/frontend/src/components/data-table/download-actions.tsxindex 118fd03a95..9e708e0fdd 100644--- a/frontend/src/components/data-table/download-actions.tsx+++ b/frontend/src/components/data-table/download-actions.tsx@@ -5,6 +5,10 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuSeparator,DropdownMenuTrigger,} from "../ui/dropdown-menu";import { toast } from "../ui/use-toast";@@ -13,11 +17,17 @@ import {BracesIcon,BrickWallIcon,ChevronDownIcon,+ ClipboardListIcon,TableIcon,} from "lucide-react";+import { jsonToTSV } from "@/utils/json/json-parser";+import { copyToClipboard } from "@/utils/copy";+import { logNever } from "@/utils/assertNever";++type DownloadFormat = "csv" | "json" | "parquet";export interface DownloadActionProps {- downloadAs: (req: { format: "csv" | "json" | "parquet" }) => Promise<string>;+ downloadAs: (req: { format: DownloadFormat }) => Promise<string>;}const options = [@@ -38,6 +48,27 @@ const options = [},] as const;+const clipboardOptions = [+ {+ label: "TSV",+ format: "tsv",+ description: "Best for Excel and Google Sheets",+ icon: TableIcon,+ },+ {+ label: "JSON",+ format: "json",+ description: "Raw JSON data",+ icon: BracesIcon,+ },+ {+ label: "CSV",+ format: "csv",+ description: "Comma-separated values",+ icon: TableIcon,+ },+] as const;+export const DownloadAs: React.FC<DownloadActionProps> = (props) => {const button = (<Button data-testid="download-as-button" size="xs" variant="link">@@ -45,6 +76,51 @@ export const DownloadAs: React.FC<DownloadActionProps> = (props) => {</Button>);+ const getDownloadUrl = (format: DownloadFormat) => {+ return props.downloadAs({ format }).catch((error) => {+ toast({+ title: "Failed to download",+ description: "message" in error ? error.message : String(error),+ });+ throw error;+ });+ };++ const handleClipboardCopy = async (+ format: (typeof clipboardOptions)[number]["format"],+ ) => {+ let text: string;++ switch (format) {+ case "tsv": {+ const downloadUrl = await getDownloadUrl("json");+ const json = await fetchJson(downloadUrl);+ text = jsonToTSV(json);+ break;+ }+ case "json": {+ const downloadUrl = await getDownloadUrl("json");+ const json = await fetchJson(downloadUrl);+ text = JSON.stringify(json, null, 2);+ break;+ }+ case "csv": {+ const downloadUrl = await getDownloadUrl("csv");+ const csv = await fetchText(downloadUrl);+ text = csv;+ break;+ }+ default:+ logNever(format);+ return;+ }++ await copyToClipboard(text);+ toast({+ title: "Copied to clipboard",+ });+ };+return (<DropdownMenu modal={false}><DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>@@ -53,20 +129,7 @@ export const DownloadAs: React.FC<DownloadActionProps> = (props) => {<DropdownMenuItemkey={option.label}onSelect={async () => {- const downloadUrl = await props- .downloadAs({- format: option.format,- })- .catch((error) => {- toast({- title: "Failed to download",- description:- "message" in error ? error.message : String(error),- });- });- if (!downloadUrl) {- return;- }+ const downloadUrl = await getDownloadUrl(option.format);const ext = option.format;downloadByURL(downloadUrl, `download.${ext}`);}}@@ -75,7 +138,48 @@ export const DownloadAs: React.FC<DownloadActionProps> = (props) => {{option.label}</DropdownMenuItem>))}+ <DropdownMenuSeparator />+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <ClipboardListIcon className="mo-dropdown-icon" />+ Copy to clipboard+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ {clipboardOptions.map((option) => (+ <DropdownMenuItem+ key={option.label}+ onSelect={() => handleClipboardCopy(option.format)}+ >+ <option.icon className="mo-dropdown-icon" />+ <div className="flex flex-col">+ <span>{option.label}</span>+ <span className="text-xs text-muted-foreground">+ {option.description}+ </span>+ </div>+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub></DropdownMenuContent></DropdownMenu>);};++function fetchJson(url: string): Promise<Array<Record<string, unknown>>> {+ return fetch(url).then((res) => {+ if (!res.ok) {+ throw new Error(res.statusText);+ }+ return res.json();+ });+}++function fetchText(url: string): Promise<string> {+ return fetch(url).then((res) => {+ if (!res.ok) {+ throw new Error(res.statusText);+ }+ return res.text();+ });+}diff --git a/frontend/src/utils/__tests__/json-parser.test.ts b/frontend/src/utils/__tests__/json-parser.test.tsindex 1328252941..a3c681482f 100644--- a/frontend/src/utils/__tests__/json-parser.test.ts+++ b/frontend/src/utils/__tests__/json-parser.test.ts@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { expect, it } from "vitest";-import { jsonParseWithSpecialChar } from "../json/json-parser";+import { jsonParseWithSpecialChar, jsonToTSV } from "../json/json-parser";it("can jsonParseWithSpecialChar happy path", () => {expect(jsonParseWithSpecialChar('"hello"')).toEqual("hello");@@ -54,3 +54,26 @@ it("can fail to jsonParseWithSpecialChar", () => {expect(jsonParseWithSpecialChar(undefined!)).toMatchInlineSnapshot("{}");expect(jsonParseWithSpecialChar("[nan]")).toMatchInlineSnapshot("{}");});++it("can convert json to tsv", () => {+ expect(jsonToTSV([])).toEqual("");++ expect(jsonToTSV([{ a: 1, b: 2 }])).toEqual("a\tb\n1\t2");++ expect(+ jsonToTSV([+ { a: 1, b: 2 },+ { a: 3, b: 4 },+ ]),+ ).toEqual("a\tb\n1\t2\n3\t4");++ // Does not handle sparse arrays+ expect(jsonToTSV([{ a: 1 }, { a: 2, b: 3 }])).toMatchInlineSnapshot(+ '"a\n1\n2"',+ );++ // Handles special characters+ expect(+ jsonToTSV([{ a: "hello\tworld", b: "new\nline" }]),+ ).toMatchInlineSnapshot('"a\tb\nhello\tworld\tnew\nline"');+});diff --git a/frontend/src/utils/json/json-parser.ts b/frontend/src/utils/json/json-parser.tsindex c9e6b4083f..4ffef15ac7 100644--- a/frontend/src/utils/json/json-parser.ts+++ b/frontend/src/utils/json/json-parser.ts@@ -53,3 +53,13 @@ export function jsonParseWithSpecialChar<T = unknown>(return {} as T;}}++export function jsonToTSV(json: Array<Record<string, unknown>>) {+ if (json.length === 0) {+ return "";+ }++ const keys = Object.keys(json[0]);+ const values = json.map((row) => keys.map((key) => row[key]).join("\t"));+ return `${keys.join("\t")}\n${values.join("\n")}`;+}