Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/NestPublic

Map Glitches Due to Unnecessary Re-Renders#1156

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
kasya merged 42 commits intoOWASP:mainfromsrinjoy933:srinjoy933/issue-1128
Apr 20, 2025

Conversation

srinjoy933
Copy link
Contributor

@srinjoy933srinjoy933 commentedMar 22, 2025
edited
Loading

Resolves#1128

Optimized marker management using clearLayers() instead of re-adding markers.

Ensured single map initialization with useEffect.

@coderabbitaicoderabbitai
Copy link
Contributor

coderabbitaibot commentedMar 22, 2025
edited
Loading

Summary by CodeRabbit

  • Refactor
    • Streamlined the way markers are updated and grouped on the interactive map to improve performance and responsiveness.

Walkthrough

The pull request refactors the marker cluster logic in the ChapterMap component. The code now conditionally initializes the marker cluster group and, if already set, clears its layers instead of removing and re-adding markers individually. Additionally, marker creation is refactored to generate an array using themap function and add all markers in a single operation, streamlining the update process and reducing direct manipulations on the map layers.

Changes

File(s)Change Summary
frontend/.../ChapterMap.tsxRefactored marker cluster handling: conditionally initializes the cluster group, clears existing layers instead of full removal, and usesmap for batch marker creation.

Assessment against linked issues

ObjectiveAddressedExplanation
Optimize map marker management to prevent unnecessary re-renders (#1128)

Suggested reviewers

  • arkid15r

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between73706ee and0c2d46f.

📒 Files selected for processing (1)
  • frontend/src/components/ChapterMap.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/components/ChapterMap.tsx

🪧 Tips

Chat

There are 3 ways to chat withCodeRabbit:

  • 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 generate docstrings togenerate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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 ourDocumentation for detailed information on how to use CodeRabbit.
  • Join ourDiscord Community to get help, request features, and share feedback.
  • Follow us onX/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitaicoderabbitaibot 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

🧹 Nitpick comments (3)
frontend/src/components/ChapterMap.tsx (3)

34-47:Consider extracting map configuration to constants.

While the current implementation is correct, the map configuration could be extracted to named constants for better readability and maintainability.

+const DEFAULT_MAP_VIEW = [20, 0];+const DEFAULT_ZOOM_LEVEL = 2;+const MAP_BOUNDS = [[-90, -180], [90, 180]];+const TILE_LAYER_URL = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';+const TILE_LAYER_ATTRIBUTION = '© OpenStreetMap contributors';useEffect(() => {  if (!mapRef.current) {    const map = L.map('chapter-map', {      worldCopyJump: false,      maxBounds: MAP_BOUNDS,      maxBoundsViscosity: 1.0,-    }).setView([20, 0], 2)+    }).setView(DEFAULT_MAP_VIEW, DEFAULT_ZOOM_LEVEL)-    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {-      attribution: '© OpenStreetMap contributors',+    L.tileLayer(TILE_LAYER_URL, {+      attribution: TILE_LAYER_ATTRIBUTION,      className: 'map-tiles',    }).addTo(map)

67-88:Consider extracting marker creation into a separate function.

The marker creation logic could be extracted into a separate function for better code organization and testability.

+const createMarker = (chapter) => {+  const markerIcon = new L.Icon({+    iconAnchor: [12, 41],+    iconRetinaUrl: '/img/marker-icon-2x.png',+    iconSize: [25, 41],+    iconUrl: '/img/marker-icon.png',+    popupAnchor: [1, -34],+    shadowSize: [41, 41],+    shadowUrl: '/img/marker-shadow.png',+  });++  const marker = L.marker([chapter.lat, chapter.lng], { icon: markerIcon }).bindPopup(+    `<div>${chapter.name}</div>`+  );++  marker.on('click', () => {+    window.location.href = `/chapters/${chapter.key}`;+  });++  return marker;+};// In the updateMarkers function:chapters.forEach((chapter) => {-  const markerIcon = new L.Icon({-    iconAnchor: [12, 41],-    iconRetinaUrl: '/img/marker-icon-2x.png',-    iconSize: [25, 41],-    iconUrl: '/img/marker-icon.png',-    popupAnchor: [1, -34],-    shadowSize: [41, 41],-    shadowUrl: '/img/marker-shadow.png',-  });--  const marker = L.marker([chapter.lat, chapter.lng], { icon: markerIcon }).bindPopup(-    `<div>${chapter.name}</div>`-  );--  marker.on('click', () => {-    window.location.href = `/chapters/${chapter.key}`;-  });+  const marker = createMarker(chapter);  markerClusterGroup.addLayer(marker);  bounds.push([chapter.lat, chapter.lng]);});

68-77:Consider using useMemo for the marker icon.

The marker icon configuration is recreated for each marker but remains constant. Consider usinguseMemo to create it once.

+// Create marker icon once+const markerIcon = useMemo(() => new L.Icon({+  iconAnchor: [12, 41],+  iconRetinaUrl: '/img/marker-icon-2x.png',+  iconSize: [25, 41],+  iconUrl: '/img/marker-icon.png',+  popupAnchor: [1, -34],+  shadowSize: [41, 41],+  shadowUrl: '/img/marker-shadow.png',+}), []);// In the updateMarkers function:chapters.forEach((chapter) => {-  const markerIcon = new L.Icon({-    iconAnchor: [12, 41],-    iconRetinaUrl: '/img/marker-icon-2x.png',-    iconSize: [25, 41],-    iconUrl: '/img/marker-icon.png',-    popupAnchor: [1, -34],-    shadowSize: [41, 41],-    shadowUrl: '/img/marker-shadow.png',-  });  const marker = L.marker([chapter.lat, chapter.lng], { icon: markerIcon })...
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between64abd88 andd660ad6.

📒 Files selected for processing (1)
  • frontend/src/components/ChapterMap.tsx (5 hunks)
🔇 Additional comments (9)
frontend/src/components/ChapterMap.tsx (9)

2-2:Properly added React hooks imports.

The addition ofuseMemo anduseCallback imports is correct and necessary for the performance optimizations made in this component.


21-21:Clear comment indicating purpose of useMemo.

Good practice to add explanatory comments for React hooks usage.


31-50:Improved map initialization pattern.

The map initialization has been properly isolated in its own effect with an empty dependency array to ensure it only runs once. Creating a localmap variable before assigning to the ref improves code clarity.


52-53:Informative comment for the new updateMarkers function.

The comment clearly explains the purpose of this function which helps with maintainability.


53-101:Effective use of useCallback for optimization.

Good implementation ofuseCallback to memoize theupdateMarkers function with the correct dependencies[chapters, showLocal]. This prevents unnecessary function recreations during re-renders, directly addressing the PR objective of reducing map glitches.


57-63:Optimized marker management.

The new approach of clearing existing layers instead of recreating the marker cluster group is more efficient. The conditional logic properly handles both the initial case and subsequent updates.


78-80:Simplified popup binding.

The refactored popup creation usingbindPopup directly with a template string makes the code more concise and readable.


95-95:Streamlined local chapters selection.

The modified slice operation more directly expresses the intent to include the maximum number of nearest chapters.


103-106:Proper effect for marker updates.

The new effect correctly triggers theupdateMarkers function when its dependencies change. This separation of concerns improves code organization and ensures markers are updated when needed.

`<div class="popup-content">${chapter.name}</div>`
)

