Skip to content

(feat) O3-4201: Enhance Number Question Labels Display Unit and Range (Min/Max) from Concept #454

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
33 changes: 31 additions & 2 deletions src/components/inputs/number/number.component.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,39 @@
import React, { useCallback, useMemo, useState } from 'react';
import { isNil } from 'lodash';

Check failure on line 2 in src/components/inputs/number/number.component.tsx

View workflow job for this annotation

GitHub Actions / build

'lodash' import is restricted from being used. Import specific methods from `lodash`. e.g. `import map from 'lodash/map'`
import { useTranslation } from 'react-i18next';
import { Layer, NumberInput } from '@carbon/react';
import { type Concept } from '@openmrs/esm-framework';
import classNames from 'classnames';
import { isTrue } from '../../../utils/boolean-utils';
import { shouldUseInlineLayout } from '../../../utils/form-helper';
import FieldValueView from '../../value/view/field-value-view.component';
import { type FormFieldInputProps } from '../../../types';
import styles from './number.scss';
import { useTranslation } from 'react-i18next';
import { useFormProviderContext } from '../../../provider/form-provider';
import FieldLabel from '../../field-label/field-label.component';
import { isEmpty } from '../../../validators/form-validator';


const extractFieldUnitsAndRange = (concept?: Concept): string => {
if (!concept) {
return '';
}

const { hiAbsolute, lowAbsolute, units } = concept;
const displayUnits = units ? ` ${units}` : '';
const hasLowerLimit = !isNil(lowAbsolute);
const hasUpperLimit = !isNil(hiAbsolute);

if (hasLowerLimit && hasUpperLimit) {
return `(${lowAbsolute} - ${hiAbsolute}${displayUnits})`;
} else if (hasUpperLimit) {
return `(<= ${hiAbsolute}${displayUnits})`;
} else if (hasLowerLimit) {
return `(>= ${lowAbsolute}${displayUnits})`;
}
return units ? `(${units})` : '';
};

const NumberField: React.FC<FormFieldInputProps> = ({ field, value, errors, warnings, setFieldValue }) => {
const { t } = useTranslation();
const [lastBlurredValue, setLastBlurredValue] = useState(value);
Expand Down Expand Up @@ -61,7 +84,13 @@
id={field.id}
invalid={errors.length > 0}
invalidText={errors[0]?.message}
label={<FieldLabel field={field} />}
label={<FieldLabel field={field} customLabel={t('fieldLabelWithUnitsAndRange',
'{{fieldDescription}} {{unitsAndRange}}',
{
fieldDescription: t(field.label),
unitsAndRange: extractFieldUnitsAndRange(field.meta?.concept),
interpolation: { escapeValue: false }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this necessary?

Copy link
Author

@D-matz D-matz Mar 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

without escapeValue: false, / doesn't show correctly, it becomes &#x2F; eg BMI (Kg&#x2F;m2):

})}/>}
max={Number(field.questionOptions.max) || undefined}
min={Number(field.questionOptions.min) || undefined}
name={field.id}
Expand Down
128 changes: 128 additions & 0 deletions src/components/inputs/number/number.test.tsx
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not really sure about jest.mock('react-i18next', () => ({...
it seemed needed for the new i18n label t('{{fieldDescription}} {{unitsAndRange}}'... but I'm not sure if that's correct

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,22 @@ import { act, render, screen, fireEvent } from '@testing-library/react';
import { useFormProviderContext } from 'src/provider/form-provider';
import NumberField from './number.component';

jest.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key, defaultValueOrOptions, options) => {

if (typeof defaultValueOrOptions === 'object' && 'fieldDescription' in defaultValueOrOptions) {
return `${defaultValueOrOptions.fieldDescription} ${defaultValueOrOptions.unitsAndRange}`;
}
else if (typeof options === 'object' && 'unitsAndRange' in options) {
return `${options.fieldDescription} ${options.unitsAndRange}`;
}

return key;
}
})
}));

jest.mock('src/provider/form-provider', () => ({
useFormProviderContext: jest.fn(),
}));
Expand All @@ -22,6 +38,63 @@ const numberFieldMock = {
readonly: false,
};

const numberFieldMockWithUnitsAndRange = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to have a more comprehensive set of tests.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added a few more cases (only units, only range, only max)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add one for lowAbsolute only as well? That should cover things.

label: 'Weight',
type: 'obs',
id: 'weight',
questionOptions: {
rendering: 'number',
},
meta: {
concept: {
units: 'kg',
lowAbsolute: 0,
hiAbsolute: 200,
}
},
isHidden: false,
isDisabled: false,
readonly: false,
};

