All files / modules/10-common/components/Duration Duration.tsx

100% Statements 20/20
96.3% Branches 26/27
100% Functions 4/4
100% Lines 20/20

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              628x 628x 628x 628x                       628x                   809x 809x 809x   809x 521x 499x       521x   4x       521x 500x       809x   809x 806x     809x   809x              
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useEffect, useState } from 'react'
import { Text, TextProps, timeToDisplayText } from '@wings-software/uicore'
import { isNil } from 'lodash-es'
import { useStrings } from 'framework/strings'
 
export interface DurationProps extends Omit<TextProps, 'icon'> {
  startTime?: number
  endTime?: number // if endTime is nullable, endTime is Date.now() and the duration is re-calculated by an interval
  durationText?: React.ReactNode // optional text to override the default `Duration: ` prefix: ;
  showMilliSeconds?: boolean
  showZeroSecondsResult?: boolean
  showMsLessThanOneSecond?: boolean
  icon?: TextProps['icon'] | null
}
 
export function Duration(props: DurationProps): React.ReactElement {
  const {
    startTime,
    endTime,
    durationText,
    icon,
    showMilliSeconds,
    showZeroSecondsResult,
    showMsLessThanOneSecond,
    ...textProps
  } = props
  const [_endTime, setEndTime] = useState(endTime || Date.now())
  const { getString } = useStrings()
 
  useEffect(() => {
    if (endTime) {
      setEndTime(endTime)
    }
 
    const timeoutId =
      (!endTime &&
        window.setInterval(() => {
          setEndTime(Date.now())
        }, 1000)) ||
      0
 
    return () => {
      window.clearInterval(timeoutId)
    }
  }, [endTime])
 
  let delta = startTime ? Math.abs(startTime - _endTime) : 0
 
  if ((!showMilliSeconds && !showMsLessThanOneSecond) || (showMsLessThanOneSecond && delta > 1000)) {
    delta = Math.round(delta / 1000) * 1000
  }
 
  const text = showZeroSecondsResult ? timeToDisplayText(delta) || '0s' : timeToDisplayText(delta)
 
  return (
    <Text inline icon={isNil(icon) ? undefined : icon || 'hourglass'} {...textProps}>
      {durationText ?? getString('common.durationPrefix')}
      {text}
    </Text>
  )
}