Skip to content
This repository was archived by the owner on Aug 22, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions template.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
9 changes: 9 additions & 0 deletions template/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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`
28 changes: 27 additions & 1 deletion template/src/App.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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(<ServiceWorkerNotification sw={sw} />, {
position: 'bottom-right',
hideProgressBar: true,
autoClose: false,
})
},
})
hasInstalledServiceWorker.current = true
}, [])

useEffect(() => {
if (!isOffline && isLoggedIn) {
Expand Down Expand Up @@ -69,6 +94,7 @@ export default function App() {
</Switch>
</Page>
</AppStylesProvider>
<ToastContainer transition={Slide} />
</ThemeProvider>
</Router>
)
Expand Down
53 changes: 53 additions & 0 deletions template/src/components/ServiceWorkerNotification.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<>
<InfoIcon size={24} />
<NotificationText>
App has been updated. Please{' '}
<ReloadButton onClick={onReload}>Reload</ReloadButton>
</NotificationText>
</>
)
}
3 changes: 0 additions & 3 deletions template/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -23,5 +22,3 @@ ReactDOM.render(
</React.StrictMode>,
document.getElementById('root'),
)

serviceWorkerRegistration.register()
82 changes: 45 additions & 37 deletions template/src/serviceWorkerRegistration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
});
})
}
}

Expand All @@ -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') {
Expand All @@ -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) {
Expand All @@ -108,35 +114,37 @@ 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)
) {
// 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)
})
}
}
}