Crab Fit PWA upgrade

This commit is contained in:
Ben Grant 2021-04-13 19:55:48 +10:00
parent 283b60e91b
commit 2e3091b7e6
10 changed files with 331 additions and 63 deletions

View file

@ -18,9 +18,15 @@ const App = () => {
const colortheme = useSettingsStore(state => state.theme);
const darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
const [isDark, setIsDark] = useState(darkQuery.matches);
const [offline, setOffline] = useState(!window.navigator.onLine);
darkQuery.addListener(e => colortheme === 'System' && setIsDark(e.matches));
useEffect(() => {
window.addEventListener('offline', () => setOffline(true));
window.addEventListener('online', () => setOffline(false));
}, []);
useEffect(() => {
setIsDark(colortheme === 'System' ? darkQuery.matches : colortheme === 'Dark');
}, [colortheme, darkQuery.matches]);
@ -28,7 +34,6 @@ const App = () => {
return (
<BrowserRouter>
<ThemeProvider theme={theme[isDark ? 'dark' : 'light']}>
{process.env.NODE_ENV !== 'production' && <button onClick={() => setIsDark(!isDark)} style={{ position: 'absolute', top: 0, left: 0, zIndex: 1000 }}>{isDark ? 'dark' : 'light'}</button>}
<Global
styles={theme => ({
html: {
@ -68,12 +73,12 @@ const App = () => {
<Switch>
<Route path="/" exact render={props => (
<Suspense fallback={<Loading />}>
<Home {...props} />
<Home offline={offline} {...props} />
</Suspense>
)} />
<Route path="/:id" exact render={props => (
<Suspense fallback={<Loading />}>
<Event {...props} />
<Event offline={offline} {...props} />
</Suspense>
)} />
</Switch>

View file

@ -1,6 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
@ -10,6 +11,8 @@ ReactDOM.render(
document.getElementById('root')
);
serviceWorkerRegistration.register();
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals

View file

@ -49,6 +49,7 @@ const Event = (props) => {
const { register, handleSubmit } = useForm();
const { id } = props.match.params;
const { offline } = props;
const [timezone, setTimezone] = useState(Intl.DateTimeFormat().resolvedOptions().timeZone);
const [user, setUser] = useState(null);
const [password, setPassword] = useState(null);
@ -297,10 +298,17 @@ const Event = (props) => {
</ShareInfo>
</>
) : (
<div style={{ margin: '100px 0' }}>
<EventName>Event not found</EventName>
<ShareInfo>Check that the url you entered is correct.</ShareInfo>
</div>
offline ? (
<div style={{ margin: '100px 0' }}>
<EventName>You are offline</EventName>
<ShareInfo>A Crab Fit doesn't work offline.<br />Make sure you're connected to the internet and try again.</ShareInfo>
</div>
) : (
<div style={{ margin: '100px 0' }}>
<EventName>Event not found</EventName>
<ShareInfo>Check that the url you entered is correct.</ShareInfo>
</div>
)
)}
</StyledMain>

View file

@ -32,6 +32,7 @@ import {
Stat,
StatNumber,
StatLabel,
OfflineMessage,
} from './homeStyle';
import api from 'services';
@ -43,7 +44,7 @@ dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);
const Home = () => {
const Home = ({ offline }) => {
const { register, handleSubmit } = useForm({
defaultValues: {
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
@ -154,52 +155,59 @@ const Home = () => {
<a href="#about">About</a> / <a href="#donate">Donate</a>
</Links>
<CreateForm onSubmit={handleSubmit(onSubmit)} id="create">
<TextField
label="Give your event a name!"
subLabel="Or leave blank to generate one"
type="text"
name="name"
id="name"
register={register}
/>
{offline ? (
<OfflineMessage>
<h1>🦀📵</h1>
<P>You can't create a Crab Fit when you don't have an internet connection. Please make sure you're connected.</P>
</OfflineMessage>
) : (
<CreateForm onSubmit={handleSubmit(onSubmit)} id="create">
<TextField
label="Give your event a name!"
subLabel="Or leave blank to generate one"
type="text"
name="name"
id="name"
register={register}
/>
<CalendarField
label="What dates might work?"
subLabel="Click and drag to select"
name="dates"
id="dates"
required
register={register}
/>
<CalendarField
label="What dates might work?"
subLabel="Click and drag to select"
name="dates"
id="dates"
required
register={register}
/>
<TimeRangeField
label="What times might work?"
subLabel="Click and drag to select a time range"
name="times"
id="times"
required
register={register}
/>
<TimeRangeField
label="What times might work?"
subLabel="Click and drag to select a time range"
name="times"
id="times"
required
register={register}
/>
<SelectField
label="And the timezone"
name="timezone"
id="timezone"
register={register}
options={timezones}
required
defaultOption="Select..."
/>
<SelectField
label="And the timezone"
name="timezone"
id="timezone"
register={register}
options={timezones}
required
defaultOption="Select..."
/>
{error && (
<Error onClose={() => setError(null)}>{error}</Error>
)}
{error && (
<Error onClose={() => setError(null)}>{error}</Error>
)}
<Center>
<Button type="submit" isLoading={isLoading} disabled={isLoading}>Create</Button>
</Center>
</CreateForm>
<Center>
<Button type="submit" isLoading={isLoading} disabled={isLoading}>Create</Button>
</Center>
</CreateForm>
)}
</StyledMain>
<AboutSection id="about">
@ -207,11 +215,11 @@ const Home = () => {
<h2>About Crab Fit</h2>
<Stats>
<Stat>
<StatNumber>{stats.eventCount ?? '10+'}</StatNumber>
<StatNumber>{stats.eventCount ?? '100+'}</StatNumber>
<StatLabel>Events created</StatLabel>
</Stat>
<Stat>
<StatNumber>{stats.personCount ?? '10+'}</StatNumber>
<StatNumber>{stats.personCount ?? '100+'}</StatNumber>
<StatLabel>Availabilities entered</StatLabel>
</Stat>
</Stats>

View file

@ -88,3 +88,8 @@ export const StatNumber = styled.span`
export const StatLabel = styled.span`
display: block;
`;
export const OfflineMessage = styled.div`
text-align: center;
margin: 50px 0 20px;
`;

View file

@ -0,0 +1,90 @@
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate, NetworkFirst } from 'workbox-strategies';
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
} // If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
} // If this looks like a URL for a resource, because it contains // a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
} // Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// 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('.svg')
|| url.pathname.endsWith('.jpg')
|| url.pathname.endsWith('.jpeg')
|| url.pathname.endsWith('.ico')
|| url.pathname.endsWith('.ttf')
|| url.pathname.endsWith('.woff')
|| url.pathname.endsWith('.woff2')
), // Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'res',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// 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();
}
});
// Any other custom service worker logic can go here.
registerRoute(
({ url }) => url.origin === self.location.origin && (
url.pathname.endsWith('.js')
|| url.pathname.endsWith('.css')
|| url.pathname.endsWith('.json')
),
new NetworkFirst({ cacheName: 'res' })
);

View file

@ -0,0 +1,137 @@
// 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}$/)
);
export function register(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, 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, 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);
});
}
}