-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathindex.ts
More file actions
106 lines (85 loc) · 2.84 KB
/
index.ts
File metadata and controls
106 lines (85 loc) · 2.84 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
import IdleDetector from "./idle-detector"
const INTERVAL = 1000
type StateChangeReason = 'visible' | 'idle' | 'initial'
class TrackContext {
docVisible: boolean = false
idleDetector: IdleDetector
onPause: (reason: StateChangeReason) => void
onResume: (reason: StateChangeReason) => void
constructor({ onPause, onResume }: { onPause: (reason: StateChangeReason) => void, onResume: (reason: StateChangeReason) => void }) {
this.onPause = onPause
this.onResume = onResume
this.detectDocVisible()
document?.addEventListener('visibilitychange', () => this.detectDocVisible())
this.idleDetector = new IdleDetector({
onIdle: () => this.onPause?.('idle'),
onActive: () => this.docVisible && this.onResume?.('idle')
})
}
private detectDocVisible() {
const before = this.isActive()
this.docVisible = document?.visibilityState === 'visible'
const after = this.isActive()
before && !after && this.onPause?.('visible')
!before && after && this.onResume?.('visible')
}
isActive(): boolean {
if (!this.docVisible) return false
return !this.idleDetector?.needTimeout() || !this.idleDetector?.isIdle()
}
}
export type NormalTrackerOption = {
onReport: (ev: timer.core.Event) => Promise<void>
onResume?: (reason: StateChangeReason) => void
onPause?: (reason: StateChangeReason) => void
}
/**
* Normal tracker
*/
export default class NormalTracker {
context: TrackContext | undefined
start: number = Date.now()
option: NormalTrackerOption
constructor(option: NormalTrackerOption) {
this.option = option
}
init() {
// Resume if idle before reloading
this.resume('idle')
this.context = new TrackContext({
onPause: reason => this.pause(reason),
onResume: reason => this.resume(reason),
})
setInterval(() => {
if (!this.context?.isActive()) return
this.collect()
}, INTERVAL)
}
private async collect(ignoreTabCheck?: boolean) {
const now = Date.now()
const lastTime = this.start
this.start = now
const interval = now - lastTime
if (interval <= 0 || interval > INTERVAL * 2) {
// Invalid time
return
}
const data: timer.core.Event = {
start: lastTime,
end: now,
url: location?.href,
ignoreTabCheck: !!ignoreTabCheck
}
try {
await this.option?.onReport?.(data)
} catch (_) { }
}
private pause(reason: StateChangeReason) {
this.option?.onPause?.(reason)
this.collect(true)
}
private resume(reason: StateChangeReason) {
this.option?.onResume?.(reason)
this.start = Date.now()
}
}