Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REFACTOR] naver.map.Event 적용 #80

Merged
merged 4 commits into from
Nov 28, 2024
Merged

[REFACTOR] naver.map.Event 적용 #80

merged 4 commits into from
Nov 28, 2024

Conversation

keemsebin
Copy link
Member

@keemsebin keemsebin commented Nov 27, 2024

관련 이슈

close #78

📑 작업 내용

  • 지난번 coderabbit의 리뷰대로 panTo, naver.map.Event를 통해 애니메이션을 추가했습니다.
  • 현재 위치를 보여줄 경우 포커스가 현재 위치로만 가있는 버그가 있었습니다. 따라서 addMarkerToMap 함수에서 실행하던 clearMarks 함수를 useEffect 상단에 위치시켜 모든 렌더링 사이클에서 기존 마커를 정리한 후, 새로운 상태에 따라 필요한 로직만 실행하도록 변경하였습니다.
2024-11-28.3.12.05.mov

💬 리뷰 중점 사항/기타 참고 사항

  • 우려되는 점은 현재 위치에 따라 1차적으로 공간을 탐색한 후, 화면크기에 맞게 2차로 zoom을 조정을 진행하게 되는데 이때 매끄럽지 못한 것이 아쉬운 것 같아요.

Summary by CodeRabbit

  • 새로운 기능
    • 지도 마커 관리 로직 개선으로 사용자 경험 향상.
    • 마커 추가 및 현재 위치 표시 방식 변경.
  • 버그 수정
    • 마커 추가 시 기존 마커 클리어 방식 수정.
    • 현재 위치 마커 표시 조건 개선.
  • 문서화
    • BottomSheetType 추가로 데이터 처리 방식 명확화.

@keemsebin keemsebin added the refactor 리팩토링 label Nov 27, 2024
@keemsebin keemsebin self-assigned this Nov 27, 2024
@keemsebin keemsebin requested a review from houony as a code owner November 27, 2024 18:27
Copy link

coderabbitai bot commented Nov 27, 2024

Walkthrough

이 변경 사항은 NaverMapMapView 컴포넌트의 마커 관리 및 데이터 업데이트 로직을 개선하는 데 중점을 두고 있습니다. NaverMap 컴포넌트에서는 마커를 추가하기 전에 기존 마커를 지우는 로직이 수정되었고, MapView에서는 데이터 업데이트를 위한 새로운 함수가 도입되었습니다. 또한, 마커 추가 및 현재 위치 표시와 관련된 함수들이 이벤트 기반으로 변경되어 사용자 경험을 향상시키는 방향으로 조정되었습니다.

Changes

파일 경로 변경 요약
src/components/features/NaverMap/index.tsx useEffect에서 clearMarkers() 호출 추가 및 addMarkerToMap 호출에서 clearMarkers 인수 제거. currentMarkerToMap 호출 조건 수정.
src/pages/MapView.tsx handleMarkers 함수를 handleDataUpdate로 이름 변경 및 상태 업데이트 로직 통합. handleCurrentLocation에서 상태 리셋 추가.
src/utils/naver/addMarkerToMap.ts clearExistingMarkers 매개변수 제거, 마커 추가 후 맵 경계 조정 로직 변경. 이벤트 리스너를 통해 맵의 경계를 맞추도록 수정.
src/utils/naver/currentMarkerToMap.ts setCentersetZoom 대신 panTo 및 이벤트 기반으로 줌 레벨 조정 로직으로 변경.

Assessment against linked issues

