|
|
import { sprintf, __ } from '@wordpress/i18n'; |
|
|
import { useEffect, useMemo, useState } from 'react'; |
|
|
import { useLocale } from '../../app/locale'; |
|
|
import { formatDate } from '../../utils/datetime'; |
|
|
|
|
|
function useRelativeTime( date: Date, locale: string, formatOptions?: Intl.DateTimeFormatOptions ) { |
|
|
const [ now, setNow ] = useState( () => new Date() ); |
|
|
|
|
|
useEffect( () => { |
|
|
const intervalId = setInterval( () => setNow( new Date() ), 10000 ); |
|
|
return () => clearInterval( intervalId ); |
|
|
}, [] ); |
|
|
|
|
|
return useMemo( () => { |
|
|
const millisAgo = now.getTime() - date.getTime(); |
|
|
|
|
|
|
|
|
if ( isNaN( date.getTime() ) || millisAgo < 0 ) { |
|
|
return formatDate( date, locale, formatOptions ); |
|
|
} |
|
|
|
|
|
const secondsAgo = Math.floor( millisAgo / 1000 ); |
|
|
const minutesAgo = Math.floor( secondsAgo / 60 ); |
|
|
const hoursAgo = Math.floor( minutesAgo / 60 ); |
|
|
const daysAgo = Math.floor( hoursAgo / 24 ); |
|
|
|
|
|
|
|
|
if ( secondsAgo < 60 ) { |
|
|
return __( 'just now' ); |
|
|
} |
|
|
|
|
|
|
|
|
if ( minutesAgo < 60 ) { |
|
|
return sprintf( |
|
|
|
|
|
__( '%(minutes)dm ago' ), |
|
|
{ |
|
|
minutes: minutesAgo, |
|
|
} |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
if ( hoursAgo < 24 ) { |
|
|
return sprintf( |
|
|
|
|
|
__( '%(hours)dh ago' ), |
|
|
{ |
|
|
hours: hoursAgo, |
|
|
} |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
if ( daysAgo < 7 ) { |
|
|
return sprintf( |
|
|
|
|
|
__( '%(days)dd ago' ), |
|
|
{ |
|
|
days: daysAgo, |
|
|
} |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
return formatDate( date, locale, formatOptions ); |
|
|
}, [ now, date, locale, formatOptions ] ); |
|
|
} |
|
|
|
|
|
export function useTimeSince( timestamp: string, formatOptions?: Intl.DateTimeFormatOptions ) { |
|
|
const locale = useLocale(); |
|
|
|
|
|
const date = new Date( timestamp ); |
|
|
return useRelativeTime( date, locale, formatOptions ); |
|
|
} |
|
|
|
|
|
export default function TimeSince( { |
|
|
timestamp, |
|
|
dateStyle, |
|
|
timeStyle, |
|
|
}: { |
|
|
timestamp: string; |
|
|
dateStyle?: 'full' | 'long' | 'medium' | 'short'; |
|
|
timeStyle?: 'full' | 'long' | 'medium' | 'short'; |
|
|
} ) { |
|
|
const locale = useLocale(); |
|
|
|
|
|
const date = new Date( timestamp ); |
|
|
const formatOptions = dateStyle || timeStyle ? { dateStyle, timeStyle } : undefined; |
|
|
|
|
|
const fullDate = formatDate( date, locale, formatOptions ); |
|
|
const relativeDate = useRelativeTime( date, locale, formatOptions ); |
|
|
|
|
|
return ( |
|
|
<time dateTime={ timestamp } title={ fullDate }> |
|
|
{ relativeDate } |
|
|
</time> |
|
|
); |
|
|
} |
|
|
|