Skip to content

Commit

Permalink
Warn users when their browser is offline
Browse files Browse the repository at this point in the history
  • Loading branch information
tillprochaska authored and Rosencrantz committed Jan 9, 2023
1 parent c641119 commit 491d412
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
23 changes: 22 additions & 1 deletion ui/src/components/common/UpdateStatus.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render } from 'testUtils';
import { render, act } from 'testUtils';
import UpdateStatus from './UpdateStatus';

it('renders success by default', () => {
Expand All @@ -20,3 +20,24 @@ it('supports "error" status', () => {
render(<UpdateStatus status={UpdateStatus.ERROR} />);
expect(document.body).toHaveTextContent('Error saving');
});

it('shows message when browser is offline', async () => {
render(<UpdateStatus />);
expect(document.body).toHaveTextContent('Saved');

jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(false);

await act(async () => {
window.dispatchEvent(new Event('offline'));
});

expect(document.body).toHaveTextContent('Offline');

jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(true);

await act(async () => {
window.dispatchEvent(new Event('online'));
});

expect(document.body).toHaveTextContent('Saved');
});
27 changes: 27 additions & 0 deletions ui/src/components/common/UpdateStatus.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, useState } from 'react';
import { FormattedMessage } from 'react-intl';
import { Intent, Spinner, Tag } from '@blueprintjs/core';

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

function UpdateStatus({ status }: UpdateStatusProps) {
const commonProps = { className: 'UpdateStatus', large: true, minimal: true };
const isOnline = useOnlineStatus();

if (!isOnline) {
return (
<Tag intent={Intent.DANGER} icon="error" {...commonProps}>
<FormattedMessage id="entity.status.offline" defaultMessage="Offline" />
</Tag>
);
}

if (status === Status.ERROR) {
return (
Expand Down Expand Up @@ -54,4 +64,21 @@ UpdateStatus.SUCCESS = Status.SUCCESS;
UpdateStatus.ERROR = Status.ERROR;
UpdateStatus.IN_PROGRESS = Status.IN_PROGRESS;

function useOnlineStatus() {
const [isOnline, setIsOnline] = useState<boolean>(navigator.onLine);
const onChange = () => setIsOnline(navigator.onLine);

useEffect(() => {
window.addEventListener('online', onChange);
window.addEventListener('offline', onChange);

return () => {
window.removeEventListener('online', onChange);
window.removeEventListener('offline', onChange);
};
}, []);

return isOnline;
}

export default UpdateStatus;

0 comments on commit 491d412

Please sign in to comment.