Caching service worker (#794)

* register service worker

* versioning code

* cleanup

* cache in Prod only
This commit is contained in:
Azgaar 2022-05-09 17:50:07 +03:00 committed by GitHub
parent 02e0669282
commit f5cb800295
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 155 additions and 51 deletions

View file

@ -15,6 +15,7 @@
<link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" />
<link rel="canonical" href="https://azgaar.github.io/Fantasy-Map-Generator/" />
<!-- inline css for loading screen -->
<style type="text/css">
body {
margin: 0;
@ -70,7 +71,7 @@
font-size: 7em;
margin: -12px 0 -6px 0;
}
#version {
#versionText {
text-align: right;
font-size: 2em;
margin-right: 3%;
@ -274,7 +275,7 @@
<div id="loading">
<div id="titleName"><t data-t="titleName">Azgaar's</t></div>
<div id="title"><t data-t="title">Fantasy Map Generator</t></div>
<div id="version"><t data-t="version">v. </t>1.8</div>
<div id="versionText"><t data-t="version">v. </t><span id="version"></span></div>
<p id="loading-text"><t data-t="loading">LOADING</t><span>.</span><span>.</span><span>.</span></p>
</div>
@ -6238,8 +6239,10 @@
</g>
</defs>
</svg>
<script src="libs/jquery-3.1.1.min.js"></script>
<script src="libs/jquery-ui.min.js"></script>
<script src="versioning.js"></script>
<script src="libs/d3.min.js"></script>
<script src="libs/priority-queue.min.js"></script>
<script src="libs/delaunator.min.js"></script>
@ -6272,13 +6275,11 @@
<script src="modules/submap.js"></script>
<script src="libs/polylabel.min.js"></script>
<script src="libs/lineclip.min.js"></script>
<script src="libs/jquery-ui.min.js"></script>
<script src="libs/alea.min.js"></script>
<script src="modules/fonts.js"></script>
<script src="modules/ui/layers.js"></script>
<script src="modules/ui/measurers.js"></script>
<script src="modules/ui/stylePresets.js"></script>
<!-- <script src="libs/umami.js"></script> -->
<script src="modules/ui/general.js"></script>
<script src="modules/ui/options.js"></script>

54
main.js
View file

@ -2,10 +2,7 @@
// https://github.com/Azgaar/Fantasy-Map-Generator
"use strict";
const version = "1.8"; // generator version
document.title += " v" + version;
// switches to disable/enable logging features
// set debug options
const PRODUCTION = location.hostname && location.hostname !== "localhost" && location.hostname !== "127.0.0.1";
const DEBUG = localStorage.getItem("debug");
const INFO = DEBUG || !PRODUCTION;
@ -13,10 +10,13 @@ const TIME = DEBUG || !PRODUCTION;
const WARN = true;
const ERROR = true;
// if map version is not stored, clear localStorage and show a message
if (rn(localStorage.getItem("version"), 1) !== rn(version, 1)) {
localStorage.clear();
setTimeout(showWelcomeMessage, 8000);
// register service worker responsible for caching
if (PRODUCTION && "serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("/sw.js").catch(err => {
console.error("ServiceWorker registration failed: ", err);
});
});
}
// append svg layers (in default order)
@ -449,44 +449,6 @@ function applyDefaultBiomesSystem() {
return {i: d3.range(0, name.length), name, color, biomesMartix, habitability, iconsDensity, icons, cost};
}
function showWelcomeMessage() {
const changelog = link("https://github.com/Azgaar/Fantasy-Map-Generator/wiki/Changelog", "previous versions");
const reddit = link("https://www.reddit.com/r/FantasyMapGenerator", "Reddit community");
const discord = link("https://discordapp.com/invite/X7E84HU", "Discord server");
const patreon = link("https://www.patreon.com/azgaar", "Patreon");
alertMessage.innerHTML = /* html */ `The Fantasy Map Generator is updated up to version <strong>${version}</strong>. This version is compatible with ${changelog},
loaded <i>.map</i> files will be auto-updated.
<ul>
<strong>Latest changes:</strong>
<li>Submap tool by Goteguru</li>
<li>Resample tool by Goteguru</li>
<li>Pre-defined heightmaps</li>
<li>Advanced notes editor</li>
<li>Zones editor: filter by type</li>
<li>Color picker: new hatchings</li>
<li>New style presets: Cyberpunk and Atlas</li>
<li>Burg temperature graph</li>
<li>4 new textures</li>
</ul>
<p>Join our ${discord} and ${reddit} to ask questions, share maps, discuss the Generator and Worlbuilding, report bugs and propose new features.</p>
<span><i>Thanks for all supporters on ${patreon}!</i></span>`;
$("#alert").dialog({
resizable: false,
title: "Fantasy Map Generator update",
width: "28em",
buttons: {
OK: function () {
$(this).dialog("close");
}
},
position: {my: "center center-4em", at: "center", of: "svg"},
close: () => localStorage.setItem("version", version)
});
}
function doWorkOnZoom(isScaleChanged, isPositionChanged) {
viewbox.attr("transform", `translate(${viewX} ${viewY}) scale(${scale})`);

68
sw.js Normal file
View file

@ -0,0 +1,68 @@
importScripts("https://storage.googleapis.com/workbox-cdn/releases/6.2.0/workbox-sw.js");
const {Route, registerRoute} = workbox.routing;
const {CacheFirst} = workbox.strategies;
const {CacheableResponsePlugin} = workbox.cacheableResponse;
const {ExpirationPlugin} = workbox.expiration;
const DAY = 24 * 60 * 60;
const getPolitics = ({entries, days}) => {
return [new CacheableResponsePlugin({statuses: [200]}), new ExpirationPlugin({maxEntries: entries, maxAgeSeconds: days * DAY})];
};
registerRoute(
({request, url}) => request.destination === "script" && !url.pathname.endsWith("min.js") && !url.pathname.includes("versioning.js"),
new CacheFirst({
cacheName: "fmg-scripts",
plugins: getPolitics({entries: 100, days: 30})
})
);
registerRoute(
({request}) => request.destination === "style",
new CacheFirst({
cacheName: "fmg-stylesheets",
plugins: getPolitics({entries: 100, days: 30})
})
);
registerRoute(
({request, url}) => request.destination === "script" && url.pathname.endsWith("min.js"),
new CacheFirst({
cacheName: "fmg-libs",
plugins: getPolitics({entries: 100, days: 30})
})
);
registerRoute(
new RegExp(".json$"),
new CacheFirst({
cacheName: "fmg-json",
plugins: getPolitics({entries: 100, days: 30})
})
);
registerRoute(
({request}) => request.destination === "image",
new CacheFirst({
cacheName: "fmg-images",
plugins: getPolitics({entries: 1000, days: 30})
})
);
registerRoute(
new RegExp(".svg$"),
new CacheFirst({
cacheName: "fmg-charges",
plugins: getPolitics({entries: 1000, days: 30})
})
);
registerRoute(
({request}) => request.destination === "font",
new CacheFirst({
cacheName: "fmg-fonts",
plugins: getPolitics({entries: 200, days: 30})
})
);

73
versioning.js Normal file
View file

@ -0,0 +1,73 @@
"use strict";
// version and caching control
const version = "1.81"; // generator version, update each time
{
document.title += " v" + version;
const loadingScreenVersion = document.getElementById("version");
if (loadingScreenVersion) loadingScreenVersion.innerHTML = version;
const majorVersion = Math.round(version * 10) / 10;
const storedVersion = +localStorage.getItem("version") || 0;
const showUpdate = storedVersion < majorVersion;
if (showUpdate) setTimeout(showUpdateWindow, 5000);
function showUpdateWindow() {
const changelog = "https://github.com/Azgaar/Fantasy-Map-Generator/wiki/Changelog";
const reddit = "https://www.reddit.com/r/FantasyMapGenerator";
const discord = "https://discordapp.com/invite/X7E84HU";
const patreon = "https://www.patreon.com/azgaar";
alertMessage.innerHTML = /* html */ `The Fantasy Map Generator is updated up to version <strong>${version}</strong>. This version is compatible with <a href="${changelog}" target="_blank">previous versions</a>, loaded <i>.map</i> files will be auto-updated.
${storedVersion ? "<span>Reload the page to fetch fresh code.</span>" : ""}
<ul>
<strong>Latest changes:</strong>
<li>Caching for faster startup</li>
<li>Submap tool by Goteguru</li>
<li>Resample tool by Goteguru</li>
<li>Pre-defined heightmaps</li>
<li>Advanced notes editor</li>
<li>Zones editor: filter by type</li>
<li>Color picker: new hatchings</li>
<li>New style presets: Cyberpunk and Atlas</li>
<li>Burg temperature graph</li>
<li>4 new textures</li>
</ul>
<p>Join our <a href="${discord}" target="_blank">Discord server</a> and <a href="${reddit}" target="_blank">Reddit community</a> to ask questions, share maps, discuss the Generator and Worlbuilding, report bugs and propose new features.</p>
<span><i>Thanks for all supporters on <a href="${patreon}" target="_blank">Patreon</a>!</i></span>`;
const buttons = {
Ok: function () {
$(this).dialog("close");
if (storedVersion) clearStoredData();
}
};
if (storedVersion) {
buttons.Reload = () => {
clearStoredData();
location.reload();
};
}
$("#alert").dialog({
resizable: false,
title: "Fantasy Map Generator update",
width: "28em",
position: {my: "center center-4em", at: "center", of: "svg"},
buttons
});
}
async function clearStoredData() {
localStorage.clear();
localStorage.setItem("version", version);
const cacheNames = await caches.keys();
Promise.all(cacheNames.map(cacheName => caches.delete(cacheName)));
}
}