import React, { ComponentType, ReactElement, useCallback, useRef } from "react"; import equal from "react-fast-compare" import { Field, FieldProps as FormexFieldProps, getIn } from "@firecms/formex"; import { CMSType, EntityCollection, FieldProps, FireCMSPlugin, PluginFieldBuilderParams, Property, PropertyFieldBindingProps, PropertyOrBuilder, ResolvedProperty } from "../types"; import { ReadOnlyFieldBinding } from "./field_bindings/ReadOnlyFieldBinding"; import { isHidden, isPropertyBuilder, isReadOnly, resolveProperty } from "../util"; import { useCustomizationController } from "../hooks"; import { Typography } from "@firecms/ui"; import { getFieldConfig, getFieldId } from "../core"; import { ErrorBoundary } from "../components"; /** * This component renders a form field creating the corresponding configuration * from a property. For example if bound to a string property, it will generate * a text field. * * You can use it when you are creating a custom field, and need to * render additional fields mapped to properties. This is useful if you * need to build a complex property mapping, like an array where each index * is a different property. * * Please note that if you build a custom field in a component, the * **validation** passed in the property will have no effect. You need to set * the validation in the `EntityCollection` definition. * * @param propertyKey You can use nested names such as `address.street` or `friends[2]` * @param property * @param context * @param includeDescription * @param underlyingValueHasChanged * @param disabled * @param tableMode * @param partOfArray * @param autoFocus * @group Form custom fields */ export const PropertyFieldBinding = React.memo(PropertyFieldBindingInternal, (a: PropertyFieldBindingProps, b: PropertyFieldBindingProps) => { if (a.propertyKey !== b.propertyKey) { return false; } const aIsBuilder = isPropertyBuilder(a.property) || a.property.fromBuilder; const bIsBuilder = isPropertyBuilder(b.property) || b.property.fromBuilder; const baseCheck = (aIsBuilder === bIsBuilder || equal(a.property, b.property)) && a.disabled === b.disabled; if (!baseCheck) { return false; } if (shouldPropertyReRender(b.property)) { return false; } return false; }) as typeof PropertyFieldBindingInternal; function PropertyFieldBindingInternal = Record> ({ propertyKey, property, context, includeDescription, underlyingValueHasChanged, disabled, tableMode, partOfArray, partOfBlock, autoFocus, }: PropertyFieldBindingProps): ReactElement> { const customizationController = useCustomizationController(); return ( {(fieldProps) => { let Component: ComponentType> | undefined; const resolvedProperty: ResolvedProperty | null = resolveProperty({ propertyKey, propertyOrBuilder: property, values: fieldProps.form.values, path: context.path, entityId: context.entityId, fields: customizationController.propertyConfigs }); if (resolvedProperty === null || isHidden(resolvedProperty)) { return <>; } else if (isReadOnly(resolvedProperty)) { Component = ReadOnlyFieldBinding; } else if (resolvedProperty.Field) { if (typeof resolvedProperty.Field === "function") { Component = resolvedProperty.Field as ComponentType>; } } else { const propertyConfig = getFieldConfig(resolvedProperty, customizationController.propertyConfigs); if (!propertyConfig) { console.log("INTERNAL: Could not find field config for property", { propertyKey, resolvedProperty, fields: customizationController.propertyConfigs, propertyConfig }); throw new Error(`INTERNAL: Could not find field config for property ${propertyKey}`); } const configProperty = resolveProperty({ propertyOrBuilder: propertyConfig.property, values: fieldProps.form.values, path: context.path, entityId: context.entityId, fields: customizationController.propertyConfigs }); Component = configProperty.Field as ComponentType>; } if (!Component) { console.warn(`No field component found for property ${propertyKey}`); console.warn("Property:", property); return (
{`Currently the field ${resolvedProperty.dataType} is not supported`}
); } const componentProps: ResolvedPropertyFieldBindingProps = { propertyKey, property: resolvedProperty, includeDescription, underlyingValueHasChanged, context, disabled, tableMode, partOfArray, partOfBlock, autoFocus }; return } componentProps={componentProps} fieldProps={fieldProps}/>; }}
); } type ResolvedPropertyFieldBindingProps = Record> = Omit, "property"> & { property: ResolvedProperty }; function FieldInternal> ({ Component, componentProps: { propertyKey, property, includeDescription, underlyingValueHasChanged, tableMode, partOfArray, partOfBlock, autoFocus, context, disabled }, fieldProps }: { Component: ComponentType>, componentProps: ResolvedPropertyFieldBindingProps, fieldProps: FormexFieldProps }) { const { plugins } = useCustomizationController(); const customFieldProps: any = property.customProps; const value = fieldProps.field.value; // const initialValue = fieldProps.meta.initialValue; const error = getIn(fieldProps.form.errors, propertyKey); const touched = getIn(fieldProps.form.touched, propertyKey); const showError: boolean = error && (fieldProps.form.submitCount > 0 || property.validation?.unique) && (!Array.isArray(error) || !!error.filter((e: any) => !!e).length); const WrappedComponent: ComponentType> | null = useWrappedComponent(context.path, context.collection, propertyKey, property, Component, plugins); const UsedComponent: ComponentType> = WrappedComponent ?? Component; const isSubmitting = fieldProps.form.isSubmitting; const setValue = useCallback((value: T | null, shouldValidate?: boolean) => { fieldProps.form.setFieldTouched(propertyKey, true, false); fieldProps.form.setFieldValue(propertyKey, value, shouldValidate); }, []); const setFieldValue = useCallback((otherPropertyKey: string, value: CMSType | null, shouldValidate?: boolean) => { fieldProps.form.setFieldTouched(propertyKey, true, false); fieldProps.form.setFieldValue(otherPropertyKey, value, shouldValidate); }, []); const cmsFieldProps: FieldProps = { propertyKey, value: value as T, // initialValue, setValue, setFieldValue, error, touched, showError, isSubmitting, includeDescription: includeDescription ?? true, property: property as ResolvedProperty, disabled: disabled ?? false, underlyingValueHasChanged: underlyingValueHasChanged ?? false, tableMode: tableMode ?? false, partOfArray: partOfArray ?? false, partOfBlock: partOfBlock ?? false, autoFocus: autoFocus ?? false, customProps: customFieldProps, context }; return ( {underlyingValueHasChanged && !isSubmitting && This value has been updated elsewhere } ); } const shouldPropertyReRender = (property: PropertyOrBuilder | ResolvedProperty, plugins?: FireCMSPlugin[]): boolean => { if (plugins?.some((plugin) => plugin.form?.fieldBuilder)) { return true; } if (isPropertyBuilder(property)) { return true; } const defAProperty = property as Property | ResolvedProperty; const rerenderThisProperty = Boolean(defAProperty.Field) || ("fromBuilder" in defAProperty && defAProperty.fromBuilder); if (defAProperty.dataType === "map" && defAProperty.properties) { return rerenderThisProperty || Object.values(defAProperty.properties).some((childProperty) => shouldPropertyReRender(childProperty, plugins)); } else if (defAProperty.dataType === "array" && "resolvedProperties" in defAProperty) { // @ts-ignore return rerenderThisProperty || defAProperty.resolvedProperties?.some((childProperty) => childProperty && shouldPropertyReRender(childProperty, plugins)); } else { return rerenderThisProperty; } } function useWrappedComponent = any>( path: string, collection: EntityCollection, propertyKey: string, property: ResolvedProperty, Component: ComponentType>, plugins?: FireCMSPlugin[] ): ComponentType> | null { const wrapperRef = useRef> | null>((() => { let Wrapper: ComponentType> | null = null; if (plugins) { plugins.forEach((plugin) => { const fieldId = getFieldId(property); if (fieldId && plugin.form?.fieldBuilder) { const params: PluginFieldBuilderParams = { fieldConfigId: fieldId, propertyKey, property, Field: Component, plugin, path, collection }; const enabled = plugin.form?.fieldBuilderEnabled?.(params); if (enabled === undefined || enabled) Wrapper = plugin.form.fieldBuilder(params) || Wrapper; } if (!fieldId) { console.warn("INTERNAL: Field id not found for property", property); } }); } return Wrapper; })()); return wrapperRef.current; }