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

use a single select when using related models in AutoForm #686

Draft
wants to merge 1 commit 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
use a single select when using related models in AutoForm
  • Loading branch information
infiton committed Oct 21, 2024
commit f6b1b4ac3bf2db642dcfb0c43648af55ee9f6139
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@ describeForEachAutoAdapter("AutoForm - FindBy object parameters", ({ name, adapt
mainModel: {
childModelEntries: null,
nonUniqueString: "example",
uniqueBelongsTo: {},
uniqueBelongsTo: {
update: {
id: "22",
parentUniqueString: "parent-example",
},
},
uniqueEmail: "u2@email.com",
uniqueString: "u2",
},
Expand Down Expand Up @@ -411,6 +416,11 @@ const mainModelQueryDefaultValuesResponse = {
nonUniqueString: "example",
uniqueEmail: "u2@email.com",
uniqueString: "u2",
uniqueBelongsTo: {
__typename: "UniqueFieldsParentModel",
id: "22",
parentUniqueString: "parent-example",
},
updatedAt: "2024-10-01T20:58:39.300Z",
},
__typename: "UniqueFieldsMainModelEdge",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describeForEachAutoAdapter("AutoForm - HasManyThrough fields", ({ name, adapter:
it("does not render the hasMany->joinModel input field", () => {
interceptModelActionMetadataRequest();

cy.mountWithWrapper(<AutoForm action={api.widget.create} />, wrapper);
cy.mountWithWrapper(<AutoForm action={api.hasManyThrough.baseModel.create} />, wrapper);
cy.wait("@ModelActionMetadata");

// Name field input is shown
Expand Down Expand Up @@ -149,6 +149,32 @@ const modelActionMetadataResponse = {
},
__typename: "GadgetModel",
},
{
key: "tJDsf_FvYqsi",
apiIdentifier: "joinerModel",
namespace: ["hasManyThrough"],
defaultDisplayField: {
name: "Id",
apiIdentifier: "id",
fieldType: "ID",
__typename: "GadgetModelField",
},
fields: [],
__typename: "GadgetModel",
},
{
key: "Oss4sCDW-DJU",
apiIdentifier: "siblingModel",
namespace: ["hasManyThrough"],
defaultDisplayField: {
name: "Id",
apiIdentifier: "id",
fieldType: "ID",
__typename: "GadgetModelField",
},
fields: [],
__typename: "GadgetModel",
},
],
model: {
name: "Base model",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ describeForEachAutoAdapter("AutoForm - Upsert Action", ({ name, adapter: { AutoF
cy.contains("Record Not Found Error: Gadget API returned no data at widget").should("exist");
});

it("Can properly submit with custom form contents", () => {
it.only("Can properly submit with custom form contents", () => {
mockSuccessfulWidgetFindBy();
mockSuccessfulUpsert();

Expand Down
1 change: 1 addition & 0 deletions packages/react/cypress/support/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ before(() => {

beforeEach(() => {
cy.window().then((win) => {
if (!win) return;
const mockToasts = win.document.getElementsByClassName("mock-toast");
while (mockToasts.length > 0) {
try {
Expand Down
14 changes: 7 additions & 7 deletions packages/react/spec/auto/PolarisAutoForm.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -719,12 +719,6 @@ function loadMockGizmoCreateMetadata() {
}

function loadMockWidgetCreateMetadata(opts?: { inputFields?: any[]; triggers?: any[] }) {
expect(mockUrqlClient.executeQuery.mock.calls[0][0].variables).toEqual({
modelApiIdentifier: "widget",
modelNamespace: null,
action: "create",
});

mockUrqlClient.executeQuery.pushResponse("ModelActionMetadata", {
stale: false,
hasNext: false,
Expand All @@ -738,6 +732,12 @@ function loadMockWidgetCreateMetadata(opts?: { inputFields?: any[]; triggers?: a
opts?.triggers
),
});

expect(mockUrqlClient.executeQuery.mock.calls[0][0].variables).toEqual({
modelApiIdentifier: "widget",
modelNamespace: null,
action: "create",
});
}

function loadMockWidgetUpdateMetadata() {
Expand All @@ -747,8 +747,8 @@ function loadMockWidgetUpdateMetadata() {

function loadMockWidgetUpdateMetadataWithFindBy() {
mockWidgetUpdateHelperFunctions.expectMetadataRequest();
mockWidgetUpdateHelperFunctions.mockFindByResponse();
mockWidgetUpdateHelperFunctions.mockMetadataResponse();
mockWidgetUpdateHelperFunctions.mockFindByResponse();
}

const mockWidgetUpdateHelperFunctions = {
Expand Down
40 changes: 20 additions & 20 deletions packages/react/spec/auto/inputs/PolarisAutoTextInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,26 @@ const metadata = {
};

const mockFindBy = () => {
const updateMetadata = { ...metadata, action: { ...metadata.action, apiIdentifier: "update", operatesWithRecordIdentity: true } };
mockUrqlClient.executeQuery.pushResponse("ModelActionMetadata", {
stale: false,
hasNext: false,
data: {
gadgetMeta: {
modelAndRelatedModels: [
{
name: "Widget",
apiIdentifier: "widget",
fields: updateMetadata.action.inputFields,
__typename: "GadgetModel",
},
],
model: updateMetadata,
__typename: "GadgetApplicationMeta",
},
},
});

mockUrqlClient.executeQuery.pushResponse("widget", {
stale: false,
hasNext: false,
Expand Down Expand Up @@ -361,24 +381,4 @@ const mockFindBy = () => {
},
},
});

const updateMetadata = { ...metadata, action: { ...metadata.action, apiIdentifier: "update", operatesWithRecordIdentity: true } };
mockUrqlClient.executeQuery.pushResponse("ModelActionMetadata", {
stale: false,
hasNext: false,
data: {
gadgetMeta: {
modelAndRelatedModels: [
{
name: "Widget",
apiIdentifier: "widget",
fields: updateMetadata.action.inputFields,
__typename: "GadgetModel",
},
],
model: updateMetadata,
__typename: "GadgetApplicationMeta",
},
},
});
};
8 changes: 4 additions & 4 deletions packages/react/spec/auto/support/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,16 @@ export const mockWidgetFindBy = (
action: Parameters<typeof getWidgetModelMetadata>[0],
overridesRecord?: Parameters<typeof getWidgetRecord>[0]
) => {
mockUrqlClient.executeQuery.pushResponse("widget", {
mockUrqlClient.executeQuery.pushResponse("ModelActionMetadata", {
stale: false,
hasNext: false,
data: getWidgetRecord(overridesRecord),
data: getWidgetModelMetadata(action),
});

mockUrqlClient.executeQuery.pushResponse("ModelActionMetadata", {
mockUrqlClient.executeQuery.pushResponse("widget", {
stale: false,
hasNext: false,
data: getWidgetModelMetadata(action),
data: getWidgetRecord(overridesRecord),
});
};

Expand Down
86 changes: 75 additions & 11 deletions packages/react/src/auto/AutoForm.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { ActionFunction, GadgetRecord, GlobalActionFunction } from "@gadgetinc/api-client-core";
import type { ActionFunction, FieldSelection, GadgetRecord, GlobalActionFunction } from "@gadgetinc/api-client-core";
import { yupResolver } from "@hookform/resolvers/yup";
import type { ReactNode } from "react";
import { useEffect, useMemo, useRef } from "react";
import React, { useEffect, useMemo, useRef } from "react";
import type { AnyActionWithId, RecordIdentifier, UseActionFormHookStateData } from "src/use-action-form/types.js";
import type { GadgetObjectFieldConfig } from "../internal/gql/graphql.js";
import type { FieldMetadata, GlobalActionMetadata, ModelWithOneActionMetadata } from "../metadata.js";
import { FieldType, filterAutoFormFieldList, isModelActionMetadata, useActionMetadata } from "../metadata.js";
import { FieldType, buildAutoFormFieldList, isModelActionMetadata, useActionMetadata } from "../metadata.js";
import { pathListToSelection } from "../use-table/helpers.js";
import type { FieldErrors, FieldValues } from "../useActionForm.js";
import { useActionForm } from "../useActionForm.js";
import { get, getFlattenedObjectKeys, type OptionsType } from "../utils.js";
Expand All @@ -16,6 +17,7 @@ import {
validateTriggersFromApiClient,
validateTriggersFromMetadata,
} from "./AutoFormActionValidators.js";
import { isAutoInput } from "./AutoInput.js";

/** The props that any <AutoForm/> component accepts */
export type AutoFormProps<
Expand Down Expand Up @@ -89,22 +91,22 @@ export const useFormFields = (
: [];
const nonObjectFields = action.inputFields.filter((field) => field.configuration.__typename !== "GadgetObjectFieldConfig");

const includedRootLevelFields = filterAutoFormFieldList(nonObjectFields, options as any).map(
(field) =>
const includedRootLevelFields = buildAutoFormFieldList(nonObjectFields, options as any).map(
([path, field]) =>
({
path: field.apiIdentifier,
path,
metadata: field,
} as const)
);

const includedObjectFields = objectFields.flatMap((objectField) =>
filterAutoFormFieldList((objectField.configuration as unknown as GadgetObjectFieldConfig).fields as any, {
buildAutoFormFieldList((objectField.configuration as unknown as GadgetObjectFieldConfig).fields as any, {
...(options as any),
isUpsertAction: true, // For upsert meta-actions, we allow IDs, and they are object fields instead of root level
}).map(
(innerField) =>
([innerPath, innerField]) =>
({
path: `${objectField.apiIdentifier}.${innerField.apiIdentifier}`,
path: `${objectField.apiIdentifier}.${innerPath}`,
metadata: innerField,
} as const)
)
Expand All @@ -120,6 +122,19 @@ export const useFormFields = (
}, [metadata, options]);
};

export const useFormSelection = (
modelApiIdentifier: string | undefined,
fields: readonly { path: string; metadata: FieldMetadata }[]
): FieldSelection | undefined => {
if (!modelApiIdentifier) return;
if (!fields.length) return;

const paths = fields.map((f) => f.path.replace(new RegExp(`^${modelApiIdentifier}\\.`), ""));
const fieldMetaData = fields.map((f) => f.metadata);

return pathListToSelection(paths, fieldMetaData);
};

const validateFormFieldApiIdentifierUniqueness = (actionApiIdentifier: string, inputApiIdentifiers: string[]) => {
const seen = new Set<string>();

Expand All @@ -142,7 +157,15 @@ export const useAutoForm = <
>(
props: AutoFormProps<GivenOptions, SchemaT, ActionFunc, any, any> & { findBy?: any }
) => {
const { action, record, onSuccess, onFailure, findBy } = props;
const { action, record, onSuccess, onFailure, findBy, children } = props;

let include = props.include;
let exclude = props.exclude;

if (children) {
include = extractPathsFromChildren(children);
exclude = undefined;
}

validateNonBulkAction(action);
validateTriggersFromApiClient(action);
Expand All @@ -152,12 +175,13 @@ export const useAutoForm = <
validateTriggersFromMetadata(metadata);

// filter down the fields to render only what we want to render for this form
const fields = useFormFields(metadata, props);
const fields = useFormFields(metadata, { include, exclude });
validateFindByObjectWithMetadata(fields, findBy);
const isDeleteAction = metadata && isModelActionMetadata(metadata) && metadata.action.isDeleteAction;
const isGlobalAction = action.type === "globalAction";
const operatesWithRecordId = !!(metadata && isModelActionMetadata(metadata) && metadata.action.operatesWithRecordIdentity);
const modelApiIdentifier = action.type == "action" ? action.modelApiIdentifier : undefined;
const selection = useFormSelection(modelApiIdentifier, fields);
const isUpsertMetaAction =
metadata && isModelActionMetadata(metadata) && fields.some((field) => field.metadata.fieldType === FieldType.Id);
const isUpsertWithFindBy = isUpsertMetaAction && !!findBy;
Expand Down Expand Up @@ -201,6 +225,8 @@ export const useAutoForm = <
defaultValues: defaultValues as any,
findBy: "findBy" in props ? props.findBy : undefined,
throwOnInvalidFindByObject: false,
pause: "findBy" in props ? fetchingMetadata : undefined,
select: selection as any,
resolver: useValidationResolver(metadata, fieldPathsToValidate),
send: () => {
const fieldsToSend = fields
Expand Down Expand Up @@ -282,6 +308,44 @@ export const useAutoForm = <
};
};

const extractPathsFromChildren = (children: React.ReactNode) => {
const paths = new Set<string>();

React.Children.forEach(children, (child) => {
if (React.isValidElement(child)) {
const grandChildren = child.props.children as React.ReactNode | undefined;
let childPaths: string[] = [];

if (grandChildren) {
childPaths = extractPathsFromChildren(grandChildren);
}

let field: string | undefined = undefined;

if (isAutoInput(child)) {
const props = child.props as { field: string; selectPaths?: string[]; children?: React.ReactNode };
field = props.field;

paths.add(field);

if (props.selectPaths && Array.isArray(props.selectPaths)) {
props.selectPaths.forEach((selectPath) => {
paths.add(`${field}.${selectPath}`);
});
}
}

if (childPaths.length > 0) {
for (const childPath of childPaths) {
paths.add(field ? `${field}.${childPath}` : childPath);
}
}
}
});

return Array.from(paths);
};

const removeIdFieldsUnlessUpsertWithoutFindBy = (isUpsertWithFindBy?: boolean) => {
return (field: { metadata: FieldMetadata }) => {
return field.metadata.fieldType === FieldType.Id ? !isUpsertWithFindBy : true;
Expand Down
Loading
Loading