Objective Addressed Explanation
setCenter, setZoomnaver.maps.Event, panTo로 변경 (#78)

Possibly related PRs

Suggested reviewers

  • houony

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Update: 2024년 11월 28일 03시 29분 12초
Storybook 미리보기: https://6709628f8a6eec04b29d4f39-hteymaosgj.chromatic.com/

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (5)
src/utils/naver/currentMarkerToMap.ts (1)

27-29: 줌 레벨을 구성 가능하게 만들어보세요

현재 줌 레벨이 18로 하드코딩되어 있습니다. 다양한 사용 사례에 대응하기 위해 매개변수로 받는 것이 좋을 것 같습니다.

다음과 같이 변경을 제안합니다:

 export const currentMarkerToMap = (
   position: { lat: number; lng: number },
   mapInstance: naver.maps.Map,
-  currentLocationMarkerRef: React.MutableRefObject<naver.maps.Marker | null>
+  currentLocationMarkerRef: React.MutableRefObject<naver.maps.Marker | null>,
+  zoomLevel: number = 18
 ) => {
   // ... existing code ...
   naver.maps.Event.once(mapInstance, 'idle', () => {
-    mapInstance.setZoom(18);
+    mapInstance.setZoom(zoomLevel);
   });
 };
src/utils/naver/addMarkerToMap.ts (1)

56-57: 부드러운 이동 구현에 대한 개선 제안

현재 구현은 잘 작동하지만, 다음과 같은 개선사항을 고려해보시면 좋을 것 같습니다:

  • 이동 거리에 따른 동적인 애니메이션 시간 계산
  • 줌 레벨 변경과 이동이 동시에 일어날 때의 사용자 경험 최적화

다음과 같은 구현을 제안드립니다:

- mapInstance.current?.panTo(center, { duration: 500, easing: 'easeOutCubic' });
+ const currentCenter = mapInstance.current?.getCenter();
+ const distance = currentCenter ? getDistance(currentCenter, center) : 0;
+ const duration = Math.min(Math.max(distance * 100, 300), 1000); // 300ms to 1000ms
+ mapInstance.current?.panTo(center, { duration, easing: 'easeOutCubic' });
src/components/features/NaverMap/index.tsx (1)

Line range hint 1-71: PR 목표에 명시된 panTo 구현이 누락되었습니다.

PR 목표에서 언급된 setCentersetZoompanTo로 전환하는 작업이 구현되지 않았습니다. 현재 코드에서는 여전히 정적인 방식으로 지도 중심점을 설정하고 있습니다.

다음과 같은 개선을 제안드립니다:

 useEffect(() => {
   if (mapRef.current && window.naver && !mapInstance.current) {
     const center = new window.naver.maps.LatLng(initialCenter.lat, initialCenter.lng);
     const map = new window.naver.maps.Map(mapRef.current, {
       center,
       zoom: initialZoom,
       draggable: true,
     });

     const listener = window.naver.maps.Event.addListener(map, 'zoom_changed', () => {
       const currentZoom = map.getZoom();
       handleZoomChange(currentZoom);
     });

     mapInstance.current = map;
     return () => {
       window.naver.maps.Event.removeListener(listener);
       mapInstance.current = null;
     };
   }
 }, [initialZoom, handleZoomChange, initialCenter.lat, initialCenter.lng]);

+const moveToLocation = useCallback((lat: number, lng: number) => {
+  if (mapInstance.current) {
+    const position = new window.naver.maps.LatLng(lat, lng);
+    mapInstance.current.panTo(position, { duration: 500, easing: 'easeOutCubic' });
+  }
+}, []);

 useEffect(() => {
   clearMarkers();
   if (mapInstance.current && markers.length > 0) {
     addMarkerToMap(mapInstance, markers, markersRef, markerDataRef);
+    // 첫 번째 마커 위치로 부드럽게 이동
+    if (markers[0]) {
+      moveToLocation(markers[0].lat, markers[0].lng);
+    }
   }
   if (mapInstance.current && isCurrent && markers.length === 0) {
     currentMarkerToMap(initialCenter, mapInstance.current, currentLocationMarkerRef);
+    moveToLocation(initialCenter.lat, initialCenter.lng);
   }
-}, [clearMarkers, initialCenter, isCurrent, markers]);
+}, [clearMarkers, initialCenter, isCurrent, markers, moveToLocation]);
src/pages/MapView.tsx (2)

35-41: 에러 처리 로직 추가를 고려해주세요.

handleDataUpdate 함수에 다음과 같은 개선사항을 제안드립니다:

  • 데이터 유효성 검증
  • 에러 발생 시 사용자 피드백
  const handleDataUpdate = useCallback(
    (newData: Place[], type: BottomSheetType) => {
+     if (!Array.isArray(newData)) {
+       console.error('Invalid data format');
+       return;
+     }
      clearMarkers();
      newData?.forEach(addMarker);
      setState({ data: newData, type }, token);
    },
    [clearMarkers, addMarker, setState, token]
  );

44-49: 클린업 함수 추가를 검토해주세요.

useEffect에 마커 정리를 위한 클린업 함수 추가를 권장드립니다.

  useEffect(() => {
    const extractedData = location.state?.data;
    if (extractedData?.places.length) {
      handleDataUpdate(extractedData.places, 'extract');
    }
+   return () => {
+     clearMarkers();
+   };
  }, [handleDataUpdate, location.state, setState, token]);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6a033cf and f8f1801.

📒 Files selected for processing (4)
  • src/components/features/NaverMap/index.tsx (1 hunks)
  • src/pages/MapView.tsx (4 hunks)
  • src/utils/naver/addMarkerToMap.ts (2 hunks)
  • src/utils/naver/currentMarkerToMap.ts (1 hunks)
🔇 Additional comments (8)
src/utils/naver/currentMarkerToMap.ts (1)

24-26: 애니메이션 구현이 잘 되었습니다!

panTo 메서드와 duration 설정을 통해 부드러운 애니메이션을 구현한 것이 좋습니다. PR 목표에 맞게 setCenter에서 panTo로 성공적으로 전환되었습니다.

