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

Supported nested fields #1695

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
3 changes: 3 additions & 0 deletions demo/admin/src/products/future/ProductForm.cometGen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export const ProductForm: FormConfig<GQLProduct> = {
label: "Titel", // default is generated from name (camelCaseToHumanReadable)
required: true, // default is inferred from gql schema
},
{ type: "number", name: "packageDimensions.height", label: "Height" },
{ type: "number", name: "packageDimensions.width", label: "Width" },
{ type: "number", name: "packageDimensions.depth", label: "Depth" },
{ type: "text", name: "slug" },
{ type: "text", name: "description", label: "Description", multiline: true },
{ type: "staticSelect", name: "type", label: "Type" /*, values: from gql schema (TODO overridable)*/ },
Expand Down
2 changes: 2 additions & 0 deletions demo/admin/src/products/future/ProductsGrid.cometGen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export const ProductsGrid: GridConfig<GQLProduct> = {
{ type: "text", name: "title", headerName: "Titel", width: 150 },
{ type: "text", name: "description", headerName: "Description", width: 150 },
{ type: "number", name: "price", headerName: "Price", width: 150 },
{ type: "number", name: "packageDimensions.height", headerName: "Height", width: 50 },
{ type: "number", name: "packageDimensions.width", headerName: "Width", width: 50 },
{ type: "staticSelect", name: "type" /*, values: from gql schema (TODO overridable)*/ },
{ type: "date", name: "availableSince" },
{ type: "dateTime", name: "createdAt" },
Expand Down
5 changes: 5 additions & 0 deletions demo/admin/src/products/future/generated/ProductForm.gql.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { gql } from "@apollo/client";
export const productFormFragment = gql`
fragment ProductFormDetails on Product {
title
packageDimensions {
height
width
depth
}
slug
description
type
Expand Down
42 changes: 41 additions & 1 deletion demo/admin/src/products/future/generated/ProductForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ const rootBlocks = {
image: DamImageBlock,
};

type FormValues = Omit<GQLProductFormDetailsFragment, "price"> & {
type FormValues = Omit<GQLProductFormDetailsFragment, "packageDimensions" | "price"> & {
Ben-Ho marked this conversation as resolved.
Show resolved Hide resolved
packageDimensions: { height: string; width: string; depth: string };
price: string;
image: BlockState<typeof rootBlocks.image>;
};
Expand All @@ -72,6 +73,13 @@ export function ProductForm({ id }: FormProps): React.ReactElement {
data?.product
? {
...filter<GQLProductFormDetailsFragment>(productFormFragment, data.product),
packageDimensions: data.product.packageDimensions
? {
height: String(data.product.packageDimensions.height),
width: String(data.product.packageDimensions.width),
depth: String(data.product.packageDimensions.depth),
}
: undefined,
price: String(data.product.price),
image: rootBlocks.image.input2State(data.product.image),
}
Expand All @@ -97,6 +105,11 @@ export function ProductForm({ id }: FormProps): React.ReactElement {
if (await saveConflict.checkForConflicts()) throw new Error("Conflicts detected");
const output = {
...formValues,
packageDimensions: {
height: parseFloat(formValues.packageDimensions.height),
width: parseFloat(formValues.packageDimensions.width),
depth: parseFloat(formValues.packageDimensions.depth),
},
Ben-Ho marked this conversation as resolved.
Show resolved Hide resolved
price: parseFloat(formValues.price),
image: rootBlocks.image.state2Output(formValues.image),
};
Expand Down Expand Up @@ -167,6 +180,33 @@ export function ProductForm({ id }: FormProps): React.ReactElement {
label={<FormattedMessage id="product.title" defaultMessage="Titel" />}
/>

<Field
required
fullWidth
name="packageDimensions.height"
component={FinalFormInput}
type="number"
label={<FormattedMessage id="product.packageDimensions.height" defaultMessage="Height" />}
/>

<Field
required
fullWidth
name="packageDimensions.width"
component={FinalFormInput}
type="number"
label={<FormattedMessage id="product.packageDimensions.width" defaultMessage="Width" />}
/>

<Field
required
fullWidth
name="packageDimensions.depth"
component={FinalFormInput}
type="number"
label={<FormattedMessage id="product.packageDimensions.depth" defaultMessage="Depth" />}
/>

<Field
required
fullWidth
Expand Down
14 changes: 14 additions & 0 deletions demo/admin/src/products/future/generated/ProductsGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,20 @@ export function ProductsGrid(): React.ReactElement {
{ field: "title", headerName: intl.formatMessage({ id: "product.title", defaultMessage: "Titel" }), width: 150 },
{ field: "description", headerName: intl.formatMessage({ id: "product.description", defaultMessage: "Description" }), width: 150 },
{ field: "price", headerName: intl.formatMessage({ id: "product.price", defaultMessage: "Price" }), width: 150 },
{
field: "packageDimensions.height",
headerName: intl.formatMessage({ id: "product.packageDimensions.height", defaultMessage: "Height" }),
filterable: false,
sortable: false,
width: 50,
},
{
field: "packageDimensions.width",
headerName: intl.formatMessage({ id: "product.packageDimensions.width", defaultMessage: "Width" }),
filterable: false,
sortable: false,
width: 50,
},
{
field: "type",
headerName: intl.formatMessage({ id: "product.type", defaultMessage: "Type" }),
Expand Down
2 changes: 2 additions & 0 deletions packages/admin/cms-admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"lodash.isequal": "^4.0.0",
"lodash.set": "^4.3.2",
"mime-db": "^1.0.0",
"object-path": "^0.11.8",
"p-debounce": "^4.0.0",
"pluralize": "^8.0.0",
"prop-types": "^15.7.2",
Expand Down Expand Up @@ -108,6 +109,7 @@
"@types/lodash.set": "^4.3.6",
"@types/mime-db": "^1.43.1",
"@types/node": "^18.0.0",
"@types/object-path": "^0.11.4",
"@types/pluralize": "^0.0.29",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
Expand Down
58 changes: 13 additions & 45 deletions packages/admin/cms-admin/src/generator/future/generateForm.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { IntrospectionQuery } from "graphql";

import { generateFormField } from "./generateFormField";
import { FormConfig, GeneratorReturn } from "./generator";
import { FormConfigInternal, GeneratorReturn } from "./generator";
import { camelCaseToHumanReadable } from "./utils/camelCaseToHumanReadable";
import { findRootBlocks } from "./utils/findRootBlocks";
import { generateFieldListGqlString } from "./utils/generateFieldList";
import { generateFormValuesTypeDefinition } from "./utils/generateFormValuesTypeDefinition";
import { generateImportsCode, Imports } from "./utils/generateImportsCode";
import { generateInitialValuesValue } from "./utils/generateInitialValuesValue";
import { generateOutputObject } from "./utils/generateOutputObject";

export function generateForm(
{
Expand All @@ -13,26 +17,23 @@ export function generateForm(
targetDirectory,
gqlIntrospection,
}: { exportName: string; baseOutputFilename: string; targetDirectory: string; gqlIntrospection: IntrospectionQuery },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: FormConfig<any>,
config: FormConfigInternal,
): GeneratorReturn {
const gqlType = config.gqlType;
const title = config.title ?? camelCaseToHumanReadable(gqlType);
const instanceGqlType = gqlType[0].toLowerCase() + gqlType.substring(1);
const gqlDocuments: Record<string, string> = {};
const imports: Imports = [];

const fieldNamesFromConfig: string[] = config.fields.map((field) => field.name);
const fieldList = generateFieldListGqlString(fieldNamesFromConfig);

// TODO make RootBlocks configurable (from config)
const rootBlocks = findRootBlocks({ gqlType, targetDirectory }, gqlIntrospection);

const numberFields = config.fields.filter((field) => field.type == "number");
const booleanFields = config.fields.filter((field) => field.type == "boolean");

const fragmentName = config.fragmentName ?? `${gqlType}Form`;
gqlDocuments[`${instanceGqlType}FormFragment`] = `
fragment ${fragmentName} on ${gqlType} {
${config.fields.map((field) => field.name).join("\n")}
}
fragment ${fragmentName} on ${gqlType} { ${fieldList} }
`;

gqlDocuments[`${instanceGqlType}Query`] = `
Expand Down Expand Up @@ -138,20 +139,7 @@ export function generateForm(
: ""
}

type FormValues = ${
numberFields.length > 0
? `Omit<GQL${fragmentName}Fragment, ${numberFields.map((field) => `"${String(field.name)}"`).join(" | ")}>`
: `GQL${fragmentName}Fragment`
} ${
numberFields.length > 0 || Object.keys(rootBlocks).length > 0
? `& {
${numberFields.map((field) => `${String(field.name)}: string;`).join("\n")}
${Object.keys(rootBlocks)
.map((rootBlockKey) => `${rootBlockKey}: BlockState<typeof rootBlocks.${rootBlockKey}>;`)
.join("\n")}
}`
: ""
};
type FormValues = ${generateFormValuesTypeDefinition({ fragmentName, rootBlocks, config })};

interface FormProps {
id?: string;
Expand All @@ -169,21 +157,7 @@ export function generateForm(
id ? { variables: { id } } : { skip: true },
);

const initialValues = React.useMemo<Partial<FormValues>>(() => data?.${instanceGqlType}
? {
...filter<GQL${fragmentName}Fragment>(${instanceGqlType}FormFragment, data.${instanceGqlType}),
${numberFields.map((field) => `${String(field.name)}: String(data.${instanceGqlType}.${String(field.name)}),`).join("\n")}
${Object.keys(rootBlocks)
.map((rootBlockKey) => `${rootBlockKey}: rootBlocks.${rootBlockKey}.input2State(data.${instanceGqlType}.${rootBlockKey}),`)
.join("\n")}
}
: {
${booleanFields.map((field) => `${String(field.name)}: false,`).join("\n")}
${Object.keys(rootBlocks)
.map((rootBlockKey) => `${rootBlockKey}: rootBlocks.${rootBlockKey}.defaultValues(),`)
.join("\n")}
}
, [data]);
const initialValues = ${generateInitialValuesValue({ config, fragmentName, rootBlocks, instanceGqlType })};

const saveConflict = useFormSaveConflict({
checkConflict: async () => {
Expand All @@ -198,13 +172,7 @@ export function generateForm(

const handleSubmit = async (formValues: FormValues, form: FormApi<FormValues>, event: FinalFormSubmitEvent) => {
if (await saveConflict.checkForConflicts()) throw new Error("Conflicts detected");
const output = {
...formValues,
${numberFields.map((field) => `${String(field.name)}: parseFloat(formValues.${String(field.name)}),`).join("\n")}
${Object.keys(rootBlocks)
.map((rootBlockKey) => `${rootBlockKey}: rootBlocks.${rootBlockKey}.state2Output(formValues.${rootBlockKey}),`)
.join("\n")}
};
const output = ${generateOutputObject({ rootBlocks, config })};
if (mode === "edit") {
if (!id) throw new Error();
await client.mutate<GQLUpdate${gqlType}Mutation, GQLUpdate${gqlType}MutationVariables>({
Expand Down
25 changes: 13 additions & 12 deletions packages/admin/cms-admin/src/generator/future/generateFormField.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
import { IntrospectionEnumType, IntrospectionNamedTypeRef, IntrospectionObjectType, IntrospectionQuery } from "graphql";
import { IntrospectionEnumType, IntrospectionNamedTypeRef, IntrospectionQuery } from "graphql";

import { FormConfig, FormFieldConfig, GeneratorReturn } from "./generator";
import { FormConfigInternal, FormFieldConfigInternal, GeneratorReturn } from "./generator";
import { camelCaseToHumanReadable } from "./utils/camelCaseToHumanReadable";
import { generateFieldListFromIntrospection } from "./utils/generateFieldList";
import { Imports } from "./utils/generateImportsCode";

export function generateFormField(
{ gqlIntrospection }: { gqlIntrospection: IntrospectionQuery },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: FormFieldConfig<any>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
formConfig: FormConfig<any>,
config: FormFieldConfigInternal,
formConfig: FormConfigInternal,
): GeneratorReturn & { imports: Imports } {
const gqlType = formConfig.gqlType;
const instanceGqlType = gqlType[0].toLowerCase() + gqlType.substring(1);

const name = String(config.name);
const label = config.label ?? camelCaseToHumanReadable(name);

const introspectionObject = gqlIntrospection.__schema.types.find((type) => type.kind === "OBJECT" && type.name === gqlType) as
| IntrospectionObjectType
| undefined;
if (!introspectionObject) throw new Error(`didn't find object ${gqlType} in gql introspection`);
const introspectedTypes = gqlIntrospection.__schema.types;
const introspectionObject = introspectedTypes.find((type) => type.kind === "OBJECT" && type.name === gqlType);
if (!introspectionObject || introspectionObject.kind !== "OBJECT") throw new Error(`didn't find object ${gqlType} in gql introspection`);

const introspectionField = introspectionObject.fields.find((field) => field.name === name);
if (!introspectionField) throw new Error(`didn't find field ${name} in gql introspection type ${gqlType}`);
const introspectedFields = generateFieldListFromIntrospection(gqlIntrospection, gqlType);

const introspectionFieldWithPath = introspectedFields.find((field) => field.path === name);
if (!introspectionFieldWithPath) throw new Error(`didn't find field ${name} in gql introspection type ${gqlType}`);
const introspectionField = introspectionFieldWithPath.field;
const introspectionFieldType = introspectionField.type.kind === "NON_NULL" ? introspectionField.type.ofType : introspectionField.type;

const requiredByIntrospection = introspectionField.type.kind == "NON_NULL";
Expand Down
5 changes: 2 additions & 3 deletions packages/admin/cms-admin/src/generator/future/generateGrid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from "graphql";
import { plural } from "pluralize";

import { GeneratorReturn, GridConfig } from "./generator";
import { GeneratorReturn, GridConfigInternal } from "./generator";
import { camelCaseToHumanReadable } from "./utils/camelCaseToHumanReadable";
import { findRootBlocks } from "./utils/findRootBlocks";

Expand Down Expand Up @@ -62,8 +62,7 @@ export function generateGrid(
targetDirectory,
gqlIntrospection,
}: { exportName: string; baseOutputFilename: string; targetDirectory: string; gqlIntrospection: IntrospectionQuery },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: GridConfig<any>,
config: GridConfigInternal,
): GeneratorReturn {
const gqlType = config.gqlType;
const gqlTypePlural = plural(gqlType);
Expand Down
32 changes: 23 additions & 9 deletions packages/admin/cms-admin/src/generator/future/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import { basename, dirname } from "path";

import { generateForm } from "./generateForm";
import { generateGrid } from "./generateGrid";
import { Leaves, Paths } from "./utils/deepKeyOf";
import { writeGenerated } from "./utils/writeGenerated";

type BlockReference = {
name: string;
import: string;
};

export type FormFieldConfig<T> = (
export type GeneratorEntity = { __typename?: string };

export type FormFieldConfigInternal = (
| { type: "text"; multiline?: boolean }
| { type: "number" }
| { type: "boolean" }
Expand All @@ -22,31 +25,42 @@ export type FormFieldConfig<T> = (
| { type: "staticSelect"; values?: string[] }
| { type: "asyncSelect"; values?: string[] }
| { type: "block"; block: BlockReference }
) & { name: keyof T; label?: string; required?: boolean };
) & { name: string; label?: string; required?: boolean };
export type FormFieldConfig<T extends GeneratorEntity> = FormFieldConfigInternal & { name: Leaves<T> | Paths<T> };

export type FormConfig<T extends { __typename?: string }> = {
export type FormConfigInternal = {
type: "form";
gqlType: T["__typename"];
gqlType: string;
fragmentName?: string;
fields: FormFieldConfig<T>[];
title?: string;
fields: FormFieldConfigInternal[];
};
export type FormConfig<T extends GeneratorEntity> = FormConfigInternal & {
gqlType: T["__typename"];
fields: FormFieldConfig<T>[];
};

export type TabsConfig = { type: "tabs"; tabs: { name: string; content: GeneratorConfig }[] };

export type GridColumnConfig<T> = (
export type GridColumnConfigInternal = (
| { type: "text" }
| { type: "number" }
| { type: "boolean" }
| { type: "date" }
| { type: "dateTime" }
| { type: "staticSelect"; values?: string[] }
| { type: "block"; block: BlockReference }
) & { name: keyof T; headerName?: string; width?: number };
export type GridConfig<T extends { __typename?: string }> = {
) & { name: string; headerName?: string; width?: number };
export type GridColumnConfig<T extends GeneratorEntity> = GridColumnConfigInternal & { name: Leaves<T> | Paths<T> };
Ben-Ho marked this conversation as resolved.
Show resolved Hide resolved

export type GridConfigInternal = {
type: "grid";
gqlType: T["__typename"];
gqlType: string;
fragmentName?: string;
columns: GridColumnConfigInternal[];
};
export type GridConfig<T extends GeneratorEntity> = GridConfigInternal & {
Ben-Ho marked this conversation as resolved.
Show resolved Hide resolved
gqlType: T["__typename"];
columns: GridColumnConfig<T>[];
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export type FieldsObjectType = { [key: string]: FieldsObjectType | string };
export function convertObjectToStructuredString(obj: FieldsObjectType) {
let ret = "";
let prefixField = "";
for (const key in obj) {
const valueForKey = obj[key];
if (typeof valueForKey === "string") {
ret += `${prefixField}${key}${valueForKey}`;
} else {
ret += `${prefixField}${key}: { ${convertObjectToStructuredString(valueForKey)} }`;
}
prefixField = " ";
Ben-Ho marked this conversation as resolved.
Show resolved Hide resolved
}
return ret;
}
Loading
Loading