index.tsx
75 lines
| 1 | import {MouseEventHandler, useEffect} from 'react'; |
| 2 | import cx from 'classnames'; |
| 3 | import {__} from '@wordpress/i18n'; |
| 4 | import {ExitIcon, CheckCircle, AlertTriangle} from '@givewp/components/AdminUI/Icons'; |
| 5 | import styles from './style.module.scss'; |
| 6 | |
| 7 | export interface ToastProps { |
| 8 | children: string | JSX.Element | JSX.Element[]; |
| 9 | handleClose: MouseEventHandler; |
| 10 | type?: 'info' | 'error' | 'warning' | 'success'; |
| 11 | show?: boolean; |
| 12 | position?: 'top-right' | 'bottom-right' | 'top-left' | 'bottom-left'; |
| 13 | autoClose?: number; |
| 14 | showCloseIcon?: boolean; |
| 15 | } |
| 16 | |
| 17 | export default function Toast({children, type, handleClose, position = 'top-right', show = true, autoClose = 0, showCloseIcon = true}: ToastProps) { |
| 18 | const getIcon = type => { |
| 19 | switch (type) { |
| 20 | case 'info': |
| 21 | return <></> |
| 22 | case 'error': |
| 23 | return <></> |
| 24 | case 'warning': |
| 25 | return <AlertTriangle /> |
| 26 | case 'success': |
| 27 | return <CheckCircle /> |
| 28 | } |
| 29 | |
| 30 | return null; |
| 31 | } |
| 32 | |
| 33 | useEffect(() => { |
| 34 | if(autoClose) { |
| 35 | setTimeout(handleClose, autoClose) |
| 36 | } |
| 37 | }, []); |
| 38 | |
| 39 | if (!show) return null; |
| 40 | |
| 41 | return ( |
| 42 | <div className={cx(styles.toastContainer, { |
| 43 | [styles.topLeft]: position === 'top-left', |
| 44 | [styles.topRight]: position === 'top-right', |
| 45 | [styles.bottomLeft]: position === 'bottom-left', |
| 46 | [styles.bottomRight]: position === 'bottom-right', |
| 47 | [styles.success]: type === 'success', |
| 48 | [styles.warning]: type === 'warning', |
| 49 | [styles.error]: type === 'error', |
| 50 | [styles.info]: type === 'info', |
| 51 | })}> |
| 52 | {type && ( |
| 53 | <div className={styles.icon}> |
| 54 | {getIcon(type)} |
| 55 | </div> |
| 56 | )} |
| 57 | <div className={styles.content}> |
| 58 | {children} |
| 59 | </div> |
| 60 | {showCloseIcon && handleClose && ( |
| 61 | <div> |
| 62 | <button |
| 63 | aria-label={__('Close', 'give')} |
| 64 | className={styles.close} |
| 65 | onClick={handleClose} |
| 66 | > |
| 67 | <ExitIcon aria-label={__('Close icon', 'give')} className={styles.closeIconSize} /> |
| 68 | </button> |
| 69 | </div> |
| 70 | )} |
| 71 | </div> |
| 72 | ) |
| 73 | } |
| 74 | |
| 75 |