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
29 changes: 28 additions & 1 deletion src/components/inputs/number/number.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,28 @@ 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';
import { Concept } from '@openmrs/esm-framework';
Copy link
Member

Choose a reason for hiding this comment

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

Please see our extension documentation on how imports are to be ordered.

Copy link
Author

Choose a reason for hiding this comment

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

moved useTranslation up as well



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

const { hiAbsolute, lowAbsolute, units } = concept;
const displayUnits = units ? ` ${units}` : '';
const hasLowerLimit = lowAbsolute != null;
const hasUpperLimit = hiAbsolute != null;
Copy link
Member

Choose a reason for hiding this comment

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

Again !==. But I think here it's preferential to just use isNil() from lodash.


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();
Expand Down Expand Up @@ -61,7 +83,12 @@ const NumberField: React.FC<FormFieldInputProps> = ({ field, value, errors, warn
id={field.id}
invalid={errors.length > 0}
invalidText={errors[0]?.message}
label={<FieldLabel field={field} />}
label={<FieldLabel field={field} customLabel={t('{{fieldDescription}} {{unitsAndRange}}',
Copy link
Member

Choose a reason for hiding this comment

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

We should have a real key here with this interpolation as the defaultValue.

Copy link
Author

Choose a reason for hiding this comment

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

thanks again for i18n help, I changed the test too to t: (key, defaultValueOrOptions, options), hopefully that's correct now that there's a key and default value but not sure

{
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
102 changes: 102 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,17 @@ 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, options) => {
if (options && 'fieldDescription' in options) {
return `${options.fieldDescription} ${options.unitsAndRange || ''}`.trim();
Copy link
Member

Choose a reason for hiding this comment

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

Since extractFieldUnitsAndRange() always returns a string:

Suggested change
return `${options.fieldDescription} ${options.unitsAndRange || ''}`.trim();
return `${options.fieldDescription} ${options.unitsAndRange}`.trim();

}
return key;
}
})
}));

jest.mock('src/provider/form-provider', () => ({
useFormProviderContext: jest.fn(),
}));
Expand All @@ -22,6 +33,53 @@ 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 renderNumberField = async (props) => {
await act(() => render(<NumberField {...props} />));
};
Expand Down Expand Up @@ -104,4 +162,48 @@ 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();
});
});
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
14 changes: 14 additions & 0 deletions src/hooks/useFormFieldsMeta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@ 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) {
if (matchingConcept.lowAbsolute != undefined && matchingConcept.hiAbsolute != undefined) {
Copy link
Member

Choose a reason for hiding this comment

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

It's always better to use typeof x !== 'undefined', though this kind of works, but only because SWC will re-write the undefineds here to void 0. In any case, please use exact comparisons (!== and ===).

Copy link
Member

Choose a reason for hiding this comment

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

Also, please just implement @samuelmale's suggestion. It's much cleaner.

Copy link
Author

Choose a reason for hiding this comment

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

applied suggestion @samuelmale ty

field.questionOptions.min = matchingConcept.lowAbsolute;
field.questionOptions.max = matchingConcept.hiAbsolute;
}
else if (matchingConcept.lowAbsolute != undefined) {
field.questionOptions.min = matchingConcept.lowAbsolute;
}
else if (matchingConcept.hiAbsolute != undefined) {
field.questionOptions.max = matchingConcept.hiAbsolute;
}
}

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