import React, { ReactNode, useCallback, useEffect, useRef, useState } from "react" import { LocalizeString } from "ez-localize" export interface EntityDisplayComponentProps { /** Entity type e.g. "water_point" */ entityType: string /** _id of entity */ entityId?: string /** code of entity if _id not present */ entityCode?: string /** True to render in well if present */ displayInWell?: boolean /** Gets an entity by id (entityType, entityId, callback). Required if entityId */ getEntityById?: (entityType: string, entityId: string, callback: (entity: any) => void) => void /** Gets an entity by code (entityType, entityCode, callback). Required if entityCode */ getEntityByCode?: (entityType: string, entityCode: string, callback: (entity: any) => void) => void /** Renders an entity as a React element */ renderEntityView: (entityType: string, entity: any) => ReactNode /** Called when the user clicks the edit button with the loaded entity. Only shown when provided and canEdit returns true. */ onEdit?: (entity: any) => void /** Called when the user clicks the view button with the loaded entity. Only shown when provided. */ onView?: (entity: any) => void /** If provided, controls whether the edit button is visible for the given entity. Defaults to true if onEdit is set. */ canEdit?: (entity: any) => boolean T: LocalizeString } /** Loads and displays an entity. */ export default function EntityDisplayComponent(props: EntityDisplayComponentProps) { const { entityType, entityId, entityCode, displayInWell, getEntityById, getEntityByCode, renderEntityView, onEdit, onView, canEdit, T } = props const [entity, setEntity] = useState(null) const [loading, setLoading] = useState(true) const loadSeqRef = useRef(0) const performLoad = useCallback(() => { if (!entityId && !entityCode) { setEntity(null) setLoading(false) return } loadSeqRef.current += 1 const seq = loadSeqRef.current setLoading(true) const callback = (loadedEntity: any) => { if (seq < loadSeqRef.current) { return } setEntity(loadedEntity) setLoading(false) } if (entityId) { getEntityById!(entityType, entityId, (e: any) => callback(e)) } else { getEntityByCode!(entityType, entityCode!, (e: any) => callback(e)) } }, [entityType, entityId, entityCode, getEntityById, getEntityByCode]) useEffect(() => { performLoad() }, [performLoad]) if (loading) { return
{T("Loading...")}
} if (!entityId && !entityCode) { return null } if (!entity) { return (
{T("Either site has been deleted or you do not have permission to view it")}
) } const showEdit = onEdit && (!canEdit || canEdit(entity)) const actionButtons = (showEdit || onView) ? (
{onView ? ( onView(entity)} style={{ cursor: "pointer", marginLeft: 10 }}> {T("View")} ) : null} {showEdit ? ( onEdit(entity)} style={{ cursor: "pointer", marginLeft: 10 }}> {T("Edit Site")} ) : null}
) : null if (displayInWell) { return (
{actionButtons} {renderEntityView(entityType, entity)}
) } return (
{actionButtons} {renderEntityView(entityType, entity)}
) }