2023-08-25 23:21:51 +00:00
|
|
|
import { useRouter } from 'next/router'
|
|
|
|
import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
|
|
|
|
import Button from 'react-bootstrap/Button'
|
|
|
|
import Toast from 'react-bootstrap/Toast'
|
|
|
|
import ToastBody from 'react-bootstrap/ToastBody'
|
|
|
|
import ToastContainer from 'react-bootstrap/ToastContainer'
|
|
|
|
import styles from './toast.module.css'
|
|
|
|
|
|
|
|
const ToastContext = createContext(() => {})
|
|
|
|
|
2024-02-22 00:48:42 +00:00
|
|
|
export const TOAST_DEFAULT_DELAY_MS = 5000
|
|
|
|
|
2024-02-23 15:14:51 +00:00
|
|
|
const ensureFlow = (toasts, newToast) => {
|
|
|
|
const { flowId } = newToast
|
|
|
|
if (flowId) {
|
|
|
|
// replace previous toast with same flow id
|
|
|
|
const idx = toasts.findIndex(toast => toast.flowId === flowId)
|
|
|
|
if (idx === -1) return [...toasts, newToast]
|
|
|
|
return [
|
|
|
|
...toasts.slice(0, idx),
|
|
|
|
newToast,
|
|
|
|
...toasts.slice(idx + 1)
|
|
|
|
]
|
|
|
|
}
|
|
|
|
return [...toasts, newToast]
|
|
|
|
}
|
|
|
|
|
|
|
|
const mapHidden = ({ id, tag }) => toast => {
|
|
|
|
// mark every previous toast with same tag as hidden
|
|
|
|
if (toast.tag === tag && toast.id !== id) return { ...toast, hidden: true }
|
|
|
|
return toast
|
|
|
|
}
|
|
|
|
|
2023-08-25 23:21:51 +00:00
|
|
|
export const ToastProvider = ({ children }) => {
|
|
|
|
const router = useRouter()
|
|
|
|
const [toasts, setToasts] = useState([])
|
|
|
|
const toastId = useRef(0)
|
2024-02-01 13:18:42 +00:00
|
|
|
|
|
|
|
const removeToast = useCallback(({ id, onCancel, tag }) => {
|
|
|
|
setToasts(toasts => toasts.filter(toast => {
|
2024-02-18 19:33:32 +00:00
|
|
|
if (toast.id === id) {
|
|
|
|
// remove the toast with the passed id with no exceptions
|
|
|
|
return false
|
2024-02-01 13:18:42 +00:00
|
|
|
}
|
2024-02-18 19:33:32 +00:00
|
|
|
const sameTag = tag && tag === toast.tag
|
|
|
|
if (!sameTag) {
|
|
|
|
// don't touch toasts with different tags
|
|
|
|
return true
|
|
|
|
}
|
2024-02-22 00:48:42 +00:00
|
|
|
const toRemoveHasCancel = !!toast.onCancel || !!toast.onUndo
|
2024-02-18 19:33:32 +00:00
|
|
|
if (toRemoveHasCancel) {
|
|
|
|
// don't remove this toast so the user can decide to cancel this toast now
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
// remove toasts with same tag if they are not cancelable
|
|
|
|
return false
|
2024-02-01 13:18:42 +00:00
|
|
|
}))
|
2024-04-04 23:09:42 +00:00
|
|
|
}, [setToasts])
|
|
|
|
|
|
|
|
const dispatchToast = useCallback((toast) => {
|
|
|
|
toast = {
|
|
|
|
...toast,
|
|
|
|
createdAt: +new Date(),
|
|
|
|
id: toastId.current++
|
|
|
|
}
|
|
|
|
setToasts(toasts => ensureFlow(toasts, toast).map(mapHidden(toast)))
|
|
|
|
return () => removeToast(toast)
|
|
|
|
}, [setToasts, removeToast])
|
2023-10-04 18:47:09 +00:00
|
|
|
|
2024-03-24 18:30:03 +00:00
|
|
|
const endFlow = useCallback((flowId) => {
|
|
|
|
setToasts(toasts => toasts.filter(toast => toast.flowId !== flowId))
|
2024-04-04 23:09:42 +00:00
|
|
|
}, [setToasts])
|
2024-03-24 18:30:03 +00:00
|
|
|
|
2023-08-25 23:21:51 +00:00
|
|
|
const toaster = useMemo(() => ({
|
2024-02-01 13:18:42 +00:00
|
|
|
success: (body, options) => {
|
|
|
|
const toast = {
|
2023-08-25 23:21:51 +00:00
|
|
|
body,
|
|
|
|
variant: 'success',
|
|
|
|
autohide: true,
|
2024-02-22 00:48:42 +00:00
|
|
|
delay: TOAST_DEFAULT_DELAY_MS,
|
2024-02-01 13:50:51 +00:00
|
|
|
tag: options?.tag || body,
|
2024-02-01 13:18:42 +00:00
|
|
|
...options
|
|
|
|
}
|
|
|
|
return dispatchToast(toast)
|
2023-11-19 21:09:47 +00:00
|
|
|
},
|
2024-02-01 13:18:42 +00:00
|
|
|
warning: (body, options) => {
|
|
|
|
const toast = {
|
2023-11-19 21:09:47 +00:00
|
|
|
body,
|
|
|
|
variant: 'warning',
|
|
|
|
autohide: true,
|
2024-02-22 00:48:42 +00:00
|
|
|
delay: TOAST_DEFAULT_DELAY_MS,
|
2024-02-01 13:50:51 +00:00
|
|
|
tag: options?.tag || body,
|
2024-02-01 13:18:42 +00:00
|
|
|
...options
|
|
|
|
}
|
|
|
|
return dispatchToast(toast)
|
2023-08-25 23:21:51 +00:00
|
|
|
},
|
2024-02-01 13:18:42 +00:00
|
|
|
danger: (body, options) => {
|
|
|
|
const toast = {
|
2023-08-25 23:21:51 +00:00
|
|
|
body,
|
|
|
|
variant: 'danger',
|
2023-10-04 18:47:09 +00:00
|
|
|
autohide: false,
|
2024-02-01 13:50:51 +00:00
|
|
|
tag: options?.tag || body,
|
2024-02-01 13:18:42 +00:00
|
|
|
...options
|
2023-10-04 18:47:09 +00:00
|
|
|
}
|
2024-02-01 13:18:42 +00:00
|
|
|
return dispatchToast(toast)
|
2024-03-24 18:30:03 +00:00
|
|
|
},
|
|
|
|
endFlow
|
|
|
|
}), [dispatchToast, removeToast, endFlow])
|
2023-08-25 23:21:51 +00:00
|
|
|
|
2024-02-01 13:18:42 +00:00
|
|
|
// Only clear toasts with no cancel function on page navigation
|
|
|
|
// since navigation should not interfere with being able to cancel an action.
|
2023-08-25 23:21:51 +00:00
|
|
|
useEffect(() => {
|
2024-04-21 22:25:48 +00:00
|
|
|
const handleRouteChangeStart = () => setToasts(toasts => toasts.length > 0 ? toasts.filter(({ onCancel, onUndo, persistOnNavigate }) => onCancel || onUndo || persistOnNavigate) : toasts)
|
2023-08-25 23:21:51 +00:00
|
|
|
router.events.on('routeChangeStart', handleRouteChangeStart)
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
router.events.off('routeChangeStart', handleRouteChangeStart)
|
|
|
|
}
|
2024-04-04 23:09:42 +00:00
|
|
|
}, [router.events, setToasts])
|
2023-08-25 23:21:51 +00:00
|
|
|
|
2024-02-01 13:18:42 +00:00
|
|
|
// this function merges toasts with the same tag into one toast.
|
|
|
|
// for example: 3x 'zap pending' -> '(3) zap pending'
|
|
|
|
const tagReducer = (toasts, toast) => {
|
|
|
|
const { tag } = toast
|
|
|
|
|
|
|
|
// has tag?
|
|
|
|
if (!tag) return [...toasts, toast]
|
|
|
|
|
|
|
|
// existing tag?
|
|
|
|
const idx = toasts.findIndex(toast => toast.tag === tag)
|
|
|
|
if (idx === -1) return [...toasts, toast]
|
|
|
|
|
|
|
|
// merge toasts with same tag
|
|
|
|
const prevToast = toasts[idx]
|
2024-02-27 00:10:43 +00:00
|
|
|
let { amount } = prevToast
|
2024-02-01 13:18:42 +00:00
|
|
|
amount = amount ? amount + 1 : 2
|
2024-02-27 00:10:43 +00:00
|
|
|
const body = `(${amount}) ${toast.body}`
|
2024-02-01 13:18:42 +00:00
|
|
|
return [
|
|
|
|
...toasts.slice(0, idx),
|
2024-02-27 00:10:43 +00:00
|
|
|
{ ...toast, amount, body },
|
2024-02-01 13:18:42 +00:00
|
|
|
...toasts.slice(idx + 1)
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
// only show toast with highest ID of each tag
|
|
|
|
const visibleToasts = toasts.reduce(tagReducer, [])
|
|
|
|
|
2023-08-25 23:21:51 +00:00
|
|
|
return (
|
|
|
|
<ToastContext.Provider value={toaster}>
|
2023-08-31 02:16:47 +00:00
|
|
|
<ToastContainer className={`pb-3 pe-3 ${styles.toastContainer}`} position='bottom-end' containerPosition='fixed'>
|
2024-02-01 13:18:42 +00:00
|
|
|
{visibleToasts.map(toast => {
|
|
|
|
const textStyle = toast.variant === 'warning' ? 'text-dark' : ''
|
2024-02-22 00:48:42 +00:00
|
|
|
const onClose = () => {
|
|
|
|
toast.onUndo?.()
|
|
|
|
toast.onCancel?.()
|
|
|
|
toast.onClose?.()
|
|
|
|
removeToast(toast)
|
|
|
|
}
|
|
|
|
const buttonElement = toast.onUndo
|
|
|
|
? <div className={`${styles.toastUndo} ${textStyle}`}>undo</div>
|
|
|
|
: toast.onCancel
|
|
|
|
? <div className={`${styles.toastCancel} ${textStyle}`}>cancel</div>
|
|
|
|
: <div className={`${styles.toastClose} ${textStyle}`}>X</div>
|
2024-02-23 15:14:51 +00:00
|
|
|
// a toast is unhidden if it was hidden before since it now gets rendered
|
|
|
|
const unhidden = toast.hidden
|
|
|
|
// we only need to start the animation at a different timing when it was hidden by another toast before.
|
|
|
|
// if we don't do this, the animation for rerendered toasts skips ahead and toast delay and animation get out of sync.
|
2024-02-22 00:48:42 +00:00
|
|
|
const elapsed = (+new Date() - toast.createdAt)
|
2024-02-23 15:14:51 +00:00
|
|
|
const animationDelay = unhidden ? `-${elapsed}ms` : undefined
|
2024-02-24 20:33:08 +00:00
|
|
|
const animationDuration = `${toast.delay}ms`
|
2024-02-01 13:18:42 +00:00
|
|
|
return (
|
|
|
|
<Toast
|
|
|
|
key={toast.id} bg={toast.variant} show autohide={toast.autohide}
|
2024-02-15 22:49:54 +00:00
|
|
|
delay={toast.delay} className={`${styles.toast} ${styles[toast.variant]} ${textStyle}`} onClose={() => removeToast(toast)}
|
2024-02-01 13:18:42 +00:00
|
|
|
>
|
|
|
|
<ToastBody>
|
|
|
|
<div className='d-flex align-items-center'>
|
|
|
|
<div className='flex-grow-1'>{toast.body}</div>
|
|
|
|
<Button
|
|
|
|
variant={null}
|
|
|
|
className='p-0 ps-2'
|
|
|
|
aria-label='close'
|
2024-02-22 00:48:42 +00:00
|
|
|
onClick={onClose}
|
|
|
|
>{buttonElement}
|
2024-02-01 13:18:42 +00:00
|
|
|
</Button>
|
|
|
|
</div>
|
|
|
|
</ToastBody>
|
2024-02-24 20:33:08 +00:00
|
|
|
{toast.progressBar && <div className={`${styles.progressBar} ${styles[toast.variant]}`} style={{ animationDuration, animationDelay }} />}
|
2024-02-01 13:18:42 +00:00
|
|
|
</Toast>
|
|
|
|
)
|
|
|
|
})}
|
2023-08-25 23:21:51 +00:00
|
|
|
</ToastContainer>
|
|
|
|
{children}
|
|
|
|
</ToastContext.Provider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useToast = () => useContext(ToastContext)
|
2024-02-20 01:03:30 +00:00
|
|
|
|
|
|
|
export const withToastFlow = (toaster) => flowFn => {
|
|
|
|
const wrapper = async (...args) => {
|
|
|
|
const {
|
|
|
|
flowId,
|
|
|
|
type: t,
|
|
|
|
onPending,
|
2024-02-22 00:48:42 +00:00
|
|
|
pendingMessage,
|
2024-02-20 01:03:30 +00:00
|
|
|
onSuccess,
|
|
|
|
onCancel,
|
2024-02-22 00:48:42 +00:00
|
|
|
onError,
|
|
|
|
onUndo,
|
|
|
|
hideError,
|
|
|
|
hideSuccess,
|
2024-02-24 17:38:40 +00:00
|
|
|
skipToastFlow,
|
2024-02-24 20:33:08 +00:00
|
|
|
timeout,
|
2024-02-22 00:48:42 +00:00
|
|
|
...toastProps
|
2024-02-20 01:03:30 +00:00
|
|
|
} = flowFn(...args)
|
|
|
|
let canceled
|
2024-02-22 00:48:42 +00:00
|
|
|
|
2024-02-24 17:38:40 +00:00
|
|
|
if (skipToastFlow) return onPending()
|
|
|
|
|
2024-02-22 00:48:42 +00:00
|
|
|
toaster.warning(pendingMessage || `${t} pending`, {
|
2024-02-24 20:33:08 +00:00
|
|
|
progressBar: !!timeout,
|
|
|
|
delay: timeout || TOAST_DEFAULT_DELAY_MS,
|
2024-02-22 00:48:42 +00:00
|
|
|
onCancel: onCancel
|
|
|
|
? async () => {
|
|
|
|
try {
|
|
|
|
await onCancel()
|
|
|
|
canceled = true
|
|
|
|
toaster.warning(`${t} canceled`, { ...toastProps, flowId })
|
|
|
|
} catch (err) {
|
|
|
|
toaster.danger(`failed to cancel ${t}`, { ...toastProps, flowId })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
: undefined,
|
|
|
|
onUndo: onUndo
|
|
|
|
? async () => {
|
|
|
|
try {
|
|
|
|
await onUndo()
|
|
|
|
canceled = true
|
|
|
|
} catch (err) {
|
|
|
|
toaster.danger(`failed to undo ${t}`, { ...toastProps, flowId })
|
|
|
|
}
|
2024-02-20 01:03:30 +00:00
|
|
|
}
|
2024-02-22 00:48:42 +00:00
|
|
|
: undefined,
|
|
|
|
flowId,
|
|
|
|
...toastProps
|
2024-02-20 01:03:30 +00:00
|
|
|
})
|
|
|
|
try {
|
|
|
|
const ret = await onPending()
|
|
|
|
if (!canceled) {
|
2024-02-22 00:48:42 +00:00
|
|
|
if (hideSuccess) {
|
2024-03-24 18:30:03 +00:00
|
|
|
toaster.endFlow(flowId)
|
2024-02-22 00:48:42 +00:00
|
|
|
} else {
|
|
|
|
toaster.success(`${t} successful`, { ...toastProps, flowId })
|
|
|
|
}
|
2024-02-20 01:03:30 +00:00
|
|
|
await onSuccess?.()
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
} catch (err) {
|
|
|
|
// ignore errors if canceled since they might be caused by cancellation
|
|
|
|
if (canceled) return
|
|
|
|
const reason = err?.message?.toString().toLowerCase() || 'unknown reason'
|
2024-02-22 00:48:42 +00:00
|
|
|
if (hideError) {
|
2024-03-24 18:30:03 +00:00
|
|
|
toaster.endFlow(flowId)
|
2024-02-22 00:48:42 +00:00
|
|
|
} else {
|
|
|
|
toaster.danger(`${t} failed: ${reason}`, { ...toastProps, flowId })
|
|
|
|
}
|
2024-02-20 01:03:30 +00:00
|
|
|
await onError?.()
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return wrapper
|
|
|
|
}
|