UNPKG

@madeja-studio/telar

Version:

UI component library by Madeja Studio

62 lines (61 loc) 1.94 kB
"use strict"; import { createContext, forwardRef, useCallback, useContext, useRef, useState } from 'react'; import { Overlay } from "../Overlay/index.js"; import { Toast } from "./Toast.js"; import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; const ToastContext = /*#__PURE__*/createContext({}); const TIMEOUT_DELAY = 5000; const CurrentToast = /*#__PURE__*/forwardRef(({ config }, ref) => { /** We separate the key from the other props because React doesn't like passing * the key spread. It throws the following error if done differently: * "Warning: A props object containing a "key" prop is being spread into JSX" */ const { key, ...props } = config; return /*#__PURE__*/_jsx(Overlay, { children: /*#__PURE__*/_jsx(Toast, { ref: ref, ...props }, key) }); }); export const ToastContextProvider = ({ children }) => { const [nextToastId, setNextToastId] = useState(0); const [queue, setQueue] = useState([]); const currentToastRef = useRef(null); const currentToast = queue[0]; const closeLastToast = useCallback(async () => { if (!currentToastRef.current) return; await currentToastRef.current?.close(); setQueue(q => q.slice(1)); }, []); const showToast = useCallback(config => { const timeoutId = setTimeout(closeLastToast, TIMEOUT_DELAY); setQueue(q => [...q, { ...config, key: `toast_${nextToastId}`, onClose: async () => { clearTimeout(timeoutId); await closeLastToast(); } }]); setNextToastId(id => id + 1); }, [nextToastId, closeLastToast]); return /*#__PURE__*/_jsxs(ToastContext.Provider, { value: { showToast }, children: [children, currentToast && /*#__PURE__*/_jsx(CurrentToast, { config: currentToast, ref: currentToastRef })] }); }; export const useToast = () => useContext(ToastContext); //# sourceMappingURL=ToastContextProvider.js.map