1
Fork 0

save code to localstorage

This commit is contained in:
Jan-Erik Rediger 2024-06-03 20:31:22 +02:00
parent feef2336d6
commit 8c8b2a915a
2 changed files with 25 additions and 2 deletions

View file

@ -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);
}

View file

@ -35,10 +35,12 @@
<span id="htmx-indicator">
<svg width="1em" height="1em" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12,4a8,8,0,0,1,7.89,6.7A1.53,1.53,0,0,0,21.38,12h0a1.5,1.5,0,0,0,1.48-1.75,11,11,0,0,0-21.72,0A1.5,1.5,0,0,0,2.62,12h0a1.53,1.53,0,0,0,1.49-1.3A8,8,0,0,1,12,4Z"><animateTransform attributeName="transform" type="rotate" dur="0.75s" values="0 12 12;360 12 12" repeatCount="indefinite"/></path></svg>
</span>
<span id="status" class="status"></span>
<span id="status" class="status">
<noscript>Sorry, this playground requires JavaScript. :(</noscript>
</span>
</section>
<section class="code">
<div class="editor language-c">Sorry, this playground requires JavaScript. :(</div>
<div class="editor language-c"></div>
<div class="code-output">
<div class="std-output">