-
Notifications
You must be signed in to change notification settings - Fork 504
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add service worker and make PWA installable
This commit adds a service worker to make the app installable as a PWA. In addition to caching all generated build artifacts (css and js filse) the service worker also caches all other static files via a stale-while-revalidate strategy (png, ico, json, css from the public folder). Further, this commit adds a Notification which will be shown when the service worker updates and clicking on the button inside it causes the service worker to update and the page to reload. In order to make a PWA installable we need to follow some guide lines: https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Guides/Making_PWAs_installable Fixes: #147
- Loading branch information
1 parent
23c0169
commit 06e2651
Showing
8 changed files
with
276 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,21 @@ | ||
{ | ||
"$schema": "https://json.schemastore.org/web-manifest-combined.json", | ||
"short_name": "Chat with GPT", | ||
"name": "Chat with GPT", | ||
"start_url": ".", | ||
"display": "standalone", | ||
"theme_color": "#000000", | ||
"background_color": "#ffffff" | ||
"background_color": "#ffffff", | ||
"icons": [ | ||
{ | ||
"src": "logo192.png", | ||
"type": "image/png", | ||
"sizes": "192x192" | ||
}, | ||
{ | ||
"src": "logo512.png", | ||
"type": "image/png", | ||
"sizes": "512x512" | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { Button, Notification } from "@mantine/core"; | ||
import { useCallback } from "react"; | ||
import { useAppDispatch, useAppSelector } from "../store"; | ||
import { resetUpdate, selectUpdateAvailable } from "../store/pwa"; | ||
|
||
export function InstallUpdateNotification() { | ||
const updateAvailable = useAppSelector(selectUpdateAvailable); | ||
const dispatch = useAppDispatch(); | ||
|
||
const onClose = useCallback(() => dispatch(resetUpdate()), [dispatch]); | ||
|
||
const onUpdate = useCallback(async () => { | ||
dispatch(resetUpdate()); | ||
|
||
const registration = await navigator.serviceWorker.getRegistration(); | ||
if (registration && registration.waiting) { | ||
registration.waiting.postMessage({ type: "SKIP_WAITING" }); | ||
} | ||
|
||
window.location.reload(); | ||
}, [dispatch]); | ||
|
||
return updateAvailable ? ( | ||
<Notification title="Update available!" onClose={onClose}> | ||
Click{" "} | ||
<Button compact onClick={onUpdate}> | ||
Update now | ||
</Button>{" "} | ||
to get the latest version. | ||
</Notification> | ||
) : null; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
/// <reference lib="webworker" /> | ||
/* eslint-disable no-restricted-globals */ | ||
|
||
// This service worker can be customized! | ||
// See https://developer.chrome.com/docs/workbox/modules/ | ||
// for the list of available Workbox modules, or add any other | ||
// code you'd like. | ||
|
||
import { clientsClaim } from "workbox-core"; | ||
import { precacheAndRoute } from "workbox-precaching"; | ||
import { registerRoute } from "workbox-routing"; | ||
import { StaleWhileRevalidate } from "workbox-strategies"; | ||
|
||
declare const self: ServiceWorkerGlobalScope; | ||
|
||
clientsClaim(); | ||
|
||
// Precache all of the assets generated by your build process. | ||
precacheAndRoute(self.__WB_MANIFEST); | ||
|
||
// An example runtime caching route for requests that aren't handled by the | ||
// precache, in this case same-origin .png requests like those from in public/ | ||
registerRoute( | ||
// Add in any other file extensions or routing criteria as needed. | ||
({ url }) => | ||
url.origin === self.location.origin && | ||
(url.pathname.endsWith(".png") || | ||
url.pathname.endsWith(".ico") || | ||
url.pathname.endsWith(".json") || | ||
url.pathname.endsWith(".css")), | ||
// Customize this strategy as needed, e.g., by changing to CacheFirst. | ||
new StaleWhileRevalidate({ | ||
cacheName: "static", | ||
}) | ||
); | ||
|
||
// This allows the web app to trigger skipWaiting via | ||
// registration.waiting.postMessage({type: 'SKIP_WAITING'}) | ||
self.addEventListener("message", (event) => { | ||
if (event.data && event.data.type === "SKIP_WAITING") { | ||
self.skipWaiting(); | ||
} | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
// This optional code is used to register a service worker. | ||
// register() is not called by default. | ||
|
||
// This lets the app load faster on subsequent visits in production, and gives | ||
// it offline capabilities. However, it also means that developers (and users) | ||
// will only see deployed updates on subsequent visits to a page, after all the | ||
// existing tabs open on the page have been closed, since previously cached | ||
// resources are updated in the background. | ||
|
||
// To learn more about the benefits of this model and instructions on how to | ||
// opt-in, read https://cra.link/PWA | ||
|
||
const isLocalhost = Boolean( | ||
window.location.hostname === "localhost" || | ||
// [::1] is the IPv6 localhost address. | ||
window.location.hostname === "[::1]" || | ||
// 127.0.0.0/8 are considered localhost for IPv4. | ||
window.location.hostname.match( | ||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ | ||
) | ||
); | ||
|
||
type Config = { | ||
onSuccess?: (registration: ServiceWorkerRegistration) => void; | ||
onUpdate?: (registration: ServiceWorkerRegistration) => void; | ||
}; | ||
|
||
export function register(config?: Config) { | ||
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) { | ||
// The URL constructor is available in all browsers that support SW. | ||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); | ||
if (publicUrl.origin !== window.location.origin) { | ||
// Our service worker won't work if PUBLIC_URL is on a different origin | ||
// from what our page is served on. This might happen if a CDN is used to | ||
// serve assets; see https://github.com/facebook/create-react-app/issues/2374 | ||
return; | ||
} | ||
|
||
window.addEventListener("load", () => { | ||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; | ||
|
||
if (isLocalhost) { | ||
// This is running on localhost. Let's check if a service worker still exists or not. | ||
checkValidServiceWorker(swUrl, config); | ||
|
||
// Add some additional logging to localhost, pointing developers to the | ||
// service worker/PWA documentation. | ||
navigator.serviceWorker.ready.then(() => { | ||
console.log( | ||
"This web app is being served cache-first by a service " + | ||
"worker. To learn more, visit https://cra.link/PWA" | ||
); | ||
}); | ||
} else { | ||
// Is not localhost. Just register service worker | ||
registerValidSW(swUrl, config); | ||
} | ||
}); | ||
} | ||
} | ||
|
||
function registerValidSW(swUrl: string, config?: Config) { | ||
navigator.serviceWorker | ||
.register(swUrl) | ||
.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. | ||
console.log( | ||
"New content is available and will be used when all " + | ||
"tabs for this page are closed. See https://cra.link/PWA." | ||
); | ||
|
||
// 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 checkValidServiceWorker(swUrl: string, config?: Config) { | ||
// Check if the service worker can be found. If it can't reload the page. | ||
fetch(swUrl, { | ||
headers: { "Service-Worker": "script" }, | ||
}) | ||
.then((response) => { | ||
// Ensure service worker exists, and that we really are getting a JS file. | ||
const contentType = response.headers.get("content-type"); | ||
if ( | ||
response.status === 404 || | ||
(contentType != null && contentType.indexOf("javascript") === -1) | ||
) { | ||
// No service worker found. Probably a different app. Reload the page. | ||
navigator.serviceWorker.ready.then((registration) => { | ||
registration.unregister().then(() => { | ||
window.location.reload(); | ||
}); | ||
}); | ||
} else { | ||
// Service worker found. Proceed as normal. | ||
registerValidSW(swUrl, config); | ||
} | ||
}) | ||
.catch(() => { | ||
console.log( | ||
"No internet connection found. App is running in offline mode." | ||
); | ||
}); | ||
} | ||
|
||
export function unregister() { | ||
if ("serviceWorker" in navigator) { | ||
navigator.serviceWorker.ready | ||
.then((registration) => { | ||
registration.unregister(); | ||
}) | ||
.catch((error) => { | ||
console.error(error.message); | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { createSlice } from "@reduxjs/toolkit"; | ||
import type { RootState } from "."; | ||
|
||
interface UpdateState { | ||
updateAvailable: boolean; | ||
} | ||
|
||
const initialState: UpdateState = { | ||
updateAvailable: false, | ||
}; | ||
|
||
export const updateSlice = createSlice({ | ||
name: "pwa", | ||
initialState, | ||
reducers: { | ||
setUpdateAvailable: (state) => { | ||
state.updateAvailable = true; | ||
}, | ||
resetUpdate: (state) => { | ||
state.updateAvailable = false; | ||
}, | ||
}, | ||
}); | ||
|
||
export const { setUpdateAvailable, resetUpdate } = updateSlice.actions; | ||
|
||
export const selectUpdateAvailable = (state: RootState) => | ||
state.pwa.updateAvailable; | ||
|
||
export default updateSlice.reducer; |