Bluesky app fork with some witchin' additions 💫

Add `useGetTimeAgo` and utils (#4556)

* Create a testable version of ago() and re-enable the disabled test (#4364)

* Enable the test of ago()

* Use test cases

This puts the input and the expected values next to each other.

* Create dateDiff function

This is a copy of ago(), but with the ability to specify the second date instead of using Date.now().

* Let ago() use dateDiff()

* Move constants close to usage

* Test dateDiff instead of ago

This makes it possible to test the dates without being forced to rely on what the current date is.

The commented out tests do not yet pass. This is fixed in later commits.

* Update dateDiff and enable the remaining tests

* Split up tests, use date-fns as helpers

* Remove old test

* Add long format

* Add hook

* Migrate to hooks

* Delete old code

* Or equal to

* Update comment

---------

Co-authored-by: Jan Aagaard <jan@aagaard.net>

authored by

Eric Bailey
Jan Aagaard
and committed by
GitHub
443beda7 08cfb095

+216 -133
-74
__tests__/lib/string.test.ts
··· 6 6 import {enforceLen} from '../../src/lib/strings/helpers' 7 7 import {detectLinkables} from '../../src/lib/strings/rich-text-detection' 8 8 import {shortenLinks} from '../../src/lib/strings/rich-text-manip' 9 - import {ago} from '../../src/lib/strings/time' 10 9 import { 11 10 makeRecordUri, 12 11 toNiceDomain, ··· 137 136 for (let i = 0; i < inputs.length; i++) { 138 137 const input = inputs[i] 139 138 const result = makeRecordUri(...input) 140 - expect(result).toEqual(outputs[i]) 141 - } 142 - }) 143 - }) 144 - 145 - // FIXME: Reenable after fixing non-deterministic test. 146 - describe.skip('ago', () => { 147 - const oneYearDate = new Date( 148 - new Date().setMonth(new Date().getMonth() - 11), 149 - ).setDate(new Date().getDate() - 28) 150 - 151 - const inputs = [ 152 - 1671461038, 153 - '04 Dec 1995 00:12:00 GMT', 154 - new Date(), 155 - new Date().setSeconds(new Date().getSeconds() - 10), 156 - new Date().setMinutes(new Date().getMinutes() - 10), 157 - new Date().setHours(new Date().getHours() - 1), 158 - new Date().setDate(new Date().getDate() - 1), 159 - new Date().setDate(new Date().getDate() - 20), 160 - new Date().setDate(new Date().getDate() - 25), 161 - new Date().setDate(new Date().getDate() - 28), 162 - new Date().setDate(new Date().getDate() - 29), 163 - new Date().setDate(new Date().getDate() - 30), 164 - new Date().setMonth(new Date().getMonth() - 1), 165 - new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate( 166 - new Date().getDate() - 20, 167 - ), 168 - new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate( 169 - new Date().getDate() - 25, 170 - ), 171 - new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate( 172 - new Date().getDate() - 28, 173 - ), 174 - new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate( 175 - new Date().getDate() - 29, 176 - ), 177 - new Date().setMonth(new Date().getMonth() - 11), 178 - new Date(new Date().setMonth(new Date().getMonth() - 11)).setDate( 179 - new Date().getDate() - 20, 180 - ), 181 - new Date(new Date().setMonth(new Date().getMonth() - 11)).setDate( 182 - new Date().getDate() - 25, 183 - ), 184 - oneYearDate, 185 - ] 186 - const outputs = [ 187 - new Date(1671461038).toLocaleDateString(), 188 - new Date('04 Dec 1995 00:12:00 GMT').toLocaleDateString(), 189 - 'now', 190 - '10s', 191 - '10m', 192 - '1h', 193 - '1d', 194 - '20d', 195 - '25d', 196 - '28d', 197 - '29d', 198 - '1mo', 199 - '1mo', 200 - '1mo', 201 - '1mo', 202 - '2mo', 203 - '2mo', 204 - '11mo', 205 - '11mo', 206 - '11mo', 207 - new Date(oneYearDate).toLocaleDateString(), 208 - ] 209 - 210 - it('correctly calculates how much time passed, in a string', () => { 211 - for (let i = 0; i < inputs.length; i++) { 212 - const result = ago(inputs[i]) 213 139 expect(result).toEqual(outputs[i]) 214 140 } 215 141 })
+102
src/lib/hooks/__tests__/useTimeAgo.test.ts
··· 1 + import {describe, expect, it} from '@jest/globals' 2 + import {MessageDescriptor} from '@lingui/core' 3 + import {addDays, subDays, subHours, subMinutes, subSeconds} from 'date-fns' 4 + 5 + import {dateDiff} from '../useTimeAgo' 6 + 7 + const lingui: any = (obj: MessageDescriptor) => obj.message 8 + 9 + const base = new Date('2024-06-17T00:00:00Z') 10 + 11 + describe('dateDiff', () => { 12 + it(`works with numbers`, () => { 13 + expect(dateDiff(subDays(base, 3), Number(base), {lingui})).toEqual('3d') 14 + }) 15 + it(`works with strings`, () => { 16 + expect(dateDiff(subDays(base, 3), base.toString(), {lingui})).toEqual('3d') 17 + }) 18 + it(`works with dates`, () => { 19 + expect(dateDiff(subDays(base, 3), base, {lingui})).toEqual('3d') 20 + }) 21 + 22 + it(`equal values return now`, () => { 23 + expect(dateDiff(base, base, {lingui})).toEqual('now') 24 + }) 25 + it(`future dates return now`, () => { 26 + expect(dateDiff(addDays(base, 3), base, {lingui})).toEqual('now') 27 + }) 28 + 29 + it(`values < 5 seconds ago return now`, () => { 30 + const then = subSeconds(base, 4) 31 + expect(dateDiff(then, base, {lingui})).toEqual('now') 32 + }) 33 + it(`values >= 5 seconds ago return seconds`, () => { 34 + const then = subSeconds(base, 5) 35 + expect(dateDiff(then, base, {lingui})).toEqual('5s') 36 + }) 37 + 38 + it(`values < 1 min return seconds`, () => { 39 + const then = subSeconds(base, 59) 40 + expect(dateDiff(then, base, {lingui})).toEqual('59s') 41 + }) 42 + it(`values >= 1 min return minutes`, () => { 43 + const then = subSeconds(base, 60) 44 + expect(dateDiff(then, base, {lingui})).toEqual('1m') 45 + }) 46 + it(`minutes round down`, () => { 47 + const then = subSeconds(base, 119) 48 + expect(dateDiff(then, base, {lingui})).toEqual('1m') 49 + }) 50 + 51 + it(`values < 1 hour return minutes`, () => { 52 + const then = subMinutes(base, 59) 53 + expect(dateDiff(then, base, {lingui})).toEqual('59m') 54 + }) 55 + it(`values >= 1 hour return hours`, () => { 56 + const then = subMinutes(base, 60) 57 + expect(dateDiff(then, base, {lingui})).toEqual('1h') 58 + }) 59 + it(`hours round down`, () => { 60 + const then = subMinutes(base, 119) 61 + expect(dateDiff(then, base, {lingui})).toEqual('1h') 62 + }) 63 + 64 + it(`values < 1 day return hours`, () => { 65 + const then = subHours(base, 23) 66 + expect(dateDiff(then, base, {lingui})).toEqual('23h') 67 + }) 68 + it(`values >= 1 day return days`, () => { 69 + const then = subHours(base, 24) 70 + expect(dateDiff(then, base, {lingui})).toEqual('1d') 71 + }) 72 + it(`days round down`, () => { 73 + const then = subHours(base, 47) 74 + expect(dateDiff(then, base, {lingui})).toEqual('1d') 75 + }) 76 + 77 + it(`values < 30 days return days`, () => { 78 + const then = subDays(base, 29) 79 + expect(dateDiff(then, base, {lingui})).toEqual('29d') 80 + }) 81 + it(`values >= 30 days return months`, () => { 82 + const then = subDays(base, 30) 83 + expect(dateDiff(then, base, {lingui})).toEqual('1mo') 84 + }) 85 + it(`months round down`, () => { 86 + const then = subDays(base, 59) 87 + expect(dateDiff(then, base, {lingui})).toEqual('1mo') 88 + }) 89 + it(`values are rounded by increments of 30`, () => { 90 + const then = subDays(base, 61) 91 + expect(dateDiff(then, base, {lingui})).toEqual('2mo') 92 + }) 93 + 94 + it(`values < 360 days return months`, () => { 95 + const then = subDays(base, 359) 96 + expect(dateDiff(then, base, {lingui})).toEqual('11mo') 97 + }) 98 + it(`values >= 360 days return the earlier value`, () => { 99 + const then = subDays(base, 360) 100 + expect(dateDiff(then, base, {lingui})).toEqual(then.toLocaleDateString()) 101 + }) 102 + })
+95
src/lib/hooks/useTimeAgo.ts
··· 1 + import {useCallback, useMemo} from 'react' 2 + import {msg, plural} from '@lingui/macro' 3 + import {I18nContext, useLingui} from '@lingui/react' 4 + import {differenceInSeconds} from 'date-fns' 5 + 6 + export type TimeAgoOptions = { 7 + lingui: I18nContext['_'] 8 + format?: 'long' | 'short' 9 + } 10 + 11 + export function useGetTimeAgo() { 12 + const {_} = useLingui() 13 + return useCallback( 14 + ( 15 + date: number | string | Date, 16 + options?: Omit<TimeAgoOptions, 'lingui'>, 17 + ) => { 18 + return dateDiff(date, Date.now(), {lingui: _, format: options?.format}) 19 + }, 20 + [_], 21 + ) 22 + } 23 + 24 + export function useTimeAgo( 25 + date: number | string | Date, 26 + options?: Omit<TimeAgoOptions, 'lingui'>, 27 + ): string { 28 + const timeAgo = useGetTimeAgo() 29 + return useMemo(() => { 30 + return timeAgo(date, {...options}) 31 + }, [date, options, timeAgo]) 32 + } 33 + 34 + const NOW = 5 35 + const MINUTE = 60 36 + const HOUR = MINUTE * 60 37 + const DAY = HOUR * 24 38 + const MONTH_30 = DAY * 30 39 + 40 + /** 41 + * Returns the difference between `earlier` and `later` dates, formatted as a 42 + * natural language string. 43 + * 44 + * - All month are considered exactly 30 days. 45 + * - Dates assume `earlier` <= `later`, and will otherwise return 'now'. 46 + * - Differences >= 360 days are returned as the "M/D/YYYY" string 47 + * - All values round down 48 + */ 49 + export function dateDiff( 50 + earlier: number | string | Date, 51 + later: number | string | Date, 52 + options: TimeAgoOptions, 53 + ): string { 54 + const _ = options.lingui 55 + const format = options?.format || 'short' 56 + const long = format === 'long' 57 + const diffSeconds = differenceInSeconds(new Date(later), new Date(earlier)) 58 + 59 + if (diffSeconds < NOW) { 60 + return _(msg`now`) 61 + } else if (diffSeconds < MINUTE) { 62 + return `${diffSeconds}${ 63 + long ? ` ${plural(diffSeconds, {one: 'second', other: 'seconds'})}` : 's' 64 + }` 65 + } else if (diffSeconds < HOUR) { 66 + const diff = Math.floor(diffSeconds / MINUTE) 67 + return `${diff}${ 68 + long ? ` ${plural(diff, {one: 'minute', other: 'minutes'})}` : 'm' 69 + }` 70 + } else if (diffSeconds < DAY) { 71 + const diff = Math.floor(diffSeconds / HOUR) 72 + return `${diff}${ 73 + long ? ` ${plural(diff, {one: 'hour', other: 'hours'})}` : 'h' 74 + }` 75 + } else if (diffSeconds < MONTH_30) { 76 + const diff = Math.floor(diffSeconds / DAY) 77 + return `${diff}${ 78 + long ? ` ${plural(diff, {one: 'day', other: 'days'})}` : 'd' 79 + }` 80 + } else { 81 + const diff = Math.floor(diffSeconds / MONTH_30) 82 + if (diff < 12) { 83 + return `${diff}${ 84 + long ? ` ${plural(diff, {one: 'month', other: 'months'})}` : 'mo' 85 + }` 86 + } else { 87 + const str = new Date(earlier).toLocaleDateString() 88 + 89 + if (long) { 90 + return _(msg`on ${str}`) 91 + } 92 + return str 93 + } 94 + } 95 + }
-42
src/lib/strings/time.ts
··· 1 - const NOW = 5 2 - const MINUTE = 60 3 - const HOUR = MINUTE * 60 4 - const DAY = HOUR * 24 5 - const MONTH_30 = DAY * 30 6 - const MONTH = DAY * 30.41675 // This results in 365.001 days in a year, which is close enough for nearly all cases 7 - export function ago(date: number | string | Date): string { 8 - let ts: number 9 - if (typeof date === 'string') { 10 - ts = Number(new Date(date)) 11 - } else if (date instanceof Date) { 12 - ts = Number(date) 13 - } else { 14 - ts = date 15 - } 16 - const diffSeconds = Math.floor((Date.now() - ts) / 1e3) 17 - if (diffSeconds < NOW) { 18 - return `now` 19 - } else if (diffSeconds < MINUTE) { 20 - return `${diffSeconds}s` 21 - } else if (diffSeconds < HOUR) { 22 - return `${Math.floor(diffSeconds / MINUTE)}m` 23 - } else if (diffSeconds < DAY) { 24 - return `${Math.floor(diffSeconds / HOUR)}h` 25 - } else if (diffSeconds < MONTH_30) { 26 - return `${Math.round(diffSeconds / DAY)}d` 27 - } else { 28 - let months = diffSeconds / MONTH 29 - if (months % 1 >= 0.9) { 30 - months = Math.ceil(months) 31 - } else { 32 - months = Math.floor(months) 33 - } 34 - 35 - if (months < 12) { 36 - return `${months}mo` 37 - } else { 38 - return new Date(ts).toLocaleDateString() 39 - } 40 - } 41 - } 42 - 43 1 export function niceDate(date: number | string | Date) { 44 2 const d = new Date(date) 45 3 return `${d.toLocaleDateString('en-us', {
+6 -6
src/view/com/util/TimeElapsed.tsx
··· 1 1 import React from 'react' 2 2 3 + import {useGetTimeAgo} from '#/lib/hooks/useTimeAgo' 3 4 import {useTickEveryMinute} from '#/state/shell' 4 - import {ago} from 'lib/strings/time' 5 5 6 6 export function TimeElapsed({ 7 7 timestamp, 8 8 children, 9 - timeToString = ago, 9 + timeToString, 10 10 }: { 11 11 timestamp: string 12 12 children: ({timeElapsed}: {timeElapsed: string}) => JSX.Element 13 13 timeToString?: (timeElapsed: string) => string 14 14 }) { 15 + const ago = useGetTimeAgo() 16 + const format = timeToString ?? ago 15 17 const tick = useTickEveryMinute() 16 - const [timeElapsed, setTimeAgo] = React.useState(() => 17 - timeToString(timestamp), 18 - ) 18 + const [timeElapsed, setTimeAgo] = React.useState(() => format(timestamp)) 19 19 20 20 const [prevTick, setPrevTick] = React.useState(tick) 21 21 if (prevTick !== tick) { 22 22 setPrevTick(tick) 23 - setTimeAgo(timeToString(timestamp)) 23 + setTimeAgo(format(timestamp)) 24 24 } 25 25 26 26 return children({timeElapsed})
+13 -11
src/view/screens/Log.tsx
··· 1 1 import React from 'react' 2 2 import {StyleSheet, TouchableOpacity, View} from 'react-native' 3 - import {useFocusEffect} from '@react-navigation/native' 4 3 import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome' 5 - import {NativeStackScreenProps, CommonNavigatorParams} from 'lib/routes/types' 6 - import {ScrollView} from '../com/util/Views' 7 - import {s} from 'lib/styles' 8 - import {ViewHeader} from '../com/util/ViewHeader' 9 - import {Text} from '../com/util/text/Text' 10 - import {usePalette} from 'lib/hooks/usePalette' 11 - import {getEntries} from '#/logger/logDump' 12 - import {ago} from 'lib/strings/time' 4 + import {msg} from '@lingui/macro' 13 5 import {useLingui} from '@lingui/react' 14 - import {msg} from '@lingui/macro' 6 + import {useFocusEffect} from '@react-navigation/native' 7 + 8 + import {useGetTimeAgo} from '#/lib/hooks/useTimeAgo' 9 + import {getEntries} from '#/logger/logDump' 15 10 import {useSetMinimalShellMode} from '#/state/shell' 11 + import {usePalette} from 'lib/hooks/usePalette' 12 + import {CommonNavigatorParams, NativeStackScreenProps} from 'lib/routes/types' 13 + import {s} from 'lib/styles' 14 + import {Text} from '../com/util/text/Text' 15 + import {ViewHeader} from '../com/util/ViewHeader' 16 + import {ScrollView} from '../com/util/Views' 16 17 17 18 export function LogScreen({}: NativeStackScreenProps< 18 19 CommonNavigatorParams, ··· 22 23 const {_} = useLingui() 23 24 const setMinimalShellMode = useSetMinimalShellMode() 24 25 const [expanded, setExpanded] = React.useState<string[]>([]) 26 + const timeAgo = useGetTimeAgo() 25 27 26 28 useFocusEffect( 27 29 React.useCallback(() => { ··· 70 72 /> 71 73 ) : undefined} 72 74 <Text type="sm" style={[styles.ts, pal.textLight]}> 73 - {ago(entry.timestamp)} 75 + {timeAgo(entry.timestamp)} 74 76 </Text> 75 77 </TouchableOpacity> 76 78 {expanded.includes(entry.id) ? (