Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[GEN-1340] chore: connect form validation #23

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,20 @@ const ItemValue = styled(Text)`
export const ConfiguredDestinationFields: React.FC<
ConfiguredDestinationFieldsProps
> = ({ details }) => {
const parseValue = (value: string) => {
const parseValue = (value: any) => {
try {
const parsed = JSON.parse(value);
if (typeof parsed === 'string') {
return parsed;
}

if (Array.isArray(parsed)) {
return parsed
.map((item) => {
if (typeof item === 'object' && item !== null) {
return `${item.key}: ${item.value}`;
}

return item;
})
.join(', ');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ function ModalActionComponent({
onNext,
onBack,
item,
isFormValid,
}: {
onNext: () => void;
onBack: () => void;
isFormValid?: boolean;
item: DestinationTypeItem | undefined;
}) {
return (
Expand All @@ -33,6 +35,7 @@ function ModalActionComponent({
label: 'DONE',
onClick: onNext,
variant: 'primary',
disabled: !isFormValid,
},
]
: []
Expand All @@ -47,6 +50,7 @@ export function AddDestinationModal({
}: AddDestinationModalProps) {
const submitRef = useRef<() => void | null>(null);
const [selectedItem, setSelectedItem] = useState<DestinationTypeItem>();
const [isFormValid, setIsFormValid] = useState(false);

function handleNextStep(item: DestinationTypeItem) {
setSelectedItem(item);
Expand All @@ -55,8 +59,9 @@ export function AddDestinationModal({
function renderModalBody() {
return selectedItem ? (
<ConnectDestinationModalBody
destination={selectedItem}
onSubmitRef={submitRef}
destination={selectedItem}
onFormValidChange={setIsFormValid}
/>
) : (
<ChooseDestinationModalBody onSelect={handleNextStep} />
Expand All @@ -78,6 +83,7 @@ export function AddDestinationModal({
<ModalActionComponent
onNext={handleNext}
onBack={() => setSelectedItem(undefined)}
isFormValid={isFormValid}
item={selectedItem}
/>
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const DestinationFilterComponent: React.FC<FilterComponentProps> = ({
</div>
<Dropdown
options={DROPDOWN_OPTIONS}
selectedOption={selectedTag}
value={selectedTag}
onSelect={onTagSelect}
/>
</InputAndDropdownContainer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,14 @@ const NotificationNoteWrapper = styled.div`
interface ConnectDestinationModalBodyProps {
destination: DestinationTypeItem | undefined;
onSubmitRef: React.MutableRefObject<(() => void) | null>;
onFormValidChange: (isValid: boolean) => void;
}

export function ConnectDestinationModalBody({
destination,
onSubmitRef,
onFormValidChange,
}: ConnectDestinationModalBodyProps) {
const [formData, setFormData] = useState<Record<string, any>>({});
const [destinationName, setDestinationName] = useState<string>('');
const [showConnectionError, setShowConnectionError] = useState(false);
const [dynamicFields, setDynamicFields] = useState<DynamicField[]>([]);
Expand Down Expand Up @@ -118,65 +119,112 @@ export function ConnectDestinationModalBody({
if (destination.fields && field?.name in destination.fields) {
return {
...field,
initialValue: destination.fields[field.name],
value: destination.fields[field.name],
};
}
return field;
});

setDynamicFields(newDynamicFields);
}
}, [data, destination]);

useEffect(() => {
// Assign handleSubmit to the onSubmitRef so it can be triggered externally
onSubmitRef.current = handleSubmit;
}, [formData, destinationName, exportedSignals]);
}, [dynamicFields, destinationName, exportedSignals]);

useEffect(() => {
const isFormValid = dynamicFields.every((field) =>
field.required ? field.value : true
);

onFormValidChange(isFormValid);
}, [dynamicFields]);

function handleDynamicFieldChange(name: string, value: any) {
setFormData((prev) => ({ ...prev, [name]: value }));
setShowConnectionError(false);
setDynamicFields((prev) => {
return prev.map((field) => {
if (field.name === name) {
return { ...field, value };
}
return field;
});
});
}

function handleSignalChange(signal: string, value: boolean) {
setExportedSignals((prev) => ({ ...prev, [signal]: value }));
}

