aboutsummaryrefslogtreecommitdiff
path: root/modern/src/UpdateCheckPrompt.tsx
blob: a39063044bc24d4f11181d8c0afb8a9198582eb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { Snackbar, IconButton } from '@mui/material';
import RefreshIcon from '@mui/icons-material/Refresh';
import React from 'react'
import { useTranslation } from './common/components/LocalizationProvider';
import { useAttributePreference } from './common/util/preferences';
import { useRegisterSW } from 'virtual:pwa-register/react'

// Based on https://vite-pwa-org.netlify.app/frameworks/react.html
function UpdateCheckPrompt() {
  const t = useTranslation();

  const serviceWorkerUpdateInterval = useAttributePreference('serviceWorkerUpdateInterval', 3600000);

  const {
    needRefresh: [needRefresh],
    updateServiceWorker,
  } = useRegisterSW({
    onRegisteredSW(swUrl, swRegistration) {
      if (serviceWorkerUpdateInterval > 0 && swRegistration) {
        setInterval(async () => {
          if (!(!swRegistration.installing && navigator)) {
            return;
          }
    
          if (('connection' in navigator) && !navigator.onLine) {
            return;
          }
    
          const newSW = await fetch(swUrl, {
            cache: 'no-store',
            headers: {
              'cache': 'no-store',
              'cache-control': 'no-cache',
            },
          });
    
          if (newSW?.status === 200) {
            await swRegistration.update();
          }
        }, serviceWorkerUpdateInterval);
      }
    }
  });

  return (
    <Snackbar 
      open={needRefresh} 
      message={t('settingsUpdateAvailable')}
      action={(
        <IconButton color="inherit" onClick={() => updateServiceWorker(true)}>
          <RefreshIcon />
        </IconButton>
      )}
    />
  );
}

export default UpdateCheckPrompt;