aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIlion Beyst <ilion.beyst@gmail.com>2022-02-22 18:48:59 +0100
committerIlion Beyst <ilion.beyst@gmail.com>2022-02-22 18:48:59 +0100
commit006ce356220c1a089fc468bbfdc0dea819cd9288 (patch)
treeb191563147dfda22a7b3fe4726fc65d81e78e874
parent060b585da1d6beb7dc214d1eb70bcd73ac41ed86 (diff)
downloadplanetwars.dev-006ce356220c1a089fc468bbfdc0dea819cd9288.tar.xz
planetwars.dev-006ce356220c1a089fc468bbfdc0dea819cd9288.zip
persist bot code in localstorage
-rw-r--r--web/pw-server/src/lib/bot_code.ts15
-rw-r--r--web/pw-server/src/lib/utils.ts9
-rw-r--r--web/pw-server/src/routes/index.svelte14
3 files changed, 35 insertions, 3 deletions
diff --git a/web/pw-server/src/lib/bot_code.ts b/web/pw-server/src/lib/bot_code.ts
new file mode 100644
index 0000000..088db72
--- /dev/null
+++ b/web/pw-server/src/lib/bot_code.ts
@@ -0,0 +1,15 @@
+import defaultBotCode from "../assets/bot_template.txt?raw";
+
+const BOT_CODE_KEY = "bot_code";
+
+export function getBotCode() {
+ let botCode = localStorage.getItem(BOT_CODE_KEY);
+ if (!botCode) {
+ botCode = defaultBotCode;
+ }
+ return botCode;
+}
+
+export function saveBotCode(botCode: string) {
+ localStorage.setItem(BOT_CODE_KEY, botCode);
+}
diff --git a/web/pw-server/src/lib/utils.ts b/web/pw-server/src/lib/utils.ts
new file mode 100644
index 0000000..aab9734
--- /dev/null
+++ b/web/pw-server/src/lib/utils.ts
@@ -0,0 +1,9 @@
+export function debounce(func: Function, timeout: number = 300) {
+ let timer: ReturnType<typeof setTimeout>;
+ return (...args: any[]) => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ func.apply(this, args);
+ }, timeout);
+ };
+}
diff --git a/web/pw-server/src/routes/index.svelte b/web/pw-server/src/routes/index.svelte
index 56cb6f4..59552bc 100644
--- a/web/pw-server/src/routes/index.svelte
+++ b/web/pw-server/src/routes/index.svelte
@@ -9,8 +9,8 @@
import type { Ace } from "ace-builds";
import ace from "ace-builds/src-noconflict/ace?client";
import * as AcePythonMode from "ace-builds/src-noconflict/mode-python?client";
-
- import defaultBotCode from "../assets/bot_template.txt?raw";
+ import { getBotCode, saveBotCode } from "$lib/bot_code";
+ import { debounce } from "$lib/utils";
let matches = [];
@@ -24,8 +24,16 @@
});
function init_editor() {
- editSession = new ace.EditSession(defaultBotCode);
+ editSession = new ace.EditSession(getBotCode());
editSession.setMode(new AcePythonMode.Mode());
+
+ const saveCode = () => {
+ const code = editSession.getDocument().getValue();
+ saveBotCode(code);
+ };
+
+ // cast to any because the type annotations are wrong here
+ (editSession as any).on("change", debounce(saveCode, 2000));
}
async function submitCode() {