# Code coverage report for atlas-mobile-ts/src/components/Map/MainMapComponent/OutdoorMap.tsx

# All files / atlas-mobile-ts/src/components/Map/MainMapComponent OutdoorMap.tsx

0% Statements 0/134
0% Branches 0/56
0% Functions 0/28
0% Lines 0/125

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348

     ﻿/* Copyright (C) Click & Push Accessibility, Inc - All Rights Reserved
     * Unauthorized copying of this file, via any medium is strictly prohibited
     * Proprietary and confidential
     * Written and maintained by the Click & Push Development team
     * <dev@clicknpush.ca>, January 2022
     */

    import { FontAwesome } from "@expo/vector-icons";
    import { RouteProp } from "@react-navigation/native";
    import { booleanPointInPolygon, circle } from '@turf/turf';
    import * as Notifications from 'expo-notifications';
    import { observer } from "mobx-react";
    import React, { MutableRefObject, useEffect, useState } from "react";
    import { Alert, AppState, Image, Keyboard, Platform, TouchableOpacity, TouchableWithoutFeedback, View } from "react-native";
    import { ScrollView } from "react-native-gesture-handler";
    import MapView, { LatLng, Marker, Polygon } from "react-native-maps";
    import { Chip } from "react-native-paper";
    import { PERMISSIONS } from "react-native-permissions";
    import Spokestack from 'react-native-spokestack';
    import { Landmark, useLandmarks } from "../../../hooks/useLandmarks";
    import { useProfile } from "../../../hooks/useProfile";
    import { AuthTabsParamList as AuthTabsParamList, AuthTabsNavigationProp } from "../../../navigation/AuthorizedNavigator";
    import { authStore } from "../../../libs/auth/AuthStore";
    import { NotifType } from "../../../types";
    import { checkVoicePermissions, colors, getMapPermissions, lmTypes } from "../../../utils/GlobalUtils";
    import Badge from "../../Badge";
    import { IconButton } from "../../Buttons";
    import AddLandmarkPanel from "../Panels/AddLandmarkPanel";
    import NearbyLandmarksPanel from "../Panels/NearbyLandmarksPanel";
    import { FilterPanel } from "../Panels/FilterPanel/FilterPanel";
    import LandmarkDetails from "../Panels/LandmarkDetailsPanel/LandmarkDetails";
    import { VoicePanel } from "../Panels/VoicePanel";
    import mapStyles from "./Map.styles";
    import { useMapState, useOutdoorMapState } from "./useMapState";
    import { MapStackNavigationProp, MapStackParamList } from "../../../navigation/MapNavigator";

    /**
     * An interface representing the user location retrieved from [expo-location]{@link https://docs.expo.dev/versions/latest/sdk/location/}.
     * @category Map
     */
    export interface UserLocation {
        latitude: number;
        longitude: number;
        heading?: number;
    }

    export type MapStackRouteProp = RouteProp<MapStackParamList, 'Outdoor'>;

    export type AuthTabsMapRouteProp = RouteProp<AuthTabsParamList, 'Map'>;

    /**
     * The screen component containing the Map and all related functionality. Uses [react-native-maps]{@link https://github.com/react-native-maps/react-native-maps}
     * @category Map
     * @component
     */

    interface OutdoorMapProps {
        mapNavigation: MapStackNavigationProp,
        authNavigation: AuthTabsNavigationProp,
        route: AuthTabsMapRouteProp,
        focusLandmark: (landmark: Landmark) => void,
        setSelectedLandmarkId: (id: string) => void,
        selectedLandmarkId: string,
        newLandmark: Landmark
        setNewLandmark: (landmark: Landmark) => void
        toggleLmDetails: (state: boolean) => void,
        toggleLmAdd: (state: boolean) => void,
        landmarks: Landmark[]
        applyFilters: (landmarks: Landmark[]) => Landmark[]
        promptAddLandmark: (longitude: number, latitude: number) => void
    }

    const OutdoorMap: React.FC<OutdoorMapProps> = (props) => {
        const mapState = useOutdoorMapState()

        /**
         * If the ReactNavigation route prop changes, check if it contains incoming selected landmarks, display them if there are. This will be triggered by incoming notifcations
         * (See the AuthorizedNavigator page for the useEffect that will trigger this)
         */
         useEffect(() => {
            Iif (props.route?.params?.selectedLandmark) {
                props.setSelectedLandmarkId(props.route?.params?.selectedLandmark)
            }
            Iif (props.route?.params?.selectedLandmarks) {
                mapState.toggleNearbyLmPanel(true)
            }
        }, [props.route])

        /**
         * Toggle the lm details panel when a new selected landmark is detected (triggered by pressing on a map marker, or from the list of nearby landmarks)
         */
         useEffect(() => {
            console.log("[LandmarkDetails]: Landmark selected - " + props.selectedLandmarkId)
            Iif (props.selectedLandmarkId) {
                const landmark = props.landmarks.find(lm => lm.id == props.selectedLandmarkId)
                mapState.mapRef.current.animateToRegion({latitude: landmark.latitude, longitude: landmark.longitude, latitudeDelta: 0.01, longitudeDelta: 0.01})
                props.toggleLmDetails(true)
            }
        }, [props.selectedLandmarkId])

        /**
         * Move to pressed location when newlandmark changes
         */
         useEffect(() => {
            Iif (props.selectedLandmarkId) {
                mapState.mapRef.current.animateToRegion({latitude: props.newLandmark.latitude, longitude: props.newLandmark.longitude, latitudeDelta: 0.01, longitudeDelta: 0.01})
            }
        }, [props.newLandmark])

        /**
         * Gets speech permissions from user, runs every time app is brought to foreground
         */
         useEffect(() => {
            const getSpeechPermissions = async () => {
                Iif (AppState.currentState == 'active') {
                    await getMapPermissions()
                    console.log('[Permissions]: Checking voice permissions...')
                    if (Platform.OS == 'android') {
                        const permitted = await checkVoicePermissions([PERMISSIONS.ANDROID.RECORD_AUDIO])
                        mapState.toggleVoicePermission(permitted)
                        if (permitted) console.log('[Permissions]: Voice permission granted')
                        else console.log('[Permissions]: Voice permission denied')
                    }
                    else Iif (Platform.OS == 'ios') {
                        const permitted = await checkVoicePermissions([PERMISSIONS.IOS.SPEECH_RECOGNITION, PERMISSIONS.IOS.MICROPHONE])
                        mapState.toggleVoicePermission(permitted)
                        if (permitted) console.log('[Permissions]: Voice permission granted')
                        else console.log('[Permissions]: Voice permission denied')
                    }
                }
            }
            getSpeechPermissions()
            }, [AppState.currentState])

            /**
             * Gets foreground location permissions from user, runs every time app is brought to foreground
             */
             useEffect(() => {
                const checkForegroundLocationPermissions = async () =>  {
                    Iif (AppState.currentState == 'active') {
                        console.log('Checking location permissions...')
                        if (Platform.OS == 'android') {
                            const permitted = await checkVoicePermissions([PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION, PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION])
                            mapState.toggleFgroundLocationPermission(permitted)
                            if (permitted) console.log('[Permissions]: Location permission granted')
                            else console.log('[Permissions]: Location permission denied')
                        }
                        else Iif (Platform.OS == 'ios') {
                            const permitted = await checkVoicePermissions([PERMISSIONS.IOS.LOCATION_WHEN_IN_USE])
                            mapState.toggleFgroundLocationPermission(permitted)
                            if (permitted) console.log('[Permissions]: Location permission granted')
                            else console.log('[Permissions]: Location permission denied')
                        }
                    }
                }
                checkForegroundLocationPermissions();
            }, [AppState.currentState])

            /**
             * Gets background location permissions from user, runs every time app is brought to foreground
             */
            useEffect(() => {
                const checkBackgroundLocationPermissions = async () =>  {
                    Iif (AppState.currentState == 'active') {
                        if (Platform.OS == 'android') {
                            const permitted = await checkVoicePermissions([PERMISSIONS.ANDROID.ACCESS_BACKGROUND_LOCATION])
                            mapState.toggleBgroundLocationPermission(permitted)
                            if (permitted) console.log('[Permissions]: Background location permission granted')
                            else console.log('[Permissions]: Background location permission denied')
                        }
                        else Iif (Platform.OS == 'ios') {
                            const permitted = await checkVoicePermissions([PERMISSIONS.IOS.LOCATION_ALWAYS])
                            mapState.toggleBgroundLocationPermission(permitted)
                            if (permitted) console.log('[Permissions]: Background location permission granted')
                            else console.log('[Permissions]: Background location permission denied')
                        }
                    }
                }
                checkBackgroundLocationPermissions();
            }, [AppState.currentState])

            /**
             * Gets net location permission the existing location permission states. It will check foreground and background permissions and AppState,
             * then from that it will decide if location-enabled features should be activated (through the mapState state values).
             */
             useEffect(() => {
                const updateLocationPermissionOnAppStateChange = async () => {
                    const netLocationPermissions = mapState.bgroundLocationPermission || (mapState.fgroundLocationPermission && AppState.currentState == 'active')
                    console.log('[Permissions]: Appstate, or location permissions changed, net location permissions found to be: ' + netLocationPermissions)
                    mapState.toggleLocationPermitted(netLocationPermissions)
                }
                updateLocationPermissionOnAppStateChange()
            }, [AppState.currentState, mapState.bgroundLocationPermission, mapState.fgroundLocationPermission])

        /**
         * Animates the map to fly over to and focus on the user's location.
         */
         const flyToUser = () => {
            console.log('[Map]: Centering on user')
            Iif (mapState.userLocation) {
                mapState.mapRef.current?.animateToRegion({latitude: mapState.userLocation.latitude, longitude: mapState.userLocation.longitude, latitudeDelta: 0.01, longitudeDelta: 0.01})
            }
        }

        /**
         * Activates speech recognition and opens the voice panel
         */
         const startSpeech = () => {
            props.toggleLmDetails(false);
            props.toggleLmAdd(false);
            Spokestack.activate()
        }

        /**
         * Gets initial region that map should zoom into from current user location
         */
        const getInitialRegion = () => {
            Iif (mapState.userLocation) {
                return {latitude: mapState.userLocation.latitude, longitude: mapState.userLocation.longitude, latitudeDelta: 0.01, longitudeDelta: 0.01}
            }
            return undefined
        }

        /**
         * Method that runs every time user location changes, updates user location state in memory and checks if any landmarks are nearby
         */
        const updateLocation = async (coord: LatLng) => {
            mapState.setUserLocation(coord)
            // get 10m radius around user
            const userAlertRadius = circle([coord.longitude, coord.latitude], 10, {units: 'meters'})

            // check each landmark to see if its inside user radius. if it is, and it isn't already in the list of notified landmarks, add it
            const newLandmarksNearUser = props.landmarks?.filter(lm => {
                const landmarkNearUser = booleanPointInPolygon([lm.longitude, lm.latitude], userAlertRadius)
                return landmarkNearUser
            })

            // to prevent duplicate notifications make a list of landmarks that weren't previously near the user.
            // these are the only ones that the user will be notified of
            const newLandmarksNotPreviouslyNearUser = newLandmarksNearUser.filter(lm => mapState.landmarksNearUser.some(origLm => lm == origLm.id))

            // update list
            mapState.setLandmarksNearUser(newLandmarksNearUser)

            // if there are any new landmarks near user, create a notification for them and send it
            Iif (newLandmarksNotPreviouslyNearUser?.length > 0) {
                const body = newLandmarksNotPreviouslyNearUser.length > 1 ? "There are new landmarks near by. Tap here to view" : "There is a new landmark close by. Tap here to view"
                const notifType: NotifType = newLandmarksNotPreviouslyNearUser.length > 1 ? 'near-landmarks' : 'near-landmark'
                const data = {notif_type: notifType, landmarks: newLandmarksNotPreviouslyNearUser.length == 1 ? newLandmarksNearUser : null}
                await Notifications.scheduleNotificationAsync({
                    content: {
                      title: "⚠ Landmarks close by ⚠",
                      body: body,
                      data: data
                    },
                    trigger: { seconds: 2 },
                  });
            }
        }

        const focusNearbyLandmarks = () => {
            if (mapState.landmarksNearUser?.length > 1) {
                mapState.toggleNearbyLmPanel(true)
            }
            else Iif (mapState.landmarksNearUser?.length === 1) {
                props.setSelectedLandmarkId(mapState.landmarksNearUser[0].id)
            }
        }

        return (
            <TouchableWithoutFeedback>
                <>
                {/*Main map component*/}
                <MapView
                    toolbarEnabled={false}
                    onPress={() => Keyboard.dismiss()}
                    testID="mapView"
                    ref={mapState.mapRef}
                    style={{width: '100%', height: '100%'}}
                    initialRegion={getInitialRegion()}
                    onLongPress={(e) => props.promptAddLandmark(e.nativeEvent.coordinate.longitude, e.nativeEvent.coordinate.latitude)}
                    showsUserLocation={mapState.locationPermitted}
                    onUserLocationChange={e => updateLocation(e.nativeEvent.coordinate)}
                    followsUserLocation={mapState.followUser}
                    showsMyLocationButton={false}>
                <Polygon // polygon for cameron library
                  coordinates={[
                    {latitude: 53.527190, longitude: -113.524205 },
                    {latitude: 53.526510, longitude: -113.524205 },
                    {latitude: 53.526510, longitude: -113.523452 },
                    {latitude: 53.527190, longitude: -113.523452 },
                    // { name: "5", latitude: 60, longitude: -105 },
                  ]}
                  fillColor={`rgba(100,100,200,0.3)`}
                  strokeWidth={2.5}
                  tappable={true}
                  onPress={() => props.mapNavigation.navigate("Indoor")}
                  />
                {props.applyFilters(props.landmarks)?.map((landmark) => {
                    let trackChanges = false;
                    Iif (landmark?.id == props.selectedLandmarkId) {
                        trackChanges = true;
                    }
                    return (
                        <Marker
                            tracksViewChanges={trackChanges}
                            onPress={() => props.focusLandmark(landmark)}
                            key={landmark.id}
                            coordinate={{latitude: landmark.latitude as number, longitude: landmark.longitude as number}} >
                            { landmark.landmark_type ? <Image style={{height: 35, width: 25}} source={lmTypes[landmark.landmark_type].image} /> : null}
                        </Marker>)})}
                </MapView>

                {/*Map buttons*/}
                {mapState.landmarksNearUser?.length > 0 ?
                <TouchableOpacity style={[mapStyles.lowerMapButton, mapStyles.alertButton]} onPress={focusNearbyLandmarks}>
                    <FontAwesome name='exclamation-triangle' size={20} color='white' />
                    <Badge positioning={{bottom: 7, right: 4}} value={mapState.landmarksNearUser.length}/>
                </TouchableOpacity> : null}
                {mapState.locationPermitted && mapState.voicePermission ?
                <IconButton size={20} color='white' style={[mapStyles.lowerMapButton, mapStyles.voiceButton]} icon="microphone" onPress={startSpeech}/>: null}
                <IconButton size={20} color='white' style={[mapStyles.lowerMapButton, mapStyles.addLandmarkButton]} icon="plus" onPress={() => props.promptAddLandmark(mapState.userLocation.longitude, mapState.userLocation.latitude)}/>
                <IconButton size={20} color='white' style={[mapStyles.lowerMapButton, mapStyles.userLocationButton]} icon="location-arrow" onPress={flyToUser}/>
                <NearbyLandmarksPanel
                    focusLandmark={props.focusLandmark}
                    nearbyLmPanelVisible={mapState.nearbyLmPanelVisible}
                    toggleAlertedLmPanel={mapState.toggleNearbyLmPanel}
                    nearbyLandmarks={mapState.landmarksNearUser}/>
                {/*Map Panels*/}
                {mapState.voicePermission && mapState.locationPermitted ?
                <VoicePanel
                    landmarksNearby={mapState.landmarksNearUser.length > 0}
                    toggleAlertedLandmarksVisible={mapState.toggleNearbyLmPanel}
                    navigation={props.authNavigation}
                    userCoords={{longitude: mapState.userLocation?.longitude, latitude: mapState.userLocation?.latitude}}
                    toggleVoiceVisible={mapState.toggleVoiceVisible}
                    toggleLmDetails={props.toggleLmDetails}
                    setSelectedLandmarkId={props.setSelectedLandmarkId}
                    voiceVisible={mapState.voiceVisible}
                    newLandmark={props.newLandmark}
                    setNewLandmark={props.setNewLandmark}
                    /> : null }
                </>
            </TouchableWithoutFeedback> )
    }

    export default observer(OutdoorMap);