72 lines
1.8 KiB
JavaScript
72 lines
1.8 KiB
JavaScript
import * as world from "./world.mjs";
|
|
|
|
|
|
|
|
const DEFAULT_SAVE_NAME = "boxes_save_0";
|
|
|
|
const get_elem = id => document.getElementById(id);
|
|
const create_elem = type => document.createElement(type);
|
|
|
|
const save_button = get_elem("save");
|
|
const load_button = get_elem("load");
|
|
const restart_button = get_elem("restart");
|
|
|
|
save_button.onclick = _ => {
|
|
const timestamp = new Date().getTime();
|
|
const filename = `boxes_${timestamp}.boxes`;
|
|
|
|
save_text(filename, generate_save_data());
|
|
};
|
|
|
|
function generate_save_data () {
|
|
const root = world.get_root();
|
|
return btoa(JSON.stringify(root));
|
|
}
|
|
|
|
function save_text (filename, text) {
|
|
const link = create_elem("a");
|
|
const file = new Blob([text], { type: "text/plain" });
|
|
link.href = URL.createObjectURL(file);
|
|
link.download = filename;
|
|
link.click();
|
|
}
|
|
|
|
load_button.onclick = _ => {
|
|
const input = create_elem("input");
|
|
input.type = "file";
|
|
input.addEventListener("change", e => {
|
|
const file = e.target.files[0];
|
|
const reader = new FileReader();
|
|
reader.onload = e => load_from_text(e.target.result);
|
|
reader.onerror = error => alert("couldn't load the file.");
|
|
reader.readAsText(file);
|
|
});
|
|
input.click();
|
|
}
|
|
|
|
function load_from_text (text) {
|
|
const data = JSON.parse(atob(text));
|
|
world.replace_root(data);
|
|
}
|
|
|
|
|
|
|
|
export function save_in_browser (save_name = DEFAULT_SAVE_NAME) {
|
|
const data = generate_save_data();
|
|
localStorage.setItem(save_name, data);
|
|
}
|
|
|
|
export function load_from_browser (save_name = DEFAULT_SAVE_NAME) {
|
|
if (localStorage.getItem(save_name) === null) return;
|
|
const data = localStorage.getItem(save_name);
|
|
load_from_text(data);
|
|
}
|
|
|
|
|
|
|
|
restart_button.onclick = _ => {
|
|
if (confirm("are you sure you want to create a new world? this will delete any unsaved creations.")) {
|
|
world.replace_root(world.create_new());
|
|
}
|
|
};
|