/** * WordPress dependencies */ import { noop } from 'lodash'; import { PanelBody, RadioControl } from '@safe-wordpress/components'; import { useDispatch, useSelect } from '@safe-wordpress/data'; import { _x } from '@safe-wordpress/i18n'; /** * Internal dependencies */ import { store as NAB_ACTIONS, createConversionAction as createConversionActionWithDefaults, } from '@nab/conversion-actions'; import { EMPTY_OBJECT } from '@nab/utils'; import type { ConversionAction, Goal, Maybe } from '@nab/types'; /** * Internal dependencies */ import './style.scss'; import { store as NAB_EDITOR } from '../../../store'; import type { Attributes as ElementViewAttributes } from '../../../../conversion-action-library/element-view/types'; // NOTE. Right now we assume we can only have *one* action type and *one* visibility action. export const PageViewTriggers = (): JSX.Element | null => { const experimentId = useExperimentId(); const triggerType = useVisibilityTriggerType(); const [ trigger, setTrigger ] = useVisibilityTrigger(); if ( ! triggerType ) { return null; } const Edit = triggerType.edit; const validate = triggerType?.validate ?? ( () => ( {} ) ); const errors = trigger ? validate( trigger.attributes ) : EMPTY_OBJECT; return (

{ /* translators: Followed by either “on page visit” or “when an element becomes visible.” */ _x( 'Count the page view:', 'command', 'nelio-ab-testing' ) }

setTrigger( value === 'on-page-visit' ? undefined : { mode: 'css', value: '' } ) } /> { !! trigger && (
) => setTrigger( { ...trigger.attributes, ...attrs } ) } setScope={ noop } errors={ errors } />
) }
); }; // ==== // DATA // ==== const FAKE_GOAL: Goal = { id: '', attributes: { name: '', }, conversionActions: [], }; // ===== // HOOKS // ===== const useExperimentId = () => useSelect( ( select ) => select( NAB_EDITOR ).getExperimentId(), [] ); const useVisibilityTrigger = () => { const trigger = useSelect( ( select ) => select( NAB_EDITOR ) .getPageViewTriggers() .find( ( t ): t is ConversionAction< ElementViewAttributes > => t.type === 'nab/element-view' ), [] ); const { setPageViewTriggerActions } = useDispatch( NAB_EDITOR ); const setTrigger = ( attrs: Maybe< ElementViewAttributes > ) => { if ( ! attrs ) { return setPageViewTriggerActions( [] ); } const newTrigger = trigger || createConversionActionWithDefaults( 'nab/element-view', attrs ); return setPageViewTriggerActions( [ { ...newTrigger, attributes: { ...newTrigger.attributes, ...attrs, }, }, ] ); }; return [ trigger, setTrigger ] as const; }; const useVisibilityTriggerType = () => useSelect( ( select ) => select( NAB_ACTIONS ) .getPageViewTriggerTypes() .filter( ( type ) => ! type.isActive || type.isActive( select ) ) .find( ( type ) => type.name === 'nab/element-view' ), [] );