From d5131d167d9581f09988ae78b991157bde6204c1 Mon Sep 17 00:00:00 2001 From: ZauberNerd Date: Fri, 7 Jul 2023 21:45:08 +0200 Subject: [PATCH 1/2] 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 --- app/public/manifest.json | 15 ++- app/src/components/page.tsx | 2 + app/src/components/pwa-notifications.tsx | 32 +++++ app/src/index.tsx | 8 +- app/src/service-worker.ts | 43 +++++++ app/src/serviceworker-registration.ts | 146 +++++++++++++++++++++++ app/src/store/index.ts | 2 + app/src/store/pwa.ts | 30 +++++ 8 files changed, 276 insertions(+), 2 deletions(-) create mode 100644 app/src/components/pwa-notifications.tsx create mode 100644 app/src/service-worker.ts create mode 100644 app/src/serviceworker-registration.ts create mode 100644 app/src/store/pwa.ts diff --git a/app/public/manifest.json b/app/public/manifest.json index 7806318c..d9b26b74 100644 --- a/app/public/manifest.json +++ b/app/public/manifest.json @@ -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" + } + ] } diff --git a/app/src/components/page.tsx b/app/src/components/page.tsx index a8844e5e..c42a938a 100644 --- a/app/src/components/page.tsx +++ b/app/src/components/page.tsx @@ -4,6 +4,7 @@ import { useChatSpotlightProps } from '../spotlight'; import { LoginModal, CreateAccountModal } from './auth-modals'; import Header, { HeaderProps, SubHeader } from './header'; import MessageInput from './input'; +import { InstallUpdateNotification } from './pwa-notifications'; import SettingsDrawer from './settings'; import Sidebar from './sidebar'; import AudioControls from './tts-controls'; @@ -90,6 +91,7 @@ export function Page(props: { + ; diff --git a/app/src/components/pwa-notifications.tsx b/app/src/components/pwa-notifications.tsx new file mode 100644 index 00000000..efa8f5bd --- /dev/null +++ b/app/src/components/pwa-notifications.tsx @@ -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 ? ( + + Click{" "} + {" "} + to get the latest version. + + ) : null; +} diff --git a/app/src/index.tsx b/app/src/index.tsx index 9c1f60b6..3761e0c1 100644 --- a/app/src/index.tsx +++ b/app/src/index.tsx @@ -8,6 +8,8 @@ import { createBrowserRouter, RouterProvider } from "react-router-dom"; import { PersistGate } from 'redux-persist/integration/react'; import { AppContextProvider } from './core/context'; import store, { persistor } from './store'; +import * as serviceWorkerRegistration from "./serviceworker-registration"; +import { setUpdateAvailable } from "./store/pwa"; import ChatPage from './components/pages/chat'; import LandingPage from './components/pages/landing'; @@ -86,4 +88,8 @@ async function bootstrapApplication() { ); } -bootstrapApplication(); \ No newline at end of file +bootstrapApplication(); + +serviceWorkerRegistration.register({ + onUpdate: () => store.dispatch(setUpdateAvailable()), +}); diff --git a/app/src/service-worker.ts b/app/src/service-worker.ts new file mode 100644 index 00000000..1d02d728 --- /dev/null +++ b/app/src/service-worker.ts @@ -0,0 +1,43 @@ +/// +/* 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(); + } +}); diff --git a/app/src/serviceworker-registration.ts b/app/src/serviceworker-registration.ts new file mode 100644 index 00000000..dc5caf4b --- /dev/null +++ b/app/src/serviceworker-registration.ts @@ -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); + }); + } +} diff --git a/app/src/store/index.ts b/app/src/store/index.ts index 1870901d..4aa6fedf 100644 --- a/app/src/store/index.ts +++ b/app/src/store/index.ts @@ -6,6 +6,7 @@ import messageReducer from './message'; import uiReducer from './ui'; import settingsUIReducer from './settings-ui'; import sidebarReducer from './sidebar'; +import pwaReducer from './pwa'; const persistConfig = { key: 'root', @@ -30,6 +31,7 @@ const store = configureStore({ ui: uiReducer, settingsUI: settingsUIReducer, sidebar: persistReducer(persistSidebarConfig, sidebarReducer), + pwa: pwaReducer, }, }) diff --git a/app/src/store/pwa.ts b/app/src/store/pwa.ts new file mode 100644 index 00000000..0290312e --- /dev/null +++ b/app/src/store/pwa.ts @@ -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; From 36c1cb47c084755ffa090931a76380252677364c Mon Sep 17 00:00:00 2001 From: ZauberNerd Date: Mon, 10 Jul 2023 00:42:06 +0200 Subject: [PATCH 2/2] Implement service worker using vite-plugin-pwa --- app/index.html | 31 ++--- app/package.json | 4 +- app/public/manifest.json | 21 ---- app/src/components/pwa-notifications.tsx | 53 ++++---- app/src/index.tsx | 6 - app/src/service-worker.ts | 43 ------- app/src/serviceworker-registration.ts | 146 ----------------------- app/src/store/index.ts | 2 - app/src/store/pwa.ts | 30 ----- app/src/vite-env.d.ts | 1 + app/vite.config.js | 90 +++++++++++++- 11 files changed, 132 insertions(+), 295 deletions(-) delete mode 100644 app/public/manifest.json delete mode 100644 app/src/service-worker.ts delete mode 100644 app/src/serviceworker-registration.ts delete mode 100644 app/src/store/pwa.ts diff --git a/app/index.html b/app/index.html index ec20b031..cd2a0aed 100644 --- a/app/index.html +++ b/app/index.html @@ -3,33 +3,24 @@ + + + + + + - - - Chat with GPT | Unofficial ChatGPT app - - - - - + + + + +