UNPKG

2.91 kBJavaScriptView Raw
1import _extends from "@babel/runtime/helpers/esm/extends";
2import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
3import React, { useEffect, useMemo, useRef, useCallback } from 'react';
4import classNames from 'classnames';
5import useTimeout from '@restart/hooks/useTimeout';
6import Fade from './Fade';
7import ToastHeader from './ToastHeader';
8import ToastBody from './ToastBody';
9import { useBootstrapPrefix } from './ThemeProvider';
10import ToastContext from './ToastContext';
11var Toast = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
12 var bsPrefix = _ref.bsPrefix,
13 className = _ref.className,
14 children = _ref.children,
15 _ref$transition = _ref.transition,
16 Transition = _ref$transition === void 0 ? Fade : _ref$transition,
17 _ref$show = _ref.show,
18 show = _ref$show === void 0 ? true : _ref$show,
19 _ref$animation = _ref.animation,
20 animation = _ref$animation === void 0 ? true : _ref$animation,
21 _ref$delay = _ref.delay,
22 delay = _ref$delay === void 0 ? 3000 : _ref$delay,
23 _ref$autohide = _ref.autohide,
24 autohide = _ref$autohide === void 0 ? false : _ref$autohide,
25 onClose = _ref.onClose,
26 props = _objectWithoutPropertiesLoose(_ref, ["bsPrefix", "className", "children", "transition", "show", "animation", "delay", "autohide", "onClose"]);
27
28 bsPrefix = useBootstrapPrefix(bsPrefix, 'toast'); // We use refs for these, because we don't want to restart the autohide
29 // timer in case these values change.
30
31 var delayRef = useRef(delay);
32 var onCloseRef = useRef(onClose);
33 useEffect(function () {
34 delayRef.current = delay;
35 onCloseRef.current = onClose;
36 }, [delay, onClose]);
37 var autohideTimeout = useTimeout();
38 var autohideToast = !!(autohide && show);
39 var autohideFunc = useCallback(function () {
40 if (autohideToast) {
41 onCloseRef.current == null ? void 0 : onCloseRef.current();
42 }
43 }, [autohideToast]);
44 useEffect(function () {
45 // Only reset timer if show or autohide changes.
46 autohideTimeout.set(autohideFunc, delayRef.current);
47 }, [autohideTimeout, autohideFunc]);
48 var toastContext = useMemo(function () {
49 return {
50 onClose: onClose
51 };
52 }, [onClose]);
53 var hasAnimation = !!(Transition && animation);
54 var toast = /*#__PURE__*/React.createElement("div", _extends({}, props, {
55 ref: ref,
56 className: classNames(bsPrefix, className, !hasAnimation && (show ? 'show' : 'hide')),
57 role: "alert",
58 "aria-live": "assertive",
59 "aria-atomic": "true"
60 }), children);
61 return /*#__PURE__*/React.createElement(ToastContext.Provider, {
62 value: toastContext
63 }, hasAnimation && Transition ? /*#__PURE__*/React.createElement(Transition, {
64 in: show,
65 unmountOnExit: true
66 }, toast) : toast);
67});
68Toast.displayName = 'Toast';
69export default Object.assign(Toast, {
70 Body: ToastBody,
71 Header: ToastHeader
72});
\No newline at end of file