forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseCount.ts
More file actions
84 lines (66 loc) · 2 KB
/
useCount.ts
File metadata and controls
84 lines (66 loc) · 2 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
import { onScopeDispose, ref, Ref, watch } from 'vue'
type CountDownOptions = {
countdown: number
onComplete?: NoArgCallback
onTick?: ArgCallback<number>
}
export const useCountDown = (option: CountDownOptions): NoArgCallback => {
const { countdown, onComplete, onTick } = option
const start = Date.now()
let left = countdown * 1000
const timer = setInterval(() => {
left = Math.max(start + countdown * 1000 - Date.now(), 0)
onTick?.(left)
if (!left) {
onComplete?.()
clearInterval(timer)
}
}, 100)
return () => clearInterval(timer)
}
type CountUpOptions = {
value: Ref<number>
duration?: number
onFinish?: NoArgCallback
}
export const useCountUp = (options: CountUpOptions) => {
const { value, duration = 2, onFinish } = options
const current = ref(0)
let raf: number | null = null
let startTime: number | null = null
let lastUpdate = 0
const clear = (): void => {
if (!raf) return
cancelAnimationFrame(raf)
raf = null
}
const animate = (ts: number): void => {
if (!raf) return
if (ts - lastUpdate < 50) {
raf = requestAnimationFrame(animate)
return
}
lastUpdate = ts
if (startTime === null) startTime = ts
const elapsed = ts - startTime
const progress = Math.min(elapsed / (duration * 1000), 1)
const ease = 1 - (1 - progress) ** 3
const target = Math.round(value.value)
const start = Math.round(current.value)
current.value = Math.round(start + (target - start) * ease)
if (progress >= 1) {
current.value = target
onFinish?.()
raf = null
return
}
raf = requestAnimationFrame(animate)
}
watch(value, () => {
clear()
lastUpdate = 0
raf = requestAnimationFrame(animate)
}, { immediate: true })
onScopeDispose(clear)
return { current, clear }
}