json.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { ExcalidrawElement } from "../element/types";
  2. import { AppState } from "../types";
  3. import { cleanAppStateForExport } from "../appState";
  4. import { fileOpen, fileSave } from "browser-nativefs";
  5. import { loadFromBlob } from "./blob";
  6. import { loadLibrary } from "./localStorage";
  7. import { Library } from "./library";
  8. export const serializeAsJSON = (
  9. elements: readonly ExcalidrawElement[],
  10. appState: AppState,
  11. ): string =>
  12. JSON.stringify(
  13. {
  14. type: "excalidraw",
  15. version: 2,
  16. source: window.location.origin,
  17. elements: elements.filter((element) => !element.isDeleted),
  18. appState: cleanAppStateForExport(appState),
  19. },
  20. null,
  21. 2,
  22. );
  23. export const saveAsJSON = async (
  24. elements: readonly ExcalidrawElement[],
  25. appState: AppState,
  26. fileHandle: any,
  27. ) => {
  28. const serialized = serializeAsJSON(elements, appState);
  29. const blob = new Blob([serialized], {
  30. type: "application/json",
  31. });
  32. const name = `${appState.name}.excalidraw`;
  33. (window as any).handle = await fileSave(
  34. blob,
  35. {
  36. fileName: name,
  37. description: "Excalidraw file",
  38. extensions: ["excalidraw"],
  39. },
  40. fileHandle || null,
  41. );
  42. };
  43. export const loadFromJSON = async (appState: AppState) => {
  44. const blob = await fileOpen({
  45. description: "Excalidraw files",
  46. extensions: ["json", "excalidraw"],
  47. mimeTypes: ["application/json"],
  48. });
  49. return loadFromBlob(blob, appState);
  50. };
  51. export const saveLibraryAsJSON = async () => {
  52. const library = await loadLibrary();
  53. const serialized = JSON.stringify(
  54. {
  55. type: "excalidrawlib",
  56. version: 1,
  57. library,
  58. },
  59. null,
  60. 2,
  61. );
  62. const fileName = `library.excalidrawlib`;
  63. const blob = new Blob([serialized], {
  64. type: "application/vnd.excalidrawlib+json",
  65. });
  66. await fileSave(blob, {
  67. fileName,
  68. description: "Excalidraw library file",
  69. extensions: ["excalidrawlib"],
  70. });
  71. };
  72. export const importLibraryFromJSON = async () => {
  73. const blob = await fileOpen({
  74. description: "Excalidraw library files",
  75. extensions: ["json", "excalidrawlib"],
  76. mimeTypes: ["application/json"],
  77. });
  78. Library.importLibrary(blob);
  79. };