/* eslint-disable @typescript-eslint/no-empty-function */ /* eslint-disable @typescript-eslint/no-explicit-any */ import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, } from "react"; import { Linking, Platform, Share, type StyleProp, StyleSheet, type ViewStyle, } from "react-native"; import WebView from "react-native-webview"; import type { AndroidWebViewProps, IOSWebViewProps, WebViewErrorEvent, WebViewMessageEvent, } from "react-native-webview/lib/WebViewTypes"; import SitumPlugin from "../../sdk"; import useSitum from "../hooks"; import { selectApiDomain, setError, setLocationStatus } from "../store"; import { useSelector } from "../store/utils"; import { type CartographySelectionOptions, type InternalMapViewRef, type MapViewDirectionsOptions, type MapViewError, type MapViewRef, type NavigateToCarPayload, type NavigateToPointPayload, type NavigateToPoiPayload, type OnExternalLinkClickedResult, type OnFavoritePoisUpdatedResult, type OnFloorChangedResult, type OnInternalMapViewMessageCallback, type OnPoiDeselectedResult, type OnPoiSelectedResult, type SearchFilter, type ShareLiveLocationSessionPayload, } from "../types"; import { ErrorName } from "../types/constants"; import { sendMessageToViewer } from "../utils"; import ViewerMapper from "../utils/mapper"; import { authStore, SitumAuth } from "../../sdk/authStore"; const SITUM_BASE_DOMAIN = "https://maps.situm.com"; const NETWORK_ERROR_CODE = { android: -2, ios: -1009, // These platforms are unhandled windows: 0, macos: 0, web: 0, }; // Workaround to "Type 'RefObject>' is not assignable to type 'never'". // See https://github.com/react-native-webview/react-native-webview/issues/3977. type TypedWebViewProps = IOSWebViewProps & AndroidWebViewProps; // Some WebView declarations default their generic props to `undefined`. // This proxy retains the declared props without relying on that default. const TypedWebView = WebView as unknown as React.ComponentType< TypedWebViewProps & React.RefAttributes >; export type MapViewConfiguration = { /** * A String parameter that allows you to choose the API you will be retrieving our cartography from. Default is "api.situm.com". * In most cases this parameter shouldn't be changed. */ apiDomain?: string; /** * A String parameter that allows you to specify which domain will be displayed inside our webview. Defaults to "https://maps.situm.com/". * In most cases this parameter shouldn't be changed. */ viewerDomain?: string; /** * Your Situm API key. Find your API key at your [Situm dashboard's profile](https://dashboard.situm.com/accounts/profile) * * Since 3.17.0 version this parameter is not required. Instead, you should specify your apiKey * at the root of your app with `SitumProvider.apiKey` for the correct usage of the plugin. * If {@link MapViewConfiguration.situmApiKey} is specified, this API key takes precedence over * authentication provided through `SitumProvider` or `SitumPlugin`. */ situmApiKey?: string; /** * @deprecated Use `profile` instead. * A String identifier that allows you to remotely configure all map settings. */ remoteIdentifier?: string; /** * A String that specifies the selected profile name for configuring the MapView with its corresponding remote settings. */ profile?: string; /** * ** Required ** * The building that will be loaded on the map. * In case you set a buildingIdentifier in your remote configuration, it will be prioritized over {@link MapViewConfiguration.buildingIdentifier} parameter. */ buildingIdentifier: string; /** * Sets the directionality of the texts that will be displayed inside MapView. Default is "ltr". */ directionality?: string; /** * Sets the UI language based on the given ISO 639-1 code. Checkout the [Situm docs](https://situm.com/docs/query-params/) to see the list of supported languages. */ language?: string; }; // ref https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share interface WebShareAPIParam { title?: string; url?: string; } const viewerStyles = StyleSheet.create({ webview: { minHeight: "100%", minWidth: "100%", }, }); export interface MapViewProps { /** * The required basic configuration to use our MapView. */ configuration: MapViewConfiguration; style?: StyleProp; /** * Get notified when a POI is selected. * @param event {@link OnPoiSelectedResult} object. */ onPoiSelected?: (event: OnPoiSelectedResult) => void; /** * Get notified when the selected POI is deselected. * @param event {@link OnPoiDeselectedResult} object. */ onPoiDeselected?: (event: OnPoiDeselectedResult) => void; /** * Get notified when the MapView has been loaded and is ready to receive actions. */ onLoad?: (event: any) => void; /** * Get notified when an error has occurred during the MapView load process. * @param event {@link MapViewError} object. */ onLoadError?: (event: MapViewError) => void; /** * Get notified when the current floor displayed on the map has changed. * @param event {@link OnFloorChangedResult} object. */ onFloorChanged?: (event: OnFloorChangedResult) => void; /** * Callback invoked when the user clicks on a link in the MapView that leads to a website different from the MapView's domain. * For example some POI description may contain a link to a video or a website, and if this callback is not set, * the link will be opened in the system's default browser by default. * @param event {@link OnExternalLinkClickedResult} object. */ onExternalLinkClicked?: (event: OnExternalLinkClickedResult) => void; /** * Callback invoked when the list of favoritePois is updated * @param event {@link OnFavoritePoisUpdatedResult} object. */ onFavoritePoisUpdated?: (event: OnFavoritePoisUpdatedResult) => void; } const MapView = React.forwardRef( ( { configuration, style, onLoad = () => {}, onLoadError = () => {}, onPoiSelected = () => {}, onPoiDeselected = () => {}, onFloorChanged = () => {}, onExternalLinkClicked = undefined, onFavoritePoisUpdated = () => {}, }, ref, ) => { const webViewRef = useRef(null); const internalMessageCallbackRef = useRef(); // Local states const [mapLoaded, setMapLoaded] = useState(false); const [buildingIdentifier, setBuildingIdentifier] = useState( configuration.buildingIdentifier, ); const [auth, setAuth] = useState( authStore.getAuth(), ); useEffect(() => authStore.subscribe(setAuth), []); const apiDomain = useSelector(selectApiDomain); const { init, location, locationStatus, error } = useSitum(); const sendFollowUser = () => { if ( webViewRef.current && mapLoaded && location?.position?.buildingIdentifier === configuration.buildingIdentifier ) { _followUser(true); } }; // Helper functions used on imperative handler // Navigation const _navigateToPoi = useCallback((payload: NavigateToPoiPayload) => { if (!webViewRef.current || !payload || !payload.identifier) return; sendMessageToViewer( webViewRef.current, ViewerMapper.navigateToPoi(payload), ); }, []); const _followUser = useCallback((payload: boolean) => { if (!webViewRef.current) return; sendMessageToViewer(webViewRef.current, ViewerMapper.followUser(payload)); }, []); const _navigateToCar = useCallback((payload?: NavigateToCarPayload) => { if (!webViewRef.current) return; sendMessageToViewer( webViewRef.current, ViewerMapper.navigateToCar(payload), ); }, []); const _navigateToPoint = useCallback((payload: NavigateToPointPayload) => { if ( !webViewRef.current || (!payload?.lat && !payload?.lng && !payload?.floorIdentifier) ) return; sendMessageToViewer( webViewRef.current, ViewerMapper.navigateToPoint(payload), ); }, []); // Cartography const _selectPoi = useCallback((poiId: number) => { if (!webViewRef.current) { return; } sendMessageToViewer(webViewRef.current, ViewerMapper.selectPoi(poiId)); }, []); const _selectCar = useCallback(() => { if (!webViewRef.current) { return; } sendMessageToViewer(webViewRef.current, ViewerMapper.selectCar()); }, []); const _selectPoiCategory = useCallback((categoryId: number) => { if (!webViewRef.current) { return; } sendMessageToViewer( webViewRef.current, ViewerMapper.selectPoiCategory(categoryId), ); }, []); const _selectFloor = useCallback( (floorId: number, options?: CartographySelectionOptions) => { if (!webViewRef.current) { return; } sendMessageToViewer( webViewRef.current, ViewerMapper.selectFloor(floorId, options), ); }, [], ); const _search = useCallback((payload: SearchFilter) => { sendMessageToViewer(webViewRef.current, ViewerMapper.search(payload)); }, []); const _setDirectionsOptions = useCallback( (directionsOptions: MapViewDirectionsOptions) => { if (!webViewRef.current) { return; } sendMessageToViewer( webViewRef.current, ViewerMapper.setDirectionsOptions(directionsOptions), ); }, [], ); const _setFavoritePois = useCallback((poiIds: number[]) => { if (!webViewRef.current) { return; } sendMessageToViewer( webViewRef.current, ViewerMapper.setFavoritePois(poiIds), ); }, []); //Share Live Location const _setShareLiveLocationSession = useCallback( (payload: ShareLiveLocationSessionPayload) => { if (!webViewRef.current || !payload?.identifier) return; sendMessageToViewer( webViewRef.current, ViewerMapper.setShareLiveLocationSession(payload), ); }, [], ); const _onMapIsReady = () => { if (locationStatus) { sendMessageToViewer( webViewRef.current, ViewerMapper.locationStatus(locationStatus), ); } if (error) { // Right now, status and errors share message on the viewer: sendMessageToViewer( webViewRef.current, ViewerMapper.locationError(error), ); } }; /** * API exported to the outside world from the MapViewer * * These handler allows third party developers to send actions to the MapView. * please check the MapViewRef type definitions to know the public API. * * ref.selectPoi(122)} * configuration={{ * buildingIdentifier: SITUM_BUILDING_ID, * }} * onLoad={onLoad} /> */ useImperativeHandle(ref, (): InternalMapViewRef => { return { setOnDirectionsRequestInterceptor() { // DEPRECATED }, followUser() { _followUser(true); }, unfollowUser() { _followUser(false); }, selectPoi(poiId: number) { _selectPoi(poiId); }, selectCar() { _selectCar(); }, selectPoiCategory(poiId: number) { _selectPoiCategory(poiId); }, selectFloor(poiId: number, options?: CartographySelectionOptions) { _selectFloor(poiId, options); }, setDirectionsOptions(directionsOptions: MapViewDirectionsOptions) { _setDirectionsOptions(directionsOptions); }, setFavoritePois(poiIds: number[]) { _setFavoritePois(poiIds); }, deselectPoi() { webViewRef.current && sendMessageToViewer(webViewRef.current, ViewerMapper.deselectPoi()); }, navigateToPoi(payload): void { _navigateToPoi(payload); }, navigateToCar(payload): void { _navigateToCar(payload); }, navigateToPoint(payload: NavigateToPointPayload): void { _navigateToPoint(payload); }, cancelNavigation(): void { if (!webViewRef.current) return; sendMessageToViewer( webViewRef.current, ViewerMapper.cancelNavigation(), ); }, setShareLiveLocationSession( payload: ShareLiveLocationSessionPayload, ): void { _setShareLiveLocationSession(payload); }, search(payload): void { _search(payload); }, onInternalMapViewMessageCallback( callback: OnInternalMapViewMessageCallback, ): void { internalMessageCallbackRef.current = callback; }, }; }, [ _navigateToPoi, _followUser, _navigateToCar, _navigateToPoint, _selectPoi, _selectCar, _selectPoiCategory, _selectFloor, _setDirectionsOptions, _setFavoritePois, _setShareLiveLocationSession, _search, ]); useEffect(() => { SitumPlugin.validateMapViewProjectSettings(); return () => {}; }, []); useEffect(() => { if (!error) return; console.error( "Error code:", error.code ? error.code : " no code provided", ); console.error("Error detected:", error.message); }, [error]); // Updated SDK location useEffect(() => { if (!webViewRef.current || !location || !mapLoaded) return; sendMessageToViewer(webViewRef.current, ViewerMapper.location(location)); }, [location, mapLoaded]); // locationStatus useEffect(() => { if (!webViewRef.current || !locationStatus || !mapLoaded) return; sendMessageToViewer( webViewRef.current, ViewerMapper.locationStatus(locationStatus), ); // Callbacks used in `useEffect` won't be invoked if the value of locationStatus // is set but hasn't changed. Set locationStatus to null always to avoid missing // repeated messages. setLocationStatus(null); }, [locationStatus, mapLoaded]); // locationError useEffect(() => { if (!webViewRef.current || !error || !mapLoaded) return; sendMessageToViewer( webViewRef.current, ViewerMapper.locationError(error), ); // Callbacks used in `useEffect` won't be invoked if the value of locationStatus // is set but hasn't changed. Set locationStatus to null always to avoid missing // repeated messages. setError(null); }, [error, mapLoaded]); // Update language useEffect(() => { if (!webViewRef.current || !configuration.language || !mapLoaded) return; sendMessageToViewer( webViewRef.current, ViewerMapper.setLanguage(configuration.language), ); }, [configuration.language, mapLoaded]); // Update SDK configuration useEffect(() => { if (webViewRef.current && mapLoaded) { sendMessageToViewer( webViewRef.current, ViewerMapper.initialConfiguration(style), ); _sendViewerConfigItems(); } }, [webViewRef, mapLoaded, style]); // Update follow user useEffect(() => { mapLoaded && sendFollowUser(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [mapLoaded]); const handleRequestFromViewer = (event: WebViewMessageEvent) => { let eventParsed: any = {}; try { eventParsed = JSON.parse(event.nativeEvent.data); } catch (err) { console.warn("Invalid JSON from viewer:", err); } const type = eventParsed?.type ?? "message.unknown"; const payload = eventParsed?.payload ?? {}; switch (type) { case "app.map_is_ready": init(); setMapLoaded(true); _onMapIsReady(); onLoad && onLoad(""); break; case "app.ready_for_auth": sendEffectiveAuth(); break; case "cartography.poi_selected": onPoiSelected(payload); break; case "cartography.poi_deselected": onPoiDeselected(payload); break; case "ui.favorite_pois_updated": { const favoritePoisIds = { currentPoisIdentifiers: payload.favoritePois ? [...payload.favoritePois] : [], }; onFavoritePoisUpdated(favoritePoisIds); break; } case "cartography.floor_selected": onFloorChanged(payload); break; case "cartography.building_selected": if ( !payload.identifier || payload.identifier.toString() === buildingIdentifier ) { return; } else { setBuildingIdentifier(payload.identifier.toString()); } break; case "viewer.navigation.started": case "viewer.navigation.updated": case "viewer.navigation.stopped": // Forward Viewer navigation events to the existing SDK callbacks. // This avoids introducing a separate set of callbacks just for the Viewer. // Warning: running SDK and MapView navigations at the same time may mix // events because both navigations use the same public SDK callbacks. SitumPlugin.updateNavigationState(payload); break; case "share_location.uploading_locations_started": SitumPlugin.startShareLiveLocation(payload); break; case "share_location.uploading_locations_stopped": SitumPlugin.stopShareLiveLocation(); break; case "ui.speak_aloud_text": SitumPlugin.speakAloudText(payload); break; case "native.share": if (Platform.OS !== "android") return; _onWebShareMessage(payload); break; default: break; } // Internal callback that will receive every MapView message. This callback // has been introduced to enable communication between MapView and the new AR // module, serving as a direct and extensible mode that avoids the // intermediation of this plugin. try { internalMessageCallbackRef.current?.(type, payload); } catch (e) { console.error("Error delegating:", type, e); } }; const effectiveAuth = useMemo(() => { if (configuration.situmApiKey) { return { type: "apiKey", value: configuration.situmApiKey, }; } if (auth) { return auth; } return undefined; }, [auth, configuration.situmApiKey]); const sendEffectiveAuth = useCallback(() => { if (!webViewRef.current || !effectiveAuth) { return; } sendMessageToViewer( webViewRef.current, ViewerMapper.setAuth(effectiveAuth), ); }, [effectiveAuth]); useEffect(() => { // When the auth method changes, send a message to the viewer sendEffectiveAuth(); }, [sendEffectiveAuth]); const _onWebShareMessage = useCallback(async (param: WebShareAPIParam) => { try { if (param.url == null) { return; } await Share.share( { title: param.title, message: param.url, }, { dialogTitle: param.title, }, ); } catch (e) { console.error(e); } }, []); const _onShouldStartLoadWithRequest = (request: any) => { if (request?.url === "about:blank") { return false; } if ( request && request.url && !request.url.startsWith(configuration.viewerDomain || SITUM_BASE_DOMAIN) ) { if ( onExternalLinkClicked && typeof onExternalLinkClicked === "function" ) { onExternalLinkClicked({ url: request.url }); } else { Linking.openURL(request.url); } return false; } return true; }; const _effectiveProfile = useMemo(() => { let effectiveProfile: any = ""; if ( configuration.profile?.length === 0 && configuration.remoteIdentifier?.length === 0 ) { effectiveProfile = ""; } effectiveProfile = configuration.profile; if ( configuration.remoteIdentifier && configuration.remoteIdentifier.length > 0 ) { console.warn( 'Situm> MapView> [!] "remoteIdentifier" is deprecated. Use "profile" instead.', ); if (!configuration.profile || configuration.profile.length === 0) { effectiveProfile = configuration.remoteIdentifier; } } return effectiveProfile; }, [configuration.profile, configuration.remoteIdentifier]); const _authQueryParam = useMemo(() => { return effectiveAuth?.type === "apiKey" ? `apikey=${encodeURIComponent(effectiveAuth.value)}` : "wait_for_auth=true"; }, [effectiveAuth]); const _effectiveApiDomain = useMemo(() => { let finalApiDomain = configuration.apiDomain ?? apiDomain; if (!finalApiDomain) return ""; finalApiDomain = finalApiDomain.replace("https://", ""); finalApiDomain = finalApiDomain.replace("/", ""); return `&domain=${finalApiDomain}`; }, [apiDomain, configuration.apiDomain]); const _effectiveBuildingId = useMemo(() => { let finalBuildingIdentifier = ""; const buildingId = configuration.buildingIdentifier; if (buildingId && buildingId.length > 0) { finalBuildingIdentifier = `&buildingid=${buildingId}`; } return finalBuildingIdentifier; }, [configuration.buildingIdentifier]); const _sendViewerConfigItems = async () => { const deviceId = await SitumPlugin.getDeviceId(); sendMessageToViewer( webViewRef.current, ViewerMapper.setConfigItems([ // Disable webview TTS in embed mode: { key: "internal.tts.engine", value: "mobile" }, // Device ID: { key: "internal.deviceId", value: deviceId || "" }, ]), ); }; // Override the Web Share API as it is not supported on Android WebView // See https://github.com/react-native-webview/react-native-webview/issues/1262#issuecomment-933315821 const _androidShareInjection = useMemo(() => { // Path share behavior only on Android if (Platform.OS !== "android") return undefined; return ` // Polyfill the check of being able to share for the webview if (navigator.canShare == null) { navigator.canShare = (param) => { if (param == null || typeof param !== "object") { return false; } if (Array.isArray(param.files) && param.files.length > 0) { return false; } return param.url != null || param.title != null; }; } // Polyfill the share API for the webview if (navigator.share == null) { navigator.share = (param) => { // Return a promise same as the native share API return new Promise((resolve, reject) => { try { window.ReactNativeWebView.postMessage( JSON.stringify({ type: "native.share", payload: param, }) ); resolve(); } catch (error) { reject(error); } }); }; } true; `; }, []); return ( { if (!onLoadError) return; const { nativeEvent } = evt; // TODO: on render error should probably still try to render an html if (nativeEvent.code === NETWORK_ERROR_CODE[Platform.OS]) { onLoadError({ name: ErrorName.ERR_INTERNET_DISCONNECTED, description: nativeEvent.description, }); } else { // TODO: handle more errors onLoadError({ name: ErrorName.ERR_INTERNAL_SERVER_ERROR, description: nativeEvent.description, }); } }} /> ); }, ); export default MapView;