From d56688706b6fc77868d13ef28d129365a573d73d Mon Sep 17 00:00:00 2001 From: OctoSpacc Date: Mon, 20 May 2024 23:04:03 +0200 Subject: [PATCH] offline caching preparations --- _includes/head.html | 4 +- assets/js/idb-backup-and-restore.js | 120 +++++++++++++++++++++++++++ assets/js/preferences.js | 12 +-- assets/js/pwa.js | 24 ++++-- assets/js/software-embed.js | 123 ++++++++++++++-------------- assets/js/util.js | 13 +++ pages/configuration.md | 2 +- 7 files changed, 225 insertions(+), 73 deletions(-) create mode 100644 assets/js/idb-backup-and-restore.js create mode 100644 assets/js/util.js diff --git a/_includes/head.html b/_includes/head.html index 949b54f..c670104 100644 --- a/_includes/head.html +++ b/_includes/head.html @@ -110,6 +110,8 @@ icon: {{ page.icon | jsonify }}, software_data: {{ page.software_data | jsonify }}, }; - window.SalaMuseoGames = { site: site_config, page: page_config }; + window.SMG = window.SalaMuseoGames = { site: site_config, page: page_config }; + + diff --git a/assets/js/idb-backup-and-restore.js b/assets/js/idb-backup-and-restore.js new file mode 100644 index 0000000..a649733 --- /dev/null +++ b/assets/js/idb-backup-and-restore.js @@ -0,0 +1,120 @@ +window.idbBackupAndRestore = { + +/* */ + +/** + * Export all data from an IndexedDB database + * + * @param {IDBDatabase} idbDatabase The database to export from + * @return {Promise} + */ +exportToJson: function (idbDatabase) { + return new Promise((resolve, reject) => { + const exportObject = {} + if (idbDatabase.objectStoreNames.length === 0) { + resolve(JSON.stringify(exportObject)) + } else { + const transaction = idbDatabase.transaction( + idbDatabase.objectStoreNames, + 'readonly' + ) + + transaction.addEventListener('error', reject) + + for (const storeName of idbDatabase.objectStoreNames) { + const allObjects = [] + transaction + .objectStore(storeName) + .openCursor() + .addEventListener('success', event => { + const cursor = event.target.result + if (cursor) { + // Cursor holds value, put it into store data + allObjects.push(cursor.value) + cursor.continue() + } else { + // No more values, store is done + exportObject[storeName] = allObjects + + // Last store was handled + if ( + idbDatabase.objectStoreNames.length === + Object.keys(exportObject).length + ) { + resolve(JSON.stringify(exportObject)) + } + } + }) + } + } + }) +}, + +/** + * Import data from JSON into an IndexedDB database. + * This does not delete any existing data from the database, so keys may clash. + * + * @param {IDBDatabase} idbDatabase Database to import into + * @param {string} json Data to import, one key per object store + * @return {Promise} + */ +importFromJson: function (idbDatabase, json) { + return new Promise((resolve, reject) => { + const transaction = idbDatabase.transaction( + idbDatabase.objectStoreNames, + 'readwrite' + ) + transaction.addEventListener('error', reject) + + var importObject = JSON.parse(json) + for (const storeName of idbDatabase.objectStoreNames) { + let count = 0 + for (const toAdd of importObject[storeName]) { + const request = transaction.objectStore(storeName).add(toAdd) + request.addEventListener('success', () => { + count++ + if (count === importObject[storeName].length) { + // Added all objects for this store + delete importObject[storeName] + if (Object.keys(importObject).length === 0) { + // Added all object stores + resolve() + } + } + }) + } + } + }) +}, + +/** + * Clear a database + * + * @param {IDBDatabase} idbDatabase The database to delete all data from + * @return {Promise} + */ +clearDatabase: function (idbDatabase) { + return new Promise((resolve, reject) => { + const transaction = idbDatabase.transaction( + idbDatabase.objectStoreNames, + 'readwrite' + ) + transaction.addEventListener('error', reject) + + let count = 0 + for (const storeName of idbDatabase.objectStoreNames) { + transaction + .objectStore(storeName) + .clear() + .addEventListener('success', () => { + count++ + if (count === idbDatabase.objectStoreNames.length) { + // Cleared all object stores + resolve() + } + }) + } + }) +}, + +}; diff --git a/assets/js/preferences.js b/assets/js/preferences.js index 9a1cbc7..c2500f9 100644 --- a/assets/js/preferences.js +++ b/assets/js/preferences.js @@ -2,10 +2,10 @@ var prefsIndex = 'SalaMuseoGames/Prefs/v1'; -var Prefs = { - pwaManifests: { default: true, name: "Allow installing the site as a PWA" }, - softwarePwaManifests: { default: true, dependsOn: "pwaManifests", name: "Allow installing individual games as PWAs" }, - // offlineCache: { default: true, name: "Cache site pages and game files offline", summary: "Allow faster site navigation, and gameplay without an Internet connection, by caching unlimited data offline. Disable if you want to save storage. (Note that data for some emulators and games is always cached regardless of this setting; you can only manage their data when they show an option in their interface.)" }, +var Prefs = window.SalaMuseoGames.Prefs = { + softwarePwaManifests: { default: true, /* dependsOn: "pwaManifests", */ name: "Allow installing individual games as PWAs" }, + pwaManifests: { default: false, name: "Allow installing the site home itself as a PWA" }, + offlineCache: { default: true, name: "Cache site pages and game files offline", summary: "Allow faster site navigation, and gameplay without an Internet connection, by caching unlimited data offline. Disable if you want to save storage. (Note that data for some emulators and games is always cached regardless of this setting; you can only manage their data when they show an option in their interface.)" }, // dataExport: { onclick: (function(){}), section: "data", name: "Export configuration and gamesaves" }, // dataImport: { onclick: (function(){}), section: "data", name: "Import configuration and gamesaves" }, // featurePreview: { default: false, name: "Use experimental features before their release", summary: "If some new site features or adjustments are scheduled to release soon, you might be chosen to preview them before they are officially available" }, @@ -28,8 +28,9 @@ Object.keys(Prefs).forEach(function(key){ }); var PrefsSections = { - data: { name: "Data management", visible: true }, + // data: { name: "Data management", visible: true }, developer: { name: "Development", visible: Prefs.developerMode.value }, + // advanced: { name: "Advanced", visible: true }, }; var configElem = document.querySelector('#ConfigurationCustomizer'); @@ -64,7 +65,6 @@ if (configElem) { }); } -window.SalaMuseoGames.Prefs = Prefs; SavePrefs(); })(); diff --git a/assets/js/pwa.js b/assets/js/pwa.js index 40ebe8e..b84a040 100644 --- a/assets/js/pwa.js +++ b/assets/js/pwa.js @@ -5,6 +5,7 @@ var Software = SalaMuseoGames.page.software_data; var Screen = (Software && Software.screen); var Site = SalaMuseoGames.site; var iconUrl = SalaMuseoGames.page.icon; +var coverUrl = SalaMuseoGames.page.image; var sitePath = (Site.url + Site.baseurl); function absoluteUrlFromRelative (url) { @@ -17,7 +18,7 @@ function absoluteUrlFromRelative (url) { } } -if (Prefs.pwaManifests.value) { +if (Prefs.pwaManifests.value || Prefs.softwarePwaManifests.value) { var manifestData; if (Prefs.softwarePwaManifests.value && Software) { // specific manifests on games pages @@ -30,7 +31,7 @@ if (Prefs.pwaManifests.value) { display: ((Screen && Screen.display) || "standalone"), orientation: ((Screen && Screen.orientation) || "any"), }; - } else { + } else if (Prefs.pwaManifests.value) { // site manifest on global pages var ldData; for (var elem of document.querySelectorAll('script[type="application/ld+json"]')) { @@ -53,7 +54,7 @@ if (Prefs.pwaManifests.value) { scope: location.href, background_color: (Software && Software.background_color || getComputedStyle(document.body).backgroundColor), icons: [{ - src: (iconUrl ? absoluteUrlFromRelative(iconUrl) : (sitePath + '/assets/img/icons/mediumtile.png')), + src: ((iconUrl || coverUrl) ? absoluteUrlFromRelative(iconUrl || coverUrl) : (sitePath + '/assets/img/icons/mediumtile.png')), sizes: "any", purpose: "any", }], @@ -64,8 +65,21 @@ if (Prefs.pwaManifests.value) { document.head.appendChild(manifestElem); } -if (Prefs.offlineCache.value && 'serviceWorker' in navigator) { - navigator.serviceWorker.register('/ServiceWorker.js', { scope: "/SalaMuseoGames/" }); +if ('serviceWorker' in navigator) { + var cachingScopes = ['SalaMuseoGames', 'ext-bin-1']; + if (Prefs.offlineCache.value) { + cachingScopes.forEach(function(scope){ + navigator.serviceWorker.register('/ServiceWorker.js', { scope: `/${scope}/` }); + }); + } else { + navigator.serviceWorker.getRegistrations().then((workers) => { + for (var worker of workers) { + if (cachingScopes.includes(worker.scope.split('/').slice(-2)[0])) { + worker.unregister(); + } + } + }); + } } })(); diff --git a/assets/js/software-embed.js b/assets/js/software-embed.js index 4bf8015..6d875cf 100644 --- a/assets/js/software-embed.js +++ b/assets/js/software-embed.js @@ -1,67 +1,70 @@ (function(){ - var bin1Path = 'https://gamingshitposting.github.io/ext-bin-1'; - var thisElement = document.querySelector(`script[src="${SalaMuseoGames.site.baseurl}/assets/js/software-embed.js"]`); - var data = SalaMuseoGames.page.software_data; - var platform = data.platform; - var core = data.core; - var backend = data.backend; - var romUrl = (data.rom_url || `${bin1Path}/roms/${data.rom_index}.7z`); - var frameUrl = (data.frame_url || `${bin1Path}/${data.frame_index}`); - function button (name, onclick) { return `` } +var bin1Path = 'https://gamingshitposting.github.io/ext-bin-1'; +var thisElement = document.querySelector(`script[src="${SalaMuseoGames.site.baseurl}/assets/js/software-embed.js"]`); +var data = SalaMuseoGames.page.software_data; +var platform = data.platform; +var core = data.core; +var backend = data.backend; +var romUrl = (data.rom_url || `${bin1Path}/roms/${data.rom_index}.7z`); +var frameUrl = (data.frame_url || `${bin1Path}/${data.frame_index}`); - function diyEmbedHtml (frameUrl) { return ( - button('Focus 🔳️', function(ctx){ - ctx.parentElement.scrollIntoView(); - ctx.parentElement.querySelector('iframe#software-embed-frame').focus(); - }) + ' ' + - button('Fullscreen 🖼️', function(ctx){ - ctx.parentElement.querySelector('iframe#software-embed-frame').requestFullscreen(); - }) + ' ' + - button('Enlarge ↔️', function(ctx){ - document.body.classList[ - !document.body.className.split(' ').includes('cinema-view') ? 'add' : 'remove' - ]('cinema-view'); - }) + ' ' + - button('Reload ♻️', function(ctx){ - var frame = ctx.parentElement.querySelector('iframe#software-embed-frame'); - var src = frame.src; - frame.src = ''; - frame.src = src; - }) + ' ' + - `` - ) } +function button (name, onclick) { return `` } - // TODO set any overrides if specified ... +var buttonEnlarge = button('Enlarge ↔️', function(){ + document.body.classList[ + !document.body.className.split(' ').includes('cinema-view') ? 'add' : 'remove' + ]('cinema-view'); +}); - if (platform === 'web') { +function diyEmbedHtml (frameUrl) { return ( + button('Focus 🔳️', function(ctx){ + ctx.parentElement.scrollIntoView(); + ctx.parentElement.querySelector('iframe#software-embed-frame').focus(); + }) + ' ' + + button('Fullscreen 🖼️', function(ctx){ + ctx.parentElement.querySelector('iframe#software-embed-frame').requestFullscreen(); + }) + ' ' + + buttonEnlarge + ' ' + + button('Reload ♻️', function(ctx){ + var frame = ctx.parentElement.querySelector('iframe#software-embed-frame'); + var src = frame.src; + frame.src = ''; + frame.src = src; + }) + ' ' + + `` +) } + +// TODO set any overrides if specified ... + +if (platform === 'web') { + thisElement.outerHTML = diyEmbedHtml(frameUrl); +} else switch (backend) { + default: + case 'cuttingedge': + case 'emulatorjs': + window.EJS_player = '#software-embed-frame'; + window.EJS_pathtodata = 'https://gamingshitposting.github.io/ext-bin-1/EmulatorJS/data/'; + window.EJS_core = (core || platform); + window.EJS_gameUrl = romUrl; + window.EJS_screenRecording = { videoBitrate: 150000000 }; + thisElement.parentElement.appendChild(SMG.Util.elementFromHtml(buttonEnlarge)); + thisElement.parentElement.appendChild(SMG.Util.makeElement('div', { + style: 'width: 640px; height: 480px; max-width: 100%;', + innerHTML: '
', + })); + document.body.appendChild(SMG.Util.makeElement('script', { src: `${EJS_pathtodata}loader.js` })); + break; + case 'standalone': + var frameUrl = ''; + if (platform === 'nds' || core === 'desmume') { + frameUrl = `https://octospacc.gitlab.io/Web-Archives-Misc/Repo/DeSmuME/#RomUrl=${romUrl}`; + } + else if (platform === 'dos') { + frameUrl = `https://gamingshitposting.github.io/ext-bin-1/dos.zone/${data.rom_index}/index.html`; + } thisElement.outerHTML = diyEmbedHtml(frameUrl); - } else switch (backend) { - default: - case 'cuttingedge': - case 'emulatorjs': - window.EJS_player = '#software-embed-frame'; - window.EJS_pathtodata = 'https://gamingshitposting.github.io/ext-bin-1/EmulatorJS/data/'; - window.EJS_core = (core || platform); - window.EJS_gameUrl = romUrl; - window.EJS_screenRecording = { videoBitrate: 150000000 }; - var frameElement = document.createElement('div'); - frameElement.style = 'width: 640px; height: 480px; max-width: 100%;'; - frameElement.innerHTML = '
'; - thisElement.parentElement.appendChild(frameElement); - var scriptElement = document.createElement('script'); - scriptElement.src = EJS_pathtodata+'loader.js'; - document.body.appendChild(scriptElement); - break; - case 'standalone': - var frameUrl = ''; - if (platform === 'nds' || core === 'desmume') { - frameUrl = `https://octospacc.gitlab.io/Web-Archives-Misc/Repo/DeSmuME/#RomUrl=${romUrl}`; - } - else if (platform === 'dos') { - frameUrl = `https://gamingshitposting.github.io/ext-bin-1/dos.zone/${data.rom_index}/index.html`; - } - thisElement.outerHTML = diyEmbedHtml(frameUrl); - break; - } + break; +} + })(); diff --git a/assets/js/util.js b/assets/js/util.js new file mode 100644 index 0000000..81a63d0 --- /dev/null +++ b/assets/js/util.js @@ -0,0 +1,13 @@ +(function(){ + +var Util = window.SalaMuseoGames.Util = {}; + +Util.makeElement = (function(tag, attrs){ + return Object.assign(document.createElement('tag'), attrs); +}); + +Util.elementFromHtml = (function(html){ + return Util.makeElement('div', { innerHTML: html.trim() }).children[0]; +}); + +})(); diff --git a/pages/configuration.md b/pages/configuration.md index 7ace519..3c0c8fb 100644 --- a/pages/configuration.md +++ b/pages/configuration.md @@ -20,4 +20,4 @@ All your changes are saved automatically. * Try to load games marked unavailable --> -

Loading...

+

Loading...