|
| 1 | +import { useMemo } from 'react'; |
| 2 | +import { useTranslation } from '@ifrc-go/ui/hooks'; |
| 3 | +import { isNotDefined } from '@togglecorp/fujs'; |
| 4 | + |
| 5 | +import MultiSelectOutput from '../MultiSelectOutput'; |
| 6 | + |
| 7 | +import i18n from './i18n.json'; |
| 8 | +import styles from './styles.module.css'; |
| 9 | + |
| 10 | +interface Props<VALUE, OPTION> { |
| 11 | + value: VALUE[] | undefined; |
| 12 | + oldValue: VALUE[] | undefined; |
| 13 | + options: OPTION[] | undefined; |
| 14 | + keySelector: (datum: OPTION) => VALUE; |
| 15 | + labelSelector: (datum: OPTION) => React.ReactNode; |
| 16 | + diffContainerClassName?: string; |
| 17 | + children: React.ReactNode; |
| 18 | + enabled: boolean; |
| 19 | + showOnlyDiff?: boolean; |
| 20 | + showPreviousValue?: boolean; |
| 21 | +} |
| 22 | + |
| 23 | +function MultiSelectDiffWrapper< |
| 24 | + VALUE extends number | string, OPTION |
| 25 | +>( |
| 26 | + props: Props<VALUE, OPTION>, |
| 27 | +) { |
| 28 | + const { |
| 29 | + diffContainerClassName, |
| 30 | + oldValue, |
| 31 | + value, |
| 32 | + children, |
| 33 | + enabled = false, |
| 34 | + showOnlyDiff, |
| 35 | + showPreviousValue, |
| 36 | + options, |
| 37 | + keySelector, |
| 38 | + labelSelector, |
| 39 | + } = props; |
| 40 | + |
| 41 | + const strings = useTranslation(i18n); |
| 42 | + |
| 43 | + const hasChanged = useMemo(() => { |
| 44 | + // NOTE: we consider `null` and `undefined` as same for |
| 45 | + // this scenario |
| 46 | + if (isNotDefined(oldValue) && isNotDefined(value)) { |
| 47 | + return false; |
| 48 | + } |
| 49 | + |
| 50 | + return JSON.stringify(oldValue) !== JSON.stringify(value); |
| 51 | + }, [oldValue, value]); |
| 52 | + |
| 53 | + if (!enabled) { |
| 54 | + return children; |
| 55 | + } |
| 56 | + |
| 57 | + if (!hasChanged && showOnlyDiff) { |
| 58 | + return null; |
| 59 | + } |
| 60 | + |
| 61 | + if (!hasChanged) { |
| 62 | + return children; |
| 63 | + } |
| 64 | + |
| 65 | + return ( |
| 66 | + <div className={diffContainerClassName}> |
| 67 | + {children} |
| 68 | + {showPreviousValue |
| 69 | + && ( |
| 70 | + <MultiSelectOutput |
| 71 | + className={styles.previousValue} |
| 72 | + label={strings.multiSelectPreviousValueLabel} |
| 73 | + value={oldValue} |
| 74 | + options={options} |
| 75 | + keySelector={keySelector} |
| 76 | + labelSelector={labelSelector} |
| 77 | + /> |
| 78 | + )} |
| 79 | + </div> |
| 80 | + ); |
| 81 | +} |
| 82 | + |
| 83 | +export default MultiSelectDiffWrapper; |
0 commit comments