service worker, attempt 1

This commit is contained in:
remi 2022-06-12 00:14:06 +02:00
parent 9fb89f31d5
commit 05623222c8
5 changed files with 174 additions and 30 deletions

View File

@ -40,6 +40,7 @@
<a id="showAllWords">show all words</a> <a id="randomWord">random word</a> <a href="#">resources</a> <a id="showAllWords">show all words</a> <a id="randomWord">random word</a> <a href="#">resources</a>
</div> </div>
<noscript>turn on js doofus</noscript> <noscript>turn on js doofus</noscript>
<span id="update">update available! close all open hisho tabs and reopen hisho to update.</span>
</header> </header>
<main> <main>

View File

@ -160,6 +160,10 @@ header.fullscreen #search {
max-width: 500px; max-width: 500px;
} }
header #update {
display: none;
}
.header-animation { .header-animation {
animation: clearly-cheating 1s ease-in-out; animation: clearly-cheating 1s ease-in-out;
} }

108
main.js
View File

@ -81,7 +81,7 @@ document.addEventListener("keydown", (e) => {
function stripWord(word, space = false) { function stripWord(word, space = false) {
return space == false ? word.replace(/[^a-zA-Z-]/gu, "").toLowerCase() : return space == false ? word.replace(/[^a-zA-Z-]/gu, "").toLowerCase() :
word.replace(/[^a-zA-Z-\s]/gu, "").toLowerCase(); word.replace(/[^a-zA-Z-\s]/gu, "").toLowerCase();
} }
heonianVowels = { heonianVowels = {
@ -200,7 +200,7 @@ function generateRuby(word, addLinks = false) {
} }
} }
} }
return ruby; return ruby;
} }
@ -225,12 +225,12 @@ function loadDictionary() {
//add: romanized word //add: romanized word
searchDictionary[keys[i]].push(stripWord(heonianToRoman(keys[i]))); searchDictionary[keys[i]].push(stripWord(heonianToRoman(keys[i])));
//what if i add it here. //what if i add it here.
searchDictionary[keys[i]].push(stripWord(heonianToRoman(keys[i]).replace("dsh","z"))); searchDictionary[keys[i]].push(stripWord(heonianToRoman(keys[i]).replace("dsh", "z")));
//add: translations, meanings //add: translations, meanings
for (let o = 0; o < values[i].length; o++) { for (let o = 0; o < values[i].length; o++) {
if (values[i][o].hasOwnProperty("translation")){ if (values[i][o].hasOwnProperty("translation")) {
searchDictionary[keys[i]].push(stripWord(values[i][o]["translation"], true)) searchDictionary[keys[i]].push(stripWord(values[i][o]["translation"], true))
}; };
if (values[i][o].hasOwnProperty("meaning")) searchDictionary[keys[i]].push(stripWord(values[i][o]["meaning"], true)); if (values[i][o].hasOwnProperty("meaning")) searchDictionary[keys[i]].push(stripWord(values[i][o]["meaning"], true));
} }
@ -251,7 +251,7 @@ function loadDictionary() {
function search(word, type) { function search(word, type) {
console.log(type); console.log(type);
if (type == "all") {word = ""}; if (type == "all") { word = "" };
if (type == "random") { if (type == "random") {
let random = Math.floor(Math.random() * Object.keys(json).length); let random = Math.floor(Math.random() * Object.keys(json).length);
return [Object.keys(json)[random]]; return [Object.keys(json)[random]];
@ -365,7 +365,7 @@ function doSearch(state = true) {
let meaning = document.createElement("div"); let meaning = document.createElement("div");
meaning.classList.add("result-meaning"); meaning.classList.add("result-meaning");
//ripping off jisho: Bold, word type (*required) //ripping off jisho: Bold, word type (*required)
if (last != json[results[i]][o]["type"]) meaning.innerHTML += "<b class='capitalize'>"+json[results[i]][o]["type"]+"</b><br>"; if (last != json[results[i]][o]["type"]) meaning.innerHTML += "<b class='capitalize'>" + json[results[i]][o]["type"] + "</b><br>";
last = json[results[i]][o]["type"]; last = json[results[i]][o]["type"];
if (types[json[results[i]][o]["type"]] == undefined) { if (types[json[results[i]][o]["type"]] == undefined) {
types[json[results[i]][o]["type"]] = 1; types[json[results[i]][o]["type"]] = 1;
@ -373,17 +373,17 @@ function doSearch(state = true) {
types[json[results[i]][o]["type"]]++; types[json[results[i]][o]["type"]]++;
} }
//number, meaning (*required) //number, meaning (*required)
meaning.innerHTML += "<span class='result-number'>"+(o+1)+"</span><span class='result-big'>"+json[results[i]][o]["meaning"]+"</span>"; meaning.innerHTML += "<span class='result-number'>" + (o + 1) + "</span><span class='result-big'>" + json[results[i]][o]["meaning"] + "</span>";
//longer translation (below are not required, make sure to check for them) //longer translation (below are not required, make sure to check for them)
if (json[results[i]][o]["translation"] != undefined && json[results[i]][o]["translation"].toLowerCase() != json[results[i]][o]["meaning"].toLowerCase()) { if (json[results[i]][o]["translation"] != undefined && json[results[i]][o]["translation"].toLowerCase() != json[results[i]][o]["meaning"].toLowerCase()) {
meaning.innerHTML += "<br><span class='result-translation'>"+json[results[i]][o]["translation"]+"</span>"; meaning.innerHTML += "<br><span class='result-translation'>" + json[results[i]][o]["translation"] + "</span>";
} }
//example //example
if (json[results[i]][o]["examples"] != undefined) { if (json[results[i]][o]["examples"] != undefined) {
let temp = "" let temp = ""
temp += "<details><summary>Examples</summary><p>"; temp += "<details><summary>Examples</summary><p>";
for (let e in json[results[i]][o]["examples"]) { for (let e in json[results[i]][o]["examples"]) {
temp += "<span class='heonian'>"+generateRuby(e, true)+"</span> - "+json[results[i]][o]["examples"][e]+"<br>"; temp += "<span class='heonian'>" + generateRuby(e, true) + "</span> - " + json[results[i]][o]["examples"][e] + "<br>";
} }
temp += "</p></details>"; temp += "</p></details>";
meaning.innerHTML += temp; meaning.innerHTML += temp;
@ -394,7 +394,7 @@ function doSearch(state = true) {
temp += "<details class='result-nyms'><summary>Antonyms</summary><p>"; temp += "<details class='result-nyms'><summary>Antonyms</summary><p>";
for (let e in json[results[i]][o]["antonyms"]) { for (let e in json[results[i]][o]["antonyms"]) {
let r = json[results[i]][o]["antonyms"][e]; let r = json[results[i]][o]["antonyms"][e];
temp += "<span class='heonian'>"+generateRuby(r, true); temp += "<span class='heonian'>" + generateRuby(r, true);
if (json[r] != undefined) { if (json[r] != undefined) {
temp += " - "; temp += " - ";
for (let i in json[r]) { for (let i in json[r]) {
@ -412,7 +412,7 @@ function doSearch(state = true) {
temp += "<details class='result-nyms'><summary>Synonyms</summary><p>"; temp += "<details class='result-nyms'><summary>Synonyms</summary><p>";
for (let e in json[results[i]][o]["synonyms"]) { for (let e in json[results[i]][o]["synonyms"]) {
let r = json[results[i]][o]["synonyms"][e]; let r = json[results[i]][o]["synonyms"][e];
temp += "<span class='heonian'>"+generateRuby(r, true); temp += "<span class='heonian'>" + generateRuby(r, true);
if (json[r] != undefined) { if (json[r] != undefined) {
temp += " - "; temp += " - ";
for (let i in json[r]) { for (let i in json[r]) {
@ -427,14 +427,14 @@ function doSearch(state = true) {
} }
//notes //notes
if (json[results[i]][o]["notes"] != undefined) { if (json[results[i]][o]["notes"] != undefined) {
meaning.innerHTML += "<p class='result-notes'>"+json[results[i]][o]["notes"]+"</p>"; meaning.innerHTML += "<p class='result-notes'>" + json[results[i]][o]["notes"] + "</p>";
} }
//(source, etc) //(source, etc)
if (json[results[i]][o]["canon-etymology"] != undefined) { if (json[results[i]][o]["canon-etymology"] != undefined) {
meaning.innerHTML += "<details class='result-meta'><summary>Canon Etymology</summary><p>"+json[results[i]][o]["canon-etymology"]+"</p></details>"; meaning.innerHTML += "<details class='result-meta'><summary>Canon Etymology</summary><p>" + json[results[i]][o]["canon-etymology"] + "</p></details>";
} }
if (json[results[i]][o]["meta-etymology"] != undefined) { if (json[results[i]][o]["meta-etymology"] != undefined) {
meaning.innerHTML += "<details class='result-meta'><summary>Meta Etymology</summary><p>"+json[results[i]][o]["meta-etymology"]+"</p></details>"; meaning.innerHTML += "<details class='result-meta'><summary>Meta Etymology</summary><p>" + json[results[i]][o]["meta-etymology"] + "</p></details>";
} }
//todo //todo
result.appendChild(meaning); //y, yeah. result.appendChild(meaning); //y, yeah.
@ -445,22 +445,22 @@ function doSearch(state = true) {
let header = document.createElement("div"); let header = document.createElement("div");
header.classList.add("results-header"); header.classList.add("results-header");
//When using search methods, accomodate search text. //When using search methods, accomodate search text.
switch(type) { switch (type) {
//show:all //show:all
case "all": case "all":
val = "Showing all words"; val = "Showing all words";
break; break;
case "random": case "random":
val = "Showing random word: " + results[0]; val = "Showing random word: " + results[0];
break; break;
//OMG A WORD //OMG A WORD
default: default:
val = "search results for: " + val; val = "search results for: " + val;
break; break;
} }
header.innerHTML += "<span class='heonian'>" + val + "</span><br>"; header.innerHTML += "<span class='heonian'>" + val + "</span><br>";
for (let i in types) { for (let i in types) {
if(i !== ""){header.innerHTML += "<span class='results-header-count'>"+i+"s - "+types[i]+"</span>";} if (i !== "") { header.innerHTML += "<span class='results-header-count'>" + i + "s - " + types[i] + "</span>"; }
} }
main.prepend(header); main.prepend(header);
} }
@ -476,10 +476,57 @@ function goHome(state = true) {
if (state == true) history.pushState(null, "", url); if (state == true) history.pushState(null, "", url);
} }
async function registerSW() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js').then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
header.querySelector("#update").style.display = "block";
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
}).catch(error => {
console.error('Error during service worker registration:', error);
});
}
}
function removeSW() {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
for(let registration of registrations) {
registration.unregister()
}}); //dev use only!! or whatever... i just copypasted this from SO
}
window.onload = () => { window.onload = () => {
header = document.querySelector("header"); header = document.querySelector("header");
main = document.querySelector("main"); main = document.querySelector("main");
header.querySelector("#search button").onclick = () => {toggleIME();}; header.querySelector("#search button").onclick = () => { toggleIME(); };
header.querySelector("span.heonian").onclick = () => { header.querySelector("span.heonian").onclick = () => {
if (!header.classList.contains("fullscreen")) { if (!header.classList.contains("fullscreen")) {
goHome(); goHome();
@ -513,7 +560,8 @@ window.onload = () => {
doSearch(false); doSearch(false);
} }
}); });
//also check if ?s is there . for hecks sake (todo) registerSW();
//also check if ?s is there . for hecks sake (todo) (TODO!!!!!!)
} }
const sortObject = obj => Object.keys(obj).sort().reduce((res, key) => (res[key] = obj[key], res), {}) const sortObject = obj => Object.keys(obj).sort().reduce((res, key) => (res[key] = obj[key], res), {})

91
sw.js Normal file
View File

@ -0,0 +1,91 @@
const currentVersion = 'v1';
const addResourcesToCache = async (resources) => {
const cache = await caches.open(currentVersion);
await cache.addAll(resources);
};
const putInCache = async (request, response) => {
const cache = await caches.open(currentVersion);
await cache.put(request, response);
};
const cacheFirst = async ({ request, preloadResponsePromise }) => {
// First try to get the resource from the cache
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
// Next try to use the preloaded response, if it's there
const preloadResponse = await preloadResponsePromise;
if (preloadResponse) {
console.info('using preload response', preloadResponse);
putInCache(request, preloadResponse.clone());
return preloadResponse;
}
// Next try to get the resource from the network
try {
const responseFromNetwork = await fetch(request);
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
putInCache(request, responseFromNetwork.clone());
return responseFromNetwork;
} catch (error) {
return new Response('Network error happened', {
status: 408,
headers: { 'Content-Type': 'text/plain' },
});
}
};
const deleteCache = async key => {
await caches.delete(key)
}
const deleteOldCaches = async () => {
const cacheKeepList = [currentVersion];
const keyList = await caches.keys()
const cachesToDelete = keyList.filter(key => !cacheKeepList.includes(key))
await Promise.all(cachesToDelete.map(deleteCache));
}
self.addEventListener('activate', (event) => {
event.waitUntil(deleteOldCaches());
});
const enableNavigationPreload = async () => {
if (self.registration.navigationPreload) {
// Enable navigation preloads!
await self.registration.navigationPreload.enable();
}
};
self.addEventListener('activate', (event) => {
event.waitUntil(enableNavigationPreload());
});
self.addEventListener('install', (event) => {
event.waitUntil(
addResourcesToCache([
'./heonian-resources/wordlist.json',
'./heonian-ime/ime.js',
'./font.otf',
'./index.html',
'./main.css',
'./main.js',
'./manifest.json'
])
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
cacheFirst({
request: event.request,
preloadResponsePromise: event.preloadResponse
})
);
});

BIN
temp.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB