import {TOOL_INFO_CLASSNAME, WIDE_CLASSNAME} from '../config.js'; import {hash} from '../helper.js'; import {Tool} from '../tool.js'; export class StateTool extends Tool { stored = []; setContainer(container) { super.setContainer(container); const buttons = document.createElement('div'); const save = document.createElement('button'); const list = document.createElement('div'); save.innerHTML = 'Save'; save.classList.add(WIDE_CLASSNAME); buttons.style.display = 'flex'; buttons.style.flexDirection = 'row'; buttons.appendChild(save); list.style.display = 'flex'; list.style.flexDirection = 'column'; this.div.appendChild(buttons); this.div.appendChild(list); save.addEventListener('click', async () => { const state = this.sim.toJSON(); this.stored.push(state); const item = await this.createItem(state); list.appendChild(item); }); // Check url query parameter, and load specified state if found const paramsString = window.location.search; const searchParams = new URLSearchParams(paramsString); const stateEnc = searchParams.get("state"); // a if (stateEnc) { const stateText = decodeURI(stateEnc); const state = JSON.parse(stateText); // Tools in this system can be very powerful this.sim.fromJSON(state); } } getStateDescription(state) { const d = new Date(state.dateSaved); return `${d.toLocaleDateString()} ${d.toLocaleTimeString()}`; } async createItem(state) { const item = document.createElement('div'); item.style.display = 'flex'; item.style.flexDirection = 'row'; item.style.flexWrap = 'wrap'; const description = document.createElement('button'); description.style.flex = '2'; description.classList.add(TOOL_INFO_CLASSNAME); description.innerHTML = this.getStateDescription(state); const load = document.createElement('button'); load.style.flex = '1'; load.innerHTML = 'Load'; const link = document.createElement('a'); const {url, digest} = await this.toUrl(state); link.classList.add(TOOL_INFO_CLASSNAME); link.classList.add(WIDE_CLASSNAME); link.href = url; link.innerHTML = digest.slice(0, 6); load.appendChild(link); item.appendChild(description); item.appendChild(load); load.addEventListener('click', (e) => { e.preventDefault(); // Tools in this system can wield great power this.sim.fromJSON(state); }); return item; } async toUrl(state) { const stateText = JSON.stringify(state); // const stateB64 = window.btoa(stateText); const rawUrl = `./?state=${stateText}`; const url = encodeURI(rawUrl); const digest = await hash(stateText); return {url, digest}; } }