import { CountJSONPData } from "coral-common/types/count" ; import { COUNT_SELECTOR } from "coral-framework/constants" ; import getPreviousCountStorageKey from "coral-framework/helpers/getPreviousCountStorageKey" ; type GetCountFunction = ( opts ? : { reset ? : boolean ; } ) => void ; param storyID function getPreviousCount ( storyID ) { const key = "coral:" + getPreviousCountStorageKey ( storyID ) ; let previousCount ; try { const item = localStorage . getItem ( key ) ; if ( ! item ) { return null ; } previousCount = parseInt ( item , 10 ) ; } catch ( err ) { localStorage . removeItem ( key ) ; return null ; } return previousCount ; } interface CountElementDataset { coralCount : string ; coralPreviousCount ? : string ; coralNewCount ? : string ; } function createCountElementEnhancer ( { html , count : currentCount , id : storyID , } ) { const dataset = { coralCount : currentCount . toString ( ) , } ; const element = document . createElement ( "span" ) ; element . innerHTML = html ; if ( storyID ) { const previousCount = getPreviousCount ( storyID ) ; if ( previousCount !== null && previousCount < currentCount ) { const newCount = currentCount - previousCount ; dataset . coralPreviousCount = previousCount . toString ( ) ; dataset . coralNewCount = newCount . toString ( ) ; const dividerElement = document . createElement ( "span" ) ; dividerElement . className = "coral-new-count-divider" ; dividerElement . innerText = " / " ; element . appendChild ( dividerElement ) ; const newCountNumber = document . createElement ( "span" ) ; newCountNumber . className = "coral-new-count-number" ; newCountNumber . innerText = newCount . toString ( ) ; element . appendChild ( newCountNumber ) ; const newCountText = document . createElement ( "span" ) ; newCountText . className = "coral-new-count-text" ; newCountText . innerText = " New" ; element . appendChild ( newCountText ) ; } } return ( target ) => { target . innerHTML = element . innerHTML ; target . dataset . coralCount = dataset . coralCount ; if ( dataset . coralNewCount && dataset . coralPreviousCount ) { target . dataset . coralNewCount = dataset . coralNewCount ; target . dataset . coralPreviousCount = dataset . coralPreviousCount ; } } ; } param getCount function injectJSONPCallback ( getCount ) { ( window as any ) . CoralCount = { setCount : ( data ) => { const elements = document . querySelectorAll ( `${ COUNT_SELECTOR }[data-coral-ref='${ data . ref }']` ) ; const enhance = createCountElementEnhancer ( data ) ; Array . prototype . forEach . call ( elements , ( element ) => { enhance ( element ) ; } ) ; } , getCount , } ; } export default injectJSONPCallback ;