import React, { MutableRefObject, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { CMSAnalyticsEvent, Entity, EntityAction, EntityCollection, EntityStatus, EntityValues, FormContext, PluginFormActionProps, PropertyFieldBindingProps, ResolvedEntityCollection } from "../types"; import { Formex, FormexController, getIn, setIn, useCreateFormex } from "@firecms/formex"; import { PropertyFieldBinding } from "./PropertyFieldBinding"; import { CustomFieldValidator, getYupEntitySchema } from "./validation"; import equal from "react-fast-compare" import { canCreateEntity, canDeleteEntity, getDefaultValuesFor, getEntityTitlePropertyKey, getValueInPath, isHidden, isReadOnly, resolveCollection } from "../util"; import { useAuthController, useCustomizationController, useDataSource, useFireCMSContext, useSideEntityController } from "../hooks"; import { ErrorFocus } from "./components/ErrorFocus"; import { CustomIdField } from "./components/CustomIdField"; import { Alert, Button, cn, DialogActions, IconButton, Tooltip, Typography } from "@firecms/ui"; import { ErrorBoundary } from "../components"; import { copyEntityAction, deleteEntityAction } from "../components/common/default_entity_actions"; import { useAnalyticsController } from "../hooks/useAnalyticsController"; import { ValidationError } from "yup"; import { PropertyIdCopyTooltipContent } from "../components/PropertyIdCopyTooltipContent"; /** * @group Components */ export interface EntityFormProps> { /** * New or existing status */ status: EntityStatus; /** * Path of the collection this entity is located */ path: string; /** * The collection is used to build the fields of the form */ collection: EntityCollection /** * The updated entity is passed from the parent component when the underlying data * has changed in the datasource */ entity?: Entity; /** * The callback function called when Save is clicked and validation is correct */ onEntitySaveRequested: ( props: EntityFormSaveParams ) => Promise; /** * The callback function called when discard is clicked */ onDiscard?: () => void; /** * The callback function when the form is dirty, so the values are different * from the original ones */ onModified?: (dirty: boolean) => void; /** * The callback function when the form original values have been modified */ onValuesChanged?: (values?: EntityValues) => void; /** * * @param id */ onIdChange?: (id: string) => void; currentEntityId?: string; onFormContextChange?: (formContext: FormContext) => void; hideId?: boolean; autoSave?: boolean; onIdUpdateError?: (error: any) => void; } export type EntityFormSaveParams> = { collection: ResolvedEntityCollection, path: string, entityId: string | undefined, values: EntityValues, previousValues?: EntityValues, closeAfterSave: boolean, autoSave: boolean }; /** * This is the form used internally by the CMS * @param status * @param path * @param collection * @param entity * @param onEntitySave * @param onDiscard * @param onModified * @param onValuesChanged * @constructor * @group Components */ export const EntityForm = EntityFormInternal; // export const EntityForm = React.memo>(EntityFormInternal, // (a: EntityFormProps, b: EntityFormProps) => { // return a.status === b.status && // a.path === b.path && // equal(a.entity?.values, b.entity?.values); // }) as typeof EntityFormInternal; function getDataSourceEntityValues(initialResolvedCollection: ResolvedEntityCollection, status: "new" | "existing" | "copy", entity: Entity | undefined): Partial> { const properties = initialResolvedCollection.properties; if ((status === "existing" || status === "copy") && entity) { return entity.values ?? getDefaultValuesFor(properties); } else if (status === "new") { return getDefaultValuesFor(properties); } else { console.error({ status, entity }); throw new Error("Form has not been initialised with the correct parameters"); } } function EntityFormInternal>({ status, path, collection: inputCollection, entity, onEntitySaveRequested, onDiscard, onModified, onValuesChanged, onIdChange, onFormContextChange, hideId, autoSave, onIdUpdateError, }: EntityFormProps) { const analyticsController = useAnalyticsController(); const customizationController = useCustomizationController(); const context = useFireCMSContext(); const dataSource = useDataSource(inputCollection); const plugins = customizationController.plugins; const initialResolvedCollection = useMemo(() => resolveCollection({ collection: inputCollection, path, values: entity?.values, fields: customizationController.propertyConfigs }), [entity?.values, path, customizationController.propertyConfigs]); const mustSetCustomId: boolean = (status === "new" || status === "copy") && (Boolean(initialResolvedCollection.customId) && initialResolvedCollection.customId !== "optional"); const initialEntityId = useMemo(() => { if (status === "new" || status === "copy") { if (mustSetCustomId) { return undefined; } else { return dataSource.generateEntityId(path); } } else { return entity?.id; } }, []); const closeAfterSaveRef = useRef(false); const baseDataSourceValuesRef = useRef>>(getDataSourceEntityValues(initialResolvedCollection, status, entity)); const [entityId, setEntityId] = React.useState(initialEntityId); const [entityIdError, setEntityIdError] = React.useState(false); const [savingError, setSavingError] = React.useState(); const [customIdLoading, setCustomIdLoading] = React.useState(false); // const initialValuesRef = useRef>(entity?.values ?? baseDataSourceValues as EntityValues); const [internalValues, setInternalValues] = useState | undefined>(entity?.values ?? baseDataSourceValuesRef.current as EntityValues); const save = (values: EntityValues): Promise => { return onEntitySaveRequested({ collection: resolvedCollection, path, entityId, values, previousValues: entity?.values, closeAfterSave: closeAfterSaveRef.current, autoSave: autoSave ?? false }).then(_ => { const eventName: CMSAnalyticsEvent = status === "new" ? "new_entity_saved" : (status === "copy" ? "entity_copied" : (status === "existing" ? "entity_edited" : "unmapped_event")); analyticsController.onAnalyticsEvent?.(eventName, { path }); }).catch(e => { console.error(e); setSavingError(e); }).finally(() => { closeAfterSaveRef.current = false; }); }; const onSubmit = (values: EntityValues, formexController: FormexController>) => { if (mustSetCustomId && !entityId) { console.error("Missing custom Id"); setEntityIdError(true); formexController.setSubmitting(false); return; } setSavingError(undefined); setEntityIdError(false); if (status === "existing") { if (!entity?.id) throw Error("Form misconfiguration when saving, no id for existing entity"); } else if (status === "new" || status === "copy") { if (inputCollection.customId) { if (inputCollection.customId !== "optional" && !entityId) { throw Error("Form misconfiguration when saving, entityId should be set"); } } } else { throw Error("New FormType added, check EntityForm"); } return save(values) ?.then(_ => { formexController.resetForm({ values, submitCount: 0, touched: {} }); }) .finally(() => { formexController.setSubmitting(false); }); }; const formex: FormexController = useCreateFormex({ initialValues: baseDataSourceValuesRef.current as M, onSubmit, validation: (values) => { return validationSchema?.validate(values, { abortEarly: false }) .then(() => { return {}; }) .catch((e) => { const errors: Record = {}; e.inner.forEach((error: any) => { errors[error.path] = error.message; }); return yupToFormErrors(e); }); } }); useEffect(() => { baseDataSourceValuesRef.current = getDataSourceEntityValues(initialResolvedCollection, status, entity); const initialValues = formex.initialValues; if (!formex.isSubmitting && initialValues && status === "existing") { setUnderlyingChanges( Object.entries(resolvedCollection.properties) .map(([key, property]) => { if (isHidden(property)) { return {}; } const initialValue = initialValues[key]; const latestValue = baseDataSourceValuesRef.current[key]; if (!equal(initialValue, latestValue)) { return { [key]: latestValue }; } return {}; }) .reduce((a, b) => ({ ...a, ...b }), {}) as Partial> ); } else { setUnderlyingChanges({}); } }, [entity, initialResolvedCollection, status]); const doOnValuesChanges = (values?: EntityValues) => { const initialValues = formex.initialValues; setInternalValues(values); if (onValuesChanged) onValuesChanged(values); if (autoSave && values && !equal(values, initialValues)) { save(values); } }; useEffect(() => { if (entityId && onIdChange) onIdChange(entityId); }, [entityId, onIdChange]); const resolvedCollection = resolveCollection({ collection: inputCollection, path, entityId, values: internalValues, previousValues: formex.initialValues, fields: customizationController.propertyConfigs }); const titlePropertyKey = getEntityTitlePropertyKey(resolvedCollection, customizationController.propertyConfigs); const title = internalValues && titlePropertyKey ? getValueInPath(internalValues, titlePropertyKey) : undefined; const onIdUpdate = inputCollection.callbacks?.onIdUpdate; const doOnIdUpdate = useCallback(async () => { if (onIdUpdate && internalValues && (status === "new" || status === "copy")) { setCustomIdLoading(true); try { const updatedId = await onIdUpdate({ collection: resolvedCollection, path, entityId, values: internalValues, context }); setEntityId(updatedId); } catch (e) { onIdUpdateError && onIdUpdateError(e); console.error(e); } setCustomIdLoading(false); } }, [entityId, internalValues, status]); useEffect(() => { doOnIdUpdate(); }, [doOnIdUpdate]); const [underlyingChanges, setUnderlyingChanges] = useState>>({}); const uniqueFieldValidator: CustomFieldValidator = useCallback(({ name, value, property }) => dataSource.checkUniqueField(path, name, value, entityId), [dataSource, path, entityId]); const validationSchema = useMemo(() => entityId ? getYupEntitySchema( entityId, resolvedCollection.properties, uniqueFieldValidator) : undefined, [entityId, resolvedCollection.properties, uniqueFieldValidator]); const authController = useAuthController(); const getActionsForEntity = useCallback(({ entity, customEntityActions }: { entity?: Entity, customEntityActions?: EntityAction[] }): EntityAction[] => { const createEnabled = canCreateEntity(inputCollection, authController, path, null); const deleteEnabled = entity ? canDeleteEntity(inputCollection, authController, path, entity) : true; const actions: EntityAction[] = []; if (createEnabled) actions.push(copyEntityAction); if (deleteEnabled) actions.push(deleteEntityAction); if (customEntityActions) actions.push(...customEntityActions); return actions; }, [authController, inputCollection, path]); const pluginActions: React.ReactNode[] = []; const formContext: FormContext = { // @ts-ignore setFieldValue: useCallback(formex.setFieldValue, []), values: formex.values, collection: resolvedCollection, entityId, path, save }; const submittedFormContext = useRef | null>(null); // eslint-disable-next-line react-hooks/rules-of-hooks useEffect(() => { if (onFormContextChange && !formContextsEqual(submittedFormContext.current ?? undefined, formContext)) { onFormContextChange(formContext); submittedFormContext.current = formContext; } }, [formContext, onFormContextChange]); if (plugins && inputCollection) { const actionProps: PluginFormActionProps = { entityId, path, status, collection: inputCollection, context, currentEntityId: entityId, formContext }; pluginActions.push(...plugins.map((plugin, i) => ( plugin.form?.Actions ? : null )).filter(Boolean)); } return
{pluginActions.length > 0 &&
{pluginActions}
}
{title ?? inputCollection.singularName ?? inputCollection.name} {path}/{entityId}
{!hideId && } {entityId && }
} function InnerForm>(props: FormexController & { initialValues: EntityValues, onModified: ((modified: boolean) => void) | undefined, onValuesChanged?: (changedValues?: EntityValues) => void, underlyingChanges: Partial, entity: Entity | undefined, resolvedCollection: ResolvedEntityCollection, formContext: FormContext, onDiscard?: () => void, status: "new" | "existing" | "copy", savingError?: Error, closeAfterSaveRef: MutableRefObject, autoSave?: boolean, entityActions: EntityAction[], }) { const { values, onDiscard, onModified, onValuesChanged, underlyingChanges, formContext, entity, touched, setFieldValue, resolvedCollection, isSubmitting, status, handleSubmit, resetForm, savingError, dirty, closeAfterSaveRef, autoSave, entityActions, } = props; const context = useFireCMSContext(); const formActions = entityActions.filter(a => a.includeInForm === undefined || a.includeInForm); const sideEntityController = useSideEntityController(); const modified = dirty; useEffect(() => { if (onModified) onModified(modified); if (onValuesChanged) onValuesChanged(values); }, [modified, values]); useEffect(() => { if (!autoSave && !isSubmitting && underlyingChanges && entity) { // we update the form fields from the Firestore data // if they were not touched Object.entries(underlyingChanges).forEach(([key, value]) => { const formValue = values[key]; if (!equal(value, formValue) && !touched[key]) { console.debug("Updated value from the datasource:", key, value); setFieldValue(key, value !== undefined ? value : null); } }); } }, [isSubmitting, autoSave, underlyingChanges, entity, values, touched, setFieldValue]); const formFields = (
{(resolvedCollection.propertiesOrder ?? Object.keys(resolvedCollection.properties)) .map((key) => { const property = resolvedCollection.properties[key]; if (!property) { console.warn(`Property ${key} not found in collection ${resolvedCollection.name}`); return null; } const underlyingValueHasChanged: boolean = !!underlyingChanges && Object.keys(underlyingChanges).includes(key) && !!touched[key]; const disabled = (!autoSave && isSubmitting) || isReadOnly(property) || Boolean(property.disabled); const hidden = isHidden(property); if (hidden) return null; const cmsFormFieldProps: PropertyFieldBindingProps = { propertyKey: key, disabled, property, includeDescription: property.description || property.longDescription, underlyingValueHasChanged: underlyingValueHasChanged && !autoSave, context: formContext, tableMode: false, partOfArray: false, partOfBlock: false, autoFocus: false }; return (
} delayDuration={800} side={"left"} align={"start"} sideOffset={16}>
); }) .filter(Boolean)}
); const disabled = isSubmitting || (!modified && status === "existing"); const formRef = React.useRef(null); return (
{ console.debug("Resetting form") resetForm(); return onDiscard && onDiscard(); }} noValidate>
{formFields}
{!autoSave && {savingError &&
{savingError.message}
} {entity && formActions.length > 0 &&
{formActions.map(action => ( ) => { event.stopPropagation(); if (entity) action.onClick({ entity, fullPath: resolvedCollection.path, collection: resolvedCollection, context, sideEntityController, }); }}> {action.icon} ))}
}
} ); } export function yupToFormErrors(yupError: ValidationError): Record { let errors: Record = {}; if (yupError.inner) { if (yupError.inner.length === 0) { return setIn(errors, yupError.path!, yupError.message); } for (const err of yupError.inner) { if (!getIn(errors, err.path!)) { errors = setIn(errors, err.path!, err.message); } } } return errors; } function formContextsEqual(a: FormContext | undefined, b: FormContext | undefined): boolean { return a?.path === b?.path && a?.entityId === b?.entityId && equal(a?.values, b?.values) && equal(a?.collection, b?.collection); }