浏览代码

Drag and drop JSON exports to canvas loads the scene (#676)

* Drag and drop JSON exports to canvas loads the scene

* remove unneeded onDragOver
lissitz 5 年之前
父节点
当前提交
92a0f100b8
共有 3 个文件被更改,包括 26 次插入6 次删除
  1. 16 0
      src/index.tsx
  2. 9 6
      src/scene/data.ts
  3. 1 0
      src/scene/index.ts

+ 16 - 0
src/index.tsx

@@ -37,6 +37,7 @@ import {
   addToLoadedScenes,
   loadedScenes,
   calculateScrollCenter,
+  loadFromBlob,
 } from "./scene";
 
 import { renderScene } from "./renderer";
@@ -310,6 +311,8 @@ export class App extends React.Component<any, AppState> {
     window.addEventListener("resize", this.onResize, false);
     window.addEventListener("unload", this.onUnload, false);
     window.addEventListener("blur", this.onUnload, false);
+    window.addEventListener("dragover", e => e.preventDefault(), false);
+    window.addEventListener("drop", e => e.preventDefault(), false);
 
     const searchParams = new URLSearchParams(window.location.search);
     const id = searchParams.get("id");
@@ -1784,6 +1787,19 @@ export class App extends React.Component<any, AppState> {
               const hitElement = getElementAtPosition(elements, x, y);
               document.documentElement.style.cursor = hitElement ? "move" : "";
             }}
+            onDrop={e => {
+              const file = e.dataTransfer.files[0];
+              if (file?.type === "application/json") {
+                loadFromBlob(file)
+                  .then(({ elements, appState }) =>
+                    this.syncActionResult({
+                      elements,
+                      appState,
+                    } as ActionResult),
+                  )
+                  .catch(err => console.error(err));
+              }
+            }}
           >
             {t("labels.drawingCanvas")}
           </canvas>

+ 9 - 6
src/scene/data.ts

@@ -76,8 +76,16 @@ export async function saveAsJSON(
     (window as any).handle,
   );
 }
-
 export async function loadFromJSON() {
+  const blob = await fileOpen({
+    description: "Excalidraw files",
+    extensions: ["json"],
+    mimeTypes: ["application/json"],
+  });
+  return loadFromBlob(blob);
+}
+
+export async function loadFromBlob(blob: any) {
   const updateAppState = (contents: string) => {
     const defaultAppState = getDefaultAppState();
     let elements = [];
@@ -92,11 +100,6 @@ export async function loadFromJSON() {
     return { elements, appState };
   };
 
-  const blob = await fileOpen({
-    description: "Excalidraw files",
-    extensions: ["json"],
-    mimeTypes: ["application/json"],
-  });
   if (blob.handle) {
     (window as any).handle = blob.handle;
   }

+ 1 - 0
src/scene/index.ts

@@ -10,6 +10,7 @@ export {
 export {
   exportCanvas,
   loadFromJSON,
+  loadFromBlob,
   saveAsJSON,
   restoreFromLocalStorage,
   saveToLocalStorage,