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

fix: add array fields for autogenerated forms #634

Merged
merged 3 commits into from
Sep 12, 2022
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 @@ -1161,16 +1161,119 @@ import { fetchByPath, validateField } from \\"./utils\\";
import { InputGallery } from \\"../models\\";
import { getOverrideProps } from \\"@aws-amplify/ui-react/internal\\";
import {
Badge,
Button,
CheckboxField,
Divider,
Flex,
Grid,
Icon,
Radio,
RadioGroupField,
ScrollView,
TextField,
ToggleButton,
} from \\"@aws-amplify/ui-react\\";
import { DataStore } from \\"aws-amplify\\";
function ArrayField({
defaultValues = [],
onChange,
inputFieldRef,
children,
hasError,
setFieldValue,
currentFieldValue,
}) {
const [selectedBadgeIndex, setSelectedBadgeIndex] = React.useState();
const [items, setItems] = React.useState(defaultValues);
const removeItem = async (removeIndex) => {
const newItems = items.filter((value, index) => index !== removeIndex);
await onChange(newItems);
setSelectedBadgeIndex(undefined);
setItems(newItems);
};
const addItem = async () => {
if (currentFieldValue.length && !hasError) {
const newItems = [...items];
if (selectedBadgeIndex !== undefined) {
newItems[selectedBadgeIndex] = currentFieldValue;
setItems(newItems);
setSelectedBadgeIndex(undefined);
} else {
newItems.push(currentFieldValue);
setItems(newItems);
}
await onChange(newItems);
}
};
return (
<React.Fragment>
{children}
<Flex justifyContent=\\"flex-end\\">
<Button
children=\\"Cancel\\"
type=\\"button\\"
onClick={() => {
setFieldValue(\\"\\");
}}
></Button>
<Button
children=\\"Save\\"
variation=\\"primary\\"
isDisabled={hasError}
onClick={addItem}
></Button>
</Flex>
{!!items.length && (
<ScrollView height=\\"inherit\\" width=\\"inherit\\" maxHeight={\\"7rem\\"}>
{items.map((value, index) => {
return (
<Badge
key={index}
style={{
cursor: \\"pointer\\",
alignItems: \\"center\\",
marginRight: 3,
marginTop: 3,
backgroundColor:
index === selectedBadgeIndex ? \\"#B8CEF9\\" : \\"\\",
}}
onClick={() => {
setSelectedBadgeIndex(index);
setFieldValue(items[index]);
inputFieldRef?.current?.focus();
}}
>
{value}
<Icon
style={{
cursor: \\"pointer\\",
paddingLeft: 3,
width: 20,
height: 20,
}}
viewBox={{ width: 20, height: 20 }}
paths={[
{
d: \\"M10 10l5.09-5.09L10 10l5.09 5.09L10 10zm0 0L4.91 4.91 10 10l-5.09 5.09L10 10z\\",
stroke: \\"black\\",
},
]}
ariaLabel=\\"button\\"
onClick={(event) => {
event.stopPropagation();
removeItem(index);
}}
/>
</Badge>
);
})}
</ScrollView>
)}
<Divider orientation=\\"horizontal\\" marginTop={5} />
</React.Fragment>
);
}
export default function InputGalleryCreateForm(props) {
const {
onSubmitBefore,
Expand All @@ -1190,6 +1293,9 @@ export default function InputGalleryCreateForm(props) {
const [ippy, setIppy] = React.useState(undefined);
const [timeisnow, setTimeisnow] = React.useState(undefined);
const [errors, setErrors] = React.useState({});
const [currentArrayTypeFieldValue, setCurrentArrayTypeFieldValue] =
React.useState(\\"\\");
const arrayTypeFieldRef = React.createRef();
const validations = {
num: [],
rootbeer: [],
Expand Down Expand Up @@ -1364,24 +1470,37 @@ export default function InputGalleryCreateForm(props) {
hasError={errors.maybeCheck?.hasError}
{...getOverrideProps(overrides, \\"maybeCheck\\")}
></CheckboxField>
<TextField
label=\\"Array type field\\"
isRequired={false}
isReadOnly={false}
onChange={async (e) => {
const { value } = e.target;
if (errors.arrayTypeField?.hasError) {
await runValidationTasks(\\"arrayTypeField\\", value);
}
setArrayTypeField(value);
<ArrayField
onChange={async (items) => {
setArrayTypeField(items);
setCurrentArrayTypeFieldValue(\\"\\");
}}
onBlur={async () =>
await runValidationTasks(\\"arrayTypeField\\", arrayTypeField)
}
errorMessage={errors.arrayTypeField?.errorMessage}
currentFieldValue={currentArrayTypeFieldValue}
hasError={errors.arrayTypeField?.hasError}
{...getOverrideProps(overrides, \\"arrayTypeField\\")}
></TextField>
setFieldValue={setCurrentArrayTypeFieldValue}
inputFieldRef={arrayTypeFieldRef}
>
<TextField
label=\\"Array type field\\"
isRequired={false}
isReadOnly={false}
onChange={async (e) => {
const { value } = e.target;
if (errors.arrayTypeField?.hasError) {
await runValidationTasks(\\"arrayTypeField\\", value);
}
setCurrentArrayTypeFieldValue(value);
}}
onBlur={async () =>
await runValidationTasks(\\"arrayTypeField\\", arrayTypeField)
}
errorMessage={errors.arrayTypeField?.errorMessage}
hasError={errors.arrayTypeField?.hasError}
value={currentArrayTypeFieldValue}
ref={arrayTypeFieldRef}
{...getOverrideProps(overrides, \\"arrayTypeField\\")}
></TextField>
</ArrayField>
<TextField
label=\\"Timestamp\\"
isRequired={false}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ export const addFormAttributes = (component: StudioComponent | StudioComponentCh
),
),
);
if (formMetadata.formActionType === 'update') {
if (formMetadata.formActionType === 'update' && !fieldConfig.isArray) {
attributes.push(
factory.createJsxAttribute(
factory.createIdentifier('defaultValue'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export abstract class ReactFormTemplateRenderer extends StudioTemplateRenderer<
this.formComponent = mapFormDefinitionToComponent(this.component.name, this.formDefinition);

this.componentMetadata = computeComponentMetadata(this.formComponent);
this.componentMetadata.formMetadata = mapFormMetadata(this.component, this.formDefinition);
this.componentMetadata.formMetadata = mapFormMetadata(this.component, this.formDefinition, dataSchema);
}

@handleCodegenErrors
Expand Down
11 changes: 1 addition & 10 deletions packages/codegen-ui-react/lib/react-component-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import {
getStateName,
getSetStateName,
hasChildrenProp,
isFixedPropertyWithValue,
} from './react-component-render-helper';
import {
buildOpeningElementControlEvents,
Expand Down Expand Up @@ -81,15 +80,7 @@ export class ReactComponentRenderer<TPropIn> extends ComponentRendererBase<
this.importCollection.addImport(ImportSource.UI_REACT, 'Badge');
this.importCollection.addImport(ImportSource.UI_REACT, 'ScrollView');
this.importCollection.addImport(ImportSource.UI_REACT, 'Divider');
return renderArrayFieldComponent(
this.component.name,
`${
isFixedPropertyWithValue(this.component.properties.label)
? this.component.properties.label.value
: this.component.name
}`,
element,
);
return renderArrayFieldComponent(this.component.name, element);
}

return element;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -783,7 +783,7 @@ export const generateArrayFieldComponent = () => {
/*
<ArrayField
onChange = { async(items) => {
setModelFields({ ...modelFields, breeds: items });
setBreeds(items);
setCurrentBreedsValue('');
}}
currentBreedsValue = { currentBreedsValue }
Expand All @@ -795,7 +795,7 @@ export const generateArrayFieldComponent = () => {
</ArrayField>
*/

export const renderArrayFieldComponent = (fieldName: string, label: string, inputField: JsxChild) =>
export const renderArrayFieldComponent = (fieldName: string, inputField: JsxChild) =>
factory.createJsxElement(
factory.createJsxOpeningElement(
factory.createIdentifier('ArrayField'),
Expand Down
8 changes: 8 additions & 0 deletions packages/codegen-ui/lib/__tests__/__utils__/mock-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,14 @@ export const schemaWithAssumptions: Schema = {
associatedWith: 'userPostsId',
},
},
badges: {
name: 'badges',
isArray: true,
type: 'String',
isRequired: false,
attributes: [],
isArrayNullable: true,
},
},
syncable: true,
pluralName: 'Users',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@
See the License for the specific language governing permissions and
limitations under the License.
*/
import { generateFormDefinition } from '../../generate-form-definition';
import { getGenericFromDataStore } from '../../generic-from-datastore';
import { FormDefinition, StudioForm } from '../../types';
import { mapFormMetadata } from '../../utils/form-component-metadata';
import { getBasicFormDefinition } from '../__utils__/basic-form-definition';
import { schemaWithAssumptions } from '../__utils__/mock-schemas';

describe('mapFormMetaData', () => {
it('should not map metadata for sectional elements', () => {
Expand Down Expand Up @@ -76,4 +79,25 @@ describe('mapFormMetaData', () => {
expect('name' in fieldConfigs).toBe(true);
expect('myDivider' in fieldConfigs || 'myText' in fieldConfigs || 'myHeading' in fieldConfigs).toBe(false);
});
it('should map isArray type for autogenerated datastore form', () => {
const dataSchema = getGenericFromDataStore(schemaWithAssumptions);

const form: StudioForm = {
name: 'DataStoreForm',
formActionType: 'create',
dataType: {
dataSourceType: 'DataStore',
dataTypeName: 'User',
},
fields: {},
sectionalElements: {},
style: {},
cta: {},
};

const { fieldConfigs } = mapFormMetadata(form, generateFormDefinition({ form, dataSchema }), dataSchema);

expect('badges' in fieldConfigs).toBe(true);
expect(fieldConfigs.badges.isArray).toBe(true);
});
});
11 changes: 10 additions & 1 deletion packages/codegen-ui/lib/utils/form-component-metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
FormDefinitionElement,
FormDefinitionInputElement,
StudioFieldInputConfig,
GenericDataSchema,
} from '../types';

export const getFormFieldStateName = (formName: string) => {
Expand All @@ -32,7 +33,11 @@ function elementIsInput(element: FormDefinitionElement): element is FormDefiniti
return element.componentType !== 'Text' && element.componentType !== 'Divider' && element.componentType !== 'Heading';
}

export const mapFormMetadata = (form: StudioForm, formDefinition: FormDefinition): FormMetadata => {
export const mapFormMetadata = (
form: StudioForm,
formDefinition: FormDefinition,
dataSchema?: GenericDataSchema | undefined,
): FormMetadata => {
const inputElementEntries = Object.entries(formDefinition.elements).filter(([, element]) => elementIsInput(element));
return {
id: form.id,
Expand All @@ -53,6 +58,10 @@ export const mapFormMetadata = (form: StudioForm, formDefinition: FormDefinition
if ('dataType' in config && config.dataType) {
metadata.dataType = config.dataType;
}
if (form.dataType.dataSourceType === 'DataStore' && dataSchema) {
const modelFields = dataSchema.models[form.dataType.dataTypeName].fields;
metadata.isArray = modelFields[name]?.isArray;
}
if (form.fields[name] && 'inputType' in form.fields[name]) {
const { inputType } = form.fields[name] as { inputType: StudioFieldInputConfig };
if (inputType.isArray) {
Expand Down