import { COUNT_SELECTOR , ORIGIN_FALLBACK_ID } from "coral-framework/constants" ; import detectCountScript from "coral-framework/helpers/detectCountScript" ; import resolveStoryURL from "coral-framework/helpers/resolveStoryURL" ; import jsonp from "coral-framework/utils/jsonp" ; import getCurrentScriptOrigin from "./getCurrentScriptOrigin" ; import injectJSONPCallback from "./injectJSONPCallback" ; /** Arguments that will be send to the server. */ interface CountQueryArgs { id ? : string ; url ? : string ; notext : boolean ; } /** createCountQueryRef creates a unique reference from the query args */ function createCountQueryRef ( args ) { return btoa ( `${ args . notext ? "true" : "false" };${ args . id || args . url }` ) ; } interface DetectAndInjectArgs { reset ? : boolean ; } /** Detects count elements and use jsonp to inject the counts. */ function detectAndInject ( opts = { } ) { const ORIGIN = getCurrentScriptOrigin ( ORIGIN_FALLBACK_ID ) ; const STORY_URL = resolveStoryURL ( window ) ; /** A map of references pointing to the count query arguments */ const queryMap = { } ; const elements = document . querySelectorAll ( COUNT_SELECTOR ) ; Array . prototype . forEach . call ( elements , ( element ) => { const id = element . dataset . coralId ; const notext = element . dataset . coralNotext === "true" ; let url = element . dataset . coralUrl ; if ( ! url && ! id ) { url = STORY_URL ; element . dataset . coralUrl = STORY_URL ; } const args = { id , url , notext } ; let ref = element . dataset . coralRef ; if ( ! ref ) { ref = createCountQueryRef ( args ) ; element . dataset . coralRef = ref ; } else { if ( ! opts . reset ) { return ; } } if ( ! ( ref in queryMap ) ) { queryMap [ ref ] = args ; } } ) ; Object . keys ( queryMap ) . forEach ( ( ref ) => { const { url , id , notext } = queryMap [ ref ] ; const args = { id , url , notext : notext ? "true" : "false" , ref , } ; if ( opts . reset ) { args . d = Date . now ( ) . toString ( ) ; } jsonp ( `${ ORIGIN }/api/story/count.js` , "CoralCount.setCount" , args ) ; } ) ; } export function main ( ) { injectJSONPCallback ( detectAndInject ) ; detectAndInject ( ) ; } if ( ! detectCountScript ( window ) && process . env . NODE_ENV !== "test" ) { main ( ) ; }