-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathuseIdleDetector.ts
More file actions
55 lines (48 loc) · 1.6 KB
/
useIdleDetector.ts
File metadata and controls
55 lines (48 loc) · 1.6 KB
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
/*
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { createSharedComposable } from '@vueuse/core'
import { onBeforeMount, onBeforeUnmount, readonly, ref } from 'vue'
import { grantUserGesturedPermission } from '../../../../shared/grantUserGesturedPermission.ts'
import { once } from '../../../../shared/utils.ts'
/**
* Grant IdleDetector permission
*/
const grantIdleDetectorPermission = once(async () => {
const permission = await grantUserGesturedPermission(() => IdleDetector.requestPermission())
if (permission !== 'granted') {
throw new Error('Unexpected permission denied for IdleDetector')
}
})
/**
* Use IdleDetector API
*
* @param threshold - IdleDetector's threshold
*/
export const useIdleDetector = createSharedComposable((threshold: number = 60_000) => {
const userState = ref<UserIdleState | undefined>(undefined)
const screenState = ref<ScreenIdleState | undefined>(undefined)
const abortController = new AbortController()
onBeforeMount(async () => {
try {
await grantIdleDetectorPermission()
const idleDetector = new IdleDetector()
idleDetector.addEventListener('change', () => {
userState.value = idleDetector.userState!
screenState.value = idleDetector.screenState!
})
await idleDetector.start({
threshold,
signal: abortController.signal,
})
} catch (error) {
console.error('Unexpected error on starting IdleDetector:', error)
}
})
onBeforeUnmount(() => abortController.abort())
return {
screenState: readonly(screenState),
userState: readonly(userState),
}
})