marker.on('click', () => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Please don't change the map behavior on the first click to the marker.
On the first click, it should display a popup with the chapter name, and only on the second click to the name should it redirect to that specific chapter.

kasya reacted with thumbs up emoji
Copy link
Collaborator

@Dishant1804Dishant1804 left a comment

Choose a reason for hiding this comment

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

Overall the useMemo and useCallback hook will improve the performance and avoid unnecessary re renders. please make the suggested changes
Thank you :)

const nearestChapter = chapters[0]
map.setView([nearestChapter.lat, nearestChapter.lng], maxZoom)
map.fitBounds(localBounds, { maxZoom: maxZoom })

Copy link
Collaborator

Choose a reason for hiding this comment

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

map.fitBounds() does not ensure that the nearest chapter gets focused first before fitting bounds, this will lead to unexpected zoom behavior, because thesetView() is removed which was responsible for setting the initial zoomed view on nearest chapter.
Please fix it@srinjoy933

// Create a new marker cluster group
const markerClusterGroup = L.markerClusterGroup()
// Clear existing markers if needed
if (markerClusterRef.current) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

handle the condition where themarkerClusterRef.current is null, because if the previous markers are not cleared properly this may lead to duplicate markers while re rendering.

@@ -27,9 +28,10 @@ const ChapterMap = ({
}))
}, [geoLocData])

// Function to initialize map (runs once)
Copy link
Collaborator

Choose a reason for hiding this comment

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

please remove all the comments from the file they are not necessary here :)

Copy link
Collaborator

@Rajgupta36Rajgupta36 left a comment

Choose a reason for hiding this comment

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

Agree with@abhayymishraa and@Dishant1804 comments. Try not to store tiles in the cache, as it can severely impact memory usage. This is a world map, not just for a specific place.

@abhayymishraa
Copy link
Collaborator

Agree with@Rajgupta36 and@Dishant1804 Storing cache will lead here to memory leak because Leaflet fetches images according to the zoom

@srinjoy933
Copy link
ContributorAuthor

thanks@abhayymishraa ,@Dishant1804 ,@Rajgupta36 for the suggestions . i will make the changes and come with the updated one

@srinjoy933
Copy link
ContributorAuthor

@abhayymishraa ,@Dishant1804 ,@Rajgupta36 can you please review this and tell me ,is there any changes required .thank you.

