import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react'; import { ToastVariant, Toast } from '../components/leafygreen'; import { css } from '@leafygreen-ui/emotion'; export { ToastVariant }; type ToastProperties = { title?: React.ReactNode; body: React.ReactNode; variant: ToastVariant; progress?: number; timeout?: number; }; interface ToastActions { openToast: (id: string, toastProperties: ToastProperties) => void; closeToast: (id: string) => void; } class GlobalToastState implements ToastActions { private timeouts = new Map>(); private toasts = new Map(); onToastsChange: (toasts: [string, ToastProperties][]) => void = () => { /**/ }; openToast(id: string, toastProperties: ToastProperties): void { this.clearTimeout(id); this.toasts.set(id, toastProperties); if (toastProperties.timeout) { this.timeouts.set( id, setTimeout(() => { this.closeToast(id); }, toastProperties.timeout) ); } this.onToastsChange(Array.from(this.toasts.entries())); } closeToast(id: string): void { this.clearTimeout(id); this.toasts.delete(id); this.onToastsChange(Array.from(this.toasts.entries())); } clearTimeout(id?: string) { if (id) { if (this.timeouts.has(id)) { clearTimeout(this.timeouts.get(id)!); this.timeouts.delete(id); } } else { this.timeouts.forEach((id) => { clearTimeout(id); }); this.timeouts.clear(); } } clear() { this.clearTimeout(); this.toasts.clear(); } } const toastState = new GlobalToastState(); export const openToast = toastState.openToast.bind(toastState); export const closeToast = toastState.closeToast.bind(toastState); const ToastContext = createContext({ openToast: () => { // }, closeToast: () => { // }, }); const toastStyles = css({ button: { position: 'absolute', }, }); /** * @example * * ``` * const MyButton = () => { * const { openToast } = useToast('namespace'); * return