import React, { ReactElement, useCallback, useRef } from 'react'; import { ToastMethods, ToastProps } from './interface'; import ToastRoot from './JSToast'; type ToastRefObj = { current: ToastMethods | null; }; let refs: ToastRefObj[] = []; function addNewRef(newRef: ToastMethods) { refs.push({ current: newRef, }); } function removeOldRef(oldRef: ToastMethods | null) { refs = refs.filter((r) => r.current !== oldRef); } export function ToastProvider(props: ToastProps): ReactElement { const toastRef = useRef(null); const setRef = useCallback((ref: ToastMethods | null) => { if (ref) { toastRef.current = ref; addNewRef(ref); } else { removeOldRef(toastRef.current); } }, []); return ; } function getRef() { const reversePriority = [...refs].reverse(); const activeRef = reversePriority.find((ref) => ref?.current !== null); if (!activeRef) { return null; } return activeRef.current; } export function Toast(params: ToastProps | string) { const ref = getRef(); ref?.show(params); return { setMessage: (st: string) => ref?.setMessage(st), close: () => ref?.close(), }; } export function RemoveToast() { const ref = getRef(); ref?.close(); }