|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import { rankWith, ControlProps, uiTypeIs } from '@jsonforms/core'; |
| 3 | +import { withJsonFormsControlProps } from '@jsonforms/react'; |
| 4 | +import { |
| 5 | + alpha, |
| 6 | + DetailInputWithLabelRow, |
| 7 | + Theme, |
| 8 | + useTranslation, |
| 9 | +} from '@openmsupply-client/common'; |
| 10 | +import { FORM_LABEL_WIDTH, DefaultFormRowSx } from '../styleConstants'; |
| 11 | +import { FlatButton } from '@common/components'; |
| 12 | +import { SortAscIcon, SortDescIcon } from '@common/icons'; |
| 13 | + |
| 14 | +export const SortToggleTester = rankWith(10, uiTypeIs('SortToggle')); |
| 15 | + |
| 16 | +type SortDirection = 'asc' | 'desc' | null; |
| 17 | + |
| 18 | +const UIComponent = (props: ControlProps) => { |
| 19 | + const { handleChange, label, path, enabled } = props; |
| 20 | + const t = useTranslation(); |
| 21 | + const [sortDirection, setSortDirection] = useState<SortDirection>(); |
| 22 | + |
| 23 | + if (!props.visible) { |
| 24 | + return null; |
| 25 | + } |
| 26 | + |
| 27 | + const selectedStyles = (theme: Theme) => ({ |
| 28 | + fontWeight: 'bold', |
| 29 | + backgroundColor: alpha(theme.palette.primary.main, 0.3), |
| 30 | + '&:hover': { |
| 31 | + backgroundColor: alpha(theme.palette.primary.main, 0.3), |
| 32 | + }, |
| 33 | + }); |
| 34 | + |
| 35 | + const getSelectedSx = (value: SortDirection) => |
| 36 | + sortDirection === value ? selectedStyles : undefined; |
| 37 | + |
| 38 | + const handleClick = (value: SortDirection) => { |
| 39 | + const newValue = sortDirection === value ? null : value; |
| 40 | + setSortDirection(newValue); |
| 41 | + handleChange(path, newValue); |
| 42 | + }; |
| 43 | + |
| 44 | + return ( |
| 45 | + <DetailInputWithLabelRow |
| 46 | + label={label} |
| 47 | + DisabledInput={!enabled} |
| 48 | + labelWidthPercentage={FORM_LABEL_WIDTH} |
| 49 | + sx={DefaultFormRowSx} |
| 50 | + Input={ |
| 51 | + <> |
| 52 | + <FlatButton |
| 53 | + label={t('report.ascending')} |
| 54 | + onClick={() => handleClick('asc')} |
| 55 | + startIcon={<SortAscIcon />} |
| 56 | + sx={[getSelectedSx('asc') || {}, { borderRadius: 24 }]} |
| 57 | + /> |
| 58 | + <FlatButton |
| 59 | + label={t('report.descending')} |
| 60 | + onClick={() => handleClick('desc')} |
| 61 | + startIcon={<SortDescIcon />} |
| 62 | + sx={[getSelectedSx('desc') || {}, { borderRadius: 24 }]} |
| 63 | + /> |
| 64 | + </> |
| 65 | + } |
| 66 | + /> |
| 67 | + ); |
| 68 | +}; |
| 69 | + |
| 70 | +export const SortToggle = withJsonFormsControlProps(UIComponent); |
0 commit comments