From 92a0f100b8934271b8c46fd39b8d1d87c54a598f Mon Sep 17 00:00:00 2001 From: lissitz <53315888+lissitz@users.noreply.github.com> Date: Sun, 2 Feb 2020 22:02:13 +0100 Subject: [PATCH] Drag and drop JSON exports to canvas loads the scene (#676) * Drag and drop JSON exports to canvas loads the scene * remove unneeded onDragOver --- src/index.tsx | 16 ++++++++++++++++ src/scene/data.ts | 15 +++++++++------ src/scene/index.ts | 1 + 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index 98f10edf..581df959 100644 --- a/src/index.tsx +++ b/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 { 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 { 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")} diff --git a/src/scene/data.ts b/src/scene/data.ts index 4f2a713b..584a127e 100644 --- a/src/scene/data.ts +++ b/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; } diff --git a/src/scene/index.ts b/src/scene/index.ts index e44907eb..8f34215d 100644 --- a/src/scene/index.ts +++ b/src/scene/index.ts @@ -10,6 +10,7 @@ export { export { exportCanvas, loadFromJSON, + loadFromBlob, saveAsJSON, restoreFromLocalStorage, saveToLocalStorage,