Created
January 19, 2021 11:10
-
-
Save omidgfx/d4890e9a61f12e7dc847b0b87a46c5bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function useToast(defaultPosition = 'bottomStart') { | |
const s = useSnackbar(); | |
const pos = (vertical, horizontal) => ({vertical, horizontal}); | |
const allPlaces = { | |
topStart : pos('top', 'left'), | |
topCenter : pos('top', 'center'), | |
topEnd : pos('top', 'right'), | |
bottomStart : pos('bottom', 'left'), | |
bottomCenter: pos('bottom', 'center'), | |
bottomEnd : pos('bottom', 'right'), | |
}; | |
const makePosition = (place) => { | |
return allPlaces?.[place] ?? allPlaces.bottomEnd; | |
} | |
const _toast = (message, variant, position, options, progress) => { | |
if (progress) { | |
message = <span><CircularProgress size={11} color='inherit'/><ONbsp/><ONbsp/>{message}</span>; | |
options = { | |
...options, | |
persist: true, | |
} | |
} else { | |
options = { | |
...options, | |
onClick: () => { | |
s.closeSnackbar(key) | |
}, | |
} | |
} | |
const key = s.enqueueSnackbar(message, { | |
variant : variant, | |
anchorOrigin : makePosition(position), | |
disableWindowBlurListener: true, | |
TransitionComponent : Grow, | |
...options | |
}); | |
return () => s.closeSnackbar(key); | |
} | |
const riseErrorToast = (message, position = defaultPosition || null, ...options) => _toast(message, 'error', position, options); | |
const riseWarningToast = (message, position = defaultPosition || null, ...options) => _toast(message, 'warning', position, options); | |
const riseInfoToast = (message, position = defaultPosition || null, ...options) => _toast(message, 'info', position, options); | |
const riseSuccessToast = (message, position = defaultPosition || null, ...options) => _toast(message, 'success', position, options); | |
const riseToast = (message, position = defaultPosition || null, ...options) => _toast(message, 'default', position, options); | |
const riseIndeterminate = (message, position = defaultPosition || null, ...options) => _toast(message, 'default', position, options, true); | |
return {riseToast, riseErrorToast, riseWarningToast, riseInfoToast, riseSuccessToast, riseIndeterminate}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment