Skip to content

Commit 491d412

Browse files
tillprochaskaRosencrantz
authored andcommitted
Warn users when their browser is offline
1 parent c641119 commit 491d412

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

ui/src/components/common/UpdateStatus.test.tsx

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { render } from 'testUtils';
1+
import { render, act } from 'testUtils';
22
import UpdateStatus from './UpdateStatus';
33

44
it('renders success by default', () => {
@@ -20,3 +20,24 @@ it('supports "error" status', () => {
2020
render(<UpdateStatus status={UpdateStatus.ERROR} />);
2121
expect(document.body).toHaveTextContent('Error saving');
2222
});
23+
24+
it('shows message when browser is offline', async () => {
25+
render(<UpdateStatus />);
26+
expect(document.body).toHaveTextContent('Saved');
27+
28+
jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(false);
29+
30+
await act(async () => {
31+
window.dispatchEvent(new Event('offline'));
32+
});
33+
34+
expect(document.body).toHaveTextContent('Offline');
35+
36+
jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(true);
37+
38+
await act(async () => {
39+
window.dispatchEvent(new Event('online'));
40+
});
41+
42+
expect(document.body).toHaveTextContent('Saved');
43+
});

ui/src/components/common/UpdateStatus.tsx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { useEffect, useState } from 'react';
12
import { FormattedMessage } from 'react-intl';
23
import { Intent, Spinner, Tag } from '@blueprintjs/core';
34

@@ -13,6 +14,15 @@ type UpdateStatusProps = {
1314

1415
function UpdateStatus({ status }: UpdateStatusProps) {
1516
const commonProps = { className: 'UpdateStatus', large: true, minimal: true };
17+
const isOnline = useOnlineStatus();
18+
19+
if (!isOnline) {
20+
return (
21+
<Tag intent={Intent.DANGER} icon="error" {...commonProps}>
22+
<FormattedMessage id="entity.status.offline" defaultMessage="Offline" />
23+
</Tag>
24+
);
25+
}
1626

1727
if (status === Status.ERROR) {
1828
return (
@@ -54,4 +64,21 @@ UpdateStatus.SUCCESS = Status.SUCCESS;
5464
UpdateStatus.ERROR = Status.ERROR;
5565
UpdateStatus.IN_PROGRESS = Status.IN_PROGRESS;
5666

67+
function useOnlineStatus() {
68+
const [isOnline, setIsOnline] = useState<boolean>(navigator.onLine);
69+
const onChange = () => setIsOnline(navigator.onLine);
70+
71+
useEffect(() => {
72+
window.addEventListener('online', onChange);
73+
window.addEventListener('offline', onChange);
74+
75+
return () => {
76+
window.removeEventListener('online', onChange);
77+
window.removeEventListener('offline', onChange);
78+
};
79+
}, []);
80+
81+
return isOnline;
82+
}
83+
5784
export default UpdateStatus;

0 commit comments

Comments
 (0)