Add IndexedDB autosave Background autosave of the whole session (all scenes, map backgrounds, custom token images, token positions/visibility, grid, scale, lines, measurer, GM notes, Hume level) into IndexedDB on every state change, debounced 500ms, flushed on pagehide/visibilitychange. The session is restored automatically after F5 or a closed tab; status shown in the header. Also fix a pre-existing ReferenceError in SymbolHandle.processCustomImageLoad (missing 'let' for circleHandle).
@@ -23,6 +23,7 @@ <img src="assets/images/logo1-white.png" class="logo" alt="">
<a class="topHeaderBrand" href="./">rpg.peajack.net</a> </div> <div class="d-flex align-items-center" style="gap: .5rem;"> + <span id="autosaveStatus" class="fieldLabel" style="margin-right: .35rem;" title="Фоновый автосейв в IndexedDB — сессия восстанавливается после F5"></span> <button type="button" class="btn-modern btn-modern-sm" onclick="clearCurrentScene()">Clear Map</button> <button type="button" class="btn-modern btn-modern-primary btn-modern-sm" onclick="createMirrorWindow()">Launch Player View</button> </div>@@ -226,6 +227,186 @@ globs.scenes = [];
globs.activeSceneIdx = 0; globs.gmNotes = ""; globs.humeValue = 1.0; + globs._autosaveReady = false; // flips to true only after restoreAutosave() finishes + + // --------------------------------------------------------------------------- + // IndexedDB autosave: the whole session (all scenes, backgrounds, token + // images, GM notes, Hume level) is written as a single record on every + // state change (debounced), so an accidental F5 / tab close restores it. + // Blobs are stored natively by IndexedDB — no base64 packing involved. + // --------------------------------------------------------------------------- + const AUTOSAVE_DB_NAME = 'simplyRPG'; + const AUTOSAVE_STORE = 'autosave'; + const AUTOSAVE_KEY = 'current'; + const AUTOSAVE_DEBOUNCE_MS = 500; + + let autosaveTimer = null; + let autosaveDB = null; + let autosaveInFlight = null; + let autosaveDirty = false; + + function openAutosaveDB() { + if (autosaveDB) return Promise.resolve(autosaveDB); + return new Promise((resolve, reject) => { + const req = indexedDB.open(AUTOSAVE_DB_NAME, 1); + req.onupgradeneeded = function () { + if (!req.result.objectStoreNames.contains(AUTOSAVE_STORE)) { + req.result.createObjectStore(AUTOSAVE_STORE); + } + }; + req.onsuccess = function () { + autosaveDB = req.result; + autosaveDB.onversionchange = function () { + autosaveDB.close(); + autosaveDB = null; + }; + resolve(autosaveDB); + }; + req.onerror = function () { reject(req.error); }; + req.onblocked = function () { reject(new Error('IndexedDB open blocked')); }; + }); + } + + function setAutosaveStatus(label) { + const el = document.getElementById('autosaveStatus'); + if (el) el.textContent = label || ''; + } + + function formatClock(ts) { + const d = new Date(ts); + const pad = function (n) { return String(n).padStart(2, '0'); }; + return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); + } + + // Serialise the live board: active scene is captured from the canvas first, + // the other scenes already hold their last captured state. + function buildAutosaveSnapshot() { + captureCurrentScene(); + return { + version: 2, + autosave: true, + savedAt: Date.now(), + activeSceneIdx: globs.activeSceneIdx, + gmNotes: globs.gmNotes || "", + humeValue: globs.humeValue !== undefined ? globs.humeValue : 1.0, + scenes: globs.scenes.map(scene => ({ + name: scene.name, + backgroundFile: scene.backgroundFile || null, + tokenImages: scene.tokenImages || [], + state: scene.state + })) + }; + } + + function scheduleAutosave() { + if (!globs._autosaveReady) return; + if (autosaveTimer) clearTimeout(autosaveTimer); + setAutosaveStatus('сохранение…'); + autosaveTimer = setTimeout(function () { + autosaveTimer = null; + saveAutosaveNow(); + }, AUTOSAVE_DEBOUNCE_MS); + } + + function saveAutosaveNow() { + if (!globs._autosaveReady) return Promise.resolve(); + if (autosaveTimer) { + clearTimeout(autosaveTimer); + autosaveTimer = null; + } + // A write is already running: remember that state changed again and + // run one more pass once it settles, so the newest state always lands. + if (autosaveInFlight) { + autosaveDirty = true; + return autosaveInFlight; + } + + const snapshot = buildAutosaveSnapshot(); + autosaveInFlight = openAutosaveDB() + .then(function (db) { + return new Promise(function (resolve, reject) { + const tx = db.transaction(AUTOSAVE_STORE, 'readwrite'); + tx.objectStore(AUTOSAVE_STORE).put(snapshot, AUTOSAVE_KEY); + tx.oncomplete = function () { resolve(); }; + tx.onerror = function () { reject(tx.error); }; + tx.onabort = function () { reject(tx.error); }; + }); + }) + .then(function () { + setAutosaveStatus('автосейв ' + formatClock(snapshot.savedAt)); + }) + .catch(function (err) { + setAutosaveStatus('автосейв недоступен'); + console.warn('Autosave failed:', err); + }) + .then(function () { + autosaveInFlight = null; + if (autosaveDirty) { + autosaveDirty = false; + scheduleAutosave(); + } + }); + return autosaveInFlight; + } + + // Fire any pending debounced write right now (pagehide / tab hidden). + function flushAutosave() { + if (!globs._autosaveReady) return; + if (autosaveTimer) { + clearTimeout(autosaveTimer); + autosaveTimer = null; + saveAutosaveNow(); + } + } + + function readAutosaveRecord(db) { + return new Promise(function (resolve, reject) { + const req = db.transaction(AUTOSAVE_STORE, 'readonly').objectStore(AUTOSAVE_STORE).get(AUTOSAVE_KEY); + req.onsuccess = function () { resolve(req.result); }; + req.onerror = function () { reject(req.error); }; + }); + } + + async function restoreAutosave() { + globs._autosaveReady = false; + try { + const db = await openAutosaveDB(); + const snapshot = await readAutosaveRecord(db); + if (snapshot && Array.isArray(snapshot.scenes) && snapshot.scenes.length > 0) { + const scenes = snapshot.scenes.map(function (s, idx) { + return { + name: s.name || ("Карта " + (idx + 1)), + backgroundFile: s.backgroundFile || null, + tokenImages: Array.isArray(s.tokenImages) ? s.tokenImages : [], + state: s.state + }; + }); + activateSession(scenes, snapshot.activeSceneIdx, snapshot.gmNotes, snapshot.humeValue); + setAutosaveStatus('восстановлено в ' + formatClock(snapshot.savedAt || Date.now())); + } else { + setAutosaveStatus('автосейв включён'); + } + } catch (err) { + setAutosaveStatus('автосейв недоступен'); + console.warn('Autosave restore failed:', err); + } finally { + globs._autosaveReady = true; + } + } + + // Swap the whole session in and render the active scene (shared by the + // .ttrpg loader and the IndexedDB restore). + function activateSession(scenes, activeSceneIdx, gmNotes, humeValue) { + globs.scenes = (scenes && scenes.length) ? scenes : [makeBlankScene("Карта 1")]; + globs.activeSceneIdx = Math.min(activeSceneIdx || 0, globs.scenes.length - 1); + globs.gmNotes = gmNotes || ""; + const parsedHume = parseFloat(humeValue); + globs.humeValue = isNaN(parsedHume) ? 1.0 : parsedHume; + const notesEl = document.getElementById("gmBroadcastNotes"); + if (notesEl) notesEl.value = globs.gmNotes; + renderHumeUI(globs.humeValue); + restoreScene(globs.scenes[globs.activeSceneIdx]); + } function makeBlankScene(name) { return {@@ -259,6 +440,14 @@ globs.scenes = [makeBlankScene("Карта 1")];
globs.activeSceneIdx = 0; renderSceneTabs(); renderHumeUI(globs.humeValue); + + // Autosave: flush pending writes when the tab is hidden or going away, + // then pull the last session back from IndexedDB. + window.addEventListener('pagehide', flushAutosave); + document.addEventListener('visibilitychange', function () { + if (document.visibilityState === 'hidden') flushAutosave(); + }); + restoreAutosave(); } function handleCanvasUpdates(event) {@@ -293,11 +482,13 @@ const val = parseFloat(document.getElementById("humeSlider").value);
globs.humeValue = isNaN(val) ? 1.0 : val; renderHumeUI(globs.humeValue); broadcastChannel.postMessage(['setHume', globs.humeValue]); + scheduleAutosave(); } function updateGMNotesFromInput() { globs.gmNotes = document.getElementById("gmBroadcastNotes").value; broadcastChannel.postMessage(['setGMNotes', globs.gmNotes]); + scheduleAutosave(); } function clearGMNotes() {@@ -407,6 +598,7 @@
captureCurrentScene(); globs.activeSceneIdx = idx; restoreScene(globs.scenes[idx]); + scheduleAutosave(); } function addEmptyScene() {@@ -415,6 +607,7 @@ const nextScene = makeBlankScene("Карта " + (globs.scenes.length + 1));
globs.scenes.push(nextScene); globs.activeSceneIdx = globs.scenes.length - 1; restoreScene(nextScene); + scheduleAutosave(); } function renameCurrentScene() {@@ -424,6 +617,7 @@ const nextName = window.prompt("Название карты:", scene.name);
if (nextName && nextName.trim()) { scene.name = nextName.trim(); renderSceneTabs(); + scheduleAutosave(); } }@@ -438,6 +632,7 @@ if (globs.activeSceneIdx >= globs.scenes.length) {
globs.activeSceneIdx = globs.scenes.length - 1; } restoreScene(globs.scenes[globs.activeSceneIdx]); + scheduleAutosave(); } function clearCurrentScene() {@@ -453,6 +648,7 @@ scene.state.measurer = null;
} document.getElementById('includeGrid').checked = false; renderSceneTabs(); + scheduleAutosave(); } function loadMapImageFromButton(event) {@@ -478,6 +674,7 @@ });
captureCurrentScene(); renderSceneTabs(); + scheduleAutosave(); event.target.value = ""; }@@ -485,6 +682,7 @@ function updateGridFromButton() {
const checkboxValue = document.getElementById('includeGrid').checked; updateGrid(checkboxValue, document.getElementById("canvasScale").value); broadcastChannel.postMessage(['toggleGrid', checkboxValue, document.getElementById("canvasScale").value]); + scheduleAutosave(); } function updateCanvasScaleFromSlider() {@@ -492,6 +690,7 @@ let pxPerFoot = document.getElementById("canvasScale").value;
updateCanvasScale(pxPerFoot); updateCanvasScaleLabel(); broadcastChannel.postMessage(['updateScale', pxPerFoot]); + scheduleAutosave(); } function drawNewCircleFromButton() {@@ -515,6 +714,7 @@
drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, "", null, true); broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]); renderSceneTabs(); + scheduleAutosave(); } function postLabels() {@@ -803,7 +1003,7 @@ }
if (jsonContents.version === 2 && Array.isArray(jsonContents.scenes) && jsonContents.scenes.length > 0) { let offset = 0; - globs.scenes = jsonContents.scenes.map((s, idx) => { + const scenes = jsonContents.scenes.map((s, idx) => { let bg = null; if (s.state && s.state.backgroundImageBoolean && offset < savedImages.length) { bg = savedImages[offset++];@@ -818,12 +1018,7 @@ tokenImages: tImgs,
state: s.state }; }); - globs.activeSceneIdx = Math.min(jsonContents.activeSceneIdx || 0, globs.scenes.length - 1); - globs.gmNotes = jsonContents.gmNotes || ""; - globs.humeValue = jsonContents.humeLevel !== undefined ? Number(jsonContents.humeLevel) : 1.0; - document.getElementById("gmBroadcastNotes").value = globs.gmNotes; - renderHumeUI(globs.humeValue); - restoreScene(globs.scenes[globs.activeSceneIdx]); + activateSession(scenes, jsonContents.activeSceneIdx, jsonContents.gmNotes, jsonContents.humeLevel); } else { let bg = null; let imgs = savedImages;@@ -831,15 +1026,15 @@ if (jsonContents.backgroundImageBoolean && imgs.length > 0) {
bg = imgs[0]; imgs = imgs.slice(1); } - globs.scenes = [{ + const scenes = [{ name: stripExtension(savedFile.name) || "Карта 1", backgroundFile: bg, tokenImages: imgs, state: jsonContents }]; - globs.activeSceneIdx = 0; - restoreScene(globs.scenes[0]); + activateSession(scenes, 0, "", globs.humeValue); } + scheduleAutosave(); } function download(filename, path) {
@@ -165,6 +165,15 @@ }
} else { console.log("Broadcast message not understood! "+broadcastData[0]+' '+broadcastData[1]); } + if (globs.windowLocation === 'main' && ['moveCircle', 'newRotation', 'drawLine', 'removeLineSegment', 'eraseAllLines', 'drawMeasurer', 'eraseMeasurer', 'cleanUpNullLines'].includes(broadcastData[0])) { + notifyStateChanged(); + } +} + +function notifyStateChanged() { + if (typeof window !== 'undefined' && typeof window.scheduleAutosave === 'function') { + window.scheduleAutosave(); + } } function broadcastPageElements () {@@ -398,6 +407,7 @@ }
pressup(evt) { evt.currentTarget.off("pressmove",evt.currentTarget.tmpFunction) + notifyStateChanged(); // console.log(evt.currentTarget._listeners); }@@ -475,6 +485,7 @@ circle.image.id = passThroughVariable;
circle.image.src = URL.createObjectURL(result); circle.image.onload = handlePreprocess; circle.imageFile = result; + notifyStateChanged(); } compressImageFile(file,this.circleRadius*2,handleImageCompression,this.id); }@@ -633,6 +644,7 @@ handleImageLoad(event);
}; globs.imageSrc = result; + notifyStateChanged(); } if (globs.backgroundBitmap) { stage.removeChild(globs.backgroundBitmap);@@ -780,6 +792,7 @@
function clearCanvas() { _clearCanvas(); broadcastChannel.postMessage(['clearCanvas']); + notifyStateChanged(); } function _clearCanvas() {@@ -943,6 +956,7 @@ },
handleDrawMouseUp: function (event) { stage.removeEventListener("stagemousemove", drawer.handleDrawMouseMove); + notifyStateChanged(); }, drawLine: function (startX,endX,startY,endY,width,color) {@@ -1038,6 +1052,7 @@ },
handleDrawMouseUp: function (event) { stage.removeEventListener("stagemousemove", eraser.handleDrawMouseMove); + notifyStateChanged(); }, createEraser: function (x,y,radius) {@@ -1223,6 +1238,7 @@ },
handleDrawMouseUp: function (event) { stage.removeEventListener("stagemousemove", measurer.handleDrawMouseMove); + notifyStateChanged(); }, drawLine: function (startX,endX,startY,endY) {@@ -1246,6 +1262,7 @@ stage.removeEventListener("stagemousedown", this.handleDrawMouseDown);
stage.removeEventListener("stagemouseup", this.handleDrawMouseUp); eraseMeasurer(); broadcastChannel.postMessage(['eraseMeasurer']) + notifyStateChanged(); }, redrawMeasurer (startX=this.currentLine.startX,endX=this.currentLine.startY,startY=this.currentLine.endX,endY=this.currentLine.endY) {
@@ -114,6 +114,11 @@ notesBox.style.width = "9.2em";
notesBox.style.top = ".1em" notesBox.value = notes; + notesBox.oninput = function() { + if (typeof window !== 'undefined' && typeof window.scheduleAutosave === 'function') { + window.scheduleAutosave(); + } + }; this.namedSubElements.notesBox = notesBox; let notesLabel = this.addText('Notes');@@ -189,6 +194,9 @@
labelChangeListener () { redrawCircles(); postLabels(); + if (typeof window !== 'undefined' && typeof window.scheduleAutosave === 'function') { + window.scheduleAutosave(); + } } removeFromButton () {@@ -200,6 +208,9 @@ thisSymbolHandle.removeFromMasterList();
broadcastChannel.postMessage(['removeCircle',this.id]); if (typeof renderSceneTabs === 'function') { renderSceneTabs(); + } + if (typeof window !== 'undefined' && typeof window.scheduleAutosave === 'function') { + window.scheduleAutosave(); } }@@ -231,6 +242,9 @@ }
this.div.classList.toggle('tokenHidden', !visible); if (broadcast && this.namedSubElements.circle.windowLocation === 'main') { broadcastChannel.postMessage(['setCircleVisibility', this.id, visible]); + if (typeof window !== 'undefined' && typeof window.scheduleAutosave === 'function') { + window.scheduleAutosave(); + } } updateCanvas(); }@@ -249,7 +263,7 @@ this.namedSubElements.circle.redraw();
} function loadImageToken() { - circleHandle = globs.circleHandles[this.id]; + let circleHandle = globs.circleHandles[this.id]; let divHeight = circleHandle.tokenHandle.clientHeight; let divWidth = circleHandle.tokenHandle.clientWidth;