diff --git a/template.json b/template.json index 792c17d..4cedb25 100644 --- a/template.json +++ b/template.json @@ -15,6 +15,7 @@ "react-dom": "^17.0.2", "react-router-dom": "^5.2.0", "react-scripts": "4.0.3", + "react-toastify": "^7.0.4", "styled-components": "^5.3.0", "typescript": "^4.3.5", "use-viewport-sizes": "^0.4.0", diff --git a/template/README.md b/template/README.md index 5a7d883..e1defc9 100644 --- a/template/README.md +++ b/template/README.md @@ -30,6 +30,7 @@ The variables added above will need to be configured in an `.env.local` file: ``` REACT_APP_OB_COGNITO_CLIENT_ID=abcde12345 REACT_APP_OB_FORMS_APP_ID=12345 +# REACT_APP_LOCAL_SERVICEWORKER=true ``` To start the project locally: @@ -58,3 +59,11 @@ Used to render a list of pending submissions via the pending queue. Submissions ### `./src/Scenes/Form` The Forms component, as the name suggests, allows a OneBlink form definition to be rendered. A basic Form Container is provided to allow the rendering of either a OneBlink Default Form, or a Controlled Form. The implementation provided uses Form IDs to achieve this, however this can obviously be customised to your own needs. It's recommended to familarise yourself with the differences between the Default Form and the Controlled Form. While the Default Form will be fine in the majority of cases, the Controlled Form will allow access to modify the Form Definition and Submission model programmatically on the fly. For more information, please see [https://github.com/oneblink/apps-react/blob/master/docs/OneBlinkFormControlled.md](https://github.com/oneblink/apps-react/blob/master/docs/OneBlinkFormControlled.md). + +## Testing service workers + +The service worker file must be a javascript file, therefore the project needs to be built: + +- uncomment `REACT_APP_LOCAL_SERVICEWORKER=true` in `.env.local` +- build the project (`npm run build`) +- `serve -s ./build -l 3000` diff --git a/template/src/App.tsx b/template/src/App.tsx index 1064531..3bb90cf 100644 --- a/template/src/App.tsx +++ b/template/src/App.tsx @@ -1,4 +1,4 @@ -import { useEffect } from 'react' +import { useEffect, useRef } from 'react' import { BrowserRouter as Router, Switch, Route } from 'react-router-dom' import AuthenticatedRoute from 'components/AuthenticatedRoute' import OAuthCallback from 'components/Auth/OAuthCallback' @@ -20,11 +20,36 @@ import PendingQueueListScene from 'Scenes/Pending' import { useIsOffline, useAuth } from '@oneblink/apps-react' import { submissionService } from '@oneblink/apps' +import { ToastContainer, Slide, toast } from 'react-toastify' +import 'react-toastify/dist/ReactToastify.css' + +import * as serviceWorker from './serviceWorkerRegistration' +import ServiceWorkerNotification from './components/ServiceWorkerNotification' + import '@oneblink/apps-react/dist/styles.css' export default function App() { const isOffline = useIsOffline() const { isLoggedIn } = useAuth() + const hasInstalledServiceWorker = useRef(false) + + useEffect(() => { + if (hasInstalledServiceWorker.current) return + console.log('installing service worker') + serviceWorker.register({ + onSuccess: () => { + console.log('service worker installed') + }, + onUpdate: (sw) => { + toast.info(, { + position: 'bottom-right', + hideProgressBar: true, + autoClose: false, + }) + }, + }) + hasInstalledServiceWorker.current = true + }, []) useEffect(() => { if (!isOffline && isLoggedIn) { @@ -69,6 +94,7 @@ export default function App() { + ) diff --git a/template/src/components/ServiceWorkerNotification.tsx b/template/src/components/ServiceWorkerNotification.tsx new file mode 100644 index 0000000..bd12666 --- /dev/null +++ b/template/src/components/ServiceWorkerNotification.tsx @@ -0,0 +1,53 @@ +import React from 'react' +import { Info } from '@styled-icons/material/Info' +import styled from 'styled-components' + +const InfoIcon = styled(Info)` + flex: 0 0 auto; + margin-right: 1rem; +` +InfoIcon.displayName = 'InfoIcon' + +const NotificationText = styled.p` + flex: 1 1 auto; + font-size: 0.75rem; + font-weight: ${({ theme }) => theme.fontWeight.bold}; + display: inline; +` + +const ReloadButton = styled.button.attrs(() => ({ + type: 'button', +}))` + background: none; + border: none; + font-size: inherit; + display: inline-block; + padding: 0; + color: inherit; + font-weight: inherit; + font-family: inherit; + text-decoration: underline; +` + +export default function UpdateNotification({ + sw, +}: { + sw: ServiceWorkerRegistration +}) { + const onReload = () => { + if (sw.waiting) { + sw.waiting.postMessage({ type: 'SKIP_WAITING' }) + window.location.reload() + } + } + + return ( + <> + + + App has been updated. Please{' '} + Reload + + + ) +} diff --git a/template/src/index.tsx b/template/src/index.tsx index e9cbcbe..959d3f3 100644 --- a/template/src/index.tsx +++ b/template/src/index.tsx @@ -7,7 +7,6 @@ import { } from '@oneblink/apps-react' import { authService } from '@oneblink/apps' import config from './config' -import * as serviceWorkerRegistration from './serviceWorkerRegistration' authService.init({ oAuthClientId: config.OB_COGNITO_CLIENT_ID, @@ -23,5 +22,3 @@ ReactDOM.render( , document.getElementById('root'), ) - -serviceWorkerRegistration.register() \ No newline at end of file diff --git a/template/src/serviceWorkerRegistration.ts b/template/src/serviceWorkerRegistration.ts index 4025027..0e0eb8c 100644 --- a/template/src/serviceWorkerRegistration.ts +++ b/template/src/serviceWorkerRegistration.ts @@ -15,45 +15,51 @@ const isLocalhost = Boolean( // [::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}$/) -); + 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; -}; + onSuccess?: (registration: ServiceWorkerRegistration) => void + onUpdate?: (registration: ServiceWorkerRegistration) => void +} export function register(config?: Config) { - if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { + if ( + (process.env.NODE_ENV === 'production' || + process.env.REACT_APP_LOCAL_SERVICEWORKER) && + '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); + 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; + return } window.addEventListener('load', () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + 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); + 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' - ); - }); + 'worker. To learn more, visit https://cra.link/PWA', + ) + }) } else { // Is not localhost. Just register service worker - registerValidSW(swUrl, config); + registerValidSW(swUrl, config) } - }); + }) } } @@ -62,9 +68,9 @@ function registerValidSW(swUrl: string, config?: Config) { .register(swUrl) .then((registration) => { registration.onupdatefound = () => { - const installingWorker = registration.installing; + const installingWorker = registration.installing if (installingWorker == null) { - return; + return } installingWorker.onstatechange = () => { if (installingWorker.state === 'installed') { @@ -74,31 +80,31 @@ function registerValidSW(swUrl: string, config?: Config) { // 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.' - ); + 'tabs for this page are closed. See https://cra.link/PWA.', + ) // Execute callback if (config && config.onUpdate) { - config.onUpdate(registration); + 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.'); + console.log('Content is cached for offline use.') // Execute callback if (config && config.onSuccess) { - config.onSuccess(registration); + config.onSuccess(registration) } } } - }; - }; + } + } }) .catch((error) => { - console.error('Error during service worker registration:', error); - }); + console.error('Error during service worker registration:', error) + }) } function checkValidServiceWorker(swUrl: string, config?: Config) { @@ -108,7 +114,7 @@ function checkValidServiceWorker(swUrl: string, config?: Config) { }) .then((response) => { // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); + const contentType = response.headers.get('content-type') if ( response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1) @@ -116,27 +122,29 @@ function checkValidServiceWorker(swUrl: string, config?: Config) { // No service worker found. Probably a different app. Reload the page. navigator.serviceWorker.ready.then((registration) => { registration.unregister().then(() => { - window.location.reload(); - }); - }); + window.location.reload() + }) + }) } else { // Service worker found. Proceed as normal. - registerValidSW(swUrl, config); + registerValidSW(swUrl, config) } }) .catch(() => { - console.log('No internet connection found. App is running in offline mode.'); - }); + 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(); + registration.unregister() }) .catch((error) => { - console.error(error.message); - }); + console.error(error.message) + }) } -} \ No newline at end of file +}