]> BookStack Code Mirror - bookstack/blobdiff - resources/js/services/drawio.js
Actually add the test this time
[bookstack] / resources / js / services / drawio.js
index efc071d3ec4b51a94b4060329b633d340b72ad97..46e10327a26f7438be542a48df3a1b0266202ca2 100644 (file)
@@ -1,17 +1,22 @@
 // Docs: https://www.diagrams.net/doc/faq/embed-mode
+import * as store from './store';
 
 let iFrame = null;
 let lastApprovedOrigin;
-let onInit; let
-    onSave;
+let onInit;
+let onSave;
+const saveBackupKey = 'last-drawing-save';
 
 function drawPostMessage(data) {
     iFrame.contentWindow.postMessage(JSON.stringify(data), lastApprovedOrigin);
 }
 
 function drawEventExport(message) {
+    store.set(saveBackupKey, message.data);
     if (onSave) {
-        onSave(message.data);
+        onSave(message.data).then(() => {
+            store.del(saveBackupKey);
+        });
     }
 }
 
@@ -62,16 +67,43 @@ function drawReceive(event) {
     }
 }
 
+/**
+ * Attempt to prompt and restore unsaved drawing content if existing.
+ * @returns {Promise<void>}
+ */
+async function attemptRestoreIfExists() {
+    const backupVal = await store.get(saveBackupKey);
+    const dialogEl = document.getElementById('unsaved-drawing-dialog');
+
+    if (!dialogEl) {
+        console.error('Missing expected unsaved-drawing dialog');
+    }
+
+    if (backupVal) {
+        /** @var {ConfirmDialog} */
+        const dialog = window.$components.firstOnElement(dialogEl, 'confirm-dialog');
+        const restore = await dialog.show();
+        if (restore) {
+            onInit = async () => backupVal;
+        }
+    }
+}
+
 /**
  * Show the draw.io editor.
+ * onSaveCallback must return a promise that resolves on successful save and errors on failure.
+ * onInitCallback must return a promise with the xml to load for the editor.
+ * Will attempt to provide an option to restore unsaved changes if found to exist.
  * @param {String} drawioUrl
- * @param {Function} onInitCallback - Must return a promise with the xml to load for the editor.
- * @param {Function} onSaveCallback - Is called with the drawing data on save.
+ * @param {Function<Promise<String>>} onInitCallback
+ * @param {Function<Promise>} onSaveCallback - Is called with the drawing data on save.
  */
-export function show(drawioUrl, onInitCallback, onSaveCallback) {
+export async function show(drawioUrl, onInitCallback, onSaveCallback) {
     onInit = onInitCallback;
     onSave = onSaveCallback;
 
+    await attemptRestoreIfExists();
+
     iFrame = document.createElement('iframe');
     iFrame.setAttribute('frameborder', '0');
     window.addEventListener('message', drawReceive);