UNPKG

@trellixio/roaster-coffee

Version:
40 lines (39 loc) 1.87 kB
import * as React from 'react'; import { Transition, TransitionGroup } from 'react-transition-group'; import { classNames, guid, useDidUpdate, useForceUpdate } from '@/utils'; import { useToastsEvents } from '../events'; import { ToastsContext } from '../Toasts.context'; import { ToastsContainer } from '../ToastsContainer'; import useToastsState from './useToastsState/useToastsState'; export function ToastsProvider({ className, autoClose = 4000, limit = 5, children }) { const forceUpdate = useForceUpdate(); const refs = React.useRef({}); const previousLength = React.useRef(0); const { toasts, queue, showToast, updateToast, hideToast, clean, cleanQueue } = useToastsState({ limit }); useDidUpdate(() => { if (toasts.length > previousLength.current) { setTimeout(() => forceUpdate(), 0); } previousLength.current = toasts.length; }, [toasts]); useToastsEvents({ show: showToast, hide: hideToast, update: updateToast, clean, cleanQueue, }); const items = toasts.map((toast) => { // eslint-disable-next-line no-param-reassign toast.id = toast.id || guid(); return (React.createElement(Transition, { key: toast.id, nodeRef: { current: refs.current[toast.id] } }, () => (React.createElement(ToastsContainer, { innerRef: (node) => { refs.current[toast.id] = node; }, toast: toast, onHide: hideToast, autoClose: autoClose })))); }); const contextValue = React.useMemo(() => ({ toasts, queue }), []); return (React.createElement(ToastsContext.Provider, { value: contextValue }, React.createElement("section", { className: classNames('toasts', className) }, React.createElement(TransitionGroup, null, items)), children)); } ToastsProvider.displayName = 'ToastsProvider';