Comment on lines 81 to 87
let clicked = false
popupContent.addEventListener('click', () => {
if (clicked) {
window.location.href = `/chapters/${chapter.key}`
}
clicked = true
setTimeout(() => (clicked = false), 500)
Copy link
Collaborator

Choose a reason for hiding this comment

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

As I mentioned earlier, please check outNest-Chapters.
When you click on a marker a tooltip appears. Clicking on the name inside the tooltip then it redirects you to that chapter.
We need this same behaviour as this task is for optimizing the re-renders.

Comment on lines 81 to 88
let clicked = false
popupContent.addEventListener('click', () => {
if (clicked) {
window.location.href = `/chapters/${chapter.key}`
}
clicked = true
setTimeout(() => (clicked = false), 500)
})
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
letclicked=false
popupContent.addEventListener('click',()=>{
if(clicked){
window.location.href=`/chapters/${chapter.key}`
}
clicked=true
setTimeout(()=>(clicked=false),500)
})
popupContent.addEventListener('click',()=>{
window.location.href=`/chapters/${chapter.key}`
})

Copy link
Collaborator

Choose a reason for hiding this comment

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

you can use the previous logic it will work fine

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

thanks@abhayymishraa for your suggestions, i have made the changes according to what you have said, can you review that once. thank you

Copy link
Collaborator

@Rajgupta36Rajgupta36 left a comment

Choose a reason for hiding this comment

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

Nice work@srinjoy933 👍

@srinjoy933srinjoy933 requested a review fromkasyaMarch 29, 2025 22:06
@srinjoy933
Copy link
ContributorAuthor

@arkid15r and@kasya any changes required?

Copy link
Collaborator

@kasyakasya left a comment

Choose a reason for hiding this comment

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

This looks as it was before now 👍🏼 Thanks for updating that!
Left a request forpre-commit-config file.

However, I don't see any use ofuseCallback now 🤔 . If it's not necessary anymore, could you update the description of the PR? Just asking because it was mentioned in the description of this issue/PR.

I do like that we now add and remove markers in single bulk operations 👍🏼
Once it's cleaned up and updated - we can merge this in!

@@ -26,17 +26,6 @@ repos:
types:
- html

- repo: https://github.com/jumanjihouse/pre-commit-hook-yamlfmt
Copy link
Collaborator

Choose a reason for hiding this comment

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

@srinjoy933 why you keep removing this hook? 🤔 Please revert this change.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

yes i made this change now .hope it is all ok and ready to merge.

@srinjoy933srinjoy933 requested a review fromkasyaMarch 31, 2025 14:33
@srinjoy933
Copy link
ContributorAuthor

@arkid15r ,@kasya any update for me regarding this pr

@@ -35,7 +35,7 @@ repos:
- --mapping=2
- --offset=2
- --sequence=4
exclude: (.github|frontend/pnpm-lock.yaml)
exclude: (.github|frontend/pnpm-lock.yaml|^\.pre-commit-config\.yaml$)
Copy link
Collaborator

Choose a reason for hiding this comment

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

@srinjoy933 why this change? 🤔 Can we keep it as before? The rest looks good and ready to go!

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

@ kasya can we make it same.as it will not hamper any other such hooks.but due to that hook only many a times test fails ,due to that reason i made it exclude that particular file only ,

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

i myself faced problem in the code quality tests, so i excluded it for that file only. will it be okay to make it there, as it dont hamper in any other cases

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

@kasya will it be okay for you?

Copy link
Collaborator

Choose a reason for hiding this comment

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

@srinjoy933 it doesn't seem to be the problem for other contributors though. 🤔
If you're not sure how to make it not fail the tests you can always ask in our Slack channel for guidance from other contributors.

@srinjoy933srinjoy933 requested a review fromkasyaApril 3, 2025 02:46
@srinjoy933
Copy link
ContributorAuthor

i solved the issue and now i think it is ready to merge.@kasya is it fine now?

Copy link
Collaborator

@kasyakasya left a comment

Choose a reason for hiding this comment

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

Works great! 👍🏼

@sonarqubecloudSonarQubeCloud
Copy link

@kasyakasyaenabled auto-mergeApril 20, 2025 17:23
@srinjoy933srinjoy933 requested a review fromkasyaApril 20, 2025 19:40
@kasyakasya added this pull request to themerge queueApr 20, 2025
Merged via the queue intoOWASP:main with commit0af1ad6Apr 20, 2025
22 checks passed
shdwcodr pushed a commit to shdwcodr/Nest that referenced this pull requestJun 5, 2025
* changes for the issue-1128* updated* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update ChapterMap.tsx* Update .pre-commit-config.yaml* Update ChapterMap.tsx* Update .pre-commit-config.yaml* your commit message---------Co-authored-by: Arkadii Yakovets <2201626+arkid15r@users.noreply.github.com>Co-authored-by: Kate Golovanova <kate@kgthreads.com>
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

@arkid15rarkid15rarkid15r approved these changes

@abhayymishraaabhayymishraaAwaiting requested review from abhayymishraa

@Dishant1804Dishant1804Awaiting requested review from Dishant1804

@Rajgupta36Rajgupta36Awaiting requested review from Rajgupta36

@kasyakasyaAwaiting requested review from kasyakasya is a code owner

Assignees
No one assigned
Labels
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

Map Glitches Due to Unnecessary Re-Renders
6 participants
@srinjoy933@abhayymishraa@Rajgupta36@arkid15r@kasya@Dishant1804

[8]ページ先頭

©2009-2025 Movatter.jp