import React, { useCallback, useEffect, useRef, useState } from "react"; import { Entity, EntityCollection, EntityCustomView, EntityStatus, EntityValues, FireCMSPlugin, FormContext, User } from "../types"; import { CircularProgressCenter, EntityCollectionView, EntityView, ErrorBoundary, } from "../components"; import { canEditEntity, removeInitialAndTrailingSlashes, resolveDefaultSelectedView, resolveEntityView, useDebouncedCallback } from "../util"; import { saveEntityWithCallbacks, useAuthController, useCustomizationController, useDataSource, useEntityFetch, useFireCMSContext, useSideEntityController, useSnackbarController } from "../hooks"; import { EntityForm } from "../form"; import { CircularProgress, CloseIcon, cn, defaultBorderMixin, IconButton, Tab, Tabs, Typography } from "@firecms/ui"; import { EntityFormSaveParams } from "../form/EntityForm"; import { useSideDialogContext } from "./index"; const MAIN_TAB_VALUE = "main_##Q$SC^#S6"; export interface EntityEditViewProps> { path: string; collection: EntityCollection; entityId?: string; copy?: boolean; selectedSubPath?: string; parentCollectionIds: string[]; formWidth?: number | string; onValuesAreModified: (modified: boolean) => void; onUpdate?: (params: { entity: Entity }) => void; onClose?: () => void; } /** * This is the default view that is used as the content of a side panel when * an entity is opened. * You probably don't want to use this view directly since it is bound to the * side panel. Instead, you might want to use {@link EntityForm} or {@link EntityCollectionView} */ export function EntityEditView, UserType extends User>({ path, entityId, selectedSubPath, copy, collection, parentCollectionIds, onValuesAreModified, formWidth, onUpdate, onClose, }: EntityEditViewProps) { if (collection.customId && collection.formAutoSave) { console.warn(`The collection ${collection.path} has customId and formAutoSave enabled. This is not supported and formAutoSave will be ignored`); } const [saving, setSaving] = useState(false); /** * These are the values that are being saved. They are debounced. * We use this only when autoSave is enabled. */ const [valuesToBeSaved, setValuesToBeSaved] = useState | undefined>(undefined); useDebouncedCallback(valuesToBeSaved, () => { if (valuesToBeSaved) saveEntity({ entityId: usedEntity?.id, collection, path, values: valuesToBeSaved, closeAfterSave: false }); }, false, 2000); // const largeLayout = useLargeLayout(); // const largeLayoutTabSelected = useRef(!largeLayout); // const resolvedFormWidth: string = typeof formWidth === "number" ? `${formWidth}px` : formWidth ?? FORM_CONTAINER_WIDTH; const dataSource = useDataSource(collection); const sideDialogContext = useSideDialogContext(); const sideEntityController = useSideEntityController(); const snackbarController = useSnackbarController(); const customizationController = useCustomizationController(); const context = useFireCMSContext(); const authController = useAuthController(); const [formContext, setFormContext] = useState | undefined>(undefined); const [status, setStatus] = useState(copy ? "copy" : (entityId ? "existing" : "new")); const modifiedValuesRef = useRef | undefined>(undefined); const modifiedValues = modifiedValuesRef.current; const subcollections = (collection.subcollections ?? []).filter(c => !c.hideFromNavigation); const subcollectionsCount = subcollections?.length ?? 0; const customViews = collection.entityViews; const customViewsCount = customViews?.length ?? 0; const autoSave = collection.formAutoSave && !collection.customId; const hasAdditionalViews = customViewsCount > 0 || subcollectionsCount > 0; const defaultSelectedView = selectedSubPath ?? resolveDefaultSelectedView( collection ? collection.defaultSelectedView : undefined, { status, entityId } ); const selectedTabRef = useRef(defaultSelectedView ?? MAIN_TAB_VALUE); const mainViewVisible = selectedTabRef.current === MAIN_TAB_VALUE; const { entity, dataLoading, // eslint-disable-next-line no-unused-vars dataLoadingError } = useEntityFetch({ path, entityId, collection, useCache: false }); const [usedEntity, setUsedEntity] = useState | undefined>(entity); const [readOnly, setReadOnly] = useState(undefined); useEffect(() => { if (entity) setUsedEntity(entity); }, [entity]); useEffect(() => { if (status === "new") { setReadOnly(false); } else { const editEnabled = usedEntity ? canEditEntity(collection, authController, path, usedEntity ?? null) : false; if (usedEntity) setReadOnly(!editEnabled); } }, [authController, usedEntity, status]); const onPreSaveHookError = useCallback((e: Error) => { setSaving(false); snackbarController.open({ type: "error", message: "Error before saving: " + e?.message }); console.error(e); }, [snackbarController]); const onSaveSuccessHookError = useCallback((e: Error) => { setSaving(false); snackbarController.open({ type: "error", message: "Error after saving (entity is saved): " + e?.message }); console.error(e); }, [snackbarController]); const onSaveSuccess = (updatedEntity: Entity, closeAfterSave: boolean) => { setSaving(false); if (!autoSave) snackbarController.open({ type: "success", message: `${collection.singularName ?? collection.name}: Saved correctly` }); setUsedEntity(updatedEntity); setStatus("existing"); onValuesAreModified(false); if (onUpdate) onUpdate({ entity: updatedEntity }); if (closeAfterSave) { sideDialogContext.setBlocked(false); sideDialogContext.close(true); onClose?.(); } else if (status !== "existing") { sideEntityController.replace({ path, entityId: updatedEntity.id, selectedSubPath: selectedTabRef.current, updateUrl: true, collection, }); } }; const onSaveFailure = useCallback((e: Error) => { setSaving(false); snackbarController.open({ type: "error", message: "Error saving: " + e?.message }); console.error("Error saving entity", path, entityId); console.error(e); }, [entityId, path, snackbarController]); const saveEntity = ({ values, previousValues, closeAfterSave, entityId, collection, path }: { collection: EntityCollection, path: string, entityId: string | undefined, values: M, previousValues?: M, closeAfterSave: boolean, }) => { setSaving(true); saveEntityWithCallbacks({ path, entityId, values, previousValues, collection, status, dataSource, context, onSaveSuccess: (updatedEntity: Entity) => onSaveSuccess(updatedEntity, closeAfterSave), onSaveFailure, onPreSaveHookError, onSaveSuccessHookError }).then(); }; const onSaveEntityRequest = async ({ collection, path, entityId, values, previousValues, closeAfterSave, autoSave }: EntityFormSaveParams): Promise => { if (!status) return; if (autoSave) { setValuesToBeSaved(values); } else { saveEntity({ collection, path, entityId, values, previousValues, closeAfterSave }); } }; const resolvedEntityViews = customViews ? customViews .map(e => resolveEntityView(e, customizationController.entityViews)) .filter(Boolean) as EntityCustomView[] : []; const customViewsView: React.ReactNode[] | undefined = customViews && resolvedEntityViews .map( (customView, colIndex) => { if (!customView) return null; if (selectedTabRef.current !== customView.key) return null; const Builder = customView.Builder; if (!Builder) { console.error("customView.Builder is not defined"); return null; } return
{formContext && }
; } ).filter(Boolean); const globalLoading = (dataLoading && !usedEntity) || ((!usedEntity || readOnly === undefined) && (status === "existing" || status === "copy")); const loading = globalLoading || saving; const subCollectionsViews = subcollections && subcollections.map( (subcollection, colIndex) => { const subcollectionId = subcollection.id ?? subcollection.path; const fullPath = usedEntity ? `${path}/${usedEntity?.id}/${removeInitialAndTrailingSlashes(subcollectionId)}` : undefined; if (selectedTabRef.current !== subcollectionId) return null; return (
{loading && } {!globalLoading && (usedEntity && fullPath ? :
You need to save your entity before adding additional collections
) }
); } ).filter(Boolean); const onDiscard = useCallback(() => { onValuesAreModified(false); }, []); const onSideTabClick = (value: string) => { selectedTabRef.current = value; sideEntityController.replace({ path, entityId, selectedSubPath: value === MAIN_TAB_VALUE ? undefined : value, updateUrl: true, collection, }); }; const onValuesChanged = useCallback((values?: EntityValues) => { modifiedValuesRef.current = values; }, []); // eslint-disable-next-line n/handle-callback-err const onIdUpdateError = useCallback((error: any) => { snackbarController.open({ type: "error", message: "Error updating id, check the console" }); }, []); const onIdChange = useCallback((id: string) => { setUsedEntity((prevEntity) => prevEntity ? { ...prevEntity, id } : undefined); }, []); const onModified = (dirty: boolean) => { if (!autoSave) onValuesAreModified(dirty); } function buildForm() { const plugins = customizationController.plugins; let form = ; if (plugins) { plugins.forEach((plugin: FireCMSPlugin) => { if (plugin.form?.provider) { form = ( {form} ); } }); } return {form}; } const form = (readOnly === undefined) ? <> : (!readOnly ? buildForm() : ( <> {collection.singularName ?? collection.name} } path={path} collection={collection}/> )); const subcollectionTabs = subcollections && subcollections.map( (subcollection) => {subcollection.name} ); const customViewTabs = resolvedEntityViews.map( (view) => {view.name} ); return (
{ <>
{ onClose?.(); return sideDialogContext.close(false); }} size="large">
{globalLoading &&
} { onSideTabClick(value); }} className="pl-4 pr-4 pt-0"> {collection.singularName ?? collection.name} {customViewTabs} {subcollectionTabs}
{customViewsView} {subCollectionsViews}
}
); }