const numberFieldMockWithUnitsOnly = {
...numberFieldMockWithUnitsAndRange,
meta: {
concept: {
units: 'kg',
}
},
};

const numberFieldMockWithRangeOnly = {
...numberFieldMockWithUnitsAndRange,
meta: {
concept: {
lowAbsolute: 0,
hiAbsolute: 200,
}
},
};

const numberFieldMockWithHiAbsoluteOnly = {
...numberFieldMockWithUnitsAndRange,
meta: {
concept: {
hiAbsolute: 200,
}
},
};

const numberFieldMockWithLowAbsoluteOnly = {
...numberFieldMockWithUnitsAndRange,
meta: {
concept: {
lowAbsolute: 0,
}
},
};


const renderNumberField = async (props) => {
await act(() => render(<NumberField {...props} />));
};
Expand Down Expand Up @@ -104,4 +177,59 @@ describe('NumberField Component', () => {
const inputElement = screen.getByLabelText('Weight(kg):') as HTMLInputElement;
expect(inputElement).toBeDisabled();
});

it('renders units and range', async () => {
await renderNumberField({
field: numberFieldMockWithUnitsAndRange,
value: '',
errors: [],
warnings: [],
setFieldValue: jest.fn(),
});
expect(screen.getByLabelText('Weight (0 - 200 kg)')).toBeInTheDocument();
});

it('renders units only', async () => {
await renderNumberField({
field: numberFieldMockWithUnitsOnly,
value: '',
errors: [],
warnings: [],
setFieldValue: jest.fn(),
});
expect(screen.getByLabelText('Weight (kg)')).toBeInTheDocument();
});

it('renders range only', async () => {
await renderNumberField({
field: numberFieldMockWithRangeOnly,
value: '',
errors: [],
warnings: [],
setFieldValue: jest.fn(),
});
expect(screen.getByLabelText('Weight (0 - 200)')).toBeInTheDocument();
});

it('renders hiAbsolute only', async () => {
await renderNumberField({
field: numberFieldMockWithHiAbsoluteOnly,
value: '',
errors: [],
warnings: [],
setFieldValue: jest.fn(),
});
expect(screen.getByLabelText('Weight (<= 200)')).toBeInTheDocument();
});

it('renders lowAbsolute only', async () => {
await renderNumberField({
field: numberFieldMockWithLowAbsoluteOnly,
value: '',
errors: [],
warnings: [],
setFieldValue: jest.fn(),
});
expect(screen.getByLabelText('Weight (>= 0)')).toBeInTheDocument();
});
});
2 changes: 1 addition & 1 deletion src/hooks/useConcepts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useRestApiMaxResults } from './useRestApiMaxResults';
type ConceptFetchResponse = FetchResponse<{ results: Array<OpenmrsResource> }>;

const conceptRepresentation =
'custom:(uuid,display,conceptClass:(uuid,display),answers:(uuid,display),conceptMappings:(conceptReferenceTerm:(conceptSource:(name),code)))';
'custom:(units,lowAbsolute,hiAbsolute,uuid,display,conceptClass:(uuid,display),answers:(uuid,display),conceptMappings:(conceptReferenceTerm:(conceptSource:(name),code)))';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ibacher when is it necessary to use hiCritical vs lowCritical?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of the values that aren't lowAbsolute and hiAbsolute are basically only for displaying concerning results (outside the normal range, but inside the critical range) or critical results (outside the critical range, but within the absolute range). Does that make sense? lowAbsolute and hiAbsolute should be rare and only in cases where the value can never exceed that range (e.g., SpO2 is a percent, so it's always between 0 and 100; heights and weights should never be a negative number, things like that).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But we can handle critical icons in a separate PR.


export function useConcepts(references: Set<string>): {
concepts: Array<OpenmrsResource> | undefined;
Expand Down
13 changes: 13 additions & 0 deletions src/hooks/useFormFieldsMeta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ export function useFormFieldsMeta(rawFormFields: FormField[], concepts: OpenmrsR
const matchingConcept = findConceptByReference(field.questionOptions.concept, concepts);
field.questionOptions.concept = matchingConcept ? matchingConcept.uuid : field.questionOptions.concept;
field.label = field.label ? field.label : matchingConcept?.display;

if (matchingConcept) {
const { lowAbsolute, hiAbsolute } = matchingConcept;

if (lowAbsolute !== undefined) {
field.questionOptions.min = lowAbsolute;
}

if (hiAbsolute !== undefined) {
field.questionOptions.max = hiAbsolute;
}
}

if (
codedTypes.includes(field.questionOptions.rendering) &&
!field.questionOptions.answers?.length &&
Expand Down
Loading