diff --git a/main.js b/main.js index 05a42e2..6fb681a 100644 --- a/main.js +++ b/main.js @@ -99,6 +99,19 @@ function endOfComputation() { switchInputs(true); } +if ("serviceWorker" in navigator) { + navigator.serviceWorker.register("workers/service.js").then( + (registration) => { + console.log("Service worker registration successful:", registration); + }, + (error) => { + console.error(`Service worker registration failed: ${error}`); + }, + ); +} else { + console.error("Service workers are not supported."); +} + const expr = document.querySelector("#expr"); let selectionStart = 0; let selectionEnd = 0; diff --git a/workers/service.js b/workers/service.js new file mode 100644 index 0000000..d3e8308 --- /dev/null +++ b/workers/service.js @@ -0,0 +1,60 @@ +/* +Copyright (C) 2025 filifa + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +const VERSION = "v1"; + +const CACHE_NAME = `mcalc-${VERSION}`; + +const APP_STATIC_RESOURCES = [ + "../index.html", + "../legal.html", + "../styles.css", + "../main.js", + "evaluate.js", + "lexer.js", + "math.js", + "parser.js", + "../icon.svg" +]; + +// On install, cache the static resources +self.addEventListener("install", (event) => { + event.waitUntil( + (async () => { + const cache = await caches.open(CACHE_NAME); + cache.addAll(APP_STATIC_RESOURCES); + })(), + ); +}); + +// delete old caches on activate +self.addEventListener("activate", (event) => { + event.waitUntil( + (async () => { + const names = await caches.keys(); + await Promise.all( + names.map((name) => { + if (name !== CACHE_NAME) { + return caches.delete(name); + } + return undefined; + }), + ); + await clients.claim(); + })(), + ); +});