/ interactive_tutorials / duffing_islands
Sign in
interactive_tutorials / duffing_islands
duffing_islands / app / js / session.js
80 lines · 2.4 KBCodeBlameHistory
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1// Saving the page's state: in the browser (localStorage, as you go), and to
2// a file to download and open again. The file is JSON: the state, plus any
3// SoundFont, its bytes in base64, so a file brings its instruments with it.
5export const FORMAT = 'duffing-islands';
6const STORAGE_KEY = 'duffing-islands:state';
8// the state saved in this browser, or null
9export function loadLocal() {
10 try {
11 return JSON.parse(localStorage.getItem(STORAGE_KEY));
12 } catch {
13 return null;
14 }
17let lastSaved = '';
18// save the state in this browser (if it changed); false if storage failed
19export function saveLocal(state) {
20 try {
21 const text = JSON.stringify(state);
22 if (text !== lastSaved) {
23 localStorage.setItem(STORAGE_KEY, text);
24 lastSaved = text;
25 }
26 return true;
27 } catch {
28 return false;
29 }
32// the MIDI knobs assigned to controls, kept in this browser (they belong to
33// the controller, not the session): { [control id]: { ch, cc } }
34const KNOBS_KEY = 'duffing-islands:knobs';
35export function loadKnobs() {
36 try {
37 const o = JSON.parse(localStorage.getItem(KNOBS_KEY));
38 return o && typeof o === 'object' ? o : {};
39 } catch {
40 return {};
41 }
43export function saveKnobs(knobs) {
44 try { localStorage.setItem(KNOBS_KEY, JSON.stringify(knobs)); } catch { /* storage blocked */ }
47export function forgetLocal() {
48 try { localStorage.removeItem(STORAGE_KEY); } catch { /* storage blocked */ }
49 lastSaved = '';
52export function toBase64(buffer) {
53 const bytes = new Uint8Array(buffer);
54 let s = '';
55 for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
56 return btoa(s);
59export function fromBase64(text) {
60 const s = atob(text);
61 const bytes = new Uint8Array(s.length);
62 for (let i = 0; i < s.length; i++) bytes[i] = s.charCodeAt(i);
63 return bytes.buffer;
66// offer `text` as a file to save
67export const download = (text, fileName) => downloadBlob(new Blob([text], { type: 'application/json' }), fileName);
69// offer a Blob as a file to save
70export function downloadBlob(blob, fileName) {
71 const url = URL.createObjectURL(blob);
72 const a = document.createElement('a');
73 a.href = url;
74 a.download = fileName;
75 document.body.append(a);
76 a.click();
77 a.remove();
78 // (kept a while: a large file may take time to start saving)
79 setTimeout(() => URL.revokeObjectURL(url), 60000);
↑↓ move↵openescclose