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
fix: customize copy button on json viewer to avoid content shift (#3068)
Myles Scolnickb0dea053e733
diff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsxindex 1a4a4c9b1c..1afd830529 100644--- a/frontend/src/components/editor/output/JsonOutput.tsx+++ b/frontend/src/components/editor/output/JsonOutput.tsx@@ -1,11 +1,14 @@/* Copyright 2024 Marimo. All rights reserved. */import { memo, useState } from "react";import {+ type DataItemProps,type DataType,JsonViewer,booleanType,defineDataType,+ intType,nullType,+ objectType,stringType,} from "@textea/json-viewer";@@ -17,6 +20,8 @@ import { logNever } from "../../../utils/assertNever";import { useTheme } from "../../../theme/useTheme";import { isUrl } from "@/utils/urls";import { copyToClipboard } from "@/utils/copy";+import { CheckIcon, CopyIcon } from "lucide-react";+import { cn } from "@/utils/cn";interface Props {/**@@ -34,6 +39,42 @@ interface Props {className?: string;}+// eslint-disable-next-line @typescript-eslint/no-explicit-any+const CopyButton: React.FC<DataItemProps<any>> = ({ value }) => {+ const skipCopy =+ typeof value === "string" &&+ (value.startsWith("text/html:") ||+ value.startsWith("image/") ||+ value.startsWith("video/"));+ const [copied, setCopied] = useState(false);++ const handleCopy = async (evt: React.MouseEvent) => {+ evt.stopPropagation();+ await copyToClipboard(getCopyValue(value));+ setCopied(true);+ setTimeout(() => setCopied(false), 1000);+ };++ if (skipCopy) {+ return null;+ }+ return (+ <button+ onClick={handleCopy}+ className={cn(+ "inline-flex ml-2 copy-button rounded w-6 h-3 justify-center items-center relative",+ )}+ aria-label="Copy to clipboard"+ >+ {copied ? (+ <CheckIcon className="w-5 h-5 absolute -top-0.5 p-1 hover:bg-muted rounded" />+ ) : (+ <CopyIcon className="w-5 h-5 absolute -top-0.5 p-1 hover:bg-muted rounded" />+ )}+ </button>+ );+};+/*** Output component for JSON data.*/@@ -60,13 +101,12 @@ export const JsonOutput: React.FC<Props> = memo(valueTypes={VALUE_TYPE}// disable array grouping (it's misleading) by using a large valuegroupArraysAfterLength={1_000_000}- onCopy={async (_path, value) => {- await copyToClipboard(getCopyValue(value));- return value;- }}- enableClipboard={true}+ // Built-in clipboard shifts content on hover+ // so we provide our own copy button+ enableClipboard={false}/>);+case "raw":return <pre className={className}>{JSON.stringify(data, null, 2)}</pre>;default:@@ -88,13 +128,13 @@ const CollapsibleTextOutput = (props: { text: string }) => {// Doesn't need to be collapsedif (props.text.length <= COLLAPSED_TEXT_LENGTH) {- return <span>{props.text}</span>;+ return <span className="break-all">{props.text}</span>;}if (isCollapsed) {return (<span- className="cursor-pointer hover:opacity-90"+ className="cursor-pointer hover:opacity-90 break-all"onClick={() => setIsCollapsed(false)}>{props.text.slice(0, COLLAPSED_TEXT_LENGTH)}@@ -105,7 +145,7 @@ const CollapsibleTextOutput = (props: { text: string }) => {return (<span- className="cursor-pointer hover:opacity-90"+ className="cursor-pointer hover:opacity-90 break-all"onClick={() => setIsCollapsed(true)}>{props.text}@@ -132,23 +172,27 @@ const LEAF_RENDERERS = {const MIME_TYPES: Array<DataType<any>> = Object.entries(LEAF_RENDERERS).map(([leafType, render]) => ({is: (value) => typeof value === "string" && value.startsWith(leafType),+ PostComponent: CopyButton,Component: (props) => renderLeaf(props.value, render),}),);const PYTHON_BOOLEAN_TYPE = defineDataType<boolean>({...booleanType,+ PostComponent: CopyButton,Component: ({ value }) => <span>{value ? "True" : "False"}</span>,});const PYTHON_NONE_TYPE = defineDataType<null>({...nullType,+ PostComponent: CopyButton,Component: () => <span>None</span>,});const URL_TYPE = defineDataType<string>({...stringType,is: (value) => isUrl(value),+ PostComponent: CopyButton,Component: ({ value }) => (<ahref={value}@@ -161,12 +205,36 @@ const URL_TYPE = defineDataType<string>({),});+const INTEGER_TYPE = defineDataType<number>({+ ...intType,+ PostComponent: CopyButton,+});++const FALLBACK_RENDERER = defineDataType<string>({+ ...stringType,+ PostComponent: CopyButton,+});++const OBJECT_TYPE = defineDataType<object>({+ ...objectType,+ PreComponent: (props) => (+ <>+ {objectType.PreComponent && <objectType.PreComponent {...props} />}+ <CopyButton {...props} />+ </>+ ),+});+const VALUE_TYPE = [- ...MIME_TYPES,+ INTEGER_TYPE,PYTHON_BOOLEAN_TYPE,PYTHON_NONE_TYPE,+ ...MIME_TYPES,URL_TYPE,-];+ OBJECT_TYPE,+ FALLBACK_RENDERER,+].reverse();+// Last one wins, so we reverse the array.function leafData(leaf: string): string {const delimIndex = leaf.indexOf(":");@@ -244,7 +312,7 @@ function pythonJsonReplacer(key: string, value: unknown): unknown {export function getCopyValue(value: unknown): string {// Because this results in valid json, it adds quotes around None and True/False.// but we want to make this look like Python, so we remove the quotes.- return JSON.stringify(value, pythonJsonReplacer)+ return JSON.stringify(value, pythonJsonReplacer, 2).replaceAll(`"${REPLACE_PREFIX}`, "").replaceAll(`${REPLACE_SUFFIX}"`, "");}diff --git a/frontend/src/components/editor/output/Outputs.css b/frontend/src/components/editor/output/Outputs.cssindex b34420e556..3512c1908f 100644--- a/frontend/src/components/editor/output/Outputs.css+++ b/frontend/src/components/editor/output/Outputs.css@@ -68,6 +68,18 @@margin-top: 0.2rem;margin-bottom: 0.2rem;}++ .copy-button {+ @apply invisible;+ }++ .data-key-pair:hover > .copy-button {+ @apply visible;+ }++ .data-key-pair:hover > .data-key > .copy-button {+ @apply visible;+ }}.traceback-cell-link {diff --git a/frontend/src/components/editor/output/__tests__/json-output.test.ts b/frontend/src/components/editor/output/__tests__/json-output.test.tsindex 902a0f01af..e98b4cef7b 100644--- a/frontend/src/components/editor/output/__tests__/json-output.test.ts+++ b/frontend/src/components/editor/output/__tests__/json-output.test.ts@@ -28,7 +28,13 @@ describe("getCopyValue", () => {it("should handle arrays", () => {const value = ["text/plain:Hello", true, null];const result = getCopyValue(value);- expect(result).toMatchInlineSnapshot(`"["Hello",True,None]"`);+ expect(result).toMatchInlineSnapshot(`+ "[+ "Hello",+ True,+ None+ ]"+ `);});it("should handle objects", () => {@@ -39,7 +45,13 @@ describe("getCopyValue", () => {};const result = getCopyValue(value);expect(result).toMatchInlineSnapshot(- `"{"key1":"Hello","key2":False,"key3":None}"`,+ `+ "{+ "key1": "Hello",+ "key2": False,+ "key3": None+ }"+ `,);});@@ -52,7 +64,14 @@ describe("getCopyValue", () => {};const result = getCopyValue(value);expect(result).toMatchInlineSnapshot(- `"{"true":"true","None":"none","null":"null","sentence":"something true none null something"}"`,+ `+ "{+ "true": "true",+ "None": "none",+ "null": "null",+ "sentence": "something true none null something"+ }"+ `,);});@@ -66,14 +85,31 @@ describe("getCopyValue", () => {};const result = getCopyValue(value);expect(result).toMatchInlineSnapshot(- `"{"key1":{"nestedKey1":"Nested Hello","nestedKey2":True},"key2":False}"`,+ `+ "{+ "key1": {+ "nestedKey1": "Nested Hello",+ "nestedKey2": True+ },+ "key2": False+ }"+ `,);});it("should handle nested arrays", () => {const value = ["text/plain:Hello", [true, null, "text/plain:World"]];const result = getCopyValue(value);- expect(result).toMatchInlineSnapshot(`"["Hello",[True,None,"World"]]"`);+ expect(result).toMatchInlineSnapshot(`+ "[+ "Hello",+ [+ True,+ None,+ "World"+ ]+ ]"+ `);});it("should handle empty objects", () => {@@ -103,7 +139,14 @@ describe("getCopyValue", () => {it("should handle mixed types in arrays", () => {const value = [42, "text/plain:Hello", true, null];const result = getCopyValue(value);- expect(result).toMatchInlineSnapshot(`"[42,"Hello",True,None]"`);+ expect(result).toMatchInlineSnapshot(`+ "[+ 42,+ "Hello",+ True,+ None+ ]"+ `);});it("should handle mixed types in objects", () => {@@ -116,7 +159,15 @@ describe("getCopyValue", () => {};const result = getCopyValue(value);expect(result).toMatchInlineSnapshot(- `"{"key1":42,"key2":"Hello","key3":True,"key4":None,"key5":1.23}"`,+ `+ "{+ "key1": 42,+ "key2": "Hello",+ "key3": True,+ "key4": None,+ "key5": 1.23+ }"+ `,);});@@ -134,7 +185,13 @@ describe("getCopyValue", () => {};const result = getCopyValue(value);expect(result).toMatchInlineSnapshot(- `"{"key1":42,"key2":{1,2,3},"key3":True}"`,+ `+ "{+ "key1": 42,+ "key2": {1,2,3},+ "key3": True+ }"+ `,);});@@ -152,7 +209,13 @@ describe("getCopyValue", () => {};const result = getCopyValue(value);expect(result).toMatchInlineSnapshot(- `"{"key1":42,"key2":(1,2,3),"key3":True}"`,+ `+ "{+ "key1": 42,+ "key2": (1,2,3),+ "key3": True+ }"+ `,);});});diff --git a/marimo/_smoke_tests/structures.py b/marimo/_smoke_tests/structures.pyindex 54e0d79c95..02e9528a2f 100644--- a/marimo/_smoke_tests/structures.py+++ b/marimo/_smoke_tests/structures.py@@ -1,28 +1,37 @@import marimo-__generated_with = "0.9.30"+__generated_with = "0.9.31"app = marimo.App(width="medium")@app.cell-def __(mo):+def __(mo, x):+ import datetime+[{"a": 1,"b": 2.0,"c": "foo","d": True,- "e": False,+ "d.1": False,"e": mo.ui.slider(0, 10),"f": "bar" * 1000,"url": "https://www.google.com",- "g": [1, 2, 3],- "h": (1, 2, 3),- "i": {1, 2, 3},+ "g": [1, 2],+ "h": (1, 2),+ "i": {1, 2},"j": {"a": 1, "b": 2},+ "none": None,+ "nan": float("nan"),+ "inf": float("inf"),+ "x": x,+ "datetime": datetime.datetime.now(),+ "date": datetime.date.today(),+ "time": datetime.time(1, 2, 3),}]- return+ return (datetime,)@app.cell