src/utils/naver/addMarkerToMap.ts (2)

11-11: 마커 데이터 참조 추가가 적절해 보입니다!

마커의 메타데이터를 저장하기 위한 ref 추가가 잘 구현되어 있습니다.


52-54: 이벤트 핸들링 로직 검증이 필요합니다.

연속적인 호출이 발생할 경우나 컴포넌트 언마운트 시의 동작을 확인해주세요. 현재 구현에서 다음 사항들을 고려해볼 필요가 있습니다:

  • 연속적인 호출 시 이벤트 리스너의 중복 등록 가능성
  • 컴포넌트 언마운트 시 이벤트 리스너 정리 필요성
✅ Verification successful

이벤트 핸들링 구현이 적절합니다.

naver.maps.Event.once를 사용하는 현재 구현은 다음과 같은 이유로 안전합니다:

  • once 메서드는 이벤트를 한 번만 실행하고 자동으로 제거되므로 중복 등록 문제가 없습니다
  • 컴포넌트 언마운트 시 별도의 정리가 필요하지 않습니다
  • NaverMap 컴포넌트에서 다른 이벤트 리스너들의 정리가 잘 구현되어 있습니다
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for event listener cleanup in the component
# Search for useEffect cleanup functions related to map events

rg -A 5 "useEffect.*map.*Event" 

Length of output: 33


Script:

#!/bin/bash
# Let's check the component implementation more broadly
rg -A 10 "naver\.maps\.Event" 

# Also check for any cleanup patterns in the file
rg -A 10 "useEffect.*map" src/utils/naver/addMarkerToMap.ts

# Check the entire file content to understand the implementation
cat src/utils/naver/addMarkerToMap.ts

Length of output: 4317

src/components/features/NaverMap/index.tsx (2)

61-63: 마커 초기화 로직이 개선되었습니다.

마커를 추가하기 전에 기존 마커를 초기화하는 로직이 useEffect 훅의 시작 부분으로 이동된 것이 적절해 보입니다. 이는 새로운 상태를 기반으로 로직을 실행하기 전에 기존 마커들을 정리하는 일관된 방식을 제공합니다.


65-67: 현재 위치 마커 표시 조건이 개선되었습니다.

markers.length === 0 조건을 추가하여 다른 마커가 없을 때만 현재 위치 마커를 표시하도록 수정된 것이 적절해 보입니다.

src/pages/MapView.tsx (3)

9-9: 타입 안정성 개선이 확인되었습니다!

BottomSheetType 임포트 추가로 타입 안정성이 향상되었습니다.


23-33: 상태 관리 구조가 잘 구성되어 있습니다!

훅들의 구성이 명확하고 의존성이 잘 관리되어 있습니다.


100-103: 상태 초기화 및 업데이트 로직이 적절합니다!

현재 위치 초기화 후 상태를 업데이트하는 순서가 올바르게 구현되어 있습니다.

Comment on lines 73 to +79
clearMarkers();
setState({ data: null, type: null }, token);
navigator.geolocation.getCurrentPosition((position) => {
const { latitude, longitude } = position.coords;
updateLocation(latitude, longitude, 18);
});
}, [clearMarkers, updateLocation]);
}, [clearMarkers, setState, token, updateLocation]);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

위치 정보 오류 처리를 추가해주세요.

현재 위치 조회 시 발생할 수 있는 오류 상황에 대한 처리가 필요합니다.

  const handleCurrentLocation = useCallback(() => {
    clearMarkers();
    setState({ data: null, type: null }, token);
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        updateLocation(latitude, longitude, 18);
      },
+     (error) => {
+       console.error('위치 정보를 가져올 수 없습니다:', error);
+       // 사용자에게 오류 알림 표시
+     },
+     { timeout: 10000 }
    );
  }, [clearMarkers, setState, token, updateLocation]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
clearMarkers();
setState({ data: null, type: null }, token);
navigator.geolocation.getCurrentPosition((position) => {
const { latitude, longitude } = position.coords;
updateLocation(latitude, longitude, 18);
});
}, [clearMarkers, updateLocation]);
}, [clearMarkers, setState, token, updateLocation]);
clearMarkers();
setState({ data: null, type: null }, token);
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
updateLocation(latitude, longitude, 18);
},
(error) => {
console.error('위치 정보를 가져올 수 없습니다:', error);
// 사용자에게 오류 알림 표시
},
{ timeout: 10000 }
);
}, [clearMarkers, setState, token, updateLocation]);

@keemsebin keemsebin merged commit 0613a32 into main Nov 28, 2024
5 checks passed
@keemsebin keemsebin deleted the refactor/#78-mapevent branch November 28, 2024 11:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactor 리팩토링
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[REFACTOR] naver.maps.Event 적용
2 participants