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: support dropping or copying base64 image files (#4291)

Shahmir Varqha2e15bfa3c34a
diff --git a/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts b/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts
index 94b02ceef5..93010ec269 100644
--- a/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts
+++ b/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts
@@ -1,6 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { EditorState, EditorView, basicSetup } from "@uiw/react-codemirror";
-import { describe, afterEach, test, expect } from "vitest";
+import {
+ describe,
+ afterEach,
+ test,
+ expect,
+ vi,
+ beforeEach,
+ afterAll,
+} from "vitest";
import {
insertBlockquote,
insertBoldMarker,
@@ -12,6 +20,7 @@ import {
insertTextFile,
insertUL,
} from "../commands";
+import { sendCreateFileOrFolder } from "@/core/network/requests";
function createEditor(content: string) {
const state = EditorState.create({
@@ -154,18 +163,35 @@ describe("insertLink", () => {
});
});
+vi.mock("@/core/network/requests", () => ({
+ sendCreateFileOrFolder: vi.fn().mockResolvedValue({
+ success: true,
+ info: { path: "hello.png" },
+ }),
+}));
+
describe("insertImage", () => {
+ const mockPngFile = () => {
+ const png = new Uint8Array([1, 2, 3]);
+ return new File([png], "hello.png", { type: "image/png" });
+ };
+
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.spyOn(window, "prompt").mockImplementation(() => "hello.png");
+ });
+
+ afterAll(() => {
+ vi.restoreAllMocks();
+ });
+
test("inserts image at cursor position", async () => {
view = createEditor("Hello, world!");
view.dispatch({
selection: { anchor: 7, head: 7 },
});
- const png = new Uint8Array([1, 2, 3]);
- await insertImage(
- view,
- new File([png], "hello.png", { type: "image/png" }),
- );
+ await insertImage(view, mockPngFile());
expect(view.state.doc.toString()).toMatchInlineSnapshot(
`"Hello, ![](data:image/png;base64,AQID)world!"`,
@@ -178,16 +204,89 @@ describe("insertImage", () => {
selection: { anchor: 7, head: 13 },
});
- const png = new Uint8Array([1, 2, 3]);
- await insertImage(
- view,
- new File([png], "hello.png", { type: "image/png" }),
- );
+ await insertImage(view, mockPngFile());
expect(view.state.doc.toString()).toMatchInlineSnapshot(
`"Hello, ![world!](data:image/png;base64,AQID)"`,
);
});
+
+ test("saves image as file when server request succeeds", async () => {
+ view = createEditor("Hello, world!");
+ view.dispatch({
+ selection: { anchor: 7, head: 7 },
+ });
+
+ vi.mocked(sendCreateFileOrFolder).mockResolvedValueOnce({
+ success: true,
+ info: {
+ path: "hello.png",
+ name: "hello.png",
+ isMarimoFile: true,
+ isDirectory: false,
+ lastModified: null,
+ children: [],
+ id: "",
+ },
+ });
+
+ await insertImage(view, mockPngFile());
+
+ expect(sendCreateFileOrFolder).toHaveBeenCalledTimes(1);
+ expect(view.state.doc.toString()).toMatchInlineSnapshot(
+ `"Hello, ![](hello.png)world!"`,
+ );
+ });
+
+ test("saves image as file different extension", async () => {
+ view = createEditor("Hello, world!");
+ view.dispatch({
+ selection: { anchor: 7, head: 7 },
+ });
+
+ vi.mocked(sendCreateFileOrFolder).mockResolvedValueOnce({
+ success: true,
+ info: {
+ path: "hello.jpg",
+ name: "hello.jpg",
+ children: [],
+ id: "",
+ isDirectory: false,
+ isMarimoFile: false,
+ },
+ });
+
+ const mockJpgFile = () => {
+ const jpg = new Uint8Array([1, 2, 3]);
+ return new File([jpg], "hello.jpg", { type: "image/jpeg" });
+ };
+
+ await insertImage(view, mockJpgFile());
+
+ expect(sendCreateFileOrFolder).toHaveBeenCalledTimes(1);
+ expect(view.state.doc.toString()).toMatchInlineSnapshot(
+ `"Hello, ![](hello.jpg)world!"`,
+ );
+ });
+
+ test("falls back to base64 when file creation fails", async () => {
+ view = createEditor("Hello, world!");
+ view.dispatch({
+ selection: { anchor: 7, head: 7 },
+ });
+
+ vi.mocked(sendCreateFileOrFolder).mockResolvedValueOnce({
+ success: false,
+ message: "Failed to create file",
+ });
+
+ await insertImage(view, mockPngFile());
+
+ expect(sendCreateFileOrFolder).toHaveBeenCalledTimes(1);
+ expect(view.state.doc.toString()).toMatchInlineSnapshot(
+ `"Hello, ![](data:image/png;base64,AQID)world!"`,
+ );
+ });
});
describe("insertTextFile", () => {
diff --git a/frontend/src/core/codemirror/markdown/commands.ts b/frontend/src/core/codemirror/markdown/commands.ts
index 7039aec7e0..c688e7216c 100644
--- a/frontend/src/core/codemirror/markdown/commands.ts
+++ b/frontend/src/core/codemirror/markdown/commands.ts
@@ -1,4 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { toast } from "@/components/ui/use-toast";
+import { sendCreateFileOrFolder } from "@/core/network/requests";
+import type { FilePath } from "@/utils/paths";
import {
EditorSelection,
type SelectionRange,
@@ -274,11 +277,61 @@ export async function insertImage(view: EditorView, file: File) {
reader.readAsDataURL(file);
});
+ let savedFilePath: string | undefined;
+
+ // If the file is base64 encoded, we can save it locally to prevent large file strings
+ try {
+ if (dataUrl.startsWith("data:")) {
+ const base64 = dataUrl.split(",")[1];
+ let inputFilename = prompt(
+ "We can save your image as a file. Enter a filename.",
+ file.name,
+ );
+ const extension = file.type.split("/")[1];
+
+ // A cancelled prompt returns null
+ if (inputFilename !== null) {
+ if (inputFilename.trim() === "") {
+ inputFilename = file.name;
+ } else if (!inputFilename.endsWith(`.${extension}`)) {
+ inputFilename = `${inputFilename}.${extension}`;
+ }
+
+ const fileCreationResponse = await sendCreateFileOrFolder({
+ path: "" as FilePath, // Root path
+ type: "file",
+ name: inputFilename,
+ contents: base64,
+ });
+
+ if (fileCreationResponse.success) {
+ savedFilePath = fileCreationResponse.info?.path;
+ toast({
+ title: "Image uploaded successfully",
+ description: `We've uploaded your image as ${savedFilePath}`,
+ });
+ } else {
+ toast({
+ title: "Failed to upload image. Using raw base64 string.",
+ });
+ }
+ }
+ }
+ } catch {
+ toast({
+ title: "Failed to upload image. Using raw base64 string.",
+ });
+ }
+
const changes = view.state.changeByRange((range) => {
const text = view.state.sliceDoc(range.from, range.to);
return {
changes: [
- { from: range.from, to: range.to, insert: `![${text}](${dataUrl})` },
+ {
+ from: range.from,
+ to: range.to,
+ insert: `![${text}](${savedFilePath ?? dataUrl})`,
+ },
],
range,
};