From 8c8b2a915ad0d504504a4dc5ffd874ec91951e45 Mon Sep 17 00:00:00 2001 From: Jan-Erik Rediger Date: Mon, 3 Jun 2024 20:31:22 +0200 Subject: [PATCH] save code to localstorage --- frontend/app.js | 21 +++++++++++++++++++++ frontend/index.html | 6 ++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/frontend/app.js b/frontend/app.js index 5970ba0..58f26df 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -39,7 +39,24 @@ function base64Decode(bytes) { return new TextDecoder().decode(base64ToBytes(bytes)); } +function debounce(func, timeout = 300){ + let timer; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => { func.apply(this, args); }, timeout); + }; +} + +function saveToStorage(code) { + if (code.length) { + localStorage.setItem("code", code); + } else { + localStorage.removeItem("code"); + } +} + let jar = CodeJar(document.querySelector('.editor'), highlight) +jar.onUpdate(debounce(saveToStorage)); const defaultCode = `use fmt; export fn main() void = { @@ -55,9 +72,13 @@ export fn main() void = { }; };`; +let savedCode = localStorage.getItem("code"); if (location.hash) { let code = base64Decode(location.hash.substr(1)); jar.updateCode(code) + +} else if (savedCode && savedCode.length) { + jar.updateCode(savedCode); } else { jar.updateCode(defaultCode); } diff --git a/frontend/index.html b/frontend/index.html index d887e5e..faec72e 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -35,10 +35,12 @@ - + + +
-
Sorry, this playground requires JavaScript. :(
+