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
improvement: support smart paste and drag of files (#2934)
Myles Scolnickb9d7ed148d32
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex b85ed8e985..d582495e74 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -56,6 +56,7 @@ import { historyCompartment } from "./editing/extensions";import { goToDefinitionBundle } from "./go-to-definition/extension";import type { HotkeyProvider } from "../hotkeys/hotkeys";import { lightTheme } from "./theme/light";+import { dndBundle } from "./dnd/extension";export interface CodeMirrorSetupOpts {cellId: CellId;@@ -84,6 +85,7 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {return [// Editor keymaps (vim or defaults) based on user configkeymapBundle(keymapConfig, cellMovementCallbacks),+ dndBundle(),// Cell editingcellMovementBundle(cellId, cellMovementCallbacks, hotkeys),cellCodeEditingBundle(cellId, cellCodeCallbacks, hotkeys),diff --git a/frontend/src/core/codemirror/dnd/extension.ts b/frontend/src/core/codemirror/dnd/extension.tsindex 4259a88faa..9fa8736ab4 100644--- a/frontend/src/core/codemirror/dnd/extension.ts+++ b/frontend/src/core/codemirror/dnd/extension.ts@@ -1,11 +1,27 @@/* Copyright 2024 Marimo. All rights reserved. */import type { Extension } from "@codemirror/state";import { EditorView } from "@codemirror/view";+import { insertImage, insertTextFile } from "../markdown/commands";export function dndBundle(): Extension {return [EditorView.domEventHandlers({drop: (event: DragEvent, view: EditorView) => {+ // Handle files+ const file = event.dataTransfer?.files[0];+ if (file?.type.startsWith("text/")) {+ event.preventDefault();+ void insertTextFile(view, file);+ return true;+ }++ if (file?.type.startsWith("image/")) {+ event.preventDefault();+ void insertImage(view, file);+ return true;+ }++ // Handle plain textconst text = event.dataTransfer?.getData("text/plain");if (text) {event.preventDefault();@@ -19,7 +35,10 @@ export function dndBundle(): Extension {scrollIntoView: true,});}+ return true;}++ return false;},dragover: (event: DragEvent) => {event.preventDefault();diff --git a/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts b/frontend/src/core/codemirror/markdown/__tests__/commands.test.tsindex 3dc164cefd..94b02ceef5 100644--- a/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts+++ b/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts@@ -5,9 +5,11 @@ import {insertBlockquote,insertBoldMarker,insertCodeMarker,+ insertImage,insertItalicMarker,insertLink,insertOL,+ insertTextFile,insertUL,} from "../commands";@@ -152,6 +154,76 @@ describe("insertLink", () => {});});+describe("insertImage", () => {+ 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" }),+ );++ expect(view.state.doc.toString()).toMatchInlineSnapshot(+ `"Hello, world!"`,+ );+ });++ test("inserts image at cursor position with selected text", async () => {+ view = createEditor("Hello, world!");+ view.dispatch({+ selection: { anchor: 7, head: 13 },+ });++ const png = new Uint8Array([1, 2, 3]);+ await insertImage(+ view,+ new File([png], "hello.png", { type: "image/png" }),+ );++ expect(view.state.doc.toString()).toMatchInlineSnapshot(+ `"Hello, "`,+ );+ });+});++describe("insertTextFile", () => {+ test("inserts text file at cursor position", async () => {+ view = createEditor("Hello, world!");+ view.dispatch({+ selection: { anchor: 7, head: 7 },+ });++ await insertTextFile(+ view,+ new File(["csvcsvcsv"], "my.csv", { type: "text/csv" }),+ );++ expect(view.state.doc.toString()).toMatchInlineSnapshot(+ `"Hello, csvcsvcsvworld!"`,+ );+ });++ test("inserts text file at cursor position with selected text", async () => {+ view = createEditor("Hello, world!");+ view.dispatch({+ selection: { anchor: 7, head: 13 },+ });++ await insertTextFile(+ view,+ new File(["csvcsvcsv"], "my.csv", { type: "text/csv" }),+ );++ expect(view.state.doc.toString()).toMatchInlineSnapshot(+ `"Hello, csvcsvcsvworld!"`,+ );+ });+});+describe("insertBoldMarker", () => {test("inserts bold marker at cursor position", () => {view = createEditor("Hello, world!");diff --git a/frontend/src/core/codemirror/markdown/commands.ts b/frontend/src/core/codemirror/markdown/commands.tsindex a33d8b1bd1..7039aec7e0 100644--- a/frontend/src/core/codemirror/markdown/commands.ts+++ b/frontend/src/core/codemirror/markdown/commands.ts@@ -267,6 +267,71 @@ export function insertLink(view: EditorView, url = "http://") {return true;}+export async function insertImage(view: EditorView, file: File) {+ const reader = new FileReader();+ const dataUrl = await new Promise<string>((resolve) => {+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(file);+ });++ const changes = view.state.changeByRange((range) => {+ const text = view.state.sliceDoc(range.from, range.to);+ return {+ changes: [+ { from: range.from, to: range.to, insert: `` },+ ],+ range,+ };+ });++ view.dispatch(+ view.state.update(changes, {+ scrollIntoView: true,+ annotations: Transaction.userEvent.of("input"),+ }),+ );++ const { to } = changes.selection.main;+ try {+ view.dispatch({+ selection: EditorSelection.create([+ EditorSelection.range(to + 4, to + 4 + dataUrl.length),+ EditorSelection.cursor(to + 4 + dataUrl.length),+ ]),+ });+ } catch {+ // Do nothing+ }++ view.focus();++ return true;+}++export async function insertTextFile(view: EditorView, file: File) {+ const text = await file.text();++ // Just insert at the cursor+ const changes = view.state.changeByRange((range) => {+ return {+ // Insert at the start of the range, don't replace any existing text+ changes: [{ from: range.from, to: range.from, insert: text }],+ range,+ };+ });++ view.dispatch(+ view.state.update(changes, {+ scrollIntoView: true,+ annotations: Transaction.userEvent.of("input"),+ }),+ );++ view.focus();++ return true;+}+export function insertUL(view: EditorView) {// Only apply on selectionif (!hasSelection(view)) {diff --git a/frontend/src/core/codemirror/markdown/extension.ts b/frontend/src/core/codemirror/markdown/extension.tsindex 947aa8bb6c..0ddaecc655 100644--- a/frontend/src/core/codemirror/markdown/extension.ts+++ b/frontend/src/core/codemirror/markdown/extension.ts@@ -4,9 +4,11 @@ import {insertBlockquote,insertBoldMarker,insertCodeMarker,+ insertImage,insertItalicMarker,insertLink,insertOL,+ insertTextFile,insertUL,} from "./commands";import { EditorView, keymap } from "@codemirror/view";@@ -63,12 +65,12 @@ export function enhancedMarkdownExtension(},]),),- // Smart on paste of URLs+ // Smart paste of URLsEditorView.domEventHandlers({paste: (event, view) => {// If no selection, do nothingif (view.state.selection.main.empty) {- return;+ return false;}const url = event.clipboardData?.getData("text/plain");@@ -78,5 +80,27 @@ export function enhancedMarkdownExtension(}},}),+ // Smart paste of files+ EditorView.domEventHandlers({+ paste: (event, view) => {+ const file = event.clipboardData?.files[0];++ if (!file) {+ return false;+ }++ if (file.type.startsWith("image/")) {+ event.preventDefault();+ void insertImage(view, file);+ return true;+ }++ if (file.type.startsWith("text/")) {+ event.preventDefault();+ void insertTextFile(view, file);+ return true;+ }+ },+ }),];}