// Saving the page's state: in the browser (localStorage, as you go), and to // a file to download and open again. The file is JSON: the state, plus any // SoundFont, its bytes in base64, so a file brings its instruments with it. export const FORMAT = 'duffing-islands'; const STORAGE_KEY = 'duffing-islands:state'; // the state saved in this browser, or null export function loadLocal() { try { return JSON.parse(localStorage.getItem(STORAGE_KEY)); } catch { return null; } } let lastSaved = ''; // save the state in this browser (if it changed); false if storage failed export function saveLocal(state) { try { const text = JSON.stringify(state); if (text !== lastSaved) { localStorage.setItem(STORAGE_KEY, text); lastSaved = text; } return true; } catch { return false; } } // the MIDI knobs assigned to controls, kept in this browser (they belong to // the controller, not the session): { [control id]: { ch, cc } } const KNOBS_KEY = 'duffing-islands:knobs'; export function loadKnobs() { try { const o = JSON.parse(localStorage.getItem(KNOBS_KEY)); return o && typeof o === 'object' ? o : {}; } catch { return {}; } } export function saveKnobs(knobs) { try { localStorage.setItem(KNOBS_KEY, JSON.stringify(knobs)); } catch { /* storage blocked */ } } export function forgetLocal() { try { localStorage.removeItem(STORAGE_KEY); } catch { /* storage blocked */ } lastSaved = ''; } export function toBase64(buffer) { const bytes = new Uint8Array(buffer); let s = ''; for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000)); return btoa(s); } export function fromBase64(text) { const s = atob(text); const bytes = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) bytes[i] = s.charCodeAt(i); return bytes.buffer; } // offer `text` as a file to save export const download = (text, fileName) => downloadBlob(new Blob([text], { type: 'application/json' }), fileName); // offer a Blob as a file to save export function downloadBlob(blob, fileName) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; document.body.append(a); a.click(); a.remove(); // (kept a while: a large file may take time to start saving) setTimeout(() => URL.revokeObjectURL(url), 60000); }