async function handleSubmit() {
const fields = Object.entries(formData).map(([name, value]) => ({
key: name,
value,
function processFormFields() {
function processFieldValue(field) {
return field.componentType === 'dropdown'
? field.value.value
: field.value;
}

// Prepare fields for the request body
return dynamicFields.map((field) => ({
key: field.name,
value: processFieldValue(field),
}));
}

async function handleSubmit() {
// Helper function to process field values
function processFieldValue(field) {
return field.componentType === 'dropdown'
? field.value.value
: field.value;
}

// Prepare fields for the request body
const fields = processFormFields();

// Function to store configured destination
function storeConfiguredDestination() {
const destinationTypeDetails = dynamicFields.map((field) => ({
title: field.title,
value: formData[field.name],
value: processFieldValue(field),
}));

// Add 'Destination name' as the first item
destinationTypeDetails.unshift({
title: 'Destination name',
value: destinationName,
});

// Construct the configured destination object
const storedDestination: ConfiguredDestination = {
exportedSignals,
destinationTypeDetails,
type: destination?.type || '',
imageUrl: destination?.imageUrl || '',
category: '',
category: '', // Could be handled in a more dynamic way if needed
displayName: destination?.displayName || '',
};

// Dispatch action to store the destination
dispatch(addConfiguredDestination(storedDestination));
}

// Prepare the request body
const body: DestinationInput = {
name: destinationName,
type: destination?.type || '',
exportedSignals,
fields,
};

await connectEnv(body, storeConfiguredDestination);
try {
// Await connection and store the configured destination if successful
await connectEnv(body, storeConfiguredDestination);
} catch (error) {
console.error('Failed to submit destination configuration:', error);
// Handle error (e.g., show notification or alert)
}
}

if (!destination) return null;
Expand All @@ -194,15 +242,15 @@ export function ConnectDestinationModalBody({
actionButton={
destination.testConnectionSupported ? (
<TestConnection // TODO: refactor this after add form validation
onError={() => setShowConnectionError(true)}
onError={() => {
setShowConnectionError(true);
onFormValidChange(false);
}}
destination={{
name: destinationName,
type: destination?.type || '',
exportedSignals,
fields: Object.entries(formData).map(([name, value]) => ({
key: name,
value,
})),
fields: processFormFields(),
}}
/>
) : (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ export function DynamicConnectDestinationFormFields({
<Dropdown
key={field.name}
{...field}
onSelect={(option) => onChange(field.name, option.value)}
onSelect={(option) =>
onChange(field.name, { id: option.id, value: option.value })
}
/>
);
case INPUT_TYPES.MULTI_INPUT:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function useConnectDestinationForm() {
title: displayName,
onSelect: () => {},
options,
selectedOption: options[0],
placeholder: 'Select an option',
...componentPropertiesJson,
};

Expand Down
12 changes: 7 additions & 5 deletions frontend/webapp/reuseable-components/dropdown/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import { useOnClickOutside } from '@/hooks';

interface DropdownProps {
options: DropdownOption[];
selectedOption: DropdownOption | undefined;
value: DropdownOption | undefined;
onSelect: (option: DropdownOption) => void;
title?: string;
tooltip?: string;
placeholder?: string;
}

const Container = styled.div`
Expand Down Expand Up @@ -105,10 +106,11 @@ const OpenDropdownIcon = styled(Image)<{ isOpen: boolean }>`

const Dropdown: React.FC<DropdownProps> = ({
options,
selectedOption,
value,
onSelect,
title,
tooltip,
placeholder,
}) => {
const [isOpen, setIsOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
Expand Down Expand Up @@ -143,7 +145,7 @@ const Dropdown: React.FC<DropdownProps> = ({
</Tooltip>
)}
<DropdownHeader isOpen={isOpen} onClick={() => setIsOpen(!isOpen)}>
<Text size={14}>{selectedOption?.value}</Text>
<Text size={14}>{value?.value || placeholder}</Text>

<OpenDropdownIcon
src="/icons/common/extend-arrow.svg"
Expand All @@ -167,12 +169,12 @@ const Dropdown: React.FC<DropdownProps> = ({
{filteredOptions.map((option) => (
<DropdownItem
key={option.id}
isSelected={option.id === selectedOption?.id}
isSelected={option.id === value?.id}
onClick={() => handleSelect(option)}
>
<Text size={14}>{option.value}</Text>

{option.id === selectedOption?.id && (
{option.id === value?.id && (
<Image
src="/icons/common/check.svg"
alt=""
Expand Down
9 changes: 8 additions & 1 deletion frontend/webapp/reuseable-components/input-list/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface InputListProps {
initialValues?: string[];
title?: string;
tooltip?: string;
required?: boolean;
onChange: (values: string[]) => void;
}

Expand Down Expand Up @@ -55,19 +56,20 @@ const Title = styled(Text)`
font-size: 14px;
opacity: 0.8;
line-height: 22px;
margin-bottom: 4px;
`;

const HeaderWrapper = styled.div`
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 4px;
`;

const InputList: React.FC<InputListProps> = ({
initialValues = [''],
title,
tooltip,
required,
onChange,
}) => {
const [inputs, setInputs] = useState<string[]>(initialValues);
Expand Down Expand Up @@ -102,6 +104,11 @@ const InputList: React.FC<InputListProps> = ({
<Tooltip text={tooltip || ''}>
<HeaderWrapper>
<Title>{title}</Title>
{!required && (
<Text color="#7A7A7A" size={14} weight={300} opacity={0.8}>
(optional)
</Text>
)}
{tooltip && (
<Image
src="/icons/common/info.svg"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface KeyValueInputsListProps {
initialKeyValuePairs?: { key: string; value: string }[];
title?: string;
tooltip?: string;
required?: boolean;
onChange?: (validKeyValuePairs: { key: string; value: string }[]) => void;
}

Expand All @@ -23,6 +24,7 @@ const HeaderWrapper = styled.div`
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 4px;
`;

const Row = styled.div`
Expand Down Expand Up @@ -61,13 +63,13 @@ const Title = styled(Text)`
font-size: 14px;
opacity: 0.8;
line-height: 22px;
margin-bottom: 4px;
`;

export const KeyValueInputsList: React.FC<KeyValueInputsListProps> = ({
initialKeyValuePairs = [{ key: '', value: '' }],
title,
tooltip,
required,
onChange,
}) => {
const [keyValuePairs, setKeyValuePairs] =
Expand Down Expand Up @@ -124,6 +126,11 @@ export const KeyValueInputsList: React.FC<KeyValueInputsListProps> = ({
<Tooltip text={tooltip || ''}>
<HeaderWrapper>
<Title>{title}</Title>
{!required && (
<Text color="#7A7A7A" size={14} weight={300} opacity={0.8}>
(optional)
</Text>
)}
{tooltip && (
<Image
src="/icons/common/info.svg"
Expand Down
Loading