Skip to content

Commit

Permalink
feat: save excalidraw data to files instead of local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
ocapraro committed Apr 18, 2022
1 parent 01838d3 commit 7dc04d4
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 35 deletions.
41 changes: 19 additions & 22 deletions ExcalidrawCanvas.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,16 @@ const resolvablePromise = () => {
return promise;
};

const saveData = async (setInitialData, curData, id, saveToFile,closeDrawing=true,exportAsSvg=true) => {
const prevData = localStorage.getItem(`excalidrawMathData-${id}`);
const saveData = async (setInitialData, curData, id, saveToFile, readFile, closeDrawing=true, exportAsSvg=true) => {
const prevData = await readFile("data-"+id+".json", "excalidraw-files");
let formattedData = {...curData};
formattedData.appState.collaborators = [];;
formattedData.appState.collaborators = [];
if(prevData != JSON.stringify(formattedData)){
setInitialData((data)=>{
formattedData.appState.currentItemStrokeColor = data.appState.currentItemStrokeColor;
return formattedData
});
localStorage.setItem(`excalidrawMathData-${id}`, JSON.stringify(formattedData));
let lastId = localStorage.getItem("math-max-id");
if (parseInt(lastId)<id){
localStorage.setItem("math-max-id", id);
}
saveToFile("data-"+id+".json", JSON.stringify(formattedData), "excalidraw-files", false);
}
if(exportAsSvg){
await exportSVG({...formattedData}, id, saveToFile,closeDrawing);
Expand Down Expand Up @@ -66,21 +62,23 @@ const exportSVG = async (data, id, saveToFile, closeDrawing=true) => {
});
const svg = await exportToSvg(formattedData);
formattedData.elements.unshift();
saveToFile("data-"+id+".svg",svg.outerHTML, closeDrawing);
saveToFile("data-"+id+".svg",svg.outerHTML, "drawings", closeDrawing);
}

export function ExcalidrawCanvas({ id, saveToFile, gridMode, colors }) {
export function ExcalidrawCanvas({ id, saveToFile, gridMode, colors, readFile, prevData }) {
const excalidrawRef = useRef(null);
const dimensionRef = useRef();
const saveIntervalRef = useRef(null);
const [InitialData, setInitialData] = useState(localStorage.getItem(`excalidrawMathData-${id}`)?
JSON.parse(localStorage.getItem(`excalidrawMathData-${id}`))
:{
elements: [],
appState: { viewBackgroundColor: "#fff0", currentItemFontFamily: 1, currentItemStrokeColor:"#000" },
scrollToContent: false,
libraryItems: []
});
const [InitialData, setInitialData] = useState(
prevData?
JSON.parse(prevData)
:{
elements: [],
appState: { viewBackgroundColor: "#fff0", currentItemFontFamily: 1, currentItemStrokeColor:"#000" },
scrollToContent: false,
libraryItems: []
}
);

let canvas = document.getElementById(`math-canvas-${id}`);
let mathBlock = document.querySelector(`.math-block-${id}`);
Expand Down Expand Up @@ -115,9 +113,9 @@ export function ExcalidrawCanvas({ id, saveToFile, gridMode, colors }) {
};
// auto save
if(document.querySelector(`.math-block-${id}`)){
saveData(setInitialData, curData, id, saveToFile, false, false);
saveData(setInitialData, curData, id, saveToFile,readFile, false, false);
}else{
saveData(setInitialData, curData, id, saveToFile, true, true);
saveData(setInitialData, curData, id, saveToFile,readFile, true, true);
clearInterval(saveIntervalRef.current);
}
}, 1000);
Expand Down Expand Up @@ -152,7 +150,6 @@ export function ExcalidrawCanvas({ id, saveToFile, gridMode, colors }) {
let elements = excalidrawRef.current.getSceneElements();
let selectedIds = Object.keys(appState.selectedElementIds);
let canvas = document.getElementById(`math-canvas-${id}`);
let finalData;
if(canvas){
for (let i = 0; i < selectedIds.length; i++) {
let selectedElement = elements.find(elem => (elem.id===selectedIds[i]));
Expand Down Expand Up @@ -211,7 +208,7 @@ export function ExcalidrawCanvas({ id, saveToFile, gridMode, colors }) {
scrollToContent: false,
libraryItems: []
};
saveData(setInitialData, curData, id, saveToFile);
saveData(setInitialData, curData, id, saveToFile, readFile);
clearInterval(saveIntervalRef.current);
}} style={{
zIndex:5,
Expand Down
4 changes: 2 additions & 2 deletions excalidrawRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import * as React from "react";
import { ExcalidrawCanvas } from "./ExcalidrawCanvas";
import {createRoot} from 'react-dom/client';

export const renderCanvas = (container: any, id: number, saveToFile:any, gridModeEndabled:boolean, colors:Array<string>) => {
export const renderCanvas = (container: any, id: number, saveToFile:any, gridModeEndabled:boolean, colors:Array<string>, readFile:any,prevData:string) => {
let root = createRoot(container);
root.render(
<ExcalidrawCanvas id={id} saveToFile={saveToFile} gridMode={gridModeEndabled} colors={colors} />
<ExcalidrawCanvas id={id} saveToFile={saveToFile} gridMode={gridModeEndabled} colors={colors} readFile={readFile} prevData={prevData} />
);
}
24 changes: 16 additions & 8 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ export default class MathPlus extends Plugin {
const vault = this.app.vault;
const adapter = vault.adapter;

const saveToFile = async (fileName:string,data:string,closeDrawing=true) => {
let drawingPath = vault.configDir + "/plugins/obsidian-math-plus/drawings";
const saveToFile = async (fileName:string, data:string, directory:string, closeDrawing=true) => {
let directoryPath = vault.configDir + `/plugins/obsidian-math-plus/${directory}`;
// If the drawings directory isn't there, make it
if(!await adapter.exists(drawingPath)){
await adapter.mkdir(drawingPath);
if(!await adapter.exists(directoryPath)){
await adapter.mkdir(directoryPath);
}
const configPath = vault.configDir + "/plugins/obsidian-math-plus/drawings/"+fileName;
const configPath = vault.configDir + `/plugins/obsidian-math-plus/${directory}/${fileName}`;
if(await adapter.exists(configPath)){
await adapter.write(configPath,data);
}else{
Expand All @@ -75,6 +75,14 @@ export default class MathPlus extends Plugin {
}
}

const readFile = async (fileName:string, directory:string) => {
const configPath = vault.configDir + `/plugins/obsidian-math-plus/${directory}/${fileName}`;
if(await adapter.exists(configPath)){
return await adapter.read(configPath);
}
return null
}

// Parse Equation
let rawEqu = source.replace(/\|\|.+\|\|\n+/gm,"");
let equ = formatEquation(rawEqu);
Expand Down Expand Up @@ -136,7 +144,8 @@ export default class MathPlus extends Plugin {
drawButton.onClickEvent(async ()=>{
const wrapper = el.createEl("div",{cls:"excalidraw-canvas-wrapper"});
this.settings.colorPicker?null:wrapper.addClass("hidden-color-picker");
renderCanvas(wrapper, blockId, saveToFile, this.settings.gridModeEndabled, [this.settings.color1,this.settings.color2,this.settings.color3]);
let data = await readFile("data-"+blockId+".json", "excalidraw-files");
renderCanvas(wrapper, blockId, saveToFile, this.settings.gridModeEndabled, [this.settings.color1,this.settings.color2,this.settings.color3],readFile,data);
let svgWrapper = el.querySelector(".math-svg-wrapper") as HTMLElement;
if(svgWrapper){
svgWrapper.remove();
Expand Down Expand Up @@ -170,10 +179,9 @@ export default class MathPlus extends Plugin {
name: "Insert math block",
hotkeys: [{ modifiers: ["Mod"], key: "m" }],
editorCallback: (editor: Editor) => {
let id = parseInt(localStorage.getItem("math-max-id"))+1;
let id = Math.floor(Math.random() * Date.now());
editor.replaceRange("```math\n||{\"id\":"+id+"}||\n\n\n```", editor.getCursor());
editor.setCursor(editor.getCursor().line+3);
localStorage.setItem("math-max-id", id.toString());
},
});

Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "obsidian-math-plus",
"name": "Obsidian Math+",
"version": "0.2.2",
"version": "0.2.3",
"minAppVersion": "0.12.0",
"description": "This is an Obsidian plugin for taking math notes using Excalidraw.",
"author": "Oscar Capraro",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "obsidian-math-plus",
"version": "0.2.2",
"version": "0.2.3",
"description": "This is a math plugin for Obsidian (https://obsidian.md)",
"main": "main.js",
"scripts": {
Expand Down
3 changes: 2 additions & 1 deletion versions.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"0.1.2": "0.12.0",
"0.2.0": "0.12.0",
"0.2.1": "0.12.0",
"0.2.2": "0.12.0"
"0.2.2": "0.12.0",
"0.2.3": "0.12.0"
}

0 comments on commit 7dc04d4

Please sign in to comment.