|
| 1 | +import i18n from '@dhis2/d2-i18n' |
| 2 | +import { |
| 3 | + Field, |
| 4 | + OrganisationUnitTree, |
| 5 | + OrganisationUnitTreeProps, |
| 6 | +} from '@dhis2/ui' |
| 7 | +import React from 'react' |
| 8 | +import { useField } from 'react-final-form' |
| 9 | +import { useCurrentUserRootOrgUnits } from '../../../lib/user/currentUserStore' |
| 10 | + |
| 11 | +type OrganisationUnitFieldProps = { |
| 12 | + name?: string |
| 13 | +} |
| 14 | + |
| 15 | +type OrganisationUnitFormValue = { |
| 16 | + id: string |
| 17 | + path: string |
| 18 | + displayName: string |
| 19 | +} |
| 20 | + |
| 21 | +export const OrganisationUnitField = ({ name }: OrganisationUnitFieldProps) => { |
| 22 | + const { input, meta } = useField< |
| 23 | + OrganisationUnitFormValue[], |
| 24 | + HTMLElement, |
| 25 | + OrganisationUnitFormValue[] |
| 26 | + >(name ?? 'organisationUnits') |
| 27 | + |
| 28 | + const roots = useCurrentUserRootOrgUnits() |
| 29 | + |
| 30 | + const rootIds = roots.map((ou) => ou.id) |
| 31 | + |
| 32 | + const handleChange: OrganisationUnitTreeProps['onChange'] = ({ |
| 33 | + selected, |
| 34 | + displayName, |
| 35 | + id, |
| 36 | + path, |
| 37 | + }) => { |
| 38 | + const prevSelected = new Map(input.value.map((ou) => [ou.path, ou])) |
| 39 | + const newSelected = selected.map((selectedPath) => { |
| 40 | + const prev = prevSelected.get(selectedPath) |
| 41 | + return prev ?? { id, path, displayName } |
| 42 | + }) |
| 43 | + |
| 44 | + input.onChange(newSelected) |
| 45 | + input.onBlur() |
| 46 | + } |
| 47 | + |
| 48 | + const selectedPaths = input.value?.map((ou) => ou.path) ?? [] |
| 49 | + |
| 50 | + return ( |
| 51 | + <Field |
| 52 | + label={i18n.t('Select organisation units')} |
| 53 | + error={meta.touched && meta.error} |
| 54 | + validationText={meta.touched && meta.error} |
| 55 | + > |
| 56 | + <OrganisationUnitTree |
| 57 | + roots={rootIds} |
| 58 | + onChange={handleChange} |
| 59 | + selected={selectedPaths} |
| 60 | + initiallyExpanded={rootIds} |
| 61 | + /> |
| 62 | + </Field> |
| 63 | + ) |
| 64 | +} |
0 commit comments