aboutsummaryrefslogtreecommitdiff
path: root/src/components/ReloadPrompt.tsx
blob: 39ced275dd5400e6f9b0601b6529e3226d87ce00 (plain) (blame)
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
/* eslint-disable vue/one-component-per-file */
import { useRegisterSW } from 'virtual:pwa-register/vue';
import { useNotification, type NotificationReactive } from 'naive-ui';
import { defineComponent } from 'vue';
import { whenever } from '@vueuse/core';

export default defineComponent({
  setup() {
    const notificationBuilder = useNotification();

    const { needRefresh, offlineReady, updateServiceWorker } = useRegisterSW();

    let notification: NotificationReactive | null = null;

    const onUpdateClicked = () => {
      if (notification) {
        notification.action = () => (
          <n-button loading type="primary" secondary>
            Reloading
          </n-button>
        );
      }

      updateServiceWorker();
    };

    whenever(
      needRefresh,
      () => {
        notification = notificationBuilder.create({
          title: 'A new version is out!',
          content: 'Update to get the latest version of it-tools',
          closable: true,
          onClose: () => {
            needRefresh.value = false;
            return true;
          },
          action: () => (
            <n-button onClick={onUpdateClicked} type="primary" secondary>
              Reload
            </n-button>
          ),
        });
      },
      { immediate: true },
    );

    whenever(offlineReady, () => notification?.destroy(), { immediate: true });

    return () => '';
  },
});