Skip to content

Commit

Permalink
Merge pull request #29 from khusika/pwa
Browse files Browse the repository at this point in the history
PWA integration
  • Loading branch information
Khusika Dhamar Gusti authored Jul 11, 2021
2 parents 3b90474 + 98592e1 commit afccab3
Show file tree
Hide file tree
Showing 24 changed files with 411 additions and 51 deletions.
1 change: 1 addition & 0 deletions assets/css/_page/_404.scss
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
font-weight: 900;
color: $global-font-color;
letter-spacing: 1rem;
text-transform: uppercase;
margin-bottom: 5rem;
[theme=dark] & {
color: $global-font-color-dark;
Expand Down
244 changes: 244 additions & 0 deletions assets/sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
const CACHE_VERSION = new URL(location).searchParams.get("version");
const BASE_CACHE_FILES = ["/css/home.min.css", "/css/page.min.css", "/js/themes.min.js", "/site.webmanifest", "/404.html"];
const OFFLINE_CACHE_FILES = ["/css/page.min.css", "/js/themes.min.js", "/offline/index.html"];
const NOT_FOUND_CACHE_FILES = ["/css/page.min.css", "/js/themes.min.js", "/404.html"];
const OFFLINE_PAGE = "/offline/index.html";
const NOT_FOUND_PAGE = "/404.html";

const CACHE_VERSIONS = {
assets: "assets-v" + CACHE_VERSION,
content: "content-v" + CACHE_VERSION,
offline: "offline-v" + CACHE_VERSION,
notFound: "404-v" + CACHE_VERSION,
};

const MAX_TTL = {
"/": 3600,
html: 3600,
json: 86400,
js: 86400,
css: 86400,
};

const CACHE_BLACKLIST = [
(str) => {
return !str.startsWith("http://localhost");
},
];

const SUPPORTED_METHODS = ["GET"];

function isBlacklisted(url) {
return CACHE_BLACKLIST.length > 0
? !CACHE_BLACKLIST.filter((rule) => {
if (typeof rule === "function") {
return !rule(url);
} else {
return false;
}
}).length
: false;
}

function getFileExtension(url) {
let extension = url.split(".").reverse()[0].split("?")[0];
return extension.endsWith("/") ? "/" : extension;
}

function getTTL(url) {
if (typeof url === "string") {
let extension = getFileExtension(url);
if (typeof MAX_TTL[extension] === "number") {
return MAX_TTL[extension];
} else {
return null;
}
} else {
return null;
}
}

function installServiceWorker() {
return Promise.all([
caches.open(CACHE_VERSIONS.assets).then((cache) => {
return cache.addAll(BASE_CACHE_FILES);
}),
caches.open(CACHE_VERSIONS.offline).then((cache) => {
return cache.addAll(OFFLINE_CACHE_FILES);
}),
caches.open(CACHE_VERSIONS.notFound).then((cache) => {
return cache.addAll(NOT_FOUND_CACHE_FILES);
}),
]).then(() => {
return self.skipWaiting();
});
}

function cleanupLegacyCache() {
let currentCaches = Object.keys(CACHE_VERSIONS).map((key) => {
return CACHE_VERSIONS[key];
});

return new Promise((resolve, reject) => {
caches
.keys()
.then((keys) => {
return (legacyKeys = keys.filter((key) => {
return !~currentCaches.indexOf(key);
}));
})
.then((legacy) => {
if (legacy.length) {
Promise.all(
legacy.map((legacyKey) => {
return caches.delete(legacyKey);
})
)
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});
} else {
resolve();
}
})
.catch(() => {
reject();
});
});
}

function precacheUrl(url) {
if (!isBlacklisted(url)) {
caches.open(CACHE_VERSIONS.content).then((cache) => {
cache
.match(url)
.then((response) => {
if (!response) {
return fetch(url);
} else {
return null;
}
})
.then((response) => {
if (response) {
return cache.put(url, response.clone());
} else {
return null;
}
});
});
}
}

self.addEventListener("install", (event) => {
event.waitUntil(Promise.all([installServiceWorker(), self.skipWaiting()]));
});

self.addEventListener("activate", (event) => {
event.waitUntil(
Promise.all([cleanupLegacyCache(), self.clients.claim(), self.skipWaiting()]).catch((err) => {
event.skipWaiting();
})
);
});

self.addEventListener("fetch", (event) => {
event.respondWith(
caches.open(CACHE_VERSIONS.content).then((cache) => {
return cache
.match(event.request)
.then((response) => {
if (response) {
let headers = response.headers.entries();
let date = null;

for (let pair of headers) {
if (pair[0] === "date") {
date = new Date(pair[1]);
}
}

if (date) {
let age = parseInt((new Date().getTime() - date.getTime()) / 1000);
let ttl = getTTL(event.request.url);

if (ttl && age > ttl) {
return new Promise((resolve) => {
return fetch(event.request.clone())
.then((updatedResponse) => {
if (updatedResponse) {
cache.put(event.request, updatedResponse.clone());
resolve(updatedResponse);
} else {
resolve(response);
}
})
.catch(() => {
resolve(response);
});
}).catch((err) => {
return response;
});
} else {
return response;
}
} else {
return response;
}
} else {
return null;
}
})
.then((response) => {
if (response) {
return response;
} else {
return fetch(event.request.clone())
.then((response) => {
if (response.status < 400) {
if (~SUPPORTED_METHODS.indexOf(event.request.method) && !isBlacklisted(event.request.url)) {
cache.put(event.request, response.clone());
}
return response;
} else {
return caches.open(CACHE_VERSIONS.notFound).then((cache) => {
return cache.match(NOT_FOUND_PAGE);
});
}
})
.then((response) => {
if (response) {
return response;
}
})
.catch(() => {
return caches.open(CACHE_VERSIONS.offline).then((offlineCache) => {
return offlineCache.match(OFFLINE_PAGE);
});
});
}
})
.catch((error) => {
console.error(" Error in fetch handler:", error);
throw error;
});
})
);
});

