Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(DRAFT) (refactor): Migrate patient registration form to RHF #1343

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,17 @@ const BeforeSavePrompt: React.FC<BeforeSavePromptProps> = ({ when, redirect }) =
}
}, []);

useEffect(() => {
if (when && typeof target === 'undefined') {
window.addEventListener('single-spa:before-routing-event', cancelNavigation);
window.addEventListener('beforeunload', cancelUnload);
// useEffect(() => {
// if (when && typeof target === 'undefined') {
// window.addEventListener('single-spa:before-routing-event', cancelNavigation);
// window.addEventListener('beforeunload', cancelUnload);

return () => {
window.removeEventListener('beforeunload', cancelUnload);
window.removeEventListener('single-spa:before-routing-event', cancelNavigation);
};
}
}, [target, when, cancelUnload, cancelNavigation]);
// return () => {
// window.removeEventListener('beforeunload', cancelUnload);
// window.removeEventListener('single-spa:before-routing-event', cancelNavigation);
// };
// }
// }, [target, when, cancelUnload, cancelNavigation]);

useEffect(() => {
if (typeof target === 'string') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { useOrderedAddressHierarchyLevels } from './address-hierarchy.resource';
import AddressHierarchyLevels from './address-hierarchy-levels.component';
import AddressSearchComponent from './address-search.component';
import styles from '../field.scss';
import type { FormValues } from '../../patient-registration.types';
import { usePatientRegistrationContext } from '../../patient-registration-hooks';

function parseString(xmlDockAsString: string) {
const parser = new DOMParser();
Expand Down Expand Up @@ -47,16 +49,16 @@ export const AddressComponent: React.FC = () => {
},
} = config;

const { setFieldValue } = useContext(PatientRegistrationContext);
const { setValue } = usePatientRegistrationContext();
const { orderedFields, isLoadingFieldOrder, errorFetchingFieldOrder } = useOrderedAddressHierarchyLevels();

useEffect(() => {
if (addressTemplate?.elementDefaults) {
Object.entries(addressTemplate.elementDefaults).forEach(([name, defaultValue]) => {
setFieldValue(`address.${name}`, defaultValue);
setValue(`address.${name}`, defaultValue);
});
}
}, [addressTemplate, setFieldValue]);
}, [addressTemplate, setValue]);

