import _ from "lodash" import React from "react" import EntityDisplayComponent from "../EntityDisplayComponent" import AsyncLoadComponent from "@mwater/react-library/lib/AsyncLoadComponent" import { InnerFormContext } from "../formContext" export interface EntityAnswerComponentProps { value?: string entityType: string onValueChange: any formCtx: InnerFormContext } // Allows user to select an entity // State is needed for canEditEntity which requires entire entity export default class EntityAnswerComponent extends AsyncLoadComponent { focus() { // Nothing to focus return false } // Override to determine if a load is needed. Not called on mounting isLoadNeeded(newProps: any, oldProps: any) { return newProps.entityType !== oldProps.entityType || newProps.value !== oldProps.value } // Call callback with state changes load(props: any, prevProps: any, callback: any) { if (!props.value) { callback({ entity: null }) return } return this.props.formCtx.getEntityById(props.entityType, props.value, (entity: any) => { return callback({ entity }) }) } // Called to select an entity using an external mechanism (calls @ctx.selectEntity) handleSelectEntity = () => { if (!this.props.formCtx.selectEntity) { return alert(this.props.formCtx.T("Not supported on this platform")) } return this.props.formCtx.selectEntity({ entityType: this.props.entityType, callback: (value: any) => { return this.props.onValueChange(value) } }) } handleClearEntity = () => { return this.props.onValueChange(null) } handleEditEntity = () => { if (!this.props.formCtx.editEntity) { return alert(this.props.formCtx.T("Not supported on this platform")) } return this.props.formCtx.editEntity(this.props.entityType, this.props.value!, () => { this.props.onValueChange(this.props.value) return this.forceLoad() }) } renderEntityButtons() { return (
{this.props.formCtx.editEntity != null && this.props.formCtx.canEditEntity && this.props.formCtx.canEditEntity(this.props.entityType, this.state.entity) ? ( ) : undefined}
) } render() { if (this.state.loading) { return
{this.props.formCtx.T("Loading...")}
} if (!this.props.value) { // Render select button return ( ) } if (!this.state.entity) { return
{this.props.formCtx.T("Not found")}
} return (
{this.renderEntityButtons()}
) } }