Skip to content

Commit

Permalink
feat: render options for SelectField and RadioGroupField (#577)
Browse files Browse the repository at this point in the history
Co-authored-by: Hein Jeong <heinje@amazon.com>
  • Loading branch information
hein-j and Hein Jeong authored Aug 11, 2022
1 parent a83c18f commit f544500
Show file tree
Hide file tree
Showing 7 changed files with 304 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@ import {
getOverrideProps,
useStateMutationAction,
} from \\"@aws-amplify/ui-react/internal\\";
import { Button, Flex, Grid, TextField } from \\"@aws-amplify/ui-react\\";
import {
Button,
Flex,
Grid,
Radio,
RadioGroupField,
SelectField,
TextField,
} from \\"@aws-amplify/ui-react\\";
export default function customDataForm(props) {
const {
onSubmit: customDataFormOnSubmit,
Expand All @@ -19,6 +27,10 @@ export default function customDataForm(props) {
} = props;
const [nameFieldError, setNameFieldError] = useStateMutationAction({});
const [emailFieldError, setEmailFieldError] = useStateMutationAction({});
const [cityFieldError, setCityFieldError] = useStateMutationAction({});
const [categoryFieldError, setCategoryFieldError] = useStateMutationAction(
{}
);
const [modelFields, setModelFields] = useStateMutationAction({});
const [formValid, setFormValid] = useStateMutationAction(true);
return (
Expand Down Expand Up @@ -83,6 +95,88 @@ export default function customDataForm(props) {
{...getOverrideProps(overrides, \\"email\\")}
></TextField>
</Grid>
<Grid
columnGap=\\"inherit\\"
rowGap=\\"inherit\\"
templateColumns=\\"repeat(1, auto)\\"
{...getOverrideProps(overrides, \\"RowGrid2\\")}
>
<SelectField
label=\\"Label\\"
onChange={async (e) => {
const { value } = e.target;
const isValidResult = onValidate?.[\\"city\\"]
? await onValidate[\\"city\\"](value)
: validateField(value, []);
setCityFieldError({ ...cityFieldError, ...isValidResult });
setFormValid(!cityFieldError.hasError);
setModelFields({ ...modelFields, city: value });
}}
errorMessage={cityFieldError.errorMessage}
hasError={cityFieldError.hasError}
{...getOverrideProps(overrides, \\"city\\")}
>
<option
children=\\"Los Angeles\\"
value=\\"Los Angeles\\"
{...getOverrideProps(overrides, \\"cityoption0\\")}
></option>
<option
children=\\"Houston\\"
value=\\"Houston\\"
{...getOverrideProps(overrides, \\"cityoption1\\")}
></option>
<option
children=\\"New York\\"
value=\\"New York\\"
selected={true}
{...getOverrideProps(overrides, \\"cityoption2\\")}
></option>
</SelectField>
</Grid>
<Grid
columnGap=\\"inherit\\"
rowGap=\\"inherit\\"
templateColumns=\\"repeat(1, auto)\\"
{...getOverrideProps(overrides, \\"RowGrid3\\")}
>
<RadioGroupField
label=\\"Label\\"
name=\\"fieldName\\"
defaultValue=\\"Hobbies\\"
onChange={async (e) => {
const { value } = e.target;
const isValidResult = onValidate?.[\\"category\\"]
? await onValidate[\\"category\\"](value)
: validateField(value, []);
setCategoryFieldError({
...categoryFieldError,
...isValidResult,
});
setFormValid(!categoryFieldError.hasError);
setModelFields({ ...modelFields, category: value });
}}
errorMessage={categoryFieldError.errorMessage}
hasError={categoryFieldError.hasError}
{...getOverrideProps(overrides, \\"category\\")}
>
<Radio
children=\\"Hobbies\\"
value=\\"Hobbies\\"
{...getOverrideProps(overrides, \\"categoryRadio0\\")}
></Radio>
<Radio
children=\\"Travel\\"
value=\\"Travel\\"
{...getOverrideProps(overrides, \\"categoryRadio1\\")}
></Radio>
<Radio
children=\\"Health\\"
value=\\"Health\\"
{...getOverrideProps(overrides, \\"categoryRadio2\\")}
></Radio>
</RadioGroupField>
</Grid>
</Grid>
<Flex
justifyContent=\\"space-between\\"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import {
VisuallyHiddenProps,
TextProps,
} from '@aws-amplify/ui-react';
import { HTMLProps } from 'react';
import { Primitive } from '../primitive';
import CustomComponentRenderer from './customComponent';
import FormRenderer from './form';
Expand Down Expand Up @@ -139,6 +140,14 @@ export class AmplifyFormRenderer extends ReactFormTemplateRenderer {
parent,
).renderElement(renderChildren);

case 'option':
return new ReactComponentRenderer<HTMLProps<HTMLOptionElement>>(
formComponent,
this.componentMetadata,
this.importCollection,
parent,
).renderElement(renderChildren);

case Primitive.Divider:
return new ReactComponentRenderer<DividerProps>(
formComponent,
Expand Down
20 changes: 20 additions & 0 deletions packages/codegen-ui/example-schemas/forms/post-custom-create.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,26 @@
"defaultValue": "johndoe@amplify.com"
},
"label": "E-mail"
},
"city": {
"inputType": {
"type": "SelectField",
"defaultValue": "New York",
"valueMappings": {
"bindingProperties": {},
"values": [{"value": {"value": "Los Angeles"}}, {"value": {"value": "Houston"}}, {"value": {"value": "New York"}}]
}
}
},
"category": {
"inputType": {
"type": "RadioGroupField",
"defaultValue": "Hobbies",
"valueMappings": {
"bindingProperties": {},
"values": [{"value": {"value": "Hobbies"}}, {"value": {"value": "Travel"}}, {"value": {"value": "Health"}}]
}
}
}
},
"sectionalElements": {},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed 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 { FormDefinition } from '../../types';

export const getBasicFormDefinition = (): FormDefinition => ({
form: {
layoutStyle: {},
},
elements: {},
buttons: {},
elementMatrix: [[]],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed 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 { FormDefinition } from '../../../types';
import { mapFormDefinitionToComponent } from '../../../utils/form-to-component';
import { getBasicFormDefinition } from '../../__utils__/basic-form-definition';

describe('mapFormDefinitionToComponent', () => {
it('should map options for RadioGroupField', () => {
const formDefinition: FormDefinition = {
...getBasicFormDefinition(),
elements: {
city: {
componentType: 'RadioGroupField',
props: { label: 'City', name: 'city' },
valueMappings: {
bindingProperties: {},
values: [
{ value: { value: 'NEW_YORK' }, displayValue: { value: 'New York' } },
{ value: { value: 'SAN_FRANCISCO' } },
],
},
},
},
elementMatrix: [['city']],
};

const radioGroupField = mapFormDefinitionToComponent('CreateDog', formDefinition).children?.[0].children?.[0]
.children?.[0];

expect(radioGroupField?.children).toStrictEqual([
{
name: 'cityRadio0',
componentType: 'Radio',
properties: { children: { value: 'New York' }, value: { value: 'NEW_YORK' } },
},
{
name: 'cityRadio1',
componentType: 'Radio',
properties: { children: { value: 'SAN_FRANCISCO' }, value: { value: 'SAN_FRANCISCO' } },
},
]);
});

it('should map options for SelectField', () => {
const formDefinition: FormDefinition = {
...getBasicFormDefinition(),
elements: {
city: {
componentType: 'SelectField',
props: { label: 'City' },
defaultValue: 'NEW_YORK',
valueMappings: {
bindingProperties: {},
values: [
{ value: { value: 'NEW_YORK' }, displayValue: { value: 'New York' } },
{ value: { value: 'SAN_FRANCISCO' } },
],
},
},
},
elementMatrix: [['city']],
};

const selectField = mapFormDefinitionToComponent('CreateDog', formDefinition).children?.[0].children?.[0]
.children?.[0];

expect(selectField?.children).toStrictEqual([
{
name: 'cityoption0',
componentType: 'option',
properties: { children: { value: 'New York' }, value: { value: 'NEW_YORK' }, selected: { value: true } },
},
{
name: 'cityoption1',
componentType: 'option',
properties: { children: { value: 'SAN_FRANCISCO' }, value: { value: 'SAN_FRANCISCO' } },
},
]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed 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 {
FormDefinitionElement,
FormDefinitionRadioGroupFieldElement,
FormDefinitionSelectFieldElement,
StudioComponentChild,
} from '../../../types';

type MapElementChildrenReturnValue = { children: StudioComponentChild[] };

function mapOptions(
elementName: string,
element: FormDefinitionSelectFieldElement | FormDefinitionRadioGroupFieldElement,
): { children: StudioComponentChild[] } {
const options = element.valueMappings.values.map(({ displayValue, value }, index) => {
const optionType = element.componentType === 'RadioGroupField' ? 'Radio' : 'option';

const option: StudioComponentChild = {
name: `${elementName}${optionType}${index}`,
componentType: optionType,
properties: {
children: displayValue ?? value,
value,
},
};

if (element.componentType === 'SelectField' && 'value' in value && value.value === element.defaultValue) {
option.properties.selected = { value: true };
}

return option;
});

return { children: options };
}

export function mapElementChildren(elementName: string, element: FormDefinitionElement): MapElementChildrenReturnValue {
switch (element.componentType) {
case 'SelectField':
case 'RadioGroupField':
return mapOptions(elementName, element);

default:
return { children: [] };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
StudioComponentProperties,
StudioFormStyle,
} from '../../types';
import { mapElementChildren } from './helpers/map-element-children';

const getStyleResolvedValue = (config?: FormStyleConfig): string | undefined => {
return config?.value ?? config?.tokenReference;
Expand Down Expand Up @@ -77,6 +78,7 @@ const fieldComponentMapper = (name: string, formDefinition: FormDefinition): Stu
name: column,
componentType: element.componentType,
properties: mapFieldElementProps(element),
children: mapElementChildren(column, element).children,
};
}),
};
Expand Down

0 comments on commit f544500

Please sign in to comment.