Skip to content

Commit

Permalink
fix: checkForUpdates
Browse files Browse the repository at this point in the history
  • Loading branch information
Lokuyow committed Nov 28, 2023
1 parent dd215a0 commit 6125e26
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 66 deletions.
67 changes: 33 additions & 34 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -677,17 +677,27 @@ function shareViaWebAPI(originalShareText, queryParams) {
// サービスワーカー
let newVersionAvailable = false;

// サービスワーカーからのメッセージリスナー
navigator.serviceWorker.addEventListener('message', (event) => {
if (event.data && event.data.type === 'NEW_VERSION_ACTIVE') {
newVersionAvailable = true;
const updateButton = getDomElementById('checkForUpdateBtn');
const buttonText = getDomElementById('buttonText');
const spinnerWrapper = updateButton.querySelector('.spinner-wrapper');

const updateUI = getDomElementById('buttonText');
if (updateUI) {
updateUI.textContent = '更新があります';
console.log('Message from Service Worker:', event.data);

if (event.data && event.data.type === 'NEW_VERSION_INSTALLED') {
newVersionAvailable = true;
if (buttonText) {
buttonText.textContent = '更新があります';
}
spinnerWrapper.style.display = 'none';
} else if (event.data && event.data.type === 'NO_UPDATE_FOUND') {
showNotification('最新です', lastClickEvent);
spinnerWrapper.style.display = 'none';
}
});


async function registerAndHandleServiceWorker() {
if (!('serviceWorker' in navigator)) {
console.warn("Service Worker is not supported in this browser.");
Expand All @@ -705,6 +715,7 @@ async function registerAndHandleServiceWorker() {
newVersionAvailable = true;
const updateUI = getDomElementById('buttonText');
if (updateUI) {
console.log("Updating UI from Service Worker installation");
updateUI.textContent = '更新があります';
}
}
Expand All @@ -721,48 +732,36 @@ function delay(ms) {

// サイト更新ボタン
async function checkForUpdates(event) {
lastClickEvent = event; // クリックイベントを保存
const updateButton = getDomElementById('checkForUpdateBtn');
const buttonText = getDomElementById('buttonText');
const spinnerWrapper = updateButton.querySelector('.spinner-wrapper');
spinnerWrapper.style.display = 'block'; // スピナーを表示

buttonText.style.display = 'none';
spinnerWrapper.style.display = 'block';
// 新しいバージョンが利用可能な場合、ページをリロード
if (newVersionAvailable) {
window.location.reload();
return; // 以降の処理を実行させない
}

try {
await delay(250); // 最低250ミリ秒の遅延を保持
await delay(300);

const registration = await navigator.serviceWorker.getRegistration();
if (!registration) throw new Error("No active service worker registration found");

await registration.update();

if (registration && registration.waiting) {
registration.waiting.postMessage('skipWaiting');

navigator.serviceWorker.addEventListener('controllerchange', () => {
if (newVersionAvailable) {
buttonText.textContent = '更新があります'; // ここでUIを更新
spinnerWrapper.style.display = 'none'; // スピナーを非表示にする
window.location.reload();
}
});
} else if (newVersionAvailable) {
buttonText.textContent = '更新があります'; // UI更新
spinnerWrapper.style.display = 'none'; // スピナー非表示
window.location.reload();
// サービスワーカーの状態を確認
if (registration.installing || registration.waiting) {
// サービスワーカーがインストール中または待機中であれば、更新状態をチェック
navigator.serviceWorker.controller.postMessage('CHECK_UPDATE_STATUS');
} else {
console.log('No update found.');
showNotification('最新です', event); // 更新がない場合の通知
// それ以外の場合は、更新を試みる
await registration.update();
// 更新状態をチェック
navigator.serviceWorker.controller.postMessage('CHECK_UPDATE_STATUS');
}
} catch (error) {
console.error("An error occurred while checking for updates:", error);
buttonText.textContent = '更新エラー';
spinnerWrapper.style.display = 'none'; // エラー時にスピナーを非表示
} finally {
if (!newVersionAvailable) {
spinnerWrapper.style.display = 'none'; // 更新がない場合にスピナーを非表示
}
buttonText.style.display = '';
spinnerWrapper.style.display = 'none';
}
}

Expand Down
15 changes: 9 additions & 6 deletions styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -318,11 +318,11 @@ button>* {

.grid-settings {
display: grid;
grid-template-columns: 120px minmax(auto, 330px);
grid-template-columns: 120px minmax(200px, 330px);
grid-template-rows: auto auto auto;
justify-content: center;
align-items: center;
gap: 6px 26px;
gap: 6px 18px;
margin: 0 26px;
}

Expand All @@ -338,7 +338,9 @@ button>* {
border: 0;
cursor: pointer;
border-radius: 6px;
padding: 8px 10px;
height: 42px;
line-height: 42px;
padding: 0;
}

#checkForUpdateBtn {
Expand All @@ -350,7 +352,8 @@ button>* {
border: 0;
cursor: pointer;
min-width: 160px;
min-height: 42px;
height: 42px;
line-height: 42px;
border-radius: 6px;
padding: 0;
}
Expand All @@ -368,9 +371,9 @@ button>* {
.spinner-wrapper {
display: none;
position: absolute;
right: 10px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transform: translateY(-50%);
}

.spinner {
Expand Down
65 changes: 39 additions & 26 deletions sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,29 @@ const urlsToCache = [
'./images/angle-down-solid.svg'
];

const VERSION = '1.40.2';
const VERSION = '1.40.3';
let CACHE_NAME = 'sats-rate-caches-' + VERSION;
const MY_CACHES = new Set([CACHE_NAME]);

self.addEventListener('install', (ev) => ev.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME);
await cache.addAll(urlsToCache);
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME);
await cache.addAll(urlsToCache);

const keys = await caches.keys();
await Promise.all(
keys
.filter(key => !MY_CACHES.has(key))
.map(key => caches.delete(key))
);
return self.skipWaiting();
})()));
// 新しいバージョンがインストールされたことをクライアントに通知
self.clients.matchAll({ includeUncontrolled: true, type: 'window' }).then((clients) => {
clients.forEach(client => client.postMessage({ type: 'NEW_VERSION_INSTALLED' }));
});

const keys = await caches.keys();
await Promise.all(
keys
.filter(key => !MY_CACHES.has(key))
.map(key => caches.delete(key))
);
return self.skipWaiting();
})());
});

