import { useEffect , useRef , useState } from 'react' ; import last from 'lodash/last' ; import { schemaV6Adapter } from '@opentrons/shared-data' ; import { useCurrentProtocolRun } from '../ProtocolUpload/hooks' ; import { formatInterval } from '../RunTimeControl/utils' ; import type { ProtocolFile } from '@opentrons/shared-data' ; interface ProtocolDetails { displayName : string | null ; protocolData : ProtocolFile < { } > | null ; } function useInterval ( callback , delay , immediate = false ) { const savedCallback = useRef ( ) ; useEffect ( ( ) => { savedCallback . current = callback ; } , [ callback ] ) ; useEffect ( ( ) => { const tick = ( ) : unknown => savedCallback . current && savedCallback . current ( ) ; if ( delay !== null && delay > 0 ) { if ( immediate ) tick ( ) ; const id = setInterval ( tick , delay ) ; return ( ) => clearInterval ( id ) ; } } , [ delay , immediate ] ) ; } function useNow ( ) { const initialNow = Date ( ) ; const [ now , setNow ] = useState ( initialNow ) ; useInterval ( ( ) => setNow ( Date ( ) ) , 500 , true ) ; return now ; } export function useProtocolDetails ( ) { let protocolData = null ; const { protocolRecord } = useCurrentProtocolRun ( ) ; const protocolAnalysis = protocolRecord ?. data . analyses ; if ( protocolAnalysis != null ) { const lastProtocolAnalysis = protocolAnalysis [ protocolAnalysis . length - 1 ] ; if ( lastProtocolAnalysis . status === 'completed' ) { protocolData = schemaV6Adapter ( lastProtocolAnalysis ) ; } } const displayName = protocolRecord ?. data . metadata . protocolName ?? null ; return { displayName , protocolData } ; } export function useTimeElapsedSincePause ( ) { const { runRecord } = useCurrentProtocolRun ( ) ; const now = useNow ( ) ; const mostRecentAction = last ( runRecord ?. data . actions ) ; if ( runRecord ?. data && [ 'paused' , 'pause-requested' ] . includes ( runRecord ?. data . status ) && mostRecentAction != null && mostRecentAction ?. actionType === 'pause' ) { return formatInterval ( mostRecentAction . createdAt , now ) ; } return null ; } export function useFormatRunTimestamp ( ) { const { runRecord } = useCurrentProtocolRun ( ) ; return ( timestamp ) => { if ( runRecord == null ) return null ; const { actions } = runRecord . data ; const firstPlayAction = actions . find ( action => action . actionType === 'play' ) ; if ( firstPlayAction == null ) return null ; return formatInterval ( firstPlayAction . createdAt , timestamp ) ; } ; }