forked from nmn/react-timeago
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
167 lines (148 loc) · 4.56 KB
/
index.js
File metadata and controls
167 lines (148 loc) · 4.56 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
// @flow
import * as React from 'react'
import { useEffect, useState } from 'react'
import dateParser from './dateParser'
import defaultFormatter from './defaultFormatter'
export type { Formatter, Suffix, Unit } from './types'
export type Props = $ReadOnly<{
/** If the component should update itself over time */
live?: boolean,
/** minimum amount of time in seconds between re-renders */
minPeriod?: number,
/** Maximum time between re-renders in seconds. The component should update at least once every `x` seconds */
maxPeriod?: number,
/** The container to render the string into. You could use a string like `span` or a custom component */
component?: string | React.ComponentType<{ ... }>,
/**
* A title used for setting the title attribute if a <time> HTML Element is used.
*/
title?: string,
/** A function to decide how to format the date.
* If you use this, react-timeago is basically acting like a glorified setInterval for you.
*/
formatter?: Formatter,
/** The Date to display. An actual Date object or something that can be fed to new Date */
date: string | number | Date,
/** A function that returns what Date.now would return. Primarily for server
* date: string | number | Date + * rendering.
*/
now?: () => number,
...
}>
// Just some simple constants for readability
const MINUTE = 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const WEEK = DAY * 7
const MONTH = DAY * 30
const YEAR = DAY * 365
const defaultNow = () => Date.now()
export default function TimeAgo({
date,
formatter,
component = 'time',
live = true,
minPeriod = 0,
maxPeriod = WEEK,
title,
now = defaultNow,
...passDownProps
}: Props): null | React.MixedElement {
const [timeNow, setTimeNow] = useState(now())
useEffect(() => {
if (!live) {
return
}
const tick = (): 0 | TimeoutID => {
const then = dateParser(date).valueOf()
if (!then) {
console.warn('[react-timeago] Invalid Date provided')
return 0
}
const seconds = Math.round(Math.abs(timeNow - then) / 1000)
const unboundPeriod =
seconds < MINUTE
? 1000
: seconds < HOUR
? 1000 * MINUTE
: seconds < DAY
? 1000 * HOUR
: 1000 * WEEK
const period = Math.min(
Math.max(unboundPeriod, minPeriod * 1000),
maxPeriod * 1000,
)
if (period) {
return setTimeout(() => {
setTimeNow(now())
}, period)
}
return 0
}
const timeoutId = tick()
return () => {
if (timeoutId) {
clearTimeout(timeoutId)
}
}
}, [date, live, maxPeriod, minPeriod, now, timeNow])
useEffect(() => {
setTimeNow(now())
}, [date])
const Komponent = component
const then = dateParser(date).valueOf()
if (!then) {
return null
}
const seconds = Math.round(Math.abs(timeNow - then) / 1000)
const suffix = then < timeNow ? 'ago' : 'from now'
const [value, unit] =
seconds < MINUTE
? [Math.round(seconds), 'second']
: seconds < HOUR
? [Math.round(seconds / MINUTE), 'minute']
: seconds < DAY
? [Math.round(seconds / HOUR), 'hour']
: seconds < WEEK
? [Math.round(seconds / DAY), 'day']
: seconds < MONTH
? [Math.round(seconds / WEEK), 'week']
: seconds < YEAR
? [Math.round(seconds / MONTH), 'month']
: [Math.round(seconds / YEAR), 'year']
const passDownTitle =
typeof title === 'undefined'
? typeof date === 'string'
? date
: dateParser(date).toISOString().substring(0, 16).replace('T', ' ')
: title
const spreadProps =
Komponent === 'time'
? { ...passDownProps, dateTime: dateParser(date).toISOString() }
: passDownProps
const nextFormatter = (
value: number = value,
unit: Unit = unit,
suffix: Suffix = suffix,
epochMilliseconds: number = then,
nextFormatter: Formatter = defaultFormatter,
now: () => number = now,
) =>
defaultFormatter(value, unit, suffix, epochMilliseconds, nextFormatter, now)
const effectiveFormatter: Formatter = formatter || defaultFormatter
let content
try {
content = effectiveFormatter(value, unit, suffix, then, nextFormatter, now)
if (!content) {
content = defaultFormatter(value, unit, suffix, then, nextFormatter, now)
}
} catch (error) {
console.error('[react-timeago] Formatter threw an error:', error)
content = defaultFormatter(value, unit, suffix, then, nextFormatter, now)
}
return (
<Komponent {...spreadProps} title={passDownTitle}>
{content}
</Komponent>
)
}