-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathcountdown.taro.tsx
More file actions
363 lines (331 loc) · 9.22 KB
/
countdown.taro.tsx
File metadata and controls
363 lines (331 loc) · 9.22 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import React, {
useState,
useRef,
useEffect,
ForwardRefRenderFunction,
useImperativeHandle,
} from 'react'
import classNames from 'classnames'
import { View } from '@tarojs/components'
import { ComponentDefaults } from '@/utils/typings'
import { padZero } from '@/utils/pad-zero'
import { web } from '@/utils/taro/platform'
import { TaroCountDownProps, CountDownTime } from '@/types'
const defaultProps = {
...ComponentDefaults,
type: 'default',
paused: false,
startTime: Date.now(),
endTime: Date.now(),
remainingTime: 0,
millisecond: false,
format: 'HH:mm:ss',
autoStart: true,
time: 0,
destroy: false,
ariaLabel: '倒计时',
} as TaroCountDownProps
const InternalCountDown: ForwardRefRenderFunction<
unknown,
Partial<TaroCountDownProps>
> = (props, ref) => {
const {
type,
paused,
startTime,
endTime,
remainingTime,
millisecond,
format,
autoStart,
time,
destroy,
className,
style,
onEnd,
onPaused,
onRestart,
onUpdate,
children,
ariaLabel,
...rest
} = { ...defaultProps, ...props }
const classPrefix = 'nut-countdown'
const [restTimeStamp, setRestTime] = useState(0)
const stateRef = useRef({
pauseTime: 0,
curr: 0,
isPaused: paused,
isIninted: false,
timer: 0,
restTime: 0,
counting: !paused && autoStart, // 是否处于倒计时中
handleEndTime: Date.now(), // 最终截止时间
diffTime: 0, // 设置了 startTime 时,与 date.now() 的差异
})
const [role, setRole] = useState('')
// ARIA alert提示内容
const [alertContent, setAlertContent] = useState('')
const alertTimerRef = useRef<number>()
// 时间戳转换 或 获取当前时间的时间戳
const getTimeStamp = (timeStr?: string | number) => {
if (!timeStr) return Date.now()
let t = timeStr
t = Number(t) > 0 ? +t : t.toString().replace(/-/g, '/')
return new Date(t).getTime()
}
// 倒计时 interval
const initTime = () => {
if (remainingTime) {
stateRef.current.handleEndTime = Date.now() + Number(remainingTime)
} else {
stateRef.current.handleEndTime = endTime
if (web()) {
stateRef.current.diffTime = Date.now() - getTimeStamp(startTime) // 时间差
}
}
if (!stateRef.current.counting) stateRef.current.counting = true
tick()
}
const tick = () => {
stateRef.current.timer = requestAnimationFrame(() => {
if (stateRef.current.counting) {
const currentTime = Date.now() - stateRef.current.diffTime
const remainTime = Math.max(
stateRef.current.handleEndTime - currentTime,
0
)
stateRef.current.restTime = remainTime
setRestTime(remainTime)
if (!remainTime) {
stateRef.current.counting = false
pause()
onEnd && onEnd()
setRole('alert')
setAlertContent(`${ariaLabel}倒计时结束`)
alertTimerRef.current = window.setTimeout(() => {
setRole('')
setAlertContent('')
}, 3000)
}
if (remainTime > 0) {
tick()
}
}
})
}
// 将倒计时剩余时间格式化 参数:t时间戳 type custom 自定义类型
const formatRemainTime = (t: number, type?: string) => {
const ts = t
const rest = {
d: 0,
h: 0,
m: 0,
s: 0,
ms: 0,
}
const SECOND = 1000
const MINUTE = 60 * SECOND
const HOUR = 60 * MINUTE
const DAY = 24 * HOUR
if (ts > 0) {
rest.d = ts >= SECOND ? Math.floor(ts / DAY) : 0
rest.h = Math.floor((ts % DAY) / HOUR)
rest.m = Math.floor((ts % HOUR) / MINUTE)
rest.s = Math.floor((ts % MINUTE) / SECOND)
rest.ms = Math.floor(ts % SECOND)
}
return type === 'custom' ? rest : parseFormat({ ...rest })
}
const parseFormat = (time: CountDownTime) => {
const { d } = time
let { h, m, s, ms } = time
let formatCache = format
if (formatCache.includes('DD')) {
formatCache = formatCache.replace('DD', padZero(d))
} else {
h += Number(d) * 24
}
if (formatCache.includes('HH')) {
formatCache = formatCache.replace('HH', padZero(h))
} else {
m += Number(h) * 60
}
if (formatCache.includes('mm')) {
formatCache = formatCache.replace('mm', padZero(m))
} else {
s += Number(m) * 60
}
if (formatCache.includes('ss')) {
formatCache = formatCache.replace('ss', padZero(s))
} else {
ms += Number(s) * 1000
}
if (formatCache.includes('S')) {
const msC = padZero(ms, 3).toString()
if (formatCache.includes('SSS')) {
formatCache = formatCache.replace('SSS', msC)
} else if (formatCache.includes('SS')) {
formatCache = formatCache.replace('SS', msC.slice(0, 2))
} else if (formatCache.includes('S')) {
formatCache = formatCache.replace('S', msC.slice(0, 1))
}
}
return formatCache
}
const pause = () => {
cancelAnimationFrame(stateRef.current.timer)
stateRef.current.counting = false
onPaused && onPaused(stateRef.current.restTime)
}
useImperativeHandle(ref, () => ({
start: () => {
if (!stateRef.current.counting && !autoStart) {
stateRef.current.counting = true
stateRef.current.handleEndTime =
Date.now() + Number(stateRef.current.restTime)
tick()
onRestart && onRestart(stateRef.current.restTime)
}
},
pause: () => {
cancelAnimationFrame(stateRef.current.timer)
stateRef.current.counting = false
onPaused && onPaused(stateRef.current.restTime)
},
reset: () => {
if (!autoStart) {
pause()
stateRef.current.restTime = time
setRestTime(time)
}
},
}))
// 监听值变更
useEffect(() => {
const tranTime = formatRemainTime(stateRef.current.restTime, 'custom')
onUpdate && onUpdate(tranTime as CountDownTime)
}, [restTimeStamp])
// 监听暂停
useEffect(() => {
if (stateRef.current.isIninted) {
if (paused) {
if (stateRef.current.counting) {
pause()
}
} else {
if (!stateRef.current.counting) {
stateRef.current.counting = true
stateRef.current.handleEndTime =
Date.now() + Number(stateRef.current.restTime)
tick()
}
onRestart && onRestart(stateRef.current.restTime)
}
}
}, [paused])
// 监听开始结束时间变更
useEffect(() => {
if (stateRef.current.isIninted) {
initTime()
}
}, [endTime, startTime, remainingTime])
// 初始化
useEffect(() => {
if (autoStart) {
initTime()
} else {
stateRef.current.restTime = time
setRestTime(time)
}
if (!stateRef.current.isIninted) {
stateRef.current.isIninted = true
}
return componentWillUnmount
}, [])
const componentWillUnmount = () => {
destroy && cancelAnimationFrame(stateRef.current.timer)
if (alertTimerRef.current) {
clearTimeout(alertTimerRef.current)
}
}
const getUnit = (unit: string) => {
const formatArr = format.split(/(DD|HH|mm|ss|S)/)
const index = formatArr.indexOf(unit)
return index > -1 ? formatArr[index + 1] : ':'
}
const renderTimeItem = (
formatUnit: string,
time: number | string,
unit = ''
) => {
return (
<>
{format.includes(formatUnit) ? (
<>
<View
className={classNames({
[`${classPrefix}-number`]: type === 'default',
[`${classPrefix}-number-primary`]: type === 'primary',
[`${classPrefix}-number-text`]: type === 'text',
})}
>
{(unit && unit !== 'DD') || (!unit && formatUnit === 'ss')
? padZero(time)
: time}
</View>
{unit ? (
<View className={`${classPrefix}-unit`}>{getUnit(unit)}</View>
) : null}
</>
) : null}
</>
)
}
const renderTaroTime = () => {
const formatCache = formatRemainTime(stateRef.current.restTime, 'custom')
const { d, h, m, s, ms } = formatCache as CountDownTime
const digit = format.match(/S/g)?.length
// format可能是DD天HH时mm分SSS秒或者DD天HH时mm分S秒或是DD:HH:mm:ss
return (
<>
{renderTimeItem('DD', d, 'DD')}
{renderTimeItem('HH', h, 'HH')}
{renderTimeItem('mm', m, 'mm')}
{renderTimeItem('ss', s)}
{(format.includes('S') || getUnit('ss') !== ':') && (
<>
<View className={`${classPrefix}-unit`}>{getUnit('ss')}</View>
</>
)}
{renderTimeItem(
'S',
padZero(ms, 3)
.toString()
.slice(0, digit || 1)
)}
</>
)
}
return (
<>
{children || (
<View
className={`${classPrefix} ${className}`}
style={{ ...style }}
ariaLabel={ariaLabel}
{...rest}
>
{renderTaroTime()}
<View role={role} style={{ display: 'none' }}>
{alertContent}
</View>
</View>
)}
</>
)
}
export const CountDown = React.forwardRef<unknown, Partial<TaroCountDownProps>>(
InternalCountDown
)
CountDown.displayName = 'NutCountDown'