# Code coverage report for atlas-mobile-ts/src/components/Map/Panels/LandmarkDetailsPanel/LandmarkDetails.tsx

# All files / atlas-mobile-ts/src/components/Map/Panels/LandmarkDetailsPanel LandmarkDetails.tsx

0% Statements 0/121
0% Branches 0/67
0% Functions 0/33
0% Lines 0/121

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
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472

     ﻿/* 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 React, { memo, useEffect, useRef, useState } from "react";
    import { ActivityIndicator, Alert, Dimensions, FlatList, Image, Keyboard, Platform, SafeAreaView, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";
    import { ScrollView } from "react-native-gesture-handler";
    import Modal from 'react-native-modal';
    import { LMComment, useComments } from "../../../../hooks/useComments";
    import { Landmark, LMPhoto, useLandmarks } from "../../../../hooks/useLandmarks";
    import { useProfile } from "../../../../hooks/useProfile";
    import { authStore } from "../../../../libs/auth/AuthStore";
    import { colors } from "../../../../utils/GlobalUtils";
    import { IconButton, PrimaryButton } from "../../../Buttons";
    import { DetailsBody } from "./DetailsBody";
    import { DetailsHeader } from "./DetailsHeader";

    /**
     * Props for the {@link LandmarkDetails} component.
     */
    export interface LandmarkDetailsProps {
        /**
         * The {@link Landmark} object being displayed/edited in the {@link LandmarkDetails} modal.
         */
        landmarkId: string | undefined
        /**
         * The state setter for {@link Landmark} object being displayed/edited in the {@link LandmarkDetails} modal.
         */
        setLandmark: (landmark: string) => void;
        /**
         * A callback passed from the parent {@link Map} that toggles the visibility of the {@link LandmarkDetails} modal.
         */
        toggleDetailsPanel: (state: boolean) => void;
        /**
         * A callback passed from the parent {@link Map} that toggles the ability to edit the {@link Landmark} in {@link LandmarkDetails} modal.
         */
        setEditing: (state: boolean) => void;
        /**
         * A flag that determines whether the properties of the {@link Landmark} displayed in the {@link LandmarkDetails} modal can be edited
         */
        editingEnabled: boolean,
        visible: boolean,
        toggleLmDetails: (state: boolean) => void
    }

    /**
     * Component that renders the details of a selected {@link Landmark} and allows the user to edit those details. Contained within a [react-native-modal]{@link https://github.com/react-native-modal/react-native-modal}.
     * @component
     * @category Map
     */
    const LandmarkDetails: React.FC<LandmarkDetailsProps> = ({landmarkId, setLandmark, toggleDetailsPanel, setEditing, editingEnabled, visible, toggleLmDetails}) => {
        // /**
        //  * Holds the state of the {@link Landmark} being displayed.
        //  */
        // const selectedLandmarkState = undefined;
        // const [selectedLandmark, setLandmark] = useState<Landmark | undefined>(selectedLandmarkState);
        /**
         * Holds state of a {@link Landmark} object parallel to {@linkcode selectedLandmarkState} that is manipulated when {@linkcode editingEnabled} is true.
         */
        const [updatedLandmark, setUpdatedLandmark] = useState<Landmark | undefined>(undefined);
        /**
         * Holds text of the current {@link LMComment} being added to this {@link Landmark}.
         */
         const [newCommentId, setNewComment] = useState<string>("");
        /**
         * Holds id of the focused {@link LMComment} in the comment list.
         */
        const [focusedCommentId, setFocusedComment] = useState<string>("");
        /**
         * Holds state of the {@link LMComment} being currently edited.
         */
         const [commentBeingEdited, setCommentBeingEdited] = useState<LMComment | undefined>(undefined);

        /**
         * Flag that tracks if the keyboard is open
         */
        const [keyboardOpened, setKeyboardOpened] = useState<boolean>(false);

        /**
         * State that tracks the index of the currently selected photo, if any are selected
         */
        const [selectedImage, setSelectedImage] = useState<number>(-1)

        const [photosBusy, setPhotosBusy] = useState<boolean>(false)
        const [processingPhoto, setProcessingPhoto] = useState<boolean>(false)

        const {
            updateLandmark, updateLandmarkStatus, resetUpdateLm,
            rateLandmarkAsync, rateLandmarkStatus, resetRateLandmark, rating,
            deleteLandmark, deleteLandmarkStatus, resetDeleteLm,
            landmarkRatedByUser, refetchCheckIfRatedByUser,
            landmark, getLandmarkStatus, refetchLandmark,
            addPhoto, addPhotoStatus, resetAddPhoto,
            deletePhoto, deletePhotoStatus, resetDeletePhoto
        } = useLandmarks({
            landmarkId: landmarkId,
            userLMPairing: {userId: authStore.userId, landmarkId: landmarkId}
        });

        const {
            comments,
            addCommentAsync, addCommentStatus, resetAddComment,
            updateCommentAsync, updateCommentStatus, resetUpdateComment,
            deleteCommentAsync, deleteCommentStatus, resetDeleteComment,
        } = useComments(landmarkId)
        const { profile } = useProfile(authStore.userId)

        /**
         * Holds a reference to the Flatlist containing the comments.
         */
        const commentListRef = useRef<FlatList>();
        /**
         * Holds a reference to the text input for posting a new comment
         */
        const commentTextInputRef = useRef<TextInput>();

        useEffect(() => {
        const keyboardDidShowListener = Keyboard.addListener(
          'keyboardDidShow',
          () => {
            setKeyboardOpened(true); // or some other action
          }
        );
        const keyboardDidHideListener = Keyboard.addListener(
          'keyboardDidHide',
          () => {
            setKeyboardOpened(false); // or some other action
          }
        );

        return () => {
          keyboardDidHideListener.remove();
          keyboardDidShowListener.remove();
        };
      }, []);

        useEffect(() => {
            /**
             * Resets the {@linkcode rateLandmark} mutation on successful update.
             * Embedded in a useEffect that listens to the {@linkcode rateLandmarkStatus} value from the {@link useLandmarks} hook.
             * @memberOf LandmarkDetails
             */
             const resetUpdateLandmark = async () => {
                Iif (rateLandmarkStatus == 'success') {
                    resetRateLandmark();
                    await refetchLandmark()
                }

                Iif (updateLandmarkStatus == 'success') {
                    resetUpdateLm();
                    await refetchLandmark()
                }
            }
            resetUpdateLandmark();
        }, [rateLandmarkStatus, updateLandmarkStatus]);

        useEffect(() => {
            /**
             * Resets the {@linkcode updateComment} mutation on successful update.
             * Embedded in a useEffect that listens to the {@linkcode updateCommentStatus} value from the {@link useComments} hook.
             * @memberOf LandmarkDetails
             */
             const resetUpdateComment = () => {
                Iif (updateCommentStatus == 'success') {
                    commentListRef.current?.scrollToItem({animated: true, item: commentBeingEdited});
                    setCommentBeingEdited(undefined)
                    Keyboard.dismiss();
                }
            }
            resetUpdateComment();
        }, [updateCommentStatus]);

        useEffect(() => {
            /**
             * Resets the {@linkcode deleteLandmark} mutation on successful delete.
             * Embedded in a useEffect that listens to the {@linkcode deleteLandmarkStatus} value from the {@link useLandmarks} hook.
             * @memberOf LandmarkDetails
             */
            const resetDeleteLMOnSuccess = () => {
                Iif (deleteLandmarkStatus == 'success') {
                    resetDeleteLm();
                }
            }
            resetDeleteLMOnSuccess();
        }, [deleteLandmarkStatus]);

        useEffect(() => {
            /**
             * Resets the {@link addCommentAsync} mutation on successful add.
             * Embedded in a useEffect that listens to the {@link addCommentAsync} value from the {@link useComment} hook.
             * @memberOf LandmarkDetailsLandmark
             */
            const resetAddCommentOnSuccess = () => {
                Iif (addCommentStatus == 'success') {
                    resetAddComment();
                }
                setNewComment('')
                commentListRef.current?.scrollToIndex({animated: true, index: 0});
                Keyboard.dismiss();
            }
            resetAddCommentOnSuccess();
        }, [addCommentStatus]);

        useEffect(() => {
            /**
             * Clears selected comment when {@linkcode newCommentId} state changes.
             * @memberOf LandmarkDetails
             */
            const clearSelectedOnNewCommentChange = () => {
                setFocusedComment('')
            }
            clearSelectedOnNewCommentChange();
        }, [newCommentId]);

        useEffect(() => {
            /**
             * Refetch the user's rate pairing for the current landmark when {@linkcode landmark} state changes.
             * @memberOf LandmarkDetails
             */
            const refetechRateStatus = async () => {
                await refetchCheckIfRatedByUser();
            }
            refetechRateStatus();
        }, [landmark]);

        /**
         * Calls the {@linkcode updateLandmark} mutation from the {@link useLandmarks} hook and closes the modal once finished.
         */
        const editLandmark = async () => {
            Iif (updatedLandmark) {
                await updateLandmark(updatedLandmark);
            }

            setEditing(false);
        }

        /**
         * Calls the {@linkcode rateLandmarkAsunc} mutation from the {@link useLandmarks} hook. If 1, the landmark will be upvoted. If -1, it will be downvoted
         */
         const rateLandmark = async (rating: 1 | -1) => {
            Iif (landmark) {
                await rateLandmarkAsync({id: landmark.id, rating: rating});
            }
        }

        /**
         * Calls the {@linkcode deleteLandmark} mutation from the {@link useLandmarks} hook and closes the modal once finished.
         */
        const removeLandmark = async () => {
            await deleteLandmark(landmark?.id);
            toggleDetailsPanel(false);
        }

        /**
         * Calls the {@linkcode addComment} mutation from the {@link useComments} hook.
         */
        const addComment = async () => {
            Iif (newCommentId) {
                await addCommentAsync({
                    edited: false,
                    content: newCommentId,
                    landmark: landmark?.id,
                    poster: authStore.userId,
                    poster_name: profile.username,
                    id: ''
                });
            }
        }

        /**
         * Set a comment to be focused in the comment box. It will expand and show delete and edit controls for that comment.
         * If the comment id given is already selected, the comment will be unselected
         */
        const focusComment = (id: string) => {
            if (focusedCommentId == id) {
                setFocusedComment("");
            }
            else {
                setFocusedComment(id);
            }
        }

        /**
         * Set a comment to be the comment currently edited.
         */
        const startEditingComment = (comment: LMComment) => {
            setCommentBeingEdited(comment);
            commentTextInputRef.current.focus();
        }

        /**
         * Calls the {@linkcode editComment} mutation from the {@link useComments} hook.
         */
        const editComment = async (comment: LMComment) => {
            await updateCommentAsync(comment);
        }

        /**
         * Calls the {@linkcode deleteComment} mutation from the {@link useComments} hook.
         */
        const deleteComment = async (id: string) => {
            deleteCommentAsync(id);
        }

        const getWindowWidth = () => {
            return Dimensions.get('window').width
        }

        /**
         * Prompts user for a confirmation to delete the photo that they just tried to delete
         */
        const tryDeletePhoto = (photoId: string) => {
            Alert.alert(
                'Confirm photo removal',
                'Are you sure you want to delete this photo?',
                [
                    {text: 'Yes',
                    onPress: async () => {
                        setPhotosBusy(true)
                        await deletePhoto(photoId)
                        setSelectedImage(-1)
                        await refetchLandmark()
                    }},
                    {text: 'No'}
                ])
        }

        /**
         * Returns a height for the modal depending on if an image is maximzed, if the keyboard is opened, and if the current landmark has photos associated with it
         */
        const determineModalHeight = () => {
            if (selectedImage > -1)
                return Dimensions.get("window").height
            else if (keyboardOpened && Platform.OS == 'android' || editingEnabled || (profile?.id != landmark?.user && landmark?.photos?.length == 0))
                return Dimensions.get("window").height * .5
            else if (landmark?.photos?.length > 0)
                return Dimensions.get("window").height * .9
            else
                return Dimensions.get("window").height * .7
        }

        return (
            <Modal
                useNativeDriver={true}
                useNativeDriverForBackdrop={true}
                avoidKeyboard={false}
                onBackdropPress={() => {
                    if (editingEnabled) {
                        Keyboard.dismiss();
                    } else {
                        toggleLmDetails(false)
                    }
                }}
                style={{justifyContent: "flex-end", height: '100%', margin: 0}}
                isVisible={visible}>
                <SafeAreaView
                    style={[styles.container, {height: determineModalHeight()}]}>
                    {selectedImage > -1 ?
                    <View style={{ padding: 14}}>
                        <View style={{justifyContent: 'space-between', flexDirection: 'row'}}>
                            <TouchableOpacity onPress={() => setSelectedImage(-1)}>
                                <>
                                    <Text style={{color: 'white', fontSize:20}}><FontAwesome name="arrow-left" color="white" size={20}/> Back</Text>
                                </>
                            </TouchableOpacity>
                            <IconButton style={{alignSelf: 'flex-end', marginBottom: 20}} icon="trash" color="white" size={25} onPress={() => tryDeletePhoto(landmark?.photos[selectedImage].id)}/>
                        </View>
                        <ScrollView style={{width: '100%', }}>
                            <Image style={{resizeMode: 'contain', alignSelf: 'center', height: Dimensions.get('window').height * .9, width: getWindowWidth()}} source={{uri: 'data:image/png;base64,' + landmark?.photos[selectedImage].image_b64}}/>
                        </ScrollView>
                    </View>
                    :
                    (getLandmarkStatus == 'success' || getLandmarkStatus == 'idle') &&
                    updateLandmarkStatus == "idle" || updateLandmarkStatus == "success" &&
                    deleteLandmarkStatus == "idle" || deleteLandmarkStatus == "success" ?
                    <>
                    <DetailsHeader
                        processingPhoto={processingPhoto}
                        addPhotoStatus={addPhotoStatus}
                        deletePhotoStatus={deletePhotoStatus}
                        toggleDetailsPanel={toggleDetailsPanel}
                        landmark={landmark}
                        landmarkRatedByUser={landmarkRatedByUser}
                        editLandmark={editLandmark}
                        editingEnabled={editingEnabled}
                        toggleEditing={setEditing}
                        rateLandmark={rateLandmark}
                        removeLandmark={removeLandmark}
                        updatedLandmark={updatedLandmark}
                        profile={profile} />
                    <DetailsBody
                        setProcessingPhoto={setProcessingPhoto}
                        processingPhoto={processingPhoto}
                        profileId={profile?.id}
                        setKeyboardOpened={setKeyboardOpened}
                        keyboardOpened={keyboardOpened}
                        setSelectedImage={setSelectedImage}
                        landmark={landmark}
                        updatedLandmark={updatedLandmark}
                        commentListRef={commentListRef}
                        commentTextInputRef={commentTextInputRef}
                        commentBeingEdited={commentBeingEdited}
                        comments={comments}
                        addComment={addComment}
                        setCommentBeingEdited={setCommentBeingEdited}
                        newCommentId={newCommentId}
                        editComment={editComment}
                        focusComment={focusComment}
                        deleteComment={deleteComment}
                        setNewComment={setNewComment}
                        focusedCommentId={focusedCommentId}
                        startEditingComment={startEditingComment}
                        editingEnabled={editingEnabled}
                        setUpdatedLandmark={setUpdatedLandmark}
                        tryDeletePhoto={tryDeletePhoto}
                        deletePhotoStatus={deletePhotoStatus}
                        toggleLmDetails={toggleLmDetails}
                        addPhoto={addPhoto}
                        addPhotoStatus={addPhotoStatus}/>
                    </> :
                    <View style={{height: '100%', justifyContent: "space-evenly", alignItems: "center", marginHorizontal: 20}}>
                        <Text style={{color: 'white', fontSize: 20}}>{
                            getLandmarkStatus == 'loading' ? "Loading landmark..." :
                            getLandmarkStatus == 'error' ? "Something went wrong trying to load the landmark" :
                            deleteLandmarkStatus == 'loading' ? "Deleting landmark..." :
                            deleteLandmarkStatus == 'error' ? "Something went wrong trying to delete the landmark" :
                            updateLandmarkStatus == 'loading' ? "Updating landmark..." :
                            updateLandmarkStatus == 'error' ? "Something went wrong trying to update the landmark" :
                            addCommentStatus == 'loading' ? "Adding comment..." :
                            addCommentStatus == 'error' ? "Something went wrong trying to add the comment" :
                            updateCommentStatus == 'loading' ? "Updating comment..." :
                            updateCommentStatus == 'error' ? "Something went wrong trying to update the comment" :
                            deleteCommentStatus == 'loading' ? "Deleting comment..." :
                            deleteCommentStatus == 'error' ? "Something went wrong trying to delete the comment" : null}
                        </Text>
                        {
                            deleteLandmarkStatus == 'loading' || updateLandmarkStatus == 'loading' || getLandmarkStatus == "loading" ? <ActivityIndicator color='white' size="large"/> :
                            deleteLandmarkStatus == 'error' || updateLandmarkStatus == 'error' || getLandmarkStatus == "error" ? <PrimaryButton text="Okay" style={{borderColor: 'white', borderWidth: 1}} onPress={() => refetchLandmark()} /> : null
                        }
                    </View>}
                </SafeAreaView>
            </Modal>
        )
    }

    const styles = StyleSheet.create({
        container: {
            backgroundColor: colors.red,
        },
        detailsContainer: {
            flex: 1,
            marginHorizontal: 20
        },

        commentContainer: {
            flex: 5,
            marginBottom: 40,
        },
        title: {

        },
        input: {
            padding: 5,
            color: 'black'
        }
    })

    export default memo(LandmarkDetails);