Skip to content

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.

improvement: add copy/paste to json viewer, support urls (#3050)

Myles Scolnick59a99b88dad1
diff --git a/frontend/src/components/data-table/url-detector.tsx b/frontend/src/components/data-table/url-detector.tsx
index 6c8c8e7948..187d9cb1a6 100644
--- a/frontend/src/components/data-table/url-detector.tsx
+++ b/frontend/src/components/data-table/url-detector.tsx
@@ -1,9 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { Events } from "@/utils/events";
+const urlRegex = /(https?:\/\/\S+)/g;
export const UrlDetector = ({ text }: { text: string }) => {
- const urlRegex = /(https?:\/\/\S+)/g;
-
const createMarkup = (text: string) => {
const parts = text.split(urlRegex);
diff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsx
index 2e6bc3924f..1a4a4c9b1c 100644
--- a/frontend/src/components/editor/output/JsonOutput.tsx
+++ b/frontend/src/components/editor/output/JsonOutput.tsx
@@ -6,6 +6,7 @@ import {
booleanType,
defineDataType,
nullType,
+ stringType,
} from "@textea/json-viewer";
import { HtmlOutput } from "./HtmlOutput";
@@ -14,6 +15,8 @@ import { TextOutput } from "./TextOutput";
import { VideoOutput } from "./VideoOutput";
import { logNever } from "../../../utils/assertNever";
import { useTheme } from "../../../theme/useTheme";
+import { isUrl } from "@/utils/urls";
+import { copyToClipboard } from "@/utils/copy";
interface Props {
/**
@@ -53,13 +56,15 @@ export const JsonOutput: React.FC<Props> = memo(
style={{
backgroundColor: "transparent",
}}
+ collapseStringsAfterLength={COLLAPSED_TEXT_LENGTH}
valueTypes={VALUE_TYPE}
// disable array grouping (it's misleading) by using a large value
groupArraysAfterLength={1_000_000}
- // TODO(akshayka): disable clipboard until we have a better
- // solution: copies raw values, shifts content; can use onCopy prop
- // to override what is copied to clipboard
- enableClipboard={false}
+ onCopy={async (_path, value) => {
+ await copyToClipboard(getCopyValue(value));
+ return value;
+ }}
+ enableClipboard={true}
/>
);
case "raw":
@@ -76,19 +81,34 @@ function inferBestFormat(data: unknown): "tree" | "raw" {
return typeof data === "object" && data !== null ? "tree" : "raw";
}
-// Text with length > 500 is collapsed by default, and can be expanded by clicking on it.
+const COLLAPSED_TEXT_LENGTH = 100;
+// Text with length > COLLAPSED_TEXT_LENGTH is collapsed by default, and can be expanded by clicking on it.
const CollapsibleTextOutput = (props: { text: string }) => {
const [isCollapsed, setIsCollapsed] = useState(true);
+
+ // Doesn't need to be collapsed
+ if (props.text.length <= COLLAPSED_TEXT_LENGTH) {
+ return <span>{props.text}</span>;
+ }
+
+ if (isCollapsed) {
+ return (
+ <span
+ className="cursor-pointer hover:opacity-90"
+ onClick={() => setIsCollapsed(false)}
+ >
+ {props.text.slice(0, COLLAPSED_TEXT_LENGTH)}
+ {props.text.length > COLLAPSED_TEXT_LENGTH && "..."}
+ </span>
+ );
+ }
+
return (
- <span className="cursor-pointer">
- {isCollapsed ? (
- <span onClick={() => setIsCollapsed(false)}>
- {props.text.slice(0, 500)}
- {props.text.length > 500 && "..."}
- </span>
- ) : (
- <span onClick={() => setIsCollapsed(true)}>{props.text}</span>
- )}
+ <span
+ className="cursor-pointer hover:opacity-90"
+ onClick={() => setIsCollapsed(true)}
+ >
+ {props.text}
</span>
);
};
@@ -101,9 +121,11 @@ const CollapsibleTextOutput = (props: { text: string }) => {
const LEAF_RENDERERS = {
"image/": (value: string) => <ImageOutput src={value} />,
"video/": (value: string) => <VideoOutput src={value} />,
- "text/html": (value: string) => <HtmlOutput html={value} inline={true} />,
+ "text/html:": (value: string) => <HtmlOutput html={value} inline={true} />,
"text/plain+float:": (value: string) => <span>{value}</span>,
- "text/plain": (value: string) => <CollapsibleTextOutput text={value} />,
+ "text/plain+set:": (value: string) => <span>set{value}</span>,
+ "text/plain+tuple:": (value: string) => <span>{value}</span>,
+ "text/plain:": (value: string) => <CollapsibleTextOutput text={value} />,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -124,7 +146,27 @@ const PYTHON_NONE_TYPE = defineDataType<null>({
Component: () => <span>None</span>,
});
-const VALUE_TYPE = [...MIME_TYPES, PYTHON_BOOLEAN_TYPE, PYTHON_NONE_TYPE];
+const URL_TYPE = defineDataType<string>({
+ ...stringType,
+ is: (value) => isUrl(value),
+ Component: ({ value }) => (
+ <a
+ href={value}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-link hover:underline"
+ >
+ {value}
+ </a>
+ ),
+});
+
+const VALUE_TYPE = [
+ ...MIME_TYPES,
+ PYTHON_BOOLEAN_TYPE,
+ PYTHON_NONE_TYPE,
+ URL_TYPE,
+];
function leafData(leaf: string): string {
const delimIndex = leaf.indexOf(":");
@@ -153,3 +195,56 @@ function renderLeaf(
return <TextOutput text={`Invalid leaf: ${leaf}`} />;
}
}
+
+const MIME_PREFIXES = Object.keys(LEAF_RENDERERS);
+const REPLACE_PREFIX = "<marimo-replace>";
+const REPLACE_SUFFIX = "</marimo-replace>";
+/**
+ * Get the string representation (as Python) of a value.
+ * - recursively handles lists and dictionaries
+ * - trims mimetype prefix
+ * - maps booleans to True and False
+ * - maps null/undefined to None
+ */
+function pythonJsonReplacer(key: string, value: unknown): unknown {
+ if (value == null) {
+ return `${REPLACE_PREFIX}None${REPLACE_SUFFIX}`;
+ }
+ if (typeof value === "object") {
+ return value;
+ }
+ if (Array.isArray(value)) {
+ return value;
+ }
+ if (typeof value === "string") {
+ // If float, we want to keep the quotes around the number.
+ if (value.startsWith("text/plain+float:")) {
+ return `${REPLACE_PREFIX}${leafData(value)}${REPLACE_SUFFIX}`;
+ }
+ if (value.startsWith("text/plain+tuple:")) {
+ // replace first and last characters [] with ()
+ return `${REPLACE_PREFIX}(${leafData(value).slice(1, -1)})${REPLACE_SUFFIX}`;
+ }
+ if (value.startsWith("text/plain+set:")) {
+ // replace first and last characters [] with {}
+ return `${REPLACE_PREFIX}{${leafData(value).slice(1, -1)}}${REPLACE_SUFFIX}`;
+ }
+
+ if (MIME_PREFIXES.some((prefix) => value.startsWith(prefix))) {
+ return leafData(value);
+ }
+ return value;
+ }
+ if (typeof value === "boolean") {
+ return `${REPLACE_PREFIX}${value ? "True" : "False"}${REPLACE_SUFFIX}`;
+ }
+ return value;
+}
+
+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)
+ .replaceAll(`"${REPLACE_PREFIX}`, "")
+ .replaceAll(`${REPLACE_SUFFIX}"`, "");
+}
diff --git a/frontend/src/components/editor/output/Outputs.css b/frontend/src/components/editor/output/Outputs.css
index 17996564a6..b34420e556 100644
--- a/frontend/src/components/editor/output/Outputs.css
+++ b/frontend/src/components/editor/output/Outputs.css
@@ -63,11 +63,11 @@
* margin collapse. */
overflow: auto;
@apply text-xs;
-}
-.marimo-json-output .data-key-pair:not(:last-child) {
- margin-top: 0.2rem;
- margin-bottom: 0.2rem;
+ .data-key-pair:not(:last-child) {
+ margin-top: 0.2rem;
+ margin-bottom: 0.2rem;
+ }
}
.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.ts
new file mode 100644
index 0000000000..902a0f01af
--- /dev/null
+++ b/frontend/src/components/editor/output/__tests__/json-output.test.ts
@@ -0,0 +1,158 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { getCopyValue } from "../JsonOutput";
+
+describe("getCopyValue", () => {
+ it("should handle strings without MIME prefixes", () => {
+ const value = "simple string";
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`""simple string""`);
+ });
+
+ it("should handle strings with MIME prefixes", () => {
+ const value = "text/plain:Hello, World!";
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`""Hello, World!""`);
+ });
+
+ it("should handle booleans", () => {
+ expect(getCopyValue(true)).toMatchInlineSnapshot(`"True"`);
+ expect(getCopyValue(false)).toMatchInlineSnapshot(`"False"`);
+ });
+
+ it("should handle null and undefined", () => {
+ expect(getCopyValue(null)).toMatchInlineSnapshot(`"None"`);
+ expect(getCopyValue(undefined)).toMatchInlineSnapshot(`"None"`);
+ });
+
+ it("should handle arrays", () => {
+ const value = ["text/plain:Hello", true, null];
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`"["Hello",True,None]"`);
+ });
+
+ it("should handle objects", () => {
+ const value = {
+ key1: "text/plain:Hello",
+ key2: false,
+ key3: null,
+ };
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(
+ `"{"key1":"Hello","key2":False,"key3":None}"`,
+ );
+ });
+
+ it("should handle a string called true and None", () => {
+ const value = {
+ true: "true",
+ None: "none",
+ null: "null",
+ sentence: "something true none null something",
+ };
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(
+ `"{"true":"true","None":"none","null":"null","sentence":"something true none null something"}"`,
+ );
+ });
+
+ it("should handle nested objects", () => {
+ const value = {
+ key1: {
+ nestedKey1: "text/plain:Nested Hello",
+ nestedKey2: true,
+ },
+ key2: false,
+ };
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(
+ `"{"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"]]"`);
+ });
+
+ it("should handle empty objects", () => {
+ const value = {};
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`"{}"`);
+ });
+
+ it("should handle empty arrays", () => {
+ const value: string[] = [];
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`"[]"`);
+ });
+
+ it("should handle numbers", () => {
+ const value = 42;
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`"42"`);
+ });
+
+ it("should handle special characters in strings", () => {
+ const value = "text/plain:Hello, \nWorld!";
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`""Hello, \\nWorld!""`);
+ });
+
+ 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]"`);
+ });
+
+ it("should handle mixed types in objects", () => {
+ const value = {
+ key1: 42,
+ key2: "text/plain:Hello",
+ key3: true,
+ key4: null,
+ key5: "text/plain+float:1.23",
+ };
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(
+ `"{"key1":42,"key2":"Hello","key3":True,"key4":None,"key5":1.23}"`,
+ );
+ });
+
+ it("should handle sets", () => {
+ const value = "text/plain+set:[1,2,3]";
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`"{1,2,3}"`);
+ });
+
+ it("should handle sets in mixed types", () => {
+ const value = {
+ key1: 42,
+ key2: "text/plain+set:[1,2,3]",
+ key3: true,
+ };
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(
+ `"{"key1":42,"key2":{1,2,3},"key3":True}"`,
+ );
+ });
+
+ it("should handle tuples", () => {
+ const value = "text/plain+tuple:[1,2,3]";
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(`"(1,2,3)"`);
+ });
+
+ it("should handle tuples in mixed types", () => {
+ const value = {
+ key1: 42,
+ key2: "text/plain+tuple:[1,2,3]",
+ key3: true,
+ };
+ const result = getCopyValue(value);
+ expect(result).toMatchInlineSnapshot(
+ `"{"key1":42,"key2":(1,2,3),"key3":True}"`,
+ );
+ });
+});
diff --git a/frontend/src/utils/urls.ts b/frontend/src/utils/urls.ts
index e088900d3e..cb571e3e7e 100644
--- a/frontend/src/utils/urls.ts
+++ b/frontend/src/utils/urls.ts
@@ -26,3 +26,8 @@ export function newNotebookURL() {
const initializationId = `__new__${sessionId}`;
return asURL(`?file=${initializationId}`).toString();
}
+
+const urlRegex = /(https?:\/\/\S+)/g;
+export function isUrl(value: unknown): boolean {
+ return typeof value === "string" && urlRegex.test(value);
+}
diff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.py
index e1bbf55dba..c49bbe1313 100644
--- a/marimo/_output/formatters/structures.py
+++ b/marimo/_output/formatters/structures.py
@@ -29,6 +29,10 @@ def _leaf_formatter(value: object) -> bool | None | str | int:
return f"text/plain+float:{value}"
if value is None:
return value
+ if isinstance(value, set):
+ return f"text/plain+set:{str(value)}"
+ if isinstance(value, tuple):
+ return f"text/plain+tuple:{json.dumps(value)}"
try:
return f"text/plain:{json.dumps(value)}"
diff --git a/marimo/_smoke_tests/structures.py b/marimo/_smoke_tests/structures.py
index c269d21ac2..54e0d79c95 100644
--- a/marimo/_smoke_tests/structures.py
+++ b/marimo/_smoke_tests/structures.py
@@ -1,11 +1,11 @@
import marimo
-__generated_with = "0.9.29"
+__generated_with = "0.9.30"
app = marimo.App(width="medium")
@app.cell
-def __():
+def __(mo):
[
{
"a": 1,
@@ -13,6 +13,13 @@ def __():
"c": "foo",
"d": True,
"e": 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},
+ "j": {"a": 1, "b": 2},
}
]
return
diff --git a/tests/_output/formatters/test_structures.py b/tests/_output/formatters/test_structures.py
index 56a6e1f705..1daaacea38 100644
--- a/tests/_output/formatters/test_structures.py
+++ b/tests/_output/formatters/test_structures.py
@@ -218,3 +218,13 @@ def test_format_structure_subclasses_with_different_built_in_repr() -> None:
assert get_and_format(sys.version_info)[1].startswith(
"<pre style='font-size: 12px'>sys.version_info(major=3"
)
+
+
+def test_format_structure_set() -> None:
+ test_set = {1, 2, 3}
+ assert format_structure([test_set]) == (["text/plain+set:{1, 2, 3}"])
+
+
+def test_format_structure_tuple() -> None:
+ test_tuple = (1, 2, 3)
+ assert format_structure(test_tuple) == (1, 2, 3)