overleaf/services/web/frontend/js/features/ui/components/bootstrap-3/toast.tsx
Mathias Jakobsen cb72799fff [web] Add toast notifications to editor (#21567)
GitOrigin-RevId: 7f7ab83d4615f564c0e79bc2a05ca6cb9e5239fd
2024-11-11 09:05:12 +00:00

51 lines
1 KiB
TypeScript

import classNames from 'classnames'
import { FC, useCallback, useEffect, useRef } from 'react'
type ToastProps = {
onClose?: () => void
onExited?: () => void
autohide?: boolean
delay?: number
show: boolean
className?: string
}
export const Toast: FC<ToastProps> = ({
children,
delay = 5000,
onClose,
onExited,
autohide,
show,
className,
}) => {
const delayRef = useRef(delay)
const onCloseRef = useRef(onClose)
const onExitedRef = useRef(onExited)
const shouldAutoHide = Boolean(autohide && show)
const handleTimeout = useCallback(() => {
if (shouldAutoHide) {
onCloseRef.current?.()
onExitedRef.current?.()
}
}, [shouldAutoHide])
useEffect(() => {
const timeout = window.setTimeout(handleTimeout, delayRef.current)
return () => window.clearTimeout(timeout)
}, [handleTimeout])
if (!show) {
return null
}
return (
<div
className={classNames('toast', show ? 'show' : 'hide', className)}
aria-live="assertive"
role="alert"
>
{children}
</div>
)
}