From 731403e16542902fac468fe24a41de314dba94d4 Mon Sep 17 00:00:00 2001
From: ezsh <ezsh.junk@gmail.com>
Date: Thu, 7 Feb 2019 08:13:05 +0100
Subject: [PATCH] Add sidebar link for dumping the game state

---
 devTools/sugarcube.d.ts           |  1 +
 src/002-config/fc-js-init.js      |  3 ++-
 src/debugging/debugJS.js          | 31 +++++++++++++++++++++++++++++++
 src/uncategorized/storyCaption.tw |  2 ++
 4 files changed, 36 insertions(+), 1 deletion(-)

diff --git a/devTools/sugarcube.d.ts b/devTools/sugarcube.d.ts
index e24730b925d..644ea40581d 100644
--- a/devTools/sugarcube.d.ts
+++ b/devTools/sugarcube.d.ts
@@ -1310,6 +1310,7 @@ declare namespace SugarCubeLib {
 	declare interface ISugarCube {
 		Config: Config;
 		Macro: Macro;
+		Save: Save;
 		State: State;
 		Story: Story;
 		/**
diff --git a/src/002-config/fc-js-init.js b/src/002-config/fc-js-init.js
index ec07dba98be..3966b6a6838 100644
--- a/src/002-config/fc-js-init.js
+++ b/src/002-config/fc-js-init.js
@@ -5,6 +5,7 @@
 */
 window.App = { };
 // the same declaration for code parsers that don't line the line above
-var App = App || {};
+var App = window.App || {};
 
+App.Debug = {};
 App.Entity = {};
diff --git a/src/debugging/debugJS.js b/src/debugging/debugJS.js
index 7f1a9650c8a..aac1d50c784 100644
--- a/src/debugging/debugJS.js
+++ b/src/debugging/debugJS.js
@@ -80,3 +80,34 @@ window.findNaN = function findNan() {
 	}
 	return result;
 };
+
+/**
+ * Dumps game save as a readable JSON to the browser for saving in a file
+ */
+App.Debug.dumpGameState = function () {
+	// helper to download a blob
+	// borrowed from stackexchange
+	function downloadToFile(content, fileName, contentType) {
+		var a = document.createElement("a");
+		var file = new Blob([content], {
+			type: contentType
+		});
+		a.href = URL.createObjectURL(file);
+		a.download = fileName;
+		a.click();
+	}
+
+	// we will replace SugarCube onSave handler
+	let oldHandler = SugarCube.Config.saves.onSave;
+	try {
+		SugarCube.Config.saves.onSave = function (save) {
+			if (oldHandler) {
+				oldHandler(save);
+			}
+			downloadToFile(JSON.stringify(save, null, 2), save.id + ".js", "text/plain");
+		}
+		SugarCube.Save.serialize();
+	} finally {
+		SugarCube.Config.saves.onSave = oldHandler;
+	}
+};
diff --git a/src/uncategorized/storyCaption.tw b/src/uncategorized/storyCaption.tw
index a0256f5a148..43d4d162006 100644
--- a/src/uncategorized/storyCaption.tw
+++ b/src/uncategorized/storyCaption.tw
@@ -830,6 +830,8 @@
 		<</if>>
 		<<goto _Pass>>
 	<</link>>
+	<br>
+	<<link "Dump Game State">><<run App.Debug.dumpGameState()>><</link>>
 <</if>>
 
 <</nobr>>
-- 
GitLab