-
Notifications
You must be signed in to change notification settings - Fork 474
/
app-idle.js
42 lines (35 loc) · 1.08 KB
/
app-idle.js
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
// Extracted from https://github.com/HenrikJoreteg/redux-bundler/blob/c1b8ce7629ee6c389f4155b3254e530bd09c868e/src/bundles/create-reactor-bundle.js
import { debounce, ric, raf } from 'redux-bundler'
const defaults = {
idleTimeout: 2000,
idleAction: 'APP_IDLE',
stopWhenTabInactive: false
}
const ricOptions = { timeout: 500 }
export const getIdleDispatcher = (stopWhenInactive, timeout, fn) =>
debounce(() => {
// the requestAnimationFrame ensures it doesn't run when tab isn't active
stopWhenInactive ? raf(() => ric(fn, ricOptions)) : ric(fn, ricOptions)
}, timeout)
export default spec => ({
name: 'appIdle',
init: store => {
const opts = Object.assign({}, defaults, spec)
const { idleAction, idleTimeout } = opts
let idleDispatcher
if (idleTimeout) {
idleDispatcher = getIdleDispatcher(
opts.stopWhenTabInactive,
idleTimeout,
() => store.dispatch({ type: idleAction })
)
}
const callback = () => {
if (idleDispatcher) {
idleDispatcher()
}
}
store.subscribe(callback)
callback()
}
})