self.addEventListener("message", (event) => {
if (typeof event.data === "object" && typeof event.data.action === "string") {
switch (event.data.action) {
case "cache":
precacheUrl(event.data.url);
break;
default:
console.log("Unknown action: " + event.data.action);
break;
}
}
});

5 changes: 5 additions & 0 deletions content/offline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
title: "Offline"
draft: false
offline: true
---
7 changes: 7 additions & 0 deletions exampleSite/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,13 @@ ignoreErrors = ["err-missing-comment-accesstoken", "err-missing-oembed-accesstok
# whether to enable CSS and JS source mapping
SourceMap = false

# PWA config
[params.pwa]
# whether to enable PWA support
enable = true
# service-worker version
version = "1.0.0"

# Header config
# 页面头部导航栏配置
[params.header]
Expand Down
11 changes: 7 additions & 4 deletions exampleSite/static/site.webmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
"start_url": "/",
"display": "standalone",
"orientation" : "portrait",
"background_color": "#FFFFFF",
"theme_color": "#FFFFFF"
}
5 changes: 5 additions & 0 deletions i18n/de.toml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ other = "Seite nicht gefunden"
other = "Leider konnte die von Ihnen angeforderte Seite nicht aufgerufen werden."
# === 404.html ===

# === Offline Page ===
[pageOffline]
other = "Sie sind offline. Prüfe deine Internetverbindung."
# === Offline Page ===

# === shortcodes/admonition.html ===
[note]
other = "Notiz"
Expand Down
5 changes: 5 additions & 0 deletions i18n/en.toml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ other = "Page not found"
other = "The page you're looking for doesn't exist. Sorry."
# === 404.html ===

# === Offline Page ===
[pageOffline]
other = "You're offline. Check your internet connection."
# === Offline Page ===

# === shortcodes/admonition.html ===
[note]
other = "Note"
Expand Down
5 changes: 5 additions & 0 deletions i18n/es.toml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ other = "Página no encontrada"
other = "La página que estás buscando no existe. Lo siento."
# === 404.html ===

# === Offline Page ===
[pageOffline]
other = "Estás desconectado. Comprueba tu conexión a Internet."
# === Offline Page ===

# === shortcodes/admonition.html ===
[note]
other = "Nota"
Expand Down
5 changes: 5 additions & 0 deletions i18n/fr.toml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ other = "Page non trouvée"
other = "Désolé, la page recherchée n'existe pas."
# === 404.html ===

# === Offline Page ===
[pageOffline]
other = "Tu es hors ligne. Vérifiez votre connection internet."
# === Offline Page ===

# === shortcodes/admonition.html ===
[note]
other = "Remarque"
Expand Down
5 changes: 5 additions & 0 deletions i18n/id.toml
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ other = "Halaman tidak ditemukan"
other = "Maaf, halaman yang Anda cari tidak ada."
# === 404.html ===

# === Offline Page ===
[pageOffline]
other = "Anda sedang offline. Periksa koneksi internet Anda."
# === Offline Page ===

# === shortcodes/admonition.html ===
[note]
other = "Catatan"
Expand Down
5 changes: 5 additions & 0 deletions i18n/it.toml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ other = "Pagina non trovata"
other = "Mi spiace, la pagina cercata non esiste."
# === 404.html ===

# === Offline Page ===
[pageOffline]
other = "Sei offline. Controlla la tua connessione Internet."
# === Offline Page ===

# === shortcodes/admonition.html ===
[note]
other = "Note"
Expand Down
5 changes: 5 additions & 0 deletions i18n/pl.toml
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@ other = "Nie znaleziono strony"
other = "Wybacz, chyba coś namieszaliśmy."
# === 404.html ===

# === Offline Page ===
[pageOffline]
other = "Jesteś offline. Sprawdź swoje łącze internetowe."
# === Offline Page ===

# === shortcodes/admonition.html ===
[note]
other = "Notka"
Expand Down
5 changes: 5 additions & 0 deletions i18n/pt-BR.toml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ other = "Página não encontrada"
other = "A página que você procura não existe. Desculpe"
# === 404.html ===

# === Offline Page ===
[pageOffline]
other = "Você está offline. Verifique sua conexão com a internet."
# === Offline Page ===

# === shortcodes/admonition.html ===
[note]
other = "Nota"
Expand Down
Loading

0 comments on commit afccab3

Please sign in to comment.