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

kie-issues#1542: Implement ListField in the “form-code-generator-patternfly-theme” package #2826

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
2 changes: 2 additions & 0 deletions .rat-excludes
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,8 @@ BoolField.test.tsx.snap
CheckBoxGroupField.test.tsx.snap
# packages/form-code-generator-patternfly-theme/tests/__snapshots__/DateField.test.tsx.snap
DateField.test.tsx.snap
# packages/form-code-generator-patternfly-theme/tests/__snapshots__/ListField.test.tsx.snap
ListField.test.tsx.snap
# packages/form-code-generator-patternfly-theme/tests/__snapshots__/NestField.test.tsx.snap
NestField.test.tsx.snap
# packages/form-code-generator-patternfly-theme/tests/__snapshots__/NumField.test.tsx.snap
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,9 @@
export interface FormElement {
reactImports: string[];
pfImports: string[];

pfIconImports?: string[];
requiredCode?: string[];

ref: InputReference;

stateCode: string;
jsxCode: string;
isReadonly: boolean;
Expand All @@ -33,6 +31,7 @@ export interface FormElement {
abstract class AbstractFormElement implements FormElement {
jsxCode: string;
pfImports: string[];
pfIconImports?: string[];
reactImports: string[];
requiredCode?: string[];
ref: InputReference;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { createAutoField } from "uniforms/cjs/createAutoField";

import TextField from "./TextField";
import BoolField from "./BoolField";
import ListField from "./ListField";
import NumField from "./NumField";
import NestField from "./NestField";
import DateField from "./DateField";
Expand All @@ -40,10 +41,8 @@ const AutoField = createAutoField((props) => {
}

switch (props.fieldType) {
/*
TODO: implement array support
case Array:
return ListField;*/
return ListField;
case Boolean:
return BoolField;
case Date:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,13 @@ const AutoForm: React.FC<AutoFormProps> = (props) => {
const inputs: FormElement[] = renderFormInputs(props.schema);

let pfImports: string[] = [];
let pfIconImports: string[] = [];
let reactImports: string[] = ["useCallback", "useEffect"];
let staticCodeArray: string[] = [];

inputs.forEach((input) => {
pfImports = union(pfImports, input.pfImports);
pfIconImports = union(pfIconImports, input.pfIconImports);
reactImports = union(reactImports, input.reactImports);
staticCodeArray = union(staticCodeArray, input.requiredCode);
});
Expand All @@ -61,8 +63,9 @@ const AutoForm: React.FC<AutoFormProps> = (props) => {
const staticCodeStr: string = staticCodeArray.map((id) => JSON.stringify(getStaticCodeBlock(id))).join("\n");

const formTemplate = `
import React, { ${reactImports.join(", ")} } from "react";
import { ${pfImports.join(", ")} } from "@patternfly/react-core";
import React, { ${reactImports.join(", ")} } from "react";
import { ${pfImports.join(", ")} } from "@patternfly/react-core";
${pfIconImports.length > 0 ? `import { ${pfIconImports.join(", ")} } from "@patternfly/react-icons";` : ""}

const ${formName}: React.FC<any> = ( props:any ) => {
const [formApi, setFormApi] = useState<any>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ import { FormInput, InputReference } from "../api";

import { getInputReference, getStateCodeFromRef, renderField } from "./utils/Utils";
import { BOOLEAN } from "./utils/dataTypes";
import { getListItemName, getListItemOnChange, getListItemValue, ListItemProps } from "./rendering/ListItemField";

export type BoolFieldProps = HTMLFieldProps<
boolean,
HTMLDivElement,
{
name: string;
label: string;
itemProps?: ListItemProps;
}
>;

Expand All @@ -41,12 +43,12 @@ const Bool: React.FC<BoolFieldProps> = (props: BoolFieldProps) => {

const jsxCode = `<FormGroup fieldId='${props.id}'>
<Checkbox
isChecked={${ref.stateName}}
isChecked={${props.itemProps?.isListItem ? getListItemValue({ itemProps: props.itemProps, name: props.name }) : ref.stateName}}
isDisabled={${props.disabled || "false"}}
id={'${props.id}'}
name={'${props.name}'}
name={${props.itemProps?.isListItem ? getListItemName({ itemProps: props.itemProps, name: props.name }) : `'${props.name}'`}}
label={'${props.label}'}
onChange={${ref.stateSetter}}
onChange={${props.itemProps?.isListItem ? getListItemOnChange({ itemProps: props.itemProps, name: props.name }) : ref.stateSetter}}
/>
</FormGroup>`;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { FormInput, InputReference } from "../api";
import { useAddFormElementToContext } from "./CodeGenContext";
import { CHECKBOX_GROUP_FUNCTIONS } from "./staticCode/staticCodeBlocks";
import { ARRAY } from "./utils/dataTypes";
import { getListItemName, getListItemOnChange, getListItemValue, ListItemProps } from "./rendering/ListItemField";

export type CheckBoxGroupProps = HTMLFieldProps<
string[],
Expand All @@ -34,6 +35,7 @@ export type CheckBoxGroupProps = HTMLFieldProps<
allowedValues?: string[];
required: boolean;
transform?(value: string): string;
itemProps: ListItemProps;
}
>;

Expand All @@ -42,14 +44,17 @@ const CheckBoxGroup: React.FC<CheckBoxGroupProps> = (props: CheckBoxGroupProps)

const jsxCode = props.allowedValues
?.map((value) => {
return `<Checkbox key={'${props.id}-${value}'} id={'${props.id}-${value}'} name={'${props.name}'} aria-label={'${
props.name
}'}
label={'${props.transform ? props.transform(value) : value}'}
isDisabled={${props.disabled || false}}
isChecked={${ref.stateName}.indexOf('${value}') != -1}
onChange={() => handleCheckboxGroupChange('${value}', ${ref.stateName}, ${ref.stateSetter})}
value={'${value}'}/>`;
return `<Checkbox
key={'${props.id}-${value}'}
id={'${props.id}-${value}'}
name={${props.itemProps?.isListItem ? getListItemName({ itemProps: props.itemProps, name: props.name }) : `'${props.name}'`}}
aria-label={'${props.name}'}
label={'${props.transform ? props.transform(value) : value}'}
isDisabled={${props.disabled || false}}
isChecked={${ref.stateName}.indexOf('${value}') !== -1}
onChange={${props.itemProps?.isListItem ? getListItemOnChange({ itemProps: props.itemProps, name: props.name, callback: (internalValue: string) => `handleCheckboxGroupChange(${internalValue}, ${ref.stateName}, ${ref.stateSetter})`, overrideNewValue: `'${value}'` }) : `() => handleCheckboxGroupChange('${value}', ${ref.stateName}, ${ref.stateSetter})`}}
value={${props.itemProps?.isListItem ? getListItemValue({ itemProps: props.itemProps, name: props.name }) : `'${value}'`}}
/>`;
})
.join("\n");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { buildDefaultInputElement, getInputReference, renderField } from "./util
import { useAddFormElementToContext } from "./CodeGenContext";
import { DATE_FUNCTIONS, TIME_FUNCTIONS } from "./staticCode/staticCodeBlocks";
import { DATE } from "./utils/dataTypes";
import { getListItemName, getListItemOnChange, getListItemValue, ListItemProps } from "./rendering/ListItemField";

export type DateFieldProps = HTMLFieldProps<
Date,
Expand All @@ -35,6 +36,7 @@ export type DateFieldProps = HTMLFieldProps<
required: boolean;
max?: Date;
min?: Date;
itemProps: ListItemProps;
}
>;

Expand All @@ -52,19 +54,34 @@ const Date: React.FC<DateFieldProps> = (props: DateFieldProps) => {
<DatePicker
id={'date-picker-${props.id}'}
isDisabled={${props.disabled || false}}
name={'${props.name}'}
onChange={newDate => onDateChange(newDate, ${ref.stateSetter}, ${ref.stateName})}
value={parseDate(${ref.stateName})}
name={${props.itemProps?.isListItem ? getListItemName({ itemProps: props.itemProps, name: props.name }) : `'${props.name}'`}}
onChange={${
props.itemProps?.isListItem
? getListItemOnChange({
itemProps: props.itemProps,
name: props.name,
callback: (value) => `onDateChange(${value}, ${ref.stateSetter}, ${ref.stateName})`,
})
: `newDate => onDateChange(newDate, ${ref.stateSetter}, ${ref.stateName})`
}}
value={${props.itemProps?.isListItem ? getListItemValue({ itemProps: props.itemProps, name: props.name, callback: (value: string) => `parseDate(${value})` }) : `parseDate(${ref.stateName})`}}
/>
<TimePicker
id={'time-picker-${props.id}'}
isDisabled={${props.disabled || false}}
name={'${props.name}'}
onChange={(time, hours?, minutes?) => onTimeChange(time, ${ref.stateSetter}, ${
ref.stateName
}, hours, minutes)}
name={${props.itemProps?.isListItem ? getListItemName({ itemProps: props.itemProps, name: props.name }) : `'${props.name}'`}}
onChange={${
props.itemProps?.isListItem
? getListItemOnChange({
itemProps: props.itemProps,
name: props.name,
callback: (_) => `onTimeChange(time, ${ref.stateSetter}, ${ref.stateName}, hours, minutes)`,
overrideParam: "(time, hours?, minutes?)",
})
: `(time, hours?, minutes?) => onTimeChange(time, ${ref.stateSetter}, ${ref.stateName}, hours, minutes)`
}}
style={{ width: '120px' }}
time={parseTime(${ref.stateName})}
time={${props.itemProps?.isListItem ? getListItemValue({ itemProps: props.itemProps, name: props.name, callback: (value: string) => `parseTime(${value})` }) : `parseTime(${ref.stateName})`}}
/>
</InputGroup>
</FlexItem>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import React, { useContext } from "react";
import { connectField, context, HTMLFieldProps, joinName } from "uniforms/cjs";
import { getInputReference, getStateCode, renderField } from "./utils/Utils";
import { codeGenContext } from "./CodeGenContext";
import { FormInput, InputReference } from "../api";
import { ARRAY } from "./utils/dataTypes";
import { renderListItemFragmentWithContext } from "./rendering/RenderingUtils";
import { ListItemProps } from "./rendering/ListItemField";

export type ListFieldProps = HTMLFieldProps<
unknown[],
HTMLDivElement,
{
itemProps?: ListItemProps;
maxCount?: number;
minCount?: number;
}
>;

const List: React.FC<ListFieldProps> = (props: ListFieldProps) => {
const ref: InputReference = getInputReference(props.name, ARRAY);

const uniformsContext = useContext(context);
const codegenCtx = useContext(codeGenContext);

const listItem = renderListItemFragmentWithContext(
uniformsContext,
"$",
{
isListItem: true,
indexVariableName: "itemIndex",
listName: props.name,
listStateName: ref.stateName,
listStateSetter: ref.stateSetter,
},
props.disabled
);

const getNewItemProps = () => {
const typeName = listItem?.ref.dataType.name;
if (typeName?.endsWith("[]")) {
return listItem?.ref.dataType.defaultValue ?? [];
}
switch (typeName) {
case "string":
return listItem?.ref.dataType.defaultValue ?? "";
case "number":
return listItem?.ref.dataType.defaultValue ?? null;
case "boolean":
return listItem?.ref.dataType.defaultValue ?? false;
case "object":
return listItem?.ref.dataType.defaultValue ?? {};
default: // any
return listItem?.ref.dataType.defaultValue;
}
Comment on lines +63 to +74
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to add one private field into CandidateDate like:

private List<Offer> offers;

Also getters and setters added and constructor adapted. However then in the run of mvn clean quarkus:dev -Pdevelopment of process-compact-architecture can not display the hiring form.

image

In other words, does patternfly forms support list fields only for number, string and boolean?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure of what happened here. The form code was correctly generated? Can you share it here, please? What is a Offer?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Offer is class from process-compact-architecture example.

Here is the CandidateData.java

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.kie.kogito.hr;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class CandidateData {

    private String name;

    private String lastName;

    private String email;

    private Integer experience;

    private List<String> skills;

    private List<Offer> offers;

    public CandidateData() {
    }

    public CandidateData(String name, String lastName, String email, Integer experience, List<String> skills, List<Offer> offers) {
        this.name = name;
        this.lastName = lastName;
        this.email = email;
        this.experience = experience;
        this.skills = skills;
        this.offers = offers;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getExperience() {
        return experience;
    }

    public void setExperience(Integer experience) {
        this.experience = experience;
    }

    public List<String> getSkills() {
        return skills;
    }

    public void setSkills(List<String> skills) {
        this.skills = skills;
    }

    public List<Offer> getOffers() {
        return offers;
    }

    public void setOffers(List<Offer> offers) {
        this.offers = offers;
    }

    @JsonIgnore
    public String getFullName() {
        return name + " " + lastName;
    }
}

and here is hiring.tsx:

import React, { useCallback, useEffect, useState } from 'react';
import {
	Card,
	CardBody,
	TextInput,
	FormGroup,
	Split,
	SplitItem,
	Button,
} from '@patternfly/react-core';
import { PlusCircleIcon, MinusCircleIcon } from '@patternfly/react-icons';
const Form__hiring: React.FC<any> = (props: any) => {
	const [formApi, setFormApi] = useState<any>();
	const [candidateData__email, set__candidateData__email] =
		useState<string>('');
	const [candidateData__experience, set__candidateData__experience] =
		useState<number>();
	const [candidateData__lastName, set__candidateData__lastName] =
		useState<string>('');
	const [candidateData__name, set__candidateData__name] = useState<string>('');
	const [candidateData__offers, set__candidateData__offers] = useState<
		string[]
	>([]);
	const [candidateData__skills, set__candidateData__skills] = useState<
		string[]
	>([]);
	/* Utility function that fills the form with the data received from the kogito runtime */
	const setFormData = (data) => {
		if (!data) {
			return;
		}
		set__candidateData__email(data?.candidateData?.email ?? '');
		set__candidateData__experience(data?.candidateData?.experience);
		set__candidateData__lastName(data?.candidateData?.lastName ?? '');
		set__candidateData__name(data?.candidateData?.name ?? '');
		set__candidateData__offers(data?.candidateData?.offers ?? []);
		set__candidateData__skills(data?.candidateData?.skills ?? []);
	};
	/* Utility function to generate the expected form output as a json object */
	const getFormData = useCallback(() => {
		const formData: any = {};
		formData.candidateData = {};
		formData.candidateData.email = candidateData__email;
		formData.candidateData.experience = candidateData__experience;
		formData.candidateData.lastName = candidateData__lastName;
		formData.candidateData.name = candidateData__name;
		formData.candidateData.offers = candidateData__offers;
		formData.candidateData.skills = candidateData__skills;
		return formData;
	}, [
		candidateData__email,
		candidateData__experience,
		candidateData__lastName,
		candidateData__name,
		candidateData__offers,
		candidateData__skills,
	]);
	/* Utility function to validate the form on the 'beforeSubmit' Lifecycle Hook */
	const validateForm = useCallback(() => {}, []);
	/* Utility function to perform actions on the on the 'afterSubmit' Lifecycle Hook */
	const afterSubmit = useCallback((result) => {}, []);
	useEffect(() => {
		if (formApi) {
			/*
        Form Lifecycle Hook that will be executed before the form is submitted.
        Throwing an error will stop the form submit. Usually should be used to validate the form.
      */
			formApi.beforeSubmit = () => validateForm();
			/*
        Form Lifecycle Hook that will be executed after the form is submitted.
        It will receive a response object containing the `type` flag indicating if the submit has been successful and `info` with extra information about the submit result.
      */
			formApi.afterSubmit = (result) => afterSubmit(result);
			/* Generates the expected form output object to be posted */
			formApi.getFormData = () => getFormData();
		}
	}, [getFormData, validateForm, afterSubmit]);
	useEffect(() => {
		/*
      Call to the Kogito console form engine. It will establish the connection with the console embeding the form
      and return an instance of FormAPI that will allow hook custom code into the form lifecycle.
      The `window.Form.openForm` call expects an object with the following entries:
        - onOpen: Callback that will be called after the connection with the console is established. The callback
        will receive the following arguments:
          - data: the data to be bound into the form
          - ctx: info about the context where the form is being displayed. This will contain information such as the form JSON Schema, process/task, user...
    */
		const api = window.Form.openForm({
			onOpen: (data, context) => {
				setFormData(data);
			},
		});
		setFormApi(api);
	}, []);
	return (
		<div className={'pf-c-form'}>
			<Card>
				<CardBody className='pf-c-form'>
					<label>
						<b>Candidate data</b>
					</label>
					<FormGroup
						fieldId={'uniforms-000i-0002'}
						label={'Email'}
						isRequired={false}>
						<TextInput
							name={'candidateData.email'}
							id={'uniforms-000i-0002'}
							isDisabled={false}
							placeholder={''}
							type={'text'}
							value={candidateData__email}
							onChange={set__candidateData__email}
						/>
					</FormGroup>
					<FormGroup
						fieldId={'uniforms-000i-0004'}
						label={'Experience'}
						isRequired={false}>
						<TextInput
							type={'number'}
							name={'candidateData.experience'}
							isDisabled={false}
							id={'uniforms-000i-0004'}
							placeholder={''}
							step={1}
							value={candidateData__experience}
							onChange={(newValue) =>
								set__candidateData__experience(Number(newValue))
							}
						/>
					</FormGroup>
					<FormGroup
						fieldId={'uniforms-000i-0005'}
						label={'Last name'}
						isRequired={false}>
						<TextInput
							name={'candidateData.lastName'}
							id={'uniforms-000i-0005'}
							isDisabled={false}
							placeholder={''}
							type={'text'}
							value={candidateData__lastName}
							onChange={set__candidateData__lastName}
						/>
					</FormGroup>
					<FormGroup
						fieldId={'uniforms-000i-0006'}
						label={'Name'}
						isRequired={false}>
						<TextInput
							name={'candidateData.name'}
							id={'uniforms-000i-0006'}
							isDisabled={false}
							placeholder={''}
							type={'text'}
							value={candidateData__name}
							onChange={set__candidateData__name}
						/>
					</FormGroup>
					<div>
						<Split hasGutter>
							<SplitItem>
								{'Offers' && (
									<label className={'pf-c-form__label'}>
										<span className={'pf-c-form__label-text'}>Offers</span>
									</label>
								)}
							</SplitItem>
							<SplitItem isFilled />
							<SplitItem>
								<Button
									name='$'
									variant='plain'
									style={{ paddingLeft: '0', paddingRight: '0' }}
									disabled={false}
									onClick={() => {
										!false &&
											set__candidateData__offers(
												(candidateData__offers ?? []).concat([undefined])
											);
									}}>
									<PlusCircleIcon color='#0088ce' />
								</Button>
							</SplitItem>
						</Split>
						<div>
							{candidateData__offers?.map((_, itemIndex) => (
								<div
									key={itemIndex}
									style={{
										marginBottom: '1rem',
										display: 'flex',
										justifyContent: 'space-between',
									}}>
									<div style={{ width: '100%', marginRight: '10px' }}>
										<Card>
											<CardBody className='pf-c-form'>
												<FormGroup
													fieldId={'uniforms-000i-000b'}
													label={'Category'}
													isRequired={false}>
													<TextInput
														name={`candidateData.offers.${itemIndex}.category`}
														id={'uniforms-000i-000b'}
														isDisabled={false}
														placeholder={''}
														type={'text'}
														value={candidateData__offers[itemIndex].category}
														onChange={(newValue) => {
															set__candidateData__offers((s) => {
																const newState = [...s];
																newState[itemIndex].category = newValue;
																return newState;
															});
														}}
													/>
												</FormGroup>
												<FormGroup
													fieldId={'uniforms-000i-000d'}
													label={'Salary'}
													isRequired={false}>
													<TextInput
														type={'number'}
														name={`candidateData.offers.${itemIndex}.salary`}
														isDisabled={false}
														id={'uniforms-000i-000d'}
														placeholder={''}
														step={1}
														value={candidateData__offers[itemIndex].salary}
														onChange={(newValue) => {
															set__candidateData__offers((s) => {
																const newState = [...s];
																newState[itemIndex].salary = Number(newValue);
																return newState;
															});
														}}
													/>
												</FormGroup>
											</CardBody>
										</Card>
									</div>
									<div>
										<Button
											disabled={false}
											variant='plain'
											style={{ paddingLeft: '0', paddingRight: '0' }}
											onClick={() => {
												const value = [...candidateData__offers];
												value.splice(itemIndex, 1);
												!false && set__candidateData__offers(value);
											}}>
											<MinusCircleIcon color='#cc0000' />
										</Button>
									</div>
								</div>
							))}
						</div>
					</div>
					<div>
						<Split hasGutter>
							<SplitItem>
								{'Skills' && (
									<label className={'pf-c-form__label'}>
										<span className={'pf-c-form__label-text'}>Skills</span>
									</label>
								)}
							</SplitItem>
							<SplitItem isFilled />
							<SplitItem>
								<Button
									name='$'
									variant='plain'
									style={{ paddingLeft: '0', paddingRight: '0' }}
									disabled={false}
									onClick={() => {
										!false &&
											set__candidateData__skills(
												(candidateData__skills ?? []).concat([''])
											);
									}}>
									<PlusCircleIcon color='#0088ce' />
								</Button>
							</SplitItem>
						</Split>
						<div>
							{candidateData__skills?.map((_, itemIndex) => (
								<div
									key={itemIndex}
									style={{
										marginBottom: '1rem',
										display: 'flex',
										justifyContent: 'space-between',
									}}>
									<div style={{ width: '100%', marginRight: '10px' }}>
										<FormGroup
											fieldId={'uniforms-000i-000g'}
											label={''}
											isRequired={false}>
											<TextInput
												name={`candidateData.skills.${itemIndex}`}
												id={'uniforms-000i-000g'}
												isDisabled={false}
												placeholder={''}
												type={'text'}
												value={candidateData__skills[itemIndex]}
												onChange={(newValue) => {
													set__candidateData__skills((s) => {
														const newState = [...s];
														newState[itemIndex] = newValue;
														return newState;
													});
												}}
											/>
										</FormGroup>
									</div>
									<div>
										<Button
											disabled={false}
											variant='plain'
											style={{ paddingLeft: '0', paddingRight: '0' }}
											onClick={() => {
												const value = [...candidateData__skills];
												value.splice(itemIndex, 1);
												!false && set__candidateData__skills(value);
											}}>
											<MinusCircleIcon color='#cc0000' />
										</Button>
									</div>
								</div>
							))}
						</div>
					</div>
				</CardBody>
			</Card>
		</div>
	);
};
export default Form__hiring;

};

const jsxCode = `<div fieldId={'${props.id}'}>
<Split hasGutter>
<SplitItem>
{'${props.label}' && (
<label className={"pf-c-form__label"}>
<span className={"pf-c-form__label-text"}>
${props.label}
</span>
</label>
)}
</SplitItem>
<SplitItem isFilled />
<SplitItem>
<Button
name='$'
variant='plain'
style={{ paddingLeft: '0', paddingRight: '0' }}
disabled={${props.maxCount === undefined ? props.disabled : `${props.disabled} || !(${props.maxCount} <= (${ref.stateName}?.length ?? -1))`}}
onClick={() => {
!${props.disabled} && ${props.maxCount === undefined ? `${ref.stateSetter}((${ref.stateName} ?? []).concat([${getNewItemProps()}]))` : `!(${props.maxCount} <= (${ref.stateName}?.length ?? -1)) && ${ref.stateSetter}((${ref.stateName} ?? []).concat([]))`};
}}
>
<PlusCircleIcon color='#0088ce' />
</Button>
</SplitItem>
</Split>
<div>
{${ref.stateName}?.map((_, itemIndex) =>
(<div
key={itemIndex}
style={{
marginBottom: '1rem',
display: 'flex',
justifyContent: 'space-between',
}}
>
<div style={{ width: '100%', marginRight: '10px' }}>${listItem?.jsxCode}</div>
<div>
<Button
disabled={${props.minCount === undefined ? props.disabled : `${props.disabled} || (${props.minCount} >= (${ref.stateName}?.length ?? -1))`}}
variant='plain'
style={{ paddingLeft: '0', paddingRight: '0' }}
onClick={() => {
const value = [...${ref.stateName}]
value.splice(itemIndex, 1);
!${props.disabled} && ${props.minCount === undefined ? `${ref.stateSetter}(value)` : `!(${props.minCount} >= (${ref.stateName}?.length ?? -1)) && ${ref.stateSetter}(value)`};
}}
>
<MinusCircleIcon color='#cc0000' />
</Button>
</div>
</div>)
)}
</div>
</div>`;

const element: FormInput = {
ref,
pfImports: [...new Set(["Split", "SplitItem", "Button", ...(listItem?.pfImports ?? [])])],
pfIconImports: [...new Set(["PlusCircleIcon", "MinusCircleIcon", ...(listItem?.pfIconImports ?? [])])],
reactImports: [...new Set([...(listItem?.reactImports ?? [])])],
jsxCode,
stateCode: getStateCode(ref.stateName, ref.stateSetter, "any[]", "[]"),
isReadonly: props.disabled,
};

codegenCtx?.rendered.push(element);

return renderField(element);
};

export default connectField(List);
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { codeGenContext } from "./CodeGenContext";
import { union } from "lodash";
import { OBJECT } from "./utils/dataTypes";

export type NestFieldProps = HTMLFieldProps<object, HTMLDivElement, { itemProps?: object }>;
export type NestFieldProps = HTMLFieldProps<object, HTMLDivElement, { itemProps?: any }>;

const Nest: React.FunctionComponent<NestFieldProps> = ({
id,
Expand All @@ -49,6 +49,7 @@ const Nest: React.FunctionComponent<NestFieldProps> = ({
const nestedJsx: string[] = [];

let pfImports: string[] = ["Card", "CardBody"];
let pfIconImports: string[] = [];
let reactImports: string[] = [];
let requiredCode: string[] = [];

Expand All @@ -65,6 +66,7 @@ const Nest: React.FunctionComponent<NestFieldProps> = ({
nestedRefs.push(...nestedContainer.childRefs);
}
pfImports = union(pfImports, renderedInput.pfImports);
pfIconImports = union(pfIconImports, renderedInput.pfIconImports);
reactImports = union(reactImports, renderedInput.reactImports);
if (renderedInput.requiredCode) {
requiredCode = union(requiredCode, renderedInput.requiredCode);
Expand All @@ -75,7 +77,7 @@ const Nest: React.FunctionComponent<NestFieldProps> = ({
});
}

const bodyLabel = label ? `<label><b>${label}</b></label>` : "";
const bodyLabel = label && !itemProps?.isListItem ? `<label><b>${label}</b></label>` : "";

const stateCode = nestedStates.join("\n");
const jsxCode = `<Card>
Expand All @@ -86,6 +88,7 @@ const Nest: React.FunctionComponent<NestFieldProps> = ({

const rendered: InputsContainer = {
pfImports,
pfIconImports,
reactImports,
requiredCode: requiredCode,
stateCode,
Expand Down
Loading
Loading