PromucFlow_constructor/app/client/src/components/formControls/KeyValueArrayControl.tsx
albinAppsmith 629999f124
feat: [epic] appsmith design system version 2 deduplication (#22030)
## Description

### Fixes
- [x] https://github.com/appsmithorg/appsmith/issues/19383
- [x] https://github.com/appsmithorg/appsmith/issues/19384
- [x] https://github.com/appsmithorg/appsmith/issues/19385
- [x] https://github.com/appsmithorg/appsmith/issues/19386
- [x] https://github.com/appsmithorg/appsmith/issues/19387
- [x] https://github.com/appsmithorg/appsmith/issues/19388
- [x] https://github.com/appsmithorg/appsmith/issues/19389
- [x] https://github.com/appsmithorg/appsmith/issues/19390
- [x] https://github.com/appsmithorg/appsmith/issues/19391
- [x] https://github.com/appsmithorg/appsmith/issues/19392
- [x] https://github.com/appsmithorg/appsmith/issues/19393
- [x] https://github.com/appsmithorg/appsmith/issues/19394
- [x] https://github.com/appsmithorg/appsmith/issues/19395
- [x] https://github.com/appsmithorg/appsmith/issues/19396
- [x] https://github.com/appsmithorg/appsmith/issues/19397
- [x] https://github.com/appsmithorg/appsmith/issues/19398
- [x] https://github.com/appsmithorg/appsmith/issues/19399
- [x] https://github.com/appsmithorg/appsmith/issues/19400
- [x] https://github.com/appsmithorg/appsmith/issues/19401
- [x] https://github.com/appsmithorg/appsmith/issues/19402
- [x] https://github.com/appsmithorg/appsmith/issues/19403
- [x] https://github.com/appsmithorg/appsmith/issues/19404
- [x] https://github.com/appsmithorg/appsmith/issues/19405
- [x] https://github.com/appsmithorg/appsmith/issues/19406
- [x] https://github.com/appsmithorg/appsmith/issues/19407
- [x] https://github.com/appsmithorg/appsmith/issues/19408
- [x] https://github.com/appsmithorg/appsmith/issues/19409

Fixes # (issue)
> if no issue exists, please create an issue and ask the maintainers
about this first


Media
> A video or a GIF is preferred. when using Loom, don’t embed because it
looks like it’s a GIF. instead, just link to the video


## Type of change

> Please delete options that are not relevant.

- Bug fix (non-breaking change which fixes an issue)
- New feature (non-breaking change which adds functionality)
- Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- Chore (housekeeping or task changes that don't impact user perception)
- This change requires a documentation update


## How Has This Been Tested?
> Please describe the tests that you ran to verify your changes. Provide
instructions, so we can reproduce.
> Please also list any relevant details for your test configuration.
> Delete anything that is not important

- Manual
- Jest
- Cypress

### Test Plan
> Add Testsmith test cases links that relate to this PR

### Issues raised during DP testing
> Link issues raised during DP testing for better visiblity and tracking
(copy link from comments dropped on this PR)


## Checklist:
### Dev activity
- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] PR is being merged under a feature flag


### QA activity:
- [ ] Test plan has been approved by relevant developers
- [ ] Test plan has been peer reviewed by QA
- [ ] Cypress test cases have been added and approved by either SDET or
manual QA
- [ ] Organized project review call with relevant stakeholders after
Round 1/2 of QA
- [ ] Added Test Plan Approved label after reveiwing all Cypress test

---------

Co-authored-by: Ankita Kinger <ankita@appsmith.com>
Co-authored-by: akash-codemonk <67054171+akash-codemonk@users.noreply.github.com>
Co-authored-by: Tanvi Bhakta <tanvi@appsmith.com>
Co-authored-by: Arsalan <arsalanyaldram0211@outlook.com>
Co-authored-by: Aman Agarwal <aman@appsmith.com>
Co-authored-by: Rohit Agarwal <rohit_agarwal@live.in>
Co-authored-by: Nilesh Sarupriya <nilesh@appsmith.com>
Co-authored-by: Nilesh Sarupriya <20905988+nsarupr@users.noreply.github.com>
Co-authored-by: Tanvi Bhakta <tanvibhakta@gmail.com>
Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
Co-authored-by: Parthvi Goswami <parthvigoswami@Parthvis-MacBook-Pro.local>
Co-authored-by: Vijetha-Kaja <vijetha@appsmith.com>
Co-authored-by: Parthvi <80334441+Parthvi12@users.noreply.github.com>
Co-authored-by: Apple <nandan@thinkify.io>
Co-authored-by: Saroj <43822041+sarojsarab@users.noreply.github.com>
Co-authored-by: Sangeeth Sivan <74818788+berzerkeer@users.noreply.github.com>
Co-authored-by: Ashok Kumar M <35134347+marks0351@users.noreply.github.com>
Co-authored-by: Aishwarya-U-R <91450662+Aishwarya-U-R@users.noreply.github.com>
Co-authored-by: rahulramesha <rahul@appsmith.com>
Co-authored-by: Aswath K <aswath.sana@gmail.com>
Co-authored-by: Preet Sidhu <preetsidhu.bits@gmail.com>
Co-authored-by: Vijetha-Kaja <119562824+Vijetha-Kaja@users.noreply.github.com>
Co-authored-by: Shrikant Sharat Kandula <shrikant@appsmith.com>
2023-05-20 00:07:06 +05:30

269 lines
7.9 KiB
TypeScript

import React, { useEffect, useCallback } from "react";
import type {
WrappedFieldArrayProps,
WrappedFieldMetaProps,
WrappedFieldInputProps,
} from "redux-form";
import { Field, FieldArray } from "redux-form";
import styled from "styled-components";
import type { ControlProps, ControlData } from "./BaseControl";
import BaseControl from "./BaseControl";
import type { ControlType } from "constants/PropertyControlConstants";
import DynamicTextField from "components/editorComponents/form/fields/DynamicTextField";
import type { InputProps } from "design-system";
import { setDefaultKeyValPairFlag } from "actions/datasourceActions";
import { useDispatch } from "react-redux";
import { Button, Input } from "design-system";
export interface KeyValueArrayControlProps extends ControlProps {
name: string;
label: string;
maxLen?: number;
description?: string;
actionConfig?: any;
extraData?: ControlData[];
isRequired?: boolean;
}
const FormRowWithLabel = styled.div`
display: flex;
flex: 1;
flex-direction: row;
align-items: start;
margin-bottom: 5px;
& svg {
cursor: pointer;
}
.form-input-field {
width: 270px;
+ .form-input-field {
margin-left: 5px;
}
}
`;
const StyledInput = styled(Input)`
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
margin: 0px;
}
`;
const StyledButton = styled(Button)`
margin-left: 5px;
`;
const AddMoreButton = styled(Button)``;
function KeyValueRow(
props: KeyValueArrayControlProps & WrappedFieldArrayProps,
) {
const { extraData = [] } = props;
const keyName = getFieldName(extraData[0]?.configProperty);
const valueName = getFieldName(extraData[1]?.configProperty);
const keyFieldProps = extraData[0];
const dispatch = useDispatch();
const addRow = useCallback(() => {
if (keyName && valueName) {
props.fields.push({ [keyName[1]]: "", [valueName[1]]: "" });
} else {
props.fields.push({ key: "", value: "" });
}
}, [keyName, valueName]);
useEffect(() => {
// Always maintain 1 row
if (props.fields.length < 1) {
for (let i = props.fields.length; i < 1; i += 1) {
addRow();
// Since we are initializing one default key value pair, it needs to stored in redux store
// so that it can be used to initilize datasource config form as well
dispatch(setDefaultKeyValPairFlag(props.configProperty));
}
}
}, [props.fields, keyName, valueName]);
useEffect(() => {
if (typeof props.fields.getAll() === "string") {
const fieldsValue: any[] = JSON.parse(`${props.fields.getAll()}`);
props.fields.removeAll();
fieldsValue.forEach((value, index) => {
props.fields.insert(index, value);
});
}
}, [props.fields]);
const isKeyFieldValid = useCallback(
(value: string) => {
if (value && keyFieldProps?.validationRegex) {
const regex = new RegExp(keyFieldProps?.validationRegex);
return regex.test(value)
? { isValid: true }
: { isValid: false, message: keyFieldProps.validationMessage };
}
return { isValid: true };
},
[keyFieldProps?.validationRegex, keyFieldProps?.validationMessage],
);
return typeof props.fields.getAll() === "object" ? (
<>
{props.fields.map((field: any, index: number) => {
let keyTextFieldName = `${field}.key`;
let valueTextFieldName = `${field}.value`;
if (keyName && Array.isArray(keyName) && keyName?.length)
keyTextFieldName = `${field}.${keyName[1]}`;
if (valueName && Array.isArray(valueName) && valueName?.length)
valueTextFieldName = `${field}.${valueName[1]}`;
return (
<FormRowWithLabel key={index}>
<div
className="form-input-field"
data-replay-id={btoa(keyTextFieldName)}
>
<Field
component={renderInput}
name={keyTextFieldName}
props={{
dataType: getType(extraData[0]?.dataType),
defaultValue: extraData[0]?.initialValue,
isKeyFieldValid: isKeyFieldValid,
placeholder: props.extraData
? props.extraData[1]?.placeholderText
: "",
isRequired: extraData[0]?.isRequired,
name: keyTextFieldName,
}}
/>
</div>
{!props.actionConfig && (
<div className="form-input-field">
<div
data-replay-id={btoa(valueTextFieldName)}
style={{ display: "flex", flexDirection: "row" }}
>
<Field
component={renderInput}
name={valueTextFieldName}
props={{
dataType: getType(extraData[1]?.dataType),
defaultValue: extraData[1]?.initialValue,
placeholder: props.extraData
? props.extraData[1]?.placeholderText
: "",
name: valueTextFieldName,
isRequired: extraData[1]?.isRequired,
}}
/>
</div>
</div>
)}
{!props.actionConfig && (
<StyledButton
className="t--delete-field"
isIconButton
kind="tertiary"
onClick={() => props.fields.remove(index)}
size="md"
startIcon="delete"
/>
)}
{props.actionConfig && (
<DynamicTextField
name={`${field}.value`}
placeholder={
props.actionConfig[index].mandatory &&
props.actionConfig[index].type
? `Value (Type: ${props.actionConfig[index].type})`
: `Value (optional)`
}
/>
)}
</FormRowWithLabel>
);
})}
<AddMoreButton
className="t--add-field t--addApiHeader btn-add-more"
kind="tertiary"
onClick={addRow}
size="md"
startIcon="add-more"
>
Add more
</AddMoreButton>
</>
) : null;
}
class KeyValueArrayControl extends BaseControl<KeyValueArrayControlProps> {
render() {
const name = getFieldName(this.props.configProperty);
return (
<FieldArray
component={KeyValueRow}
rerenderOnEveryChange={false}
{...this.props}
name={name ? name[0] : ""}
/>
);
}
getControlType(): ControlType {
return "KEYVALUE_ARRAY";
}
}
const getFieldName = (configProperty: string): string[] | undefined => {
if (configProperty) return configProperty.split("[*].");
};
const getType = (dataType: string | undefined) => {
switch (dataType) {
case "PASSWORD":
return "password";
case "NUMBER":
return "number";
default:
return "text";
}
};
function renderInput(
props: InputProps & {
dataType?: "text" | "number" | "password";
placeholder?: string;
defaultValue: string | number;
isRequired: boolean;
isKeyFieldValid?: (value: string) => { isValid: boolean; message: string };
helperText?: string;
} & {
meta: Partial<WrappedFieldMetaProps>;
input: Partial<WrappedFieldInputProps>;
},
): JSX.Element {
return (
<StyledInput
aria-label={
props.helperText || props.defaultValue || props.placeholder || "label"
}
defaultValue={props.defaultValue}
description={props.helperText}
errorMessage={props.isKeyFieldValid?.(props.input.value).message}
isValid={props.isKeyFieldValid?.(props.input.value).isValid}
name={props.input?.name}
onChange={props.input.onChange}
placeholder={props.placeholder}
size="md"
type={props.dataType}
value={props.input.value}
/>
);
}
export default KeyValueArrayControl;