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 #1542 #2826

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
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 @@ -62,7 +64,8 @@ const AutoForm: React.FC<AutoFormProps> = (props) => {

const formTemplate = `
import React, { ${reactImports.join(", ")} } from "react";
import { ${pfImports.join(", ")} } from "@patternfly/react-core";
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,126 @@
/*
* 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 jsxCode = `<div fieldId={'${props.id}'}>
<Split hasGutter>
<SplitItem>
{'${props.label}' && (
<label>
'${props.label}'
</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([]))` : `!(${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}!.slice();
value.splice(${+joinName(null, "")[joinName(null, "").length - 1]}, 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 Down Expand Up @@ -75,7 +75,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 Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { buildDefaultInputElement, getInputReference, renderField } from "./util
import { useAddFormElementToContext } from "./CodeGenContext";
import { FormInput, InputReference } from "../api";
import { NUMBER } from "./utils/dataTypes";
import { getListItemName, getListItemOnChange, getListItemValue, ListItemProps } from "./rendering/ListItemField";

export type NumFieldProps = HTMLFieldProps<
string,
Expand All @@ -34,6 +35,7 @@ export type NumFieldProps = HTMLFieldProps<
decimal?: boolean;
min?: string;
max?: string;
itemProps?: ListItemProps;
}
>;

Expand All @@ -45,13 +47,13 @@ const Num: React.FC<NumFieldProps> = (props: NumFieldProps) => {

const inputJsxCode = `<TextInput
type={'number'}
name={'${props.name}'}
name={${props.itemProps?.isListItem ? getListItemName({ itemProps: props.itemProps, name: props.name }) : `'${props.name}'`}}
isDisabled={${props.disabled || "false"}}
id={'${props.id}'}
placeholder={'${props.placeholder}'}
step={${props.decimal ? 0.01 : 1}} ${max} ${min}
value={${ref.stateName}}
onChange={(newValue) => ${ref.stateSetter}(Number(newValue))}
value={${props.itemProps?.isListItem ? getListItemValue({ itemProps: props.itemProps, name: props.name }) : ref.stateName}}
onChange={${props.itemProps?.isListItem ? getListItemOnChange({ itemProps: props.itemProps, name: props.name, callback: (value: string) => `Number(${value})` }) : `(newValue) => ${ref.stateSetter}(Number(newValue))`}}
/>`;

const element: FormInput = buildDefaultInputElement({
Expand Down
Loading
Loading