import React , { useState , useEffect , useCallback } from 'react' ; import classNames from 'classnames' ; import moment from 'moment' ; import formatRelativeTime from './formatRelativeTime' ; import { useTranslationFunction } from '../../contexts' ; const UPDATE_FREQUENCY = 60 * 1000 ; export function useInterval ( callback , delay ) { useEffect ( ( ) => { let mounted = true ; if ( delay === null || callback === null ) return ; const interval = setInterval ( ( ) => { if ( mounted === true ) callback ( ) ; } , delay ) ; return ( ) => { mounted = false ; clearInterval ( interval ) ; } ; } , [ callback , delay ] ) ; } type TimestampProps = { direction ? : 'incoming' | 'outgoing' ; module : string ; timestamp : number ; extended : boolean ; } ; const Timestamp = function Timestamp ( props ) { const { direction , timestamp , extended } = props ; const moduleName = props . module || '' ; const calculateRelativeTime = useCallback ( ( ) => formatRelativeTime ( timestamp , { extended } ) , [ timestamp , extended ] ) ; const [ relativeTime , setRelativeTime ] = useState ( ( ) => calculateRelativeTime ( ) ) ; const recalculateRelativeTime = useCallback ( ( ) => setRelativeTime ( calculateRelativeTime ( ) ) , [ calculateRelativeTime ] ) ; useInterval ( recalculateRelativeTime , UPDATE_FREQUENCY ) ; useEffect ( recalculateRelativeTime , [ timestamp , window . localeData . locale , recalculateRelativeTime , ] ) ; useTranslationFunction ( ) ; if ( timestamp === null || timestamp === undefined ) return null ; return ( < span className = { classNames ( moduleName , direction ? `${ moduleName } -- $ { direction } ` : null)} title={moment(timestamp).format('llll')}>
      {relativeTime}
    </span>);
};
export default Timestamp;
