Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

show snackbar on update ready #316

Merged
merged 20 commits into from
Nov 12, 2022
Merged
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
4 changes: 4 additions & 0 deletions craco.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const { loaderByName, addBeforeLoader } = require('@craco/craco');
const SentryCliPlugin = require('@sentry/webpack-plugin');
const { GenerateSW } = require('workbox-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const CracoWorkboxPlugin = require('craco-workbox');
const zlib = require('zlib');

const eslintConfig = require('./.eslintrc');
Expand Down Expand Up @@ -44,6 +45,9 @@ module.exports = ({ env }) => {
}

return {
plugins: [{
plugin: CracoWorkboxPlugin,
}],
eslint: {
enable: false,
config: eslintConfig,
Expand Down
2 changes: 1 addition & 1 deletion lighthouserc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module.exports = {
'http://localhost/4cf7a6ad03080c90',
'http://localhost/4cf7a6ad03080c90/1632948396703/1632949028503/',
],
numberOfRuns: 8,
numberOfRuns: 6,
},
},
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^14.4.3",
"compression-webpack-plugin": "^7.1.2",
"craco-workbox": "^0.2.0",
"env-cmd": "^8.0.2",
"eslint-config-airbnb": "19.0.4",
"eslint-plugin-import": "^2.26.0",
Expand Down
2 changes: 0 additions & 2 deletions src/components/DriveView/Media.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,6 @@ class Media extends Component {
this.onPublicToggle = this.onPublicToggle.bind(this);
this.fetchRoutePreserved = this.fetchRoutePreserved.bind(this);
this.onPreserveToggle = this.onPreserveToggle.bind(this);

this.openRequests = 0;
}

componentDidMount() {
Expand Down
97 changes: 97 additions & 0 deletions src/components/ServiceWorkerWrapper/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { Button, CircularProgress, Snackbar, withStyles } from '@material-ui/core';
import React, { useEffect, useState } from 'react';

import { useWindowWidth } from '../../hooks/window';
import { register, unregister } from '../../serviceWorkerRegistration';

const styles = () => ({
button: {
textTransform: 'uppercase',
},
});

const ServiceWorkerWrapper = (props) => {
const { classes } = props;

const [showUpdate, setShowUpdate] = useState(false);
const [loading, setLoading] = useState(false);
const windowWidth = useWindowWidth();

const [waitingWorker, setWaitingWorker] = useState(null);
const [refreshing, setRefreshing] = useState(false);

const onSWUpdate = (registration) => {
console.debug('[ServiceWorkerWrapper] Update is available');
setWaitingWorker(registration.waiting);
setShowUpdate(true);
};

const onSWChange = () => {
console.debug('[ServiceWorkerWrapper] Controller changed');
if (refreshing) return;
setRefreshing(true);
window.location.reload();
};

/* eslint-disable react-hooks/exhaustive-deps */
useEffect(() => {
if (process.env.NODE_ENV === 'production' && process.env.REACT_APP_SERVICEWORKER) {
console.debug('[ServiceWorkerWrapper] Registering service worker...');
register({
// show update found message
onUpdate: onSWUpdate,

// TODO: show "connect now works offline" message
onSuccess: null,
});

navigator.serviceWorker.addEventListener('controllerchange', onSWChange);
} else {
unregister();
}
}, []);
/* eslint-enable react-hooks/exhaustive-deps */

const onReload = () => {
setLoading(true);
waitingWorker?.postMessage({ type: 'SKIP_WAITING' });
};

const onDismiss = () => {
setShowUpdate(false);
};

const action = (
<>
<Button
classes={{ root: classes.button }}
color="primary"
size="small"
disabled={loading}
onClick={onReload}
>
{loading ? <CircularProgress color="primary" size={20} /> : 'Reload'}
</Button>
<Button
classes={{ root: classes.button }}
color="primary"
size="small"
disabled={loading}
onClick={onDismiss}
>
Dismiss
</Button>
</>
);

return (
<Snackbar
open={showUpdate}
message="An update is ready. Reload to get the latest version."
action={action}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
/>
);
};

export default withStyles(styles)(ServiceWorkerWrapper);
9 changes: 2 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { CssBaseline, MuiThemeProvider } from '@material-ui/core';
import './index.css';
import App from './App';
import Theme from './theme';
import { register, unregister } from './registerServiceWorker';
import ServiceWorkerWrapper from './components/ServiceWorkerWrapper';

if (window.SENTRY_ENV) {
Sentry.init({
Expand All @@ -17,15 +17,10 @@ if (window.SENTRY_ENV) {
});
}

if (process.env.NODE_ENV === 'production' && process.env.REACT_APP_SERVICEWORKER) {
register();
} else {
unregister();
}

createRoot(document.getElementById('root')).render((
<MuiThemeProvider theme={Theme}>
<CssBaseline />
<App />
<ServiceWorkerWrapper />
</MuiThemeProvider>
));
44 changes: 31 additions & 13 deletions src/registerServiceWorker.js → src/serviceWorkerRegistration.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
// opt-in, read https://cra.link/PWA

const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
window.location.hostname === 'localhost'
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
|| 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}$/),
);

export function register(config) {
Expand All @@ -40,8 +40,8 @@ export function register(config) {
// 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'
'This web app is being served cache-first by a service '
+ 'worker. To learn more, visit https://cra.link/PWA',
);
});
} else {
Expand All @@ -56,21 +56,39 @@ function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
const interval = setInterval(() => {
if (!registration) {
clearInterval(interval);
return;
}

console.log('[ServiceWorkerRegistration] Checking for updates...');
registration.update();
}, 10 * 60 * 1000);

if (registration.waiting) {
console.log('[ServiceWorkerRegistration] Update waiting');

// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
}

registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}

console.debug('[ServiceWorkerRegistration] Update found...');
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.'
);
console.debug('[ServiceWorkerRegistration] Update ready');

// Execute callback
if (config && config.onUpdate) {
Expand All @@ -80,7 +98,7 @@ function registerValidSW(swUrl, config) {
// 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('[ServiceWorkerRegistration] Content is cached for offline use');

// Execute callback
if (config && config.onSuccess) {
Expand All @@ -105,8 +123,8 @@ function checkValidServiceWorker(swUrl, config) {
// 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)
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) => {
Expand All @@ -120,7 +138,7 @@ function checkValidServiceWorker(swUrl, config) {
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.');
console.log('[ServiceWorkerRegistration] No internet connection found. App is running in offline mode.');
});
}

Expand Down
12 changes: 9 additions & 3 deletions src/theme.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ const theme = createMuiTheme({
},
},
},
MuiSnackbarContent: {
root: {
backgroundColor: Colors.grey700,
color: Colors.white,
},
},
},
props: {
MuiSelect: {
Expand All @@ -111,9 +117,9 @@ const theme = createMuiTheme({
default: Colors.grey999,
},
primary: {
light: Colors.grey50,
main: Colors.grey900,
dark: Colors.grey999,
light: Colors.lightBlue700,
main: Colors.lightBlue900,
dark: Colors.blue100,
},
secondary: {
light: Colors.green100,
Expand Down
16 changes: 16 additions & 0 deletions workbox.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/* eslint-disable arrow-body-style */
module.exports = {
GenerateSW: (options) => {
// override GenerateSW config here
// e.g. options.skipWaiting = true;
options.skipWaiting = false;
console.log('[Workbox]', 'GenerateSW', options);
return options;
},
InjectManifest: (options) => {
// override InjectManifest config here
// e.g. options.maximumFileSizeToCacheInBytes = 10 * 1024 * 1024;
console.log('[Workbox]', 'InjectManifest', options);
return options;
},
};
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4142,6 +4142,11 @@ cosmiconfig@^7, cosmiconfig@^7.0.0, cosmiconfig@^7.0.1:
path-type "^4.0.0"
yaml "^1.10.0"

craco-workbox@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/craco-workbox/-/craco-workbox-0.2.0.tgz#13e5c3c87c49a67d3d64ad6d636868c623cd7d89"
integrity sha512-5UFq99GrBs+cvyxxHSlCPmEduUwCRLsmAmmaW6qLhpXeKwxzk1UguVYXbYZNILcjUTdOM1yuu0VLvi3a1mop/A==

create-require@^1.1.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333"
Expand Down