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

chore: tidying forms renderer #549

Merged
merged 1 commit into from
Jul 29, 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 @@ -14,25 +14,23 @@ export default function customDataForm(props) {
const {
onSubmit: customDataFormOnSubmit,
onCancel,
onValidate,
overrides,
...rest
} = props;
const [nameFieldError, setNameFieldError] = useStateMutationAction({});
const [emailFieldError, setEmailFieldError] = useStateMutationAction({});
const [customDataFormFields, setCustomDataFormFields] =
useStateMutationAction({});
const [modelFields, setModelFields] = useStateMutationAction({});
const [formValid, setFormValid] = useStateMutationAction(true);
return (
<form
onSubmit={async (event) => {
event.preventDefault();
if (onSubmitBefore) {
setCustomDataFormFields(
onSubmitBefore({ fields: customDataFormFields })
);
setModelFields(onSubmitBefore({ fields: modelFields }));
}
try {
await DataStore.save(new Post(customDataFormFields));
await DataStore.save(new Post(modelFields));
if (onSubmitComplete) {
onSubmitComplete({ saveSuccessful: true });
}
Expand Down Expand Up @@ -155,32 +153,40 @@ import React from \\"react\\";
import { validateField } from \\"./utils.js\\";
import {
getOverrideProps,
useDataStoreCreateAction,
useStateMutationAction,
} from \\"@aws-amplify/ui-react/internal\\";
import { Post } from \\"../models\\";
import { schema } from \\"../models/schema\\";
import { Button, Flex, Grid, TextField } from \\"@aws-amplify/ui-react\\";
import { DataStore } from \\"aws-amplify\\";
export default function myPostForm(props) {
const { onSubmitBefore, onSubmitComplete, onCancel, overrides, ...rest } =
props;
const [myPostFormFields, setMyPostFormFields] = useStateMutationAction({});
const {
onSubmitBefore,
onSubmitComplete,
onCancel,
onValidate,
overrides,
...rest
} = props;
const [captionFieldError, setCaptionFieldError] = useStateMutationAction({});
const [usernameFieldError, setUsernameFieldError] = useStateMutationAction(
{}
);
const [post_urlFieldError, setPost_urlFieldError] = useStateMutationAction(
{}
);
const [profile_urlFieldError, setProfile_urlFieldError] =
useStateMutationAction({});
const [modelFields, setModelFields] = useStateMutationAction({});
const [formValid, setFormValid] = useStateMutationAction(true);
const myPostFormOnSubmit = useDataStoreCreateAction({
model: Post,
fields: myPostFormFields,
schema: schema,
});
return (
<form
onSubmit={async (event) => {
event.preventDefault();
if (onSubmitBefore) {
setMyPostFormFields(onSubmitBefore({ fields: myPostFormFields }));
setModelFields(onSubmitBefore({ fields: modelFields }));
}
try {
await DataStore.save(new Post(myPostFormFields));
await DataStore.save(new Post(modelFields));
if (onSubmitComplete) {
onSubmitComplete({ saveSuccessful: true });
}
Expand Down Expand Up @@ -376,33 +382,41 @@ import React from \\"react\\";
import { validateField } from \\"./utils.js\\";
import {
getOverrideProps,
useDataStoreUpdateAction,
useStateMutationAction,
} from \\"@aws-amplify/ui-react/internal\\";
import { Post } from \\"../models\\";
import { schema } from \\"../models/schema\\";
import { Button, Flex, Grid, TextField } from \\"@aws-amplify/ui-react\\";
import { DataStore } from \\"aws-amplify\\";
export default function myPostForm(props) {
const { id, onSubmitBefore, onSubmitComplete, onCancel, overrides, ...rest } =
props;
const [myPostFormFields, setMyPostFormFields] = useStateMutationAction({});
const {
id,
onSubmitBefore,
onSubmitComplete,
onCancel,
onValidate,
overrides,
...rest
} = props;
const [captionFieldError, setCaptionFieldError] = useStateMutationAction({});
const [usernameFieldError, setUsernameFieldError] = useStateMutationAction(
{}
);
const [post_urlFieldError, setPost_urlFieldError] = useStateMutationAction(
{}
);
const [profile_urlFieldError, setProfile_urlFieldError] =
useStateMutationAction({});
const [modelFields, setModelFields] = useStateMutationAction({});
const [formValid, setFormValid] = useStateMutationAction(true);
const myPostFormOnSubmit = useDataStoreUpdateAction({
model: Post,
fields: myPostFormFields,
id: id,
schema: schema,
});
return (
<form
onSubmit={async (event) => {
event.preventDefault();
if (onSubmitBefore) {
setMyPostFormFields(onSubmitBefore({ fields: myPostFormFields }));
setModelFields(onSubmitBefore({ fields: modelFields }));
}
try {
await DataStore.save(new Post(myPostFormFields));
await DataStore.save(new Post(modelFields));
if (onSubmitComplete) {
onSubmitComplete({ saveSuccessful: true });
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`form-render utils should generate a datastore function 1`] = `"const mySampleFormOnSubmit = useDataStoreCreateAction({ model: Post, fields: mySampleFormFields, schema: schema });"`;

exports[`form-render utils should generate before & complete types if datastore config is set 1`] = `
"{
onSubmitBefore?: (fields: Record<string, string>) => Record<string, string>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
*/
import { StudioForm } from '@aws-amplify/codegen-ui';
import { EmitHint, Node } from 'typescript';
import { ImportCollection } from '../../imports';
import { buildFormPropNode, buildDataStoreActionStatement } from '../../forms';
import { buildFormPropNode } from '../../forms';
import { buildPrinter, defaultRenderConfig } from '../../react-studio-template-renderer-helper';

describe('form-render utils', () => {
Expand All @@ -29,23 +28,6 @@ describe('form-render utils', () => {
};
});

it('should generate a datastore function', () => {
const form: StudioForm = {
id: '123',
name: 'mySampleForm',
formActionType: 'create',
dataType: { dataSourceType: 'DataStore', dataTypeName: 'Post' },
fields: {},
sectionalElements: {},
style: {},
};
const importCollection = new ImportCollection();
const mutationStatement: any = buildDataStoreActionStatement(form, importCollection);
expect(mutationStatement).toBeDefined();
const node = printNode(mutationStatement);
expect(node).toMatchSnapshot();
});

it('should generate before & complete types if datastore config is set', () => {
const form: StudioForm = {
id: '123',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe('amplify form renderer tests', () => {
'forms/post-datastore-create',
'datastore/post',
);
expect(componentText).toContain('useDataStoreCreateAction');
expect(componentText).toContain('DataStore.save');
expect(componentText).toMatchSnapshot();
expect(declaration).toMatchSnapshot();
});
Expand All @@ -61,7 +61,7 @@ describe('amplify form renderer tests', () => {
'forms/post-datastore-update',
'datastore/post',
);
expect(componentText).toContain('useDataStoreUpdateAction');
expect(componentText).toContain('DataStore.save');
expect(componentText).toMatchSnapshot();
expect(declaration).toMatchSnapshot();
});
Expand All @@ -70,7 +70,7 @@ describe('amplify form renderer tests', () => {
describe('custom form tests', () => {
it('should render a custom backed form', () => {
const { componentText, declaration } = generateWithAmplifyFormRenderer('forms/post-custom-create', undefined);
expect(componentText.replace(/\s/g, '')).toContain('setCustomDataFormFields(onSubmitBefore');
expect(componentText.replace(/\s/g, '')).toContain('setModelFields(onSubmitBefore');
expect(componentText).toMatchSnapshot();
expect(declaration).toMatchSnapshot();
});
Expand Down
36 changes: 15 additions & 21 deletions packages/codegen-ui-react/lib/amplify-ui-renderers/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ import {
} from '@aws-amplify/codegen-ui';
import { factory, JsxAttribute, JsxChild, JsxElement, JsxOpeningElement, SyntaxKind } from 'typescript';
import { ReactComponentRenderer } from '../react-component-renderer';
import { buildOpeningElementProperties, getStateName, getSetStateName } from '../react-component-render-helper';
import { buildOpeningElementProperties } from '../react-component-render-helper';
import { ImportCollection } from '../imports';
import { FieldStateVariable } from '../forms/form-renderer-helper';

export default class FormRenderer extends ReactComponentRenderer<BaseComponentProps> {
constructor(
Expand Down Expand Up @@ -72,7 +71,6 @@ export default class FormRenderer extends ReactComponentRenderer<BaseComponentPr

private getFormOnSubmitAttribute(): JsxAttribute {
const {
name,
dataType: { dataTypeName },
} = this.form;
return factory.createJsxAttribute(
Expand Down Expand Up @@ -112,23 +110,19 @@ export default class FormRenderer extends ReactComponentRenderer<BaseComponentPr
factory.createBlock(
[
factory.createExpressionStatement(
factory.createCallExpression(
factory.createIdentifier(getSetStateName(FieldStateVariable(name))),
undefined,
[
factory.createCallExpression(factory.createIdentifier('onSubmitBefore'), undefined, [
factory.createObjectLiteralExpression(
[
factory.createPropertyAssignment(
factory.createIdentifier('fields'),
factory.createIdentifier(getStateName(FieldStateVariable(name))),
),
],
false,
),
]),
],
),
factory.createCallExpression(factory.createIdentifier('setModelFields'), undefined, [
factory.createCallExpression(factory.createIdentifier('onSubmitBefore'), undefined, [
factory.createObjectLiteralExpression(
[
factory.createPropertyAssignment(
factory.createIdentifier('fields'),
factory.createIdentifier('modelFields'),
),
],
false,
),
]),
]),
),
],
true,
Expand All @@ -148,7 +142,7 @@ export default class FormRenderer extends ReactComponentRenderer<BaseComponentPr
undefined,
[
factory.createNewExpression(factory.createIdentifier(dataTypeName), undefined, [
factory.createIdentifier(getStateName(FieldStateVariable(name))),
factory.createIdentifier('modelFields'),
]),
],
),
Expand Down
59 changes: 3 additions & 56 deletions packages/codegen-ui-react/lib/forms/form-renderer-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ import {
StudioFormActionType,
} from '@aws-amplify/codegen-ui';
import { BindingElement, Expression, factory, NodeFlags, PropertySignature, SyntaxKind } from 'typescript';
import { ImportCollection, ImportSource, ImportValue } from '../imports';
import { ImportCollection, ImportValue } from '../imports';
import { getStateName, getSetStateName } from '../react-component-render-helper';
import { addSchemaToArguments, getActionHookImportValue, getActionIdentifier } from '../workflow';
import { getActionIdentifier } from '../workflow';

export const FormTypeDataStoreMap: Record<StudioFormActionType, string> = {
create: 'Amplify.DataStoreCreateItemAction',
Expand Down Expand Up @@ -77,59 +77,6 @@ export const buildFieldStateStatements = (formName: string, importCollection: Im
),
);
};
/**
*
* @param form StudioForm
* @param importCollection ImportCollection
* @returns ActionStatement
* renders the state variable for datastore and adds imports
*
* ex. for form create
* const myFormonSubmit = useDataStoreCreateAction({
* model: myModel,
* fields: myFormFields,
* schema: schema
* });
*/
export const buildDataStoreActionStatement = (form: StudioForm, importCollection: ImportCollection) => {
const {
dataType: { dataTypeName },
formActionType,
} = form;
const actionHookImportValue = getActionHookImportValue(FormTypeDataStoreMap[formActionType]);
importCollection.addMappedImport(actionHookImportValue);
importCollection.addImport(ImportSource.LOCAL_MODELS, dataTypeName);
const properties = [
// model name
factory.createPropertyAssignment(factory.createIdentifier('model'), factory.createIdentifier(dataTypeName)),
// fields object name
factory.createPropertyAssignment(
factory.createIdentifier('fields'),
factory.createIdentifier(getStateName(FieldStateVariable(form.name))),
),
];
if (formActionType === 'update') {
properties.push(factory.createPropertyAssignment(factory.createIdentifier('id'), factory.createIdentifier('id')));
}
addSchemaToArguments(properties, importCollection);

return factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
factory.createIdentifier(getActionIdentifier(form.name, 'onSubmit')),
undefined,
undefined,
factory.createCallExpression(factory.createIdentifier(actionHookImportValue), undefined, [
factory.createObjectLiteralExpression(properties, false),
]),
),
],
NodeFlags.Const,
),
);
};

export const buildMutationBindings = (form: StudioForm) => {
const {
Expand Down Expand Up @@ -316,7 +263,7 @@ export const buildStateMutationStatement = (name: string, defaultValue: Expressi
);
};

export const buildOnChangeStatement = (fieldName: string, id: string) => {
export const buildOnChangeStatement = (fieldName: string, id?: string) => {
return factory.createJsxAttribute(
factory.createIdentifier('onChange'),
factory.createJsxExpression(
Expand Down
Loading