-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseIsUserActive.ts
More file actions
182 lines (159 loc) · 4.6 KB
/
useIsUserActive.ts
File metadata and controls
182 lines (159 loc) · 4.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import { useEffect, useState } from 'react'
enum State {
idle = 'idle',
active = 'active'
}
const DEFAULT_INITIAL_STATE = State.active
const DEFAULT_ACTIVITY_EVENTS = [
'click',
'mousemove',
'keydown',
'DOMMouseScroll',
'mousewheel',
'mousedown',
'touchstart',
'touchmove',
'focus'
]
const DEFAULT_INACTIVITY_EVENTS = ['blur', 'visibilitychange']
const DEFAULT_IGNORED_EVENTS_WHEN_IDLE = ['mousemove']
let hidden: 'hidden' | undefined, visibilityChangeEvent: 'visibilitychange' | undefined
if (typeof document.hidden !== 'undefined') {
hidden = 'hidden'
visibilityChangeEvent = 'visibilitychange'
} else {
const prefixes = ['webkit', 'moz', 'ms']
for (let i = 0; i < prefixes.length; i++) {
const prefix = prefixes[i]
if (
typeof (document as unknown as Record<string, unknown>)[`${prefix}Hidden`] !== 'undefined'
) {
hidden = `${prefix}Hidden` as 'hidden'
visibilityChangeEvent = `${prefix}visibilitychange` as 'visibilitychange'
break
}
}
}
interface ActivityDetectorParams {
/**
* Events which force a transition to 'active'
*/
activityEvents?: string[]
/**
* Events which force a transition to 'idle'
*/
inactivityEvents?: string[]
/**
* Events that are ignored in 'idle' state
*/
ignoredEventsWhenIdle?: string[]
/**
* Inactivity time in ms to transition to 'idle'
*/
timeToIdle?: number
/**
* One of 'active' or 'idle'
*/
initialState?: State
autoInit?: boolean
}
function createActivityDetector({
activityEvents = DEFAULT_ACTIVITY_EVENTS,
inactivityEvents = DEFAULT_INACTIVITY_EVENTS,
ignoredEventsWhenIdle = DEFAULT_IGNORED_EVENTS_WHEN_IDLE,
timeToIdle = 30000,
initialState = DEFAULT_INITIAL_STATE,
autoInit = true
}: ActivityDetectorParams = {}) {
const listeners: Record<State, (() => void)[]> = { [State.active]: [], [State.idle]: [] }
let state: State
let timer: number
const setState = (newState: State) => {
clearTimeout(timer)
if (newState === State.active) {
timer = window.setTimeout(() => setState(State.idle), timeToIdle)
}
if (state !== newState) {
state = newState
listeners[state].forEach((l) => l())
}
}
const handleUserActivityEvent = (event: Event) => {
if (state === State.active || ignoredEventsWhenIdle.indexOf(event.type) < 0) {
setState(State.active)
}
}
const handleUserInactivityEvent = () => {
setState(State.idle)
}
const handleVisibilityChangeEvent = () => {
setState(document[hidden!] ? State.idle : State.active)
}
/**
* Starts the activity detector with the given state.
*/
const init = (firstState = DEFAULT_INITIAL_STATE) => {
setState(firstState === State.active ? State.active : State.idle)
activityEvents.forEach((eventName) =>
window.addEventListener(eventName, handleUserActivityEvent)
)
inactivityEvents
.filter((eventName) => eventName !== 'visibilitychange')
.forEach((eventName) => window.addEventListener(eventName, handleUserInactivityEvent))
if (inactivityEvents.indexOf('visibilitychange') >= 0 && visibilityChangeEvent != null) {
document.addEventListener(visibilityChangeEvent, handleVisibilityChangeEvent)
}
}
/**
* Register an event listener for the required event
*/
const on = (eventName: State, listener: () => void) => {
listeners[eventName].push(listener)
const off = () => {
const index = listeners[eventName].indexOf(listener)
if (index >= 0) {
listeners[eventName].splice(index, 1)
}
}
return off
}
/**
* Stops the activity detector and clean the listeners
*/
const stop = () => {
listeners[State.active] = []
listeners[State.idle] = []
clearTimeout(timer)
activityEvents.forEach((eventName) =>
window.removeEventListener(eventName, handleUserActivityEvent)
)
inactivityEvents.forEach((eventName) =>
window.removeEventListener(eventName, handleUserInactivityEvent)
)
if (visibilityChangeEvent != null) {
document.removeEventListener(visibilityChangeEvent, handleVisibilityChangeEvent)
}
}
if (autoInit) {
init(initialState)
}
return { on, stop, init }
}
export default function useIsUserActive(timeToIdle: number): boolean {
const [active, setActive] = useState(true)
useEffect(() => {
const activityDetector = createActivityDetector({
timeToIdle
})
activityDetector.on(State.idle, () => {
setActive(false)
})
activityDetector.on(State.active, () => {
setActive(true)
})
return () => {
activityDetector.stop()
}
}, [timeToIdle])
return active
}