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

Map Glitches Due to Unnecessary Re-Renders #1156

Open
wants to merge 41 commits into
base: main
Choose a base branch
from

Conversation

srinjoy933
Copy link
Contributor

@srinjoy933 srinjoy933 commented Mar 22, 2025

Resolves #1128

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

Ensured single map initialization with useEffect.

Copy link
Contributor

coderabbitai bot commented Mar 22, 2025

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 the map 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.tsx Refactored marker cluster handling: conditionally initializes the cluster group, clears existing layers instead of full removal, and uses map for batch marker creation.

Assessment against linked issues

Objective Addressed Explanation
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 between 73706ee and 0c2d46f.

📒 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 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 generate docstrings to generate 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 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
Contributor

@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

🧹 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 class="popup-content">${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 class="popup-content">${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 using useMemo 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 between 64abd88 and d660ad6.

📒 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 of useMemo and useCallback 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 local map 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 of useCallback to memoize the updateMarkers 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 using bindPopup 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 the updateMarkers 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.

Copy link
Collaborator

@Dishant1804 Dishant1804 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 the setView() 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 the markerClusterRef.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

@Rajgupta36 Rajgupta36 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
Contributor Author

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

@srinjoy933
Copy link
Contributor Author

@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 out Nest-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
let clicked = 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
Contributor Author

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

@Rajgupta36 Rajgupta36 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 👍

@srinjoy933 srinjoy933 marked this pull request as ready for review March 28, 2025 16:51
@srinjoy933
Copy link
Contributor Author

srinjoy933 commented Mar 28, 2025

the recent one

Screenshot 2025-03-29 002149

@srinjoy933
Copy link
Contributor Author

any more changes regarding this @arkid15r ?

Copy link
Collaborator

@kasya kasya left a comment

Choose a reason for hiding this comment

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

Thanks for working on this! Left some comments ⬇️

Copy link
Collaborator

Choose a reason for hiding this comment

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

When we get to the page for the first time the map should show local zoom and not the whole world map.
Example, existing view:
Screenshot 2025-03-29 at 11 52 56 AM
View in this PR:
Screenshot 2025-03-29 at 11 53 06 AM

Copy link
Collaborator

Choose a reason for hiding this comment

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

Why did we change the style/look of the map? I'd prefer to keep it as it was before, with map detailed map with colors for different types of landscape, roads, etc.

icon: markerIcon
});

// Add popup
Copy link
Collaborator

Choose a reason for hiding this comment

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

The name content in the popup should be clickable and lead to that chapter's page.
Example, current view:
Screenshot 2025-03-29 at 11 57 16 AM
View in your PR:
Screenshot 2025-03-29 at 11 56 20 AM

Please reference https://nest.owasp.dev/chapters for all the style issues. We want to keep the map as close to how it looked before this changes, since it was not style related issue.

Copy link
Collaborator

Choose a reason for hiding this comment

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

The map stays light colored in dark mode. We need to have a dark mode map, and ideally it should match what we currently have in https://nest.owasp.dev/chapters
Screenshot 2025-03-29 at 11 58 56 AM

Also, in dark mode I can see that the tooltip point has dark color, where the rest is white. This whole thing should have dark background:
Screenshot 2025-03-29 at 11 59 12 AM

Copy link
Collaborator

Choose a reason for hiding this comment

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

One more thing I noticed.
When there's grouping for chapters - there's no circle for it anymore. For example, here on the map there's a number 4 and no mark for it at all. You can't really see it - there should be a circle to highlight this.
Again, please reference how it looks on https://nest.owasp.dev/chapters
Screenshot 2025-03-29 at 12 00 32 PM

import React, { useEffect, useMemo, useRef, useCallback } from 'react';
import 'leaflet/dist/leaflet.css';
import 'leaflet.markercluster/dist/MarkerCluster.css';
import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
Copy link
Collaborator

Choose a reason for hiding this comment

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

Also, please run checks before submitting code with make check-test-all. There are many unnecessary changes, like added ; for example. This makes it hard to review, since we have to dig through irrelevant code.

We do not use ; at the end of the lines. Running make check-test-all will clean this up for you.

return (
<div>
<style>{`
.custom-popup-container .leaflet-popup-content-wrapper {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I guess this is the reason for a completely new look.
Could you remove/update this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes for sure .
i have updated it as per the changes you suggested can you check it now and suggest any further changes is required or not.thank you @kasya

@srinjoy933 srinjoy933 requested a review from kasya March 29, 2025 22:06
@srinjoy933
Copy link
Contributor Author

@arkid15r and @kasya any changes required?

Copy link
Collaborator

@kasya kasya 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 for pre-commit-config file.

However, I don't see any use of useCallback 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
Contributor Author

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.

@srinjoy933 srinjoy933 requested a review from kasya March 31, 2025 14:33
@srinjoy933
Copy link
Contributor Author

@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
Contributor Author

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
Contributor Author

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
Contributor Author

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.

@srinjoy933 srinjoy933 requested a review from kasya April 3, 2025 02:46
Copy link

sonarqubecloud bot commented Apr 9, 2025

@srinjoy933
Copy link
Contributor Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Map Glitches Due to Unnecessary Re-Renders
6 participants