import * as React from 'react' ; import { uid } from '@twilio-paste/uid-library' ; import type { ToasterToast , ToasterPush , UseToasterReturnedProps } from './types' ; export const useToaster = ( ) : UseToasterReturnedProps => { const isMounted = React . useRef < boolean | null > ( null ) ; const [ toasts , setToasts ] = React . useState < ToasterToast [ ] > ( [ ] ) ; React . useEffect ( ( ) => { isMounted . current = true ; return ( ) => { isMounted . current = false ; /**
             * Clear all timeouts from the toaster when the component unmounts
             */ toasts . forEach ( ( toast ) => { if ( toast . timeOutId ) { window . clearTimeout ( toast . timeOutId ) ; } } ) ; } ; } , [ ] ) ; const pop = ( id ) : void => { if ( ! isMounted . current ) { return ; } setToasts ( ( currentToasts ) => currentToasts . filter ( ( toast ) => { if ( toast . id === id ) { if ( toast . timeOutId ) { window . clearTimeout ( toast . timeOutId ) ; } if ( toast . onDismiss ) { toast . onDismiss ( ) ; } } return toast . id !== id ; } ) ) ; } ; const push = ( newToast ) : void => { if ( ! isMounted . current ) { return ; } const generatedID = uid ( newToast ) ; let timeOutId ; if ( newToast . dismissAfter != null && Number . isInteger ( newToast . dismissAfter ) ) { timeOutId = window . setTimeout ( pop , newToast . dismissAfter , newToast . id || generatedID ) ; } const existingToasts = toasts . map ( ( toast ) => { const tmpToast = toast ; tmpToast . setFocus = false ; return tmpToast ; } ) ; setToasts ( [ { id : generatedID , timeOutId , setFocus : true , ... newToast } , ... existingToasts ] ) ; } ; return { toasts , push , pop } ; } ;