2020-03-07 10:20:38 -05:00
|
|
|
import { ExcalidrawElement } from "../element/types";
|
|
|
|
import { AppState } from "../types";
|
|
|
|
import { cleanAppStateForExport } from "../appState";
|
|
|
|
|
|
|
|
import { fileOpen, fileSave } from "browser-nativefs";
|
|
|
|
import { loadFromBlob } from "./blob";
|
|
|
|
|
2020-05-20 16:21:37 +03:00
|
|
|
export const serializeAsJSON = (
|
2020-03-07 10:20:38 -05:00
|
|
|
elements: readonly ExcalidrawElement[],
|
|
|
|
appState: AppState,
|
2020-05-20 16:21:37 +03:00
|
|
|
): string =>
|
|
|
|
JSON.stringify(
|
2020-03-07 10:20:38 -05:00
|
|
|
{
|
|
|
|
type: "excalidraw",
|
2020-05-27 15:14:50 +02:00
|
|
|
version: 2,
|
2020-03-07 10:20:38 -05:00
|
|
|
source: window.location.origin,
|
2020-03-23 13:05:07 +02:00
|
|
|
elements: elements.filter((element) => !element.isDeleted),
|
2020-03-07 10:20:38 -05:00
|
|
|
appState: cleanAppStateForExport(appState),
|
|
|
|
},
|
|
|
|
null,
|
|
|
|
2,
|
|
|
|
);
|
|
|
|
|
2020-05-20 16:21:37 +03:00
|
|
|
export const saveAsJSON = async (
|
2020-03-07 10:20:38 -05:00
|
|
|
elements: readonly ExcalidrawElement[],
|
|
|
|
appState: AppState,
|
2020-06-12 18:35:04 +02:00
|
|
|
fileHandle: any,
|
2020-05-20 16:21:37 +03:00
|
|
|
) => {
|
2020-03-07 10:20:38 -05:00
|
|
|
const serialized = serializeAsJSON(elements, appState);
|
2020-06-12 18:35:04 +02:00
|
|
|
const blob = new Blob([serialized], {
|
|
|
|
type: "application/json",
|
|
|
|
});
|
|
|
|
// Either "Save as" or non-supporting browser
|
|
|
|
if (!fileHandle) {
|
|
|
|
const name = `${appState.name}.excalidraw`;
|
|
|
|
const handle = await fileSave(
|
|
|
|
blob,
|
|
|
|
{
|
|
|
|
fileName: name,
|
|
|
|
description: "Excalidraw file",
|
|
|
|
extensions: ["excalidraw"],
|
|
|
|
},
|
|
|
|
fileHandle,
|
|
|
|
);
|
|
|
|
(window as any).handle = handle;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// "Save"
|
|
|
|
const writable = await fileHandle.createWritable();
|
|
|
|
await writable.write(blob);
|
|
|
|
await writable.close();
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|
2020-06-12 18:35:04 +02:00
|
|
|
|
2020-05-20 16:21:37 +03:00
|
|
|
export const loadFromJSON = async () => {
|
2020-03-07 10:20:38 -05:00
|
|
|
const blob = await fileOpen({
|
|
|
|
description: "Excalidraw files",
|
|
|
|
extensions: ["json", "excalidraw"],
|
2020-06-12 18:35:04 +02:00
|
|
|
mimeTypes: ["application/json"],
|
2020-03-07 10:20:38 -05:00
|
|
|
});
|
|
|
|
return loadFromBlob(blob);
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|