UNPKG

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