const orderedAddressFields = useMemo(() => {
if (isLoadingFieldOrder || errorFetchingFieldOrder) {
Expand Down Expand Up @@ -84,7 +86,7 @@ export const AddressComponent: React.FC = () => {
{addressLayout.map((attributes, index) => (
<Input
key={`combo_input_${index}`}
name={`address.${attributes.name}`}
name={`address.${attributes.name}` as keyof FormValues}
labelText={t(attributes.label)}
id={attributes.name}
value={selected}
Expand Down Expand Up @@ -125,7 +127,7 @@ export const AddressComponent: React.FC = () => {
orderedAddressFields.map((attributes, index) => (
<Input
key={`combo_input_${index}`}
name={`address.${attributes.name}`}
name={`address.${attributes.name}` as keyof FormValues}
labelText={t(attributes.label)}
id={attributes.name}
value={selected}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import React, { useCallback } from 'react';
import React, { useCallback, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import { useAddressEntries, useAddressEntryFetchConfig } from './address-hierarchy.resource';
import { useField } from 'formik';
import ComboInput from '../../input/combo-input/combo-input.component';
import { PatientRegistrationContext } from '../../patient-registration-context';
import type { FormValues } from '../../patient-registration.types';
import { usePatientRegistrationContext } from '../../patient-registration-hooks';

interface AddressComboBoxProps {
attribute: {
Expand All @@ -20,39 +22,37 @@ interface AddressHierarchyLevelsProps {

const AddressComboBox: React.FC<AddressComboBoxProps> = ({ attribute }) => {
const { t } = useTranslation();
const [field, meta, { setValue }] = useField(`address.${attribute.name}`);
const fieldName = `address.${attribute.name}` as keyof FormValues;
const { setValue, watch } = usePatientRegistrationContext();
const fieldValue = watch(fieldName);
const { fetchEntriesForField, searchString, updateChildElements } = useAddressEntryFetchConfig(attribute.name);
const { entries } = useAddressEntries(fetchEntriesForField, searchString);
const label = t(attribute.label) + (attribute?.required ? '' : ` (${t('optional', 'optional')})`);

const handleInputChange = useCallback(
(newValue) => {
setValue(newValue);
setValue(fieldName, newValue);
},
[setValue],
);

const handleSelection = useCallback(
(selectedItem) => {
if (meta.value !== selectedItem) {
setValue(selectedItem);
if (fieldValue !== selectedItem) {
setValue(fieldName, selectedItem);
updateChildElements();
}
},
[updateChildElements, meta.value, setValue],
[updateChildElements, fieldValue, setValue],
);

return (
<ComboInput
entries={entries}
handleSelection={handleSelection}
name={`address.${attribute.name}`}
fieldProps={{
...field,
id: attribute.name,
labelText: label,
required: attribute?.required,
}}
name={fieldName}
required={attribute?.required}
labelText={label}
handleInputChange={handleInputChange}
/>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useCallback, useContext, useEffect, useMemo } from 'react';
import { useField } from 'formik';
import useSWRImmutable from 'swr/immutable';
import { type FetchResponse, openmrsFetch } from '@openmrs/esm-framework';
import { PatientRegistrationContext } from '../../patient-registration-context';
import { usePatientRegistrationContext } from '../../patient-registration-hooks';

interface AddressFields {
addressField: string;
Expand Down Expand Up @@ -57,8 +57,9 @@ export function useAddressEntries(fetchResults, searchString) {
*/
export function useAddressEntryFetchConfig(addressField: string) {
const { orderedFields, isLoadingFieldOrder } = useOrderedAddressHierarchyLevels();
const { setFieldValue } = useContext(PatientRegistrationContext);
const [, { value: addressValues }] = useField('address');
const { setValue } = usePatientRegistrationContext();
const { watch } = usePatientRegistrationContext();
const addressValues = watch('address');

const index = useMemo(
() => (!isLoadingFieldOrder ? orderedFields.findIndex((field) => field === addressField) : -1),
Expand Down Expand Up @@ -87,9 +88,9 @@ export function useAddressEntryFetchConfig(addressField: string) {
return;
}
orderedFields.slice(index + 1).map((fieldName) => {
setFieldValue(`address.${fieldName}`, '');
setValue(`address.${fieldName}`, '');
});
}, [index, isLoadingFieldOrder, orderedFields, setFieldValue]);
}, [index, isLoadingFieldOrder, orderedFields, setValue]);

const results = useMemo(
() => ({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import React, { useState, useRef, useEffect, useMemo } from 'react';
import React, { useState, useRef, useEffect, useMemo, useContext } from 'react';
import { useAddressHierarchy } from './address-hierarchy.resource';
import { Search } from '@carbon/react';
import { useTranslation } from 'react-i18next';
import { useFormikContext } from 'formik';
import styles from './address-search.scss';
import { usePatientRegistrationContext } from '../../patient-registration-hooks';

interface AddressSearchComponentProps {
addressLayout: Array<any>;
Expand All @@ -12,6 +13,7 @@ interface AddressSearchComponentProps {
const AddressSearchComponent: React.FC<AddressSearchComponentProps> = ({ addressLayout }) => {
const { t } = useTranslation();
const separator = ' > ';
const { control, setValue } = usePatientRegistrationContext();
const searchBox = useRef(null);
const wrapper = useRef(null);
const [searchString, setSearchString] = useState<string>('');
Expand All @@ -29,8 +31,6 @@ const AddressSearchComponent: React.FC<AddressSearchComponentProps> = ({ address
return [...options];
}, [addresses, searchString]);

const { setFieldValue } = useFormikContext();

const handleInputChange = (e) => {
setSearchString(e.target.value);
};
Expand All @@ -39,7 +39,7 @@ const AddressSearchComponent: React.FC<AddressSearchComponentProps> = ({ address
if (address) {
const values = address.split(separator);
addressLayout.map(({ name }, index) => {
setFieldValue(`address.${name}`, values?.[index] ?? '');
setValue(`address.${name}`, values?.[index] ?? '');
});
setSearchString('');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { Input } from '../../input/basic-input/input/input.component';
import styles from '../field.scss';
import { type FieldDefinition } from '../../../config-schema';
import type { FormValues } from '../../patient-registration.types';

export interface AddressFieldProps {
fieldDefinition: FieldDefinition;
Expand All @@ -15,18 +16,14 @@ export const AddressField: React.FC<AddressFieldProps> = ({ fieldDefinition }) =

return (
<div className={classNames(styles.customField, styles.halfWidthInDesktopView)}>
<Field name={fieldDefinition.id}>
{({ field, form: { touched, errors }, meta }) => {
return (
<Input
id={fieldDefinition.id}
labelText={t(`${fieldDefinition.label}`, `${fieldDefinition.label}`)}
required={fieldDefinition?.validation?.required ?? false}
{...field}
/>
);
}}
</Field>
return (
<Input
id={fieldDefinition.id}
name={fieldDefinition.id as keyof FormValues}
labelText={t(`${fieldDefinition.label}`, `${fieldDefinition.label}`)}
required={fieldDefinition?.validation?.required ?? false}
/>
);
</div>
);
};
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import React, { useMemo } from 'react';
import React, { useContext, useMemo } from 'react';
import classNames from 'classnames';
import { Field, useField } from 'formik';
import { useTranslation } from 'react-i18next';
import { InlineNotification, Layer, Select, SelectItem, SelectSkeleton, TextInput } from '@carbon/react';
import { useConfig } from '@openmrs/esm-framework';
import { type RegistrationConfig } from '../../../config-schema';
import { useConceptAnswers } from '../field.resource';
import styles from '../field.scss';
import { PatientRegistrationContext } from '../../patient-registration-context';
import { Controller } from 'react-hook-form';
import { usePatientRegistrationContext } from '../../patient-registration-hooks';

export const CauseOfDeathField: React.FC = () => {
const { t } = useTranslation();
const { fieldConfigurations, freeTextFieldConceptUuid } = useConfig<RegistrationConfig>();
const [deathCause, deathCauseMeta] = useField('deathCause');
const { getFieldState, control } = usePatientRegistrationContext();
const { error, isTouched } = getFieldState('deathCause');

const conceptUuid = fieldConfigurations?.causeOfDeath?.conceptUuid;
const required = fieldConfigurations?.causeOfDeath?.required;
Expand Down Expand Up @@ -50,15 +53,17 @@ export const CauseOfDeathField: React.FC = () => {
/>
) : (
<>
<Field name="deathCause">
{({ field, form: { touched, errors }, meta }) => {
return (
<Controller
control={control}
name="deathCause"
render={({ field, fieldState: { error, isTouched } }) => (
<>
<Layer>
<Select
{...field}
id="deathCause"
invalid={errors.deathCause && touched.deathCause}
invalidText={errors.deathCause?.message}
invalid={isTouched && error?.message}
invalidText={error?.message}
labelText={t('causeOfDeathInputLabel', 'Cause of Death')}
name="deathCause"
required={required}>
Expand All @@ -68,29 +73,31 @@ export const CauseOfDeathField: React.FC = () => {
))}
</Select>
</Layer>
);
}}
</Field>
{deathCause.value === freeTextFieldConceptUuid && (
<div className={styles.nonCodedCauseOfDeath}>
<Field name="nonCodedCauseOfDeath">
{({ field, form: { touched, errors }, meta }) => {
return (
<Layer>
<TextInput
{...field}
id="nonCodedCauseOfDeath"
invalid={errors?.nonCodedCauseOfDeath && touched.nonCodedCauseOfDeath}
invalidText={errors?.nonCodedCauseOfDeath?.message}
labelText={t('nonCodedCauseOfDeath', 'Non-coded cause of death')}
placeholder={t('enterNonCodedCauseOfDeath', 'Enter non-coded cause of death')}
/>
</Layer>
);
}}
</Field>
</div>
)}
{field.value === freeTextFieldConceptUuid && (
<div className={styles.nonCodedCauseOfDeath}>
<Controller
control={control}
name="nonCodedCauseOfDeath"
render={({ field, fieldState: { isTouched, error } }) => {
return (
<Layer>
<TextInput
{...field}
id="nonCodedCauseOfDeath"
invalid={isTouched && error?.message}
invalidText={error?.message}
labelText={t('nonCodedCauseOfDeath', 'Non-coded cause of death')}
placeholder={t('enterNonCodedCauseOfDeath', 'Enter non-coded cause of death')}
/>
</Layer>
);
}}
/>
</div>
)}
</>
)}
/>
</>
)}
</div>
Expand Down
Loading
Loading