/** * WordPress dependencies */ import { Dashicon, TextControl } from '@safe-wordpress/components'; import { useSelect } from '@safe-wordpress/data'; import { useEffect } from '@safe-wordpress/element'; import { _x } from '@safe-wordpress/i18n'; /** * External dependencies */ import { PostSearcher } from '@nab/components'; import type { ExperimentEditProps } from '@nab/types'; /** * Internal dependencies */ import './style.scss'; import type { ControlAttributes, AlternativeAttributes } from '../../types'; export type AlternativeProps = ExperimentEditProps< AlternativeAttributes > & { readonly placeholder?: string; }; // NOTE. Dependency loop with @nab package. import type { store as editorStore } from '@nab/editor'; const NAB_EDITOR = 'nab/editor' as unknown as typeof editorStore; export const Alternative = ( { attributes, disabled, placeholder = _x( 'Describe your variant…', 'user', 'nelio-ab-testing' ), setAttributes, }: AlternativeProps ): JSX.Element => { const isExistingContent = useExistingContent(); useEffect( () => { setAttributes( { isExistingContent: isExistingContent ? true : undefined, } ); }, [ isExistingContent, setAttributes ] ); return isExistingContent ? ( <> // @ts-expect-error Pattern ID has the appropriate type. setAttributes( { patternId: value } ) } placeholder={ _x( 'Select variant…', 'user', 'nelio-ab-testing' ) } /> { !! attributes.unableToCreateVariant && ( ) } ) : ( <> setAttributes( { name: value } ) } placeholder={ placeholder } /> { !! attributes.unableToCreateVariant && ( ) } { /^https:/.test( attributes.name ) && ! attributes.unableToCreateVariant && ( ) } ); }; // ============ // HELPER VIEWS // ============ const Error = ( { error }: { error: keyof typeof ERRORS } ) => (

{ ERRORS[ error ] }

); // ===== // HOOKS // ===== const useExistingContent = () => !! useControl()?.attributes.testAgainstExistingPatterns; const useControl = () => useSelect( ( select ) => select( NAB_EDITOR ).getAlternative< ControlAttributes >( 'control' ), [] ); const ERRORS = { unableToCreateVariant: _x( 'Something went wrong and this variant could not be properly created. Please reset it and save the test again to see if that fixes the issue. If it doesn’t, please get in touch with support.', 'user', 'nelio-ab-testing' ), urlIsNotAVariant: _x( 'It looks like you’re entering a URL. Variant names should describe your alternative content, not link to a page. If you want to test two already existing pages, please use a page test instead.', 'user', 'nelio-ab-testing' ), };