From 70cd9806d21bd9e260acf8c9d669646795e40c7c Mon Sep 17 00:00:00 2001 From: Max <m.giller.dev@gmail.com> Date: Tue, 9 Nov 2021 23:01:20 +0100 Subject: [PATCH] Added pop up on tab close with unsaved changes --- editor/js/interactions.js | 1 + editor/js/manageddata.js | 43 +++++++++++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/editor/js/interactions.js b/editor/js/interactions.js index 8d57cf2..2c34de8 100644 --- a/editor/js/interactions.js +++ b/editor/js/interactions.js @@ -12,6 +12,7 @@ export function initInteractions() { }); jQuery("button#save").on("click", () => { saveGraphJson(SPACE, graph.getCleanData()); // space_id defined globaly through knowledge-space.php + graph.saveChanges(); }); // Fill space dropdown diff --git a/editor/js/manageddata.js b/editor/js/manageddata.js index e2f83bd..4f9058a 100644 --- a/editor/js/manageddata.js +++ b/editor/js/manageddata.js @@ -1,10 +1,37 @@ export default class ManagedData { constructor(data) { this.data = data; - this.history = []; // Newest state is always at 0 + this.history = []; // Newest state is always at 0 this.historyPosition = 0; + this.unsavedChanges = false; - this.storeCurrentData("Initial state"); + this.storeCurrentData("Initial state", false); + } + + updateUnsavedChangesHandler() { + if (this.hasUnsavedChanges()) { + console.log("Unsaved changes..."); + window.addEventListener("beforeunload", this.handleBeforeUnload); + } else { + console.log("Everything saved..."); + window.removeEventListener("beforeunload", this.handleBeforeUnload); + } + } + + handleBeforeUnload(e) { + var confirmationMessage = 'If you leave before saving, unsaved changes will be lost.'; + + (e || window.event).returnValue = confirmationMessage; //Gecko + IE + return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc. + } + + hasUnsavedChanges() { + return this.unsavedChanges; + } + + saveChanges() { + this.unsavedChanges = false; + this.updateUnsavedChangesHandler(); } onUndo() {} @@ -31,7 +58,10 @@ export default class ManagedData { step(direction = 1) { var newHistoryPosition = this.historyPosition + Math.sign(direction); - if (newHistoryPosition >= this.history.length || newHistoryPosition < 0) { + if ( + newHistoryPosition >= this.history.length || + newHistoryPosition < 0 + ) { return false; } @@ -45,7 +75,7 @@ export default class ManagedData { return data; } - storeCurrentData(description) { + storeCurrentData(description, relevantChanges = true) { var formattedData = this.storableData(this.data); this.history.unshift({ @@ -56,5 +86,10 @@ export default class ManagedData { // Forget about the currently stored potential future this.history.splice(0, this.historyPosition); this.historyPosition = 0; + + if (!this.hasUnsavedChanges() && relevantChanges) { + this.unsavedChanges = true; + this.updateUnsavedChangesHandler(); + } } } -- GitLab