import { Controller, FormProvider, useForm } from 'react-hook-form'; import { CustomSelectControl } from "../ui/custom-select-control"; import type { CustomSelectOption } from "../ui/custom-select-control"; import { Flex } from '../ui/flex'; import { Spacer } from '../ui/spacer'; import { Patient } from 'fhir/r4'; import { formatFhirHumanName } from '../../utils/fhirHumanName'; // react-hook-form derives its field-path union by walking every nested property of the form value // type. A FHIR Patient is deep enough that doing so produced a union TypeScript could not represent // (TS2589/TS2590 on the Controller below) and cost ~5.7M type instantiations in this 86-line file. // The stored value is still the Patient object LoginPage reads back from onSubmit - it is only kept // opaque to that path machinery, and narrowed at the one place it is read. interface IRelatedPatientFormValues { patient: unknown; } interface IRelatedPatientSelectorProps { onSubmit: (data: any) => void; patients?: Patient[]; selectedPatient?: Patient | null; label?: string; buttonText?: string; isLoading?: boolean; } export const RelatedPatientSelector = ({ onSubmit, patients, selectedPatient, label = 'Available Patients', buttonText = 'Select Patient', isLoading = false }: IRelatedPatientSelectorProps) => { const methods = useForm({ defaultValues: { patient: selectedPatient || '' } }); const { control, handleSubmit, formState } = methods; const options = [ { key: '', name: 'Select a patient...', value: null }, ...patients.map((patient: Patient) => ({ key: patient.id as string, name: formatFhirHumanName(patient.name), value: patient })) ]; return (
{ let currentValue: CustomSelectOption; const fieldValue = field.value as Patient | string; if (fieldValue && typeof fieldValue === 'object' && fieldValue.id) { const matchingOption = options.find(option => option.value?.id === fieldValue.id); currentValue = matchingOption || options[0]; } else { currentValue = options[0]; } return ( { field.onChange(newValue.selectedItem.value); }}/> ); }}/>
); }; export default RelatedPatientSelector;