|
| 1 | +/** |
| 2 | + * Copyright 2017-present, The Visdom Authors |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + * |
| 8 | + */ |
| 9 | + |
| 10 | +import React, { useCallback, useEffect, useRef, useState } from 'react'; |
| 11 | + |
| 12 | +const EXIT_ANIMATION_MS = 200; |
| 13 | + |
| 14 | +const Toast = ({ |
| 15 | + message, |
| 16 | + type = 'info', |
| 17 | + duration = 4000, |
| 18 | + shape = 'rect', |
| 19 | + onDismiss, |
| 20 | +}) => { |
| 21 | + const [isLeaving, setIsLeaving] = useState(false); |
| 22 | + const isLeavingRef = useRef(false); |
| 23 | + const dismissTimerRef = useRef(null); |
| 24 | + const exitTimerRef = useRef(null); |
| 25 | + const onDismissRef = useRef(onDismiss); |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + onDismissRef.current = onDismiss; |
| 29 | + }, [onDismiss]); |
| 30 | + |
| 31 | + const startExit = useCallback(() => { |
| 32 | + if (isLeavingRef.current) return; |
| 33 | + isLeavingRef.current = true; |
| 34 | + setIsLeaving(true); |
| 35 | + exitTimerRef.current = setTimeout( |
| 36 | + () => onDismissRef.current(), |
| 37 | + EXIT_ANIMATION_MS |
| 38 | + ); |
| 39 | + }, []); |
| 40 | + |
| 41 | + useEffect(() => { |
| 42 | + if (duration > 0) { |
| 43 | + dismissTimerRef.current = setTimeout(startExit, duration); |
| 44 | + } |
| 45 | + return () => { |
| 46 | + clearTimeout(dismissTimerRef.current); |
| 47 | + clearTimeout(exitTimerRef.current); |
| 48 | + }; |
| 49 | + }, [duration, startExit]); |
| 50 | + |
| 51 | + const isPill = shape === 'pill'; |
| 52 | + |
| 53 | + const className = [ |
| 54 | + 'visdom-toast', |
| 55 | + `visdom-toast-${type}`, |
| 56 | + isPill ? 'visdom-toast-pill' : '', |
| 57 | + isLeaving ? 'visdom-toast-leaving' : '', |
| 58 | + ] |
| 59 | + .filter(Boolean) |
| 60 | + .join(' '); |
| 61 | + |
| 62 | + return ( |
| 63 | + <div className={className} role="alert"> |
| 64 | + <span className="visdom-toast-message">{message}</span> |
| 65 | + |
| 66 | + {!isPill && ( |
| 67 | + <button |
| 68 | + aria-label="Dismiss notification" |
| 69 | + className="visdom-toast-close" |
| 70 | + onClick={startExit} |
| 71 | + type="button" |
| 72 | + > |
| 73 | + × |
| 74 | + </button> |
| 75 | + )} |
| 76 | + |
| 77 | + {!isPill && duration > 0 && !isLeaving && ( |
| 78 | + <div |
| 79 | + className="visdom-toast-progress" |
| 80 | + style={{ animationDuration: `${duration}ms` }} |
| 81 | + /> |
| 82 | + )} |
| 83 | + </div> |
| 84 | + ); |
| 85 | +}; |
| 86 | + |
| 87 | +export default Toast; |
0 commit comments