All files / src/components IdleTimeout.tsx

76.19% Statements 16/21
100% Branches 8/8
57.14% Functions 4/7
76.19% Lines 16/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                          3x 3x 3x 3x 3x   3x         3x         3x   1x         3x 2x 2x 2x         3x 2x     3x                                                
import { useCallback, useEffect, useState } from 'react'
 
import { deleteCookie } from 'cookies-next'
import { useTranslation } from 'next-i18next'
import { useRouter } from 'next/router'
import { IIdleTimerProps, useIdleTimer } from 'react-idle-timer'
 
import Modal from './Modal'
 
export interface IdleTimeoutProps
  extends Pick<IIdleTimerProps, 'promptBeforeIdle'>,
    Pick<IIdleTimerProps, 'timeout'> {}
 
const IdleTimeout = ({ promptBeforeIdle, timeout }: IdleTimeoutProps) => {
  const { t } = useTranslation('common')
  const router = useRouter()
  const [modalOpen, setModalOpen] = useState(false)
  const [timeRemaining, setTimeRemaining] = useState('')
 
  const handleOnIdle = () => {
    deleteCookie('agreed-to-email-esrf-terms')
    router.reload()
  }
 
  const handleOnIdleContinueSession = () => {
    setModalOpen(false)
    reset()
  }
 
  const { reset, getRemainingTime } = useIdleTimer({
    onIdle: handleOnIdle,
    onPrompt: () => setModalOpen(true),
    promptBeforeIdle: promptBeforeIdle ?? 5 * 60 * 1000, //5 minutes
    timeout: timeout ?? 15 * 60 * 1000, //15 minutes
  })
 
  const tick = useCallback(() => {
    const minutes = Math.floor(getRemainingTime() / 60000)
    const seconds = Math.floor((getRemainingTime() / 1000) % 60).toFixed(0)
    setTimeRemaining(
      minutes + ':' + (parseInt(seconds) < 10 ? '0' : '') + seconds,
    )
  }, [getRemainingTime])
 
  useEffect(() => {
    setInterval(tick, 1000)
  }, [tick])
 
  return (
    <Modal
      open={modalOpen && timeRemaining.length > 0}
      onClose={handleOnIdleContinueSession}
      actionButtons={[
        {
          onClick: () => handleOnIdle(),
          style: 'primary',
          text: t('modal-idle-timeout.end-session'),
        },
        {
          onClick: handleOnIdleContinueSession,
          style: 'default',
          text: t('modal-idle-timeout.continue-session'),
        },
      ]}
      header={t('modal-idle-timeout.header')}
    >
      <p>{t('modal-idle-timeout.description', { timeRemaining })}</p>
    </Modal>
  )
}
 
export default IdleTimeout