self.addEventListener('fetch', (ev) => void ev.respondWith((async () => {
const url = new URL(ev.request.url);
Expand All @@ -67,22 +74,28 @@ self.addEventListener('fetch', (ev) => void ev.respondWith((async () => {
return cacheResponse || fetch(requestToFetch);
})()));

self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
const clientsList = await self.clients.matchAll({ includeUncontrolled: true, type: 'window' });
for (const client of clientsList) {
client.postMessage({ type: 'NEW_VERSION_ACTIVE' });
}

return self.clients.claim();
})());
});

self.addEventListener('message', (event) => {
if (event.data.action === 'getVersion') {
event.ports[0].postMessage({ version: VERSION });
}
if (event.data === 'skipWaiting') {
self.skipWaiting();
}
if (event.data === 'CHECK_UPDATE_STATUS') {
if (self.registration.waiting) {
// 新しいバージョンがインストールされ、待機中であれば NEW_VERSION_INSTALLED を送信
event.source.postMessage({ type: 'NEW_VERSION_INSTALLED' });
} else if (self.registration.installing) {
// 新しいバージョンが現在インストール中であれば、インストールの完了を待機
const worker = self.registration.installing;
worker.addEventListener('statechange', () => {
if (worker.state === 'installed') {
event.source.postMessage({ type: 'NEW_VERSION_INSTALLED' });
}
});
} else {
// 更新がない場合、あるいはまだ新しいバージョンが準備されていない場合は NO_UPDATE_FOUND を送信
event.source.postMessage({ type: 'NO_UPDATE_FOUND' });
}
}
if (event.data.action === 'getVersion') {
event.ports[0].postMessage({ version: VERSION });
}
});

0 comments on commit 6125e26

Please sign in to comment.