Skip to content

Commit

Permalink
feat(PWA): add Service Worker update notification
Browse files Browse the repository at this point in the history
  • Loading branch information
cotes2020 committed Jun 4, 2022
1 parent 54124d5 commit d127183
Show file tree
Hide file tree
Showing 15 changed files with 199 additions and 44 deletions.
4 changes: 4 additions & 0 deletions _data/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Powered by :PLATFORM with :THEME theme.
not_found:
statment: Sorry, we've misplaced that URL or it's pointing to something that doesn't exist.

notification:
update_found: A new version of content is available.
update: Update

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/es-ES.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Hecho con :PLATFORM usando el tema :THEME.
not_found:
statment: Lo sentimos, hemos perdido esa URL o apunta a algo que no existe.

notification:
update_found: Hay una nueva versión de contenido disponible.
update: Actualizar

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/fr-FR.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Propulsé par :PLATFORM avec le thème :THEME
not_found:
statment: Désolé, nous avons égaré cette URL ou elle pointe vers quelque chose qui n'existe pas.

notification:
update_found: Une nouvelle version du contenu est disponible.
update: Mise à jour

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/id-ID.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Didukung oleh :PLATFORM dengan tema :THEME.
not_found:
statment: Maaf, kami gagal menemukan URL itu atau memang mengarah ke sesuatu yang tidak ada.

notification:
update_found: Versi konten baru tersedia.
update: Perbarui

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/ko-KR.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Powered by :PLATFORM with :THEME theme.
not_found:
statment: 해당 URL은 존재하지 않습니다.

notification:
update_found: 새 버전의 콘텐츠를 사용할 수 있습니다.
update: 업데이트

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/my-MM.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Powered by :PLATFORM with :THEME theme.
not_found:
statment: ဝမ်းနည်းပါသည်၊ ကျွန်ုပ်တို့သည် အဆိုပါ URL ကို မှားယွင်းစွာ နေရာချထားခြင်း သို့မဟုတ် ၎င်းသည် မရှိသောအရာကို ညွှန်ပြနေပါသည်။

notification:
update_found: အကြောင်းအရာဗားရှင်းအသစ်ကို ရနိုင်ပါပြီ။
update: အပ်ဒိတ်

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/pt-BR.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Feito com :PLATFORM usando o tema :THEME.
not_found:
statment: Desculpe, a página não foi encontrada.

notification:
update_found: Uma nova versão do conteúdo está disponível.
update: atualização

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/ru-RU.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Powered by :PLATFORM with :THEME theme.
not_found:
statment: Извините, эта ссылка указывает на ресурс который не существует.

notification:
update_found: Доступна новая версия контента.
update: Обновлять

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/uk-UA.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ meta: Powered by :PLATFORM with :THEME theme.
not_found:
statment: Вибачте, це посилання вказує на ресурс, що не існує.

notification:
update_found: Доступна нова версія вмісту.
update: Оновлення

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/vi-VN.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ meta: Trang web này được tạo bởi :PLATFORM với chủ đề :THEME.
not_found:
statment: Xin lỗi, chúng tôi đã đặt nhầm URL hoặc đường dẫn trỏ đến một trang nào đó không tồn tại.

notification:
update_found: Đã có phiên bản mới của nội dung.
update: Cập nhật

# ----- Posts related labels -----

post:
Expand Down
4 changes: 4 additions & 0 deletions _data/locales/zh-CN.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ meta: 本站由 :PLATFORM 生成,采用 :THEME 主题。
not_found:
statment: 抱歉,我们放错了该 URL,或者它指向了不存在的内容。

notification:
update_found: 发现新版本的内容。
update: 更新

# ----- Posts related labels -----

post:
Expand Down
15 changes: 15 additions & 0 deletions _layouts/default.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,21 @@
<i class="fas fa-angle-up"></i>
</a>

<div id="notification" class="toast" role="alert" aria-live="assertive" aria-atomic="true"
data-animation="true" data-autohide="false">
<div class="toast-header">
<button type="button" class="ml-2 ml-auto close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="toast-body text-center pt-0">
<p class="pl-2 pr-2 mb-3">{{ site.data.locales[lang].notification.update_found }}</p>
<button type="button" class="btn btn-primary" aria-label="Update">
{{ site.data.locales[lang].notification.update }}
</button>
</div>
</div>

{% include search-loader.html %}

{% include js-selector.html %}
Expand Down
45 changes: 45 additions & 0 deletions _sass/addon/commons.scss
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,51 @@ $sidebar-display: "sidebar-display";
-webkit-transform: translate3d(0, -5px, 0);
}

#notification {
@keyframes popup {
from {
opacity: 0;
bottom: 0;
}
}

.toast-header {
background: none;
border-bottom: none;
color: inherit;
}

.toast-body {
font-family: 'Lato';
line-height: 1.25rem;

button {
font-size: 90%;
min-width: 4rem;
}
}

&.toast {
display: none;

&.show {
display: block;
min-width: 20rem;
border-radius: 0.5rem;
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
background-color: rgba(255, 255, 255, 0.5);
color: #1b1b1eba;
position: fixed;
left: 50%;
bottom: 20%;
transform: translateX(-50%);
animation: popup 0.8s;
}
}

}

/*
Responsive Design:
Expand Down
57 changes: 53 additions & 4 deletions assets/js/pwa/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,56 @@ layout: compress
permalink: '/app.js'
---

/* Registering Service Worker */
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('{{ "/sw.js" | relative_url }}');
};
const keyWaiting = 'sw-waiting';
const $notification = $('#notification');
const $btnRefresh = $('#notification .toast-body>button');

function skipWating(registration) {
registration.waiting.postMessage('SKIP_WAITING');
localStorage.removeItem(keyWaiting);
}

if ('serviceWorker' in navigator) {
/* Registering Service Worker */
navigator.serviceWorker.register('{{ "/sw.js" | relative_url }}')
.then(registration => {
if (registration) {
registration.addEventListener('updatefound', () => {
/* console.log('updatefound'); */
let serviceWorker = registration.installing;

serviceWorker.addEventListener('statechange', () => {
/* console.log(`statechange -> ${serviceWorker.state}`); */
if (serviceWorker.state === 'installed') {
/* console.log('installed'); */
if (navigator.serviceWorker.controller) {
$notification.toast('show');
/* in case the user ignores the notification */
localStorage.setItem(keyWaiting, true);
}
}
});
});

$btnRefresh.click(() => {
skipWating(registration);
$notification.toast('hide');
});

/* there's a new Service Worker waiting to be activated */
if (localStorage.getItem(keyWaiting)) {
$notification.toast('show');
}
}
});

let refreshing = false;

/* Detect controller change and refresh all the opened tabs */
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (!refreshing) {
window.location.reload();
refreshing = true;
}
});
}
82 changes: 42 additions & 40 deletions assets/js/pwa/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ permalink: '/sw.js'

self.importScripts('{{ "/assets/js/data/swcache.js" | relative_url }}');

const cacheName = 'chirpy-{{ "now" | date: "%Y%m%d.%H%M" }}';
const cacheName = 'chirpy-{{ "now" | date: "%Y%m%d.%H%M%S" }}';

function verifyDomain(url) {
for (const domain of allowedDomains) {
Expand All @@ -28,60 +28,62 @@ function isExcluded(url) {
return false;
}

self.addEventListener('install', e => {
self.skipWaiting();
e.waitUntil(
self.addEventListener('install', event => {
event.waitUntil(
caches.open(cacheName).then(cache => {
return cache.addAll(resource);
})
);
});

self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keyList => {
return Promise.all(
keyList.map(key => {
if (key !== cacheName) {
return caches.delete(key);
}
})
);
})
);
});

self.addEventListener('message', (event) => {
if (event.data === 'SKIP_WAITING') {
self.skipWaiting();
}
});

self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
return response;
}
caches.match(event.request).then(response => {
if (response) {
return response;
}

return fetch(event.request)
.then(response => {
const url = event.request.url;
return fetch(event.request).then(response => {
const url = event.request.url;

if (event.request.method !== 'GET' ||
if (event.request.method !== 'GET' ||
!verifyDomain(url) ||
isExcluded(url)) {
return response;
}

/*
see: <https://developers.google.com/web/fundamentals/primers/service-workers#cache_and_return_requests>
*/
let responseToCache = response.clone();
return response;
}

caches.open(cacheName)
.then(cache => {
/* console.log('[sw] Caching new resource: ' + event.request.url); */
cache.put(event.request, responseToCache);
});
/*
see: <https://developers.google.com/web/fundamentals/primers/service-workers#cache_and_return_requests>
*/
let responseToCache = response.clone();

return response;
});
})
);
});
caches.open(cacheName).then(cache => {
/* console.log('[sw] Caching new resource: ' + event.request.url); */
cache.put(event.request, responseToCache);
});

self.addEventListener('activate', e => {
e.waitUntil(
caches.keys().then(keyList => {
return Promise.all(
keyList.map(key => {
if(key !== cacheName) {
return caches.delete(key);
}
})
);
return response;
});
})
);
});

0 comments on commit d127183

Please sign in to comment.