-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathuseAppIdle.ts
More file actions
51 lines (41 loc) · 1.41 KB
/
useAppIdle.ts
File metadata and controls
51 lines (41 loc) · 1.41 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
/*
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { createSharedComposable, useEventListener } from '@vueuse/core'
import { onBeforeUnmount, ref } from 'vue'
const WINDOW_ACTIVE_EVENTS: (keyof WindowEventMap)[] = ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel']
/**
* Whether user is idle in the app (away) - interacted with the app (mouse, keyboard, touch) in the last THRESHOLD minutes
* or made document visible
*
* @param threshold - How long user is considered active after interaction in ms, default is 1 minute
*/
export const useAppIdle = createSharedComposable((threshold: number = 60_000) => {
const isIdle = ref(false)
let activityTimeout: number
/**
* Set new isIdle value and start
*
* @param newIsIdle - New isIdle
*/
function setIsIdle(newIsIdle: boolean) {
isIdle.value = newIsIdle
clearTimeout(activityTimeout)
if (!newIsIdle) {
// TODO: separate tsconfig for main process (Node.js Environment) and renderer process (Browser Environment)
activityTimeout = setTimeout(() => setIsIdle(true), threshold) as unknown as number
}
}
useEventListener(WINDOW_ACTIVE_EVENTS, () => {
setIsIdle(false)
})
useEventListener(document, 'visibilitychange', () => {
setIsIdle(document.hidden)
})
setIsIdle(false)
onBeforeUnmount(() => {
clearTimeout(activityTimeout)
})
return isIdle
})