UNPKG

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