UNPKG

mmr-gl-react

Version:

React components for MMR GL JS-compatible libraries

94 lines 3.67 kB
import * as React from 'react'; import { useState, useRef, useEffect, useContext, useMemo, useImperativeHandle } from 'react'; import { MountedMapsContext } from './use-map'; import Mmr from '../mmr/mmr'; import createRef from '../mmr/create-ref'; import useIsomorphicLayoutEffect from '../utils/use-isomorphic-layout-effect'; import setGlobals from '../utils/set-globals'; export const MapContext = React.createContext(null); export default function Map(props, ref, defaultLib) { const mountedMapsContext = useContext(MountedMapsContext); const [mapInstance, setMapInstance] = useState(null); const containerRef = useRef(); const { current: contextValue } = useRef({ mapLib: null, map: null }); useEffect(() => { const mapLib = props.mapLib; let isMounted = true; let mmr; Promise.resolve(mapLib || defaultLib) .then((module) => { if (!isMounted) { return; } if (!module) { throw new Error('Invalid mapLib'); } const mmrgl = 'default' in module ? module.default : module; if (!mmrgl.Map) { throw new Error('Invalid mapLib'); } // workerUrl & workerClass may change the result of supported() // https://github.com/visgl/react-map-gl/discussions/2027 setGlobals(mmrgl, props); if (!mmrgl.supported || mmrgl.supported(props)) { if (props.reuseMaps) { mmr = Mmr.reuse(props, containerRef.current); } if (!mmr) { mmr = new Mmr(mmrgl.Map, props, containerRef.current); } contextValue.map = createRef(mmr); contextValue.mapLib = mmrgl; setMapInstance(mmr); mountedMapsContext === null || mountedMapsContext === void 0 ? void 0 : mountedMapsContext.onMapMount(contextValue.map, props.id); } else { throw new Error('Map is not supported by this browser'); } }) .catch(error => { const { onError } = props; if (onError) { onError({ type: 'error', target: null, originalEvent: null, error }); } else { console.error(error); // eslint-disable-line } }); return () => { isMounted = false; if (mmr) { mountedMapsContext === null || mountedMapsContext === void 0 ? void 0 : mountedMapsContext.onMapUnmount(props.id); if (props.reuseMaps) { mmr.recycle(); } else { mmr.destroy(); } } }; }, []); useIsomorphicLayoutEffect(() => { if (mapInstance) { mapInstance.setProps(props); } }); useImperativeHandle(ref, () => contextValue.map, [mapInstance]); const style = useMemo(() => ({ position: 'relative', width: '100%', height: '100%', ...props.style }), [props.style]); const CHILD_CONTAINER_STYLE = { height: '100%' }; return (React.createElement("div", { id: props.id, ref: containerRef, style: style }, mapInstance && (React.createElement(MapContext.Provider, { value: contextValue }, React.createElement("div", { "mmrgl-children": "", style: CHILD_CONTAINER_STYLE }, props.children))))); } //# sourceMappingURL=map.js.map