|
| 1 | +import { ReactNode, useCallback } from 'react'; |
| 2 | +import { makeStyles, createStyles, Dialog, DialogActions, DialogContent, DialogProps } from '@material-ui/core'; |
| 3 | +import { AppButton } from '..'; |
| 4 | +import { AppDialogTitle } from './components'; |
| 5 | +import { ColorName, dialogStyles } from '../../utils/style'; |
| 6 | + |
| 7 | +const useStyles = makeStyles((theme) => |
| 8 | + createStyles({ |
| 9 | + root: {}, |
| 10 | + ...dialogStyles(theme), |
| 11 | + }) |
| 12 | +); |
| 13 | + |
| 14 | +/** |
| 15 | + * Shows generic "Common" dialog |
| 16 | + * @param {function} props.onConfirm - event for Confirm button, called as onConfirm(data) |
| 17 | + * @param {function} props.onClose - event for Close and Cancel buttons and the backdrop |
| 18 | + */ |
| 19 | +interface Props extends DialogProps { |
| 20 | + data?: unknown; |
| 21 | + title?: string; |
| 22 | + text?: string; |
| 23 | + body?: ReactNode; |
| 24 | + hideCancelButton?: boolean; |
| 25 | + confirmButtonText?: string; |
| 26 | + confirmButtonColor?: ColorName; |
| 27 | + onConfirm?: (data: unknown) => void; |
| 28 | + onClose?: (event: {}) => void; |
| 29 | +} |
| 30 | +const CommonDialog: React.FC<Props> = ({ |
| 31 | + open = false, // Don't show dialog by default |
| 32 | + data, // optional data passed to onConfirm callback |
| 33 | + title = 'Missing title...', |
| 34 | + text = 'Text is missing...', |
| 35 | + body, // JSX to render instead of .text |
| 36 | + hideCancelButton = false, |
| 37 | + confirmButtonText = 'Confirm', |
| 38 | + confirmButtonColor = 'primary', |
| 39 | + onConfirm, |
| 40 | + onClose, |
| 41 | + ...props |
| 42 | +}) => { |
| 43 | + const classes = useStyles(); |
| 44 | + |
| 45 | + const handleOnConfirm = useCallback(() => { |
| 46 | + if (onConfirm && typeof onConfirm === 'function') { |
| 47 | + onConfirm(data); |
| 48 | + } |
| 49 | + }, [data, onConfirm]); |
| 50 | + |
| 51 | + return ( |
| 52 | + <Dialog |
| 53 | + className={classes.root} |
| 54 | + classes={{ paper: classes.paper }} |
| 55 | + open={open} |
| 56 | + onClose={onClose} |
| 57 | + aria-labelledby="form-dialog-title" |
| 58 | + {...props} |
| 59 | + > |
| 60 | + <AppDialogTitle id="form-dialog-title" onClose={onClose}> |
| 61 | + {title} |
| 62 | + </AppDialogTitle> |
| 63 | + <DialogContent>{body || text}</DialogContent> |
| 64 | + <DialogActions className={classes.actions}> |
| 65 | + {!hideCancelButton && <AppButton onClick={onClose}>Cancel</AppButton>} |
| 66 | + <AppButton onClick={handleOnConfirm} color={confirmButtonColor} mr={0}> |
| 67 | + {confirmButtonText} |
| 68 | + </AppButton> |
| 69 | + </DialogActions> |
| 70 | + </Dialog> |
| 71 | + ); |
| 72 | +}; |
| 73 | + |
| 74 | +export default CommonDialog; |
0 commit comments