forked from elk-zone/elk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpage-lifecycle.client.ts
45 lines (38 loc) · 1.17 KB
/
page-lifecycle.client.ts
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
import lifecycle from 'page-lifecycle/dist/lifecycle.mjs'
import { ELK_PAGE_LIFECYCLE_FROZEN } from '~/constants'
import { closeDatabases } from '~/utils/elk-idb'
export default defineNuxtPlugin(() => {
const state = ref(lifecycle.state)
const frozenListeners: (() => void)[] = []
const frozenState = useLocalStorage(ELK_PAGE_LIFECYCLE_FROZEN, false)
lifecycle.addEventListener('statechange', (evt) => {
if (evt.newState === 'hidden' && evt.oldState === 'frozen') {
frozenState.value = false
nextTick().then(() => window.location.reload())
return
}
if (evt.newState === 'frozen') {
frozenState.value = true
frozenListeners.forEach(listener => listener())
}
else {
state.value = evt.newState
}
})
const addFrozenListener = (listener: () => void) => {
frozenListeners.push(listener)
}
addFrozenListener(() => {
if (useAppConfig().pwaEnabled && navigator.serviceWorker.controller)
navigator.serviceWorker.controller.postMessage(ELK_PAGE_LIFECYCLE_FROZEN)
closeDatabases()
})
return {
provide: {
pageLifecycle: reactive({
state,
addFrozenListener,
}),
},
}
})