|
| 1 | +/* |
| 2 | + * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors |
| 3 | + * SPDX-License-Identifier: AGPL-3.0-or-later |
| 4 | + */ |
| 5 | + |
| 6 | +import { createSharedComposable } from '@vueuse/core' |
| 7 | +import { onBeforeMount, onBeforeUnmount, readonly, ref } from 'vue' |
| 8 | +import { grantUserGesturedPermission } from '../../../../shared/grantUserGesturedPermission.ts' |
| 9 | +import { once } from '../../../../shared/utils.ts' |
| 10 | + |
| 11 | +/** |
| 12 | + * Grant IdleDetector permission |
| 13 | + */ |
| 14 | +const grantIdleDetectorPermission = once(async () => { |
| 15 | + const permission = await grantUserGesturedPermission(() => IdleDetector.requestPermission()) |
| 16 | + if (permission !== 'granted') { |
| 17 | + throw new Error('Unexpected permission denied for IdleDetector') |
| 18 | + } |
| 19 | +}) |
| 20 | + |
| 21 | +/** |
| 22 | + * Use IdleDetector API |
| 23 | + * |
| 24 | + * @param threshold - IdleDetector's threshold |
| 25 | + */ |
| 26 | +export const useIdleDetector = createSharedComposable((threshold: number = 60_000) => { |
| 27 | + const userState = ref<UserIdleState | undefined>(undefined) |
| 28 | + const screenState = ref<ScreenIdleState | undefined>(undefined) |
| 29 | + const abortController = new AbortController() |
| 30 | + |
| 31 | + onBeforeMount(async () => { |
| 32 | + try { |
| 33 | + await grantIdleDetectorPermission() |
| 34 | + |
| 35 | + const idleDetector = new IdleDetector() |
| 36 | + idleDetector.addEventListener('change', () => { |
| 37 | + userState.value = idleDetector.userState! |
| 38 | + screenState.value = idleDetector.screenState! |
| 39 | + }) |
| 40 | + await idleDetector.start({ |
| 41 | + threshold, |
| 42 | + signal: abortController.signal, |
| 43 | + }) |
| 44 | + } catch (error) { |
| 45 | + console.error('Unexpected error on starting IdleDetector:', error) |
| 46 | + } |
| 47 | + }) |
| 48 | + |
| 49 | + onBeforeUnmount(() => abortController.abort()) |
| 50 | + |
| 51 | + return { |
| 52 | + screenState: readonly(screenState), |
| 53 | + userState: readonly(userState), |
| 54 | + } |
| 55 | +}) |
0 commit comments