/** * Internal dependencies */ import { LISTENERS } from './listeners'; import { sendConversions } from './sync'; import { getAllActions, getConvertingGoals } from './utils'; import { once } from '../utils/lodash'; import type { ConvertibleAction, Session } from '../types'; import type { Attributes as ClickAttrs } from '../../../../packages/conversion-action-library/click/types'; import type { Attributes as EngagementAttrs } from '../../../../packages/conversion-action-library/engagement/types'; import type { Attributes as ScrollAttrs } from '../../../../packages/conversion-action-library/scroll/types'; import type { Attributes as TimeAttrs } from '../../../../packages/conversion-action-library/time-on-page/types'; export const initConversionTracking = once( ( session: Session ): void => { sendConvertingPageViews( session ); addActionListeners( session ); } ); // ======= // HELPERS // ======= function sendConvertingPageViews( session: Session ) { const { experiments } = session; const events = getConvertingGoals( experiments, ( action ) => action.active && 'nab/page-view' === action.type ); sendConversions( events, session ); } function addActionListeners( session: Session ) { const allActions = getAllActions( session.experiments ) .filter( ( action ) => action.active ) .filter( ( action ) => 'nab/page-view' !== action.type ) .flatMap( ( action ) => isEngagementAction( action ) ? expandEngagementAction( action ) : [ action ] ); LISTENERS.forEach( ( listener ) => listener( allActions, ( actions ) => sendConversions( actions, session ) ) ); } const isEngagementAction = ( action: ConvertibleAction ): action is ConvertibleAction< EngagementAttrs > => action.type === 'nab/engagement'; function expandEngagementAction( action: ConvertibleAction ): [ ConvertibleAction< ClickAttrs >, ConvertibleAction< ScrollAttrs >, ConvertibleAction< TimeAttrs >, ] { return [ { ...action, type: 'nab/click', attributes: { mode: 'css', value: 'a, button, input, textarea, select, summary, [role="button"], [tabindex], [data-clickable="true"]', delay: 3, }, }, { ...action, type: 'nab/scroll', attributes: { value: 50, }, }, { ...action, type: 'nab/time-on-page', attributes: { value: 10, }, }, ]; }