import { EventedProps , LeafletContextInterface , LeafletElement , SetOpenFunc , createOverlayComponent , } from '@react-leaflet/core' ; import { LatLngExpression , Popup as LeafletPopup , PopupEvent , PopupOptions , } from 'leaflet' ; import { ReactNode , useEffect } from 'react' ; export interface PopupProps extends PopupOptions , EventedProps { children ? : ReactNode ; onClose ? : ( ) => void ; onOpen ? : ( ) => void ; position ? : LatLngExpression ; } export const Popup = createOverlayComponent < LeafletPopup , PopupProps > ( function createPopup ( props , context ) { return { instance : new LeafletPopup ( props , context . overlayContainer ) , context , } ; } , function usePopupLifecycle ( element , context , props , setOpen ) { const { onClose , onOpen , position } = props ; useEffect ( function addPopup ( ) { const { instance } = element ; function onPopupOpen ( event ) { if ( event . popup === instance ) { instance . update ( ) ; setOpen ( true ) ; onOpen ?. ( ) ; } } function onPopupClose ( event ) { if ( event . popup === instance ) { setOpen ( false ) ; onClose ?. ( ) ; } } context . map . on ( { popupopen : onPopupOpen , popupclose : onPopupClose , } ) ; if ( context . overlayContainer == null ) { if ( position != null ) { instance . setLatLng ( position ) ; } instance . openOn ( context . map ) ; } else { context . overlayContainer . bindPopup ( instance ) ; } return function removePopup ( ) { context . map . off ( { popupopen : onPopupOpen , popupclose : onPopupClose , } ) ; context . overlayContainer ?. unbindPopup ( ) ; context . map . removeLayer ( instance ) ; } ; } , [ element , context , setOpen , onClose , onOpen , position ] ) ; } ) ;