import React, { Component } from 'react'; import { __, sprintf } from '@wordpress/i18n'; import './Conditionals.css'; import { SelectControl, TextControl, Button, IconButton, } from '@wordpress/components'; interface ConditionalsProps { variant: ABTestVariant; onAddCondition: (id: string, key: string, value: string) => void; onRemoveCondition: (id: string, key: string, value: string) => void; } interface ConditionalsState { isOpened: boolean; showErrors: boolean; newConditionType: number; newConditionKey: string; newConditionValue: string; } const defaultState: ConditionalsState = { isOpened: false, showErrors: false, newConditionType: 0, newConditionKey: __('key', 'ab-testing-for-wp'), newConditionValue: __('value', 'ab-testing-for-wp'), }; class Conditionals extends Component { constructor(props: ConditionalsProps) { super(props); this.state = defaultState; } setOpened(isOpened: boolean): void { this.setState({ isOpened }); } setNewConditionType(conditionType: string): void { let newConditionKey = ''; const newConditionType = parseInt(conditionType, 10); switch (newConditionType) { case 1: newConditionKey = 'utm_source'; break; case 2: newConditionKey = 'utm_medium'; break; case 3: newConditionKey = 'utm_campaign'; break; default: newConditionKey = __('key', 'ab-testing-for-wp'); } this.setState({ newConditionType, newConditionKey }); } setNewConditionKey(newConditionKey: string): void { this.setState({ newConditionKey }); } setNewConditionValue(newConditionValue: string): void { this.setState({ newConditionValue }); } cancelNew(): void { this.setState(defaultState); } addCondition(): void { const { variant, onAddCondition } = this.props; const { newConditionKey, newConditionValue } = this.state; if (newConditionKey.trim() === '' || newConditionValue.trim() === '') { this.setState({ showErrors: true, }); return; } onAddCondition(variant.id, newConditionKey, newConditionValue); this.setState(defaultState); } removeCondition(condition: { key: string; value: string }): void { const { variant, onRemoveCondition } = this.props; onRemoveCondition(variant.id, condition.key, condition.value); } render(): React.ReactElement { const { variant } = this.props; const { newConditionType, newConditionKey, newConditionValue, isOpened, showErrors, } = this.state; return (
{variant.conditions && variant.conditions.length > 0 && (
{sprintf(__('Force variant %s when either', 'ab-testing-for-wp'), variant.name)}
{variant.conditions.map((condition) => ( this.removeCondition(condition)} /> ))}
)} {isOpened ? (
this.setNewConditionType(value)} />
{newConditionType === 0 && ( <> this.setNewConditionKey(value)} />
=
)} this.setNewConditionValue(value)} />
{`${newConditionKey || 'key'}=${newConditionValue || 'value'}`}
) : ( )}
); } } export default Conditionals;