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

hide filter option condition added #2396

Merged
merged 4 commits into from
Feb 12, 2025
Merged

Conversation

shyambhongle
Copy link
Contributor

In this PR, I have added a filter condition to hide options when an intervention is not available in the project.

  • If only one intervention is present, only that option will be shown.
  • If multiple interventions are available, the default selection will be "All Interventions," along with the specific interventions present.
    Note: I have removed the default "Single/Multi Intervention" option, as it was confusing and seemed unnecessary.

Copy link

vercel bot commented Feb 5, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
planet-webapp-multi-tenancy-setup ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 12, 2025 9:28am
2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
planet-webapp ⬜️ Ignored (Inspect) Feb 12, 2025 9:28am
planet-webapp-temp ⬜️ Ignored (Inspect) Feb 12, 2025 9:28am

Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

Walkthrough

This pull request introduces an existingIntervention property (an array of strings) to the props of two components related to intervention selection. The changes update filtering logic in the intervention list to conditionally render items based on whether they exist in the provided array. Additionally, the MapControls component now computes unique plant types using useMemo, which are then passed as the intervention data for display. The overall control flow of how interventions are chosen and rendered is modified to incorporate these new conditions.

Changes

File(s) Change Summary
src/features/.../InterventionDropDown/InterventionList.tsx
src/features/.../InterventionDropDown/index.tsx
Added existingIntervention: string[] to props; updated filtering logic to skip rendering interventions not present in the array, and introduced a selection function (showVisibleOption) to conditionally choose intervention data.
src/features/.../MapControls.tsx Integrated useMemo to compute uniquePlantTypes from plantLocations; passed this value as existingIntervention to InterventionDropDown; adjusted rendering conditions and class formatting.

Sequence Diagram(s)

sequenceDiagram
    participant MC as MapControls
    participant DD as InterventionDropdown
    participant IL as InterventionList
    participant FS as findMatchingIntervention
    MC->>MC: Retrieve plantLocations
    MC->>MC: Compute uniquePlantTypes via useMemo
    MC->>DD: Pass uniquePlantTypes as existingIntervention
    DD->>DD: Call showVisibleOption()
    alt Single intervention exists
        DD->>FS: findMatchingIntervention(existingIntervention[0])
    else multiple or none
        DD->>DD: Use selectedInterventionType
    end
    DD->>IL: Render intervention list with existingIntervention
    IL->>IL: Filter out interventions not in the existingIntervention array
Loading

Possibly related PRs

  • Fix data explorer queries for single tree registrations #2273: The changes in the main PR are related to the modifications in the existingIntervention property and rendering logic in the InterventionList component, which aligns with the updates in the retrieved PR that also focus on handling specific intervention types and their display logic.
  • Feature/intervention #2343: The changes in the main PR are related to the modifications in the retrieved PR as both involve the introduction of the existingIntervention property and its usage in the InterventionList and InterventionDropdown components, indicating a direct connection in their implementation.
  • Hotfix/intervention-filter #2370: The changes in the main PR are related to those in the retrieved PR as both modify the InterventionList and InterventionDropdown components to include a new property, existingIntervention, which affects their rendering logic.

Suggested reviewers

  • sunilsabatp
  • mohitb35

Poem

I hop in lively code fields where snippets bloom,
A carrot of logic lights up each room.
With filters and hooks, my work takes flight,
Rendering interventions just right.
Celebrate with a twitch of ear and a joyful byte! 🐰✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn config production Use --omit=dev instead.
npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: eslint-config-airbnb@18.2.1
npm error Found: eslint@8.57.1
npm error node_modules/eslint
npm error dev eslint@"^8.26.0" from the root project
npm error peer eslint@"6 || 7 || 8" from @emotion/eslint-plugin@11.12.0
npm error node_modules/@emotion/eslint-plugin
npm error dev @emotion/eslint-plugin@"^11.12.0" from the root project
npm error 15 more (@eslint-community/eslint-utils, ...)
npm error
npm error Could not resolve dependency:
npm error peer eslint@"^5.16.0 || ^6.8.0 || ^7.2.0" from eslint-config-airbnb@18.2.1
npm error node_modules/eslint-config-airbnb
npm error dev eslint-config-airbnb@"^18.2.0" from the root project
npm error
npm error Conflicting peer dependency: eslint@7.32.0
npm error node_modules/eslint
npm error peer eslint@"^5.16.0 || ^6.8.0 || ^7.2.0" from eslint-config-airbnb@18.2.1
npm error node_modules/eslint-config-airbnb
npm error dev eslint-config-airbnb@"^18.2.0" from the root project
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with --force or --legacy-peer-deps
npm error to accept an incorrect (and potentially broken) dependency resolution.
npm error
npm error
npm error For a full report see:
npm error /.npm/_logs/2025-02-12T09_23_42_119Z-eresolve-report.txt
npm error A complete log of this run can be found in: /.npm/_logs/2025-02-12T09_23_42_119Z-debug-0.log


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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 (2)
src/features/projectsV2/ProjectsMap/InterventionDropDown/index.tsx (1)

65-70: Consider memoizing showVisibleOption for performance.

Since this function depends only on existingIntervention and selectedInterventionType, it could benefit from memoization to prevent unnecessary recalculations.

Apply this diff to memoize the function:

-  const showVisibleOption = () => {
+  const showVisibleOption = useMemo(() => {
     if (existingIntervention.length === 1) {
       return findMatchingIntervention(existingIntervention[0]);
     }
     return findMatchingIntervention(selectedInterventionType);
-  }
+  }, [existingIntervention, selectedInterventionType]);
src/features/projectsV2/ProjectsMap/MapControls.tsx (1)

64-66: Improve optional chaining in map function.

The optional chaining operator is used unnecessarily since the existence of plantLocations is already checked.

Apply this diff to simplify the code:

    const uniqueTypes = new Set(
-      plantLocations?.map(location => location.type)
+      plantLocations.map(location => location.type)
    );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b812ab1 and 11e3fd4.

📒 Files selected for processing (3)
  • src/features/projectsV2/ProjectsMap/InterventionDropDown/InterventionList.tsx (1 hunks)
  • src/features/projectsV2/ProjectsMap/InterventionDropDown/index.tsx (4 hunks)
  • src/features/projectsV2/ProjectsMap/MapControls.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
src/features/projectsV2/ProjectsMap/InterventionDropDown/InterventionList.tsx (1)

39-42: LGTM! Filtering logic looks good.

The implementation correctly filters out interventions that don't exist in the project.

src/features/projectsV2/ProjectsMap/MapControls.tsx (2)

61-69: LGTM! Good use of memoization.

The implementation of uniquePlantTypes using useMemo is efficient and prevents unnecessary recalculations.


159-166: LGTM! Improved intervention dropdown visibility logic.

The condition uniquePlantTypes.length > 0 ensures the dropdown is only shown when there are actual interventions available.

Also applies to: 179-185

Comment on lines 43 to 45
if (intervention.value == 'all' && existingIntervention.length === 1) {
return
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incomplete return statement.

The early return for the 'all' intervention case is missing a value, which could lead to undefined behavior.

Apply this diff to fix the return statement:

-          return
+          return null
📝 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
if (intervention.value == 'all' && existingIntervention.length === 1) {
return
}
if (intervention.value == 'all' && existingIntervention.length === 1) {
return null
}

Copy link
Contributor

@mariahosfeld mariahosfeld left a comment

Choose a reason for hiding this comment

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

Functionality looks good to me.

@shyambhongle
Copy link
Contributor Author

@sunilsabatp I have refactored code based on your feedback, could you please review it again.

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: 0

🧹 Nitpick comments (3)
src/features/projectsV2/ProjectsMap/InterventionDropDown/InterventionList.tsx (2)

34-41: Consider adding input validation.

The shouldRenderIntervention function should validate the input to handle edge cases.

Apply this diff to add input validation:

 const shouldRenderIntervention = (interventionValue: string) => {
+  if (!interventionValue || !Array.isArray(existingIntervention)) {
+    return false;
+  }
   const showAllIntervention = interventionValue === 'all';
   const showExisitingIntervention = existingIntervention.includes(interventionValue);
   if (showAllIntervention && existingIntervention.length === 1) {
     return false;
   }
   return showExisitingIntervention || showAllIntervention;
 };

46-63: Simplify template literals in className.

The template literal for className can be simplified by moving the ternary outside.

Apply this diff to improve readability:

-    <ul
-      className={`${styles.interventionListOptions} ${!hasProjectSites ? styles.interventionListOptionsAbove : styles.interventionListOptionsBelow
-        }`}
-    >
+    <ul
+      className={`${styles.interventionListOptions} ${
+        hasProjectSites ? styles.interventionListOptionsBelow : styles.interventionListOptionsAbove
+      }`}
+    >
src/features/projectsV2/ProjectsMap/MapControls.tsx (1)

136-141: Simplify nested ternary operator.

The layerToggleClass uses nested ternary operators which can be hard to read and maintain.

Consider using a more readable approach:

-  const layerToggleClass = `${styles.layerToggle} ${isMobile
-    ? mobileOS === 'android'
-      ? styles.layerToggleAndroid
-      : styles.layerToggleIos
-    : styles.layerToggleDesktop
-    }`;
+  const getLayerToggleStyle = () => {
+    if (!isMobile) return styles.layerToggleDesktop;
+    return mobileOS === 'android' ? styles.layerToggleAndroid : styles.layerToggleIos;
+  };
+  const layerToggleClass = `${styles.layerToggle} ${getLayerToggleStyle()}`;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 11e3fd4 and 38bef94.

📒 Files selected for processing (3)
  • src/features/projectsV2/ProjectsMap/InterventionDropDown/InterventionList.tsx (1 hunks)
  • src/features/projectsV2/ProjectsMap/InterventionDropDown/index.tsx (4 hunks)
  • src/features/projectsV2/ProjectsMap/MapControls.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/features/projectsV2/ProjectsMap/InterventionDropDown/index.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
src/features/projectsV2/ProjectsMap/InterventionDropDown/InterventionList.tsx (1)

18-18: LGTM! Props interface updated correctly.

The existingIntervention prop is properly typed as string[] in the InterventionListProps interface.

src/features/projectsV2/ProjectsMap/MapControls.tsx (2)

61-69: Optimize Set initialization.

The current implementation of uniquePlantTypes can be further optimized.

As suggested in the past review comments, consider using a for loop for better performance with large datasets. Additionally, pre-allocate the Set size if possible:

 const uniquePlantTypes = useMemo(() => {
   if (!plantLocations) return [];
 
-  const types = new Set();
+  const types = new Set(plantLocations.length);
   for (let i = 0; i < plantLocations.length; i++) {
     types.add(plantLocations[i].type);
   }
   return [...types];
 }, [plantLocations]);

159-166: Verify the impact of uniquePlantTypes on rendering.

The component now relies on uniquePlantTypes.length to conditionally render the InterventionDropDown. Ensure this doesn't cause flickering during initial load or re-renders.

Run this script to check the usage of uniquePlantTypes:

Also applies to: 179-185

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check for potential race conditions or flickering issues
# Look for useEffect or other hooks that might affect plantLocations

ast-grep --pattern 'useEffect($$$) {
  $$$
  plantLocations
  $$$
}'

Length of output: 70


Below are additional confirmation steps to ensure we understand how uniquePlantTypes behaves. It appears that the earlier search for asynchronous usage (via a useEffect hook) related to a similar variable (initially targeting plantLocations) yielded no results. To double‐check whether the value of uniquePlantTypes might be changing asynchronously in a way that could cause flickering in the rendering of InterventionDropDown, please run the following shell scripts:

If these searches don’t reveal any asynchronous hooks (like a useEffect) or state updates that cause a delayed update to uniquePlantTypes, then the conditional render based on uniquePlantTypes.length > 0 should not inherently lead to flickering.

Action: After reviewing the output from these scripts, please manually verify (in the UI and during component lifecycle analysis) that the value of uniquePlantTypes remains stable between the initial render and subsequent updates. This manual check is key to being confident that no flickering occurs during initial load or re-renders.


🏁 Script executed:

[run_scripts]
#!/bin/bash
# Check for occurrences and context of "uniquePlantTypes" in the file
rg "uniquePlantTypes" -n -C 5 src/features/projectsV2/ProjectsMap/MapControls.tsx

Length of output: 1841


🏁 Script executed:

[run_scripts]
#!/bin/bash
# Look for usage of useMemo (or similar patterns) that compute uniquePlantTypes,
# which would help ensure that its value is memoized and stable between renders.
rg "useMemo.*uniquePlantTypes" -n src/features/projectsV2/ProjectsMap/MapControls.tsx

Length of output: 209


UniquePlantTypes Rendering Stability Verified

  • uniquePlantTypes is computed using useMemo (line 61) so its value is memoized based on plantLocations.
  • There are no additional asynchronous hooks (e.g., useEffect) affecting its calculation that could induce rendering flicker.
  • The dropdown is conditionally rendered only when uniquePlantTypes.length > 0, which prevents unstable behavior.

Manual UI verification is recommended, but the static analysis confirms no evidence of flickering issues.

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 (1)
src/features/projectsV2/ProjectsMap/MapControls.tsx (1)

79-82: Consider renaming for clarity.

While the logic is correct, consider renaming canShowInterventionDropdown to something more explicit like hasMultipleInterventions to better reflect its purpose.

-  const canShowInterventionDropdown =
+  const hasMultipleInterventions =
     isProjectDetailsPage &&
     selectedTab === 'field' &&
     uniquePlantTypes.length > 1;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3286e9d and 76da4c5.

📒 Files selected for processing (1)
  • src/features/projectsV2/ProjectsMap/MapControls.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
src/features/projectsV2/ProjectsMap/MapControls.tsx (2)

5-5: LGTM!

The addition of useMemo import and plantLocations prop is clean and follows React best practices.

Also applies to: 57-57


60-68: LGTM! Optimized implementation using for loop.

The implementation follows the suggested optimization for better performance with large datasets.

@@ -146,6 +160,7 @@ const MapControls = ({
{...interventionDropDownProps}
isMobile={isMobile}
hasProjectSites={hasProjectSites}
existingIntervention={uniquePlantTypes}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the type definition of existingIntervention prop.

The prop is consistently added, but let's verify its type definition in the InterventionDropDown component.

Also applies to: 182-182


🏁 Script executed:

#!/bin/bash
# Search for the InterventionDropDown component's prop types
ast-grep --pattern 'interface $name {
  $$$
  existingIntervention$_
  $$$
}'

Length of output: 79


I'll now run an additional shell script to locate the file(s) for the InterventionDropDown component and inspect its prop types—including the definition for the existingIntervention prop—to verify its type definition.


🏁 Script executed:

#!/bin/bash
# Find files with "InterventionDropDown" in the filename and display their contents
fd -e tsx -i "InterventionDropDown" | xargs -I {} sh -c 'echo "File: {}"; echo "------"; cat {}'

Length of output: 98


I'll now run a script to search the entire repository for the keyword "existingIntervention" to locate where and how its type is defined.


🏁 Script executed:

#!/bin/bash
# Search for occurrences of "existingIntervention" in TypeScript/TSX files
rg -n "existingIntervention" -ttsx

Length of output: 62


I'll now run a script to search for the keyword "InterventionDropDown" across the repository to locate its definition and references for further inspection of its prop types.


🏁 Script executed:

#!/bin/bash
# Search for any occurrence of "InterventionDropDown" to locate its definition or usage.
rg -n "InterventionDropDown" .

Length of output: 509


Missing or Undeclared Type for existingIntervention in InterventionDropDown

Our investigation couldn’t locate an explicit type declaration for the existingIntervention prop in the InterventionDropDown component. This suggests that the prop may currently be handled implicitly (or not declared at all) rather than through a formally defined interface or type. To improve type safety and clarity, please verify and add an appropriate type definition—such as by defining an InterventionDropDownProps interface that includes an explicit type for existingIntervention (matching the type of uniquePlantTypes) and applying it to the component’s props.

  • Location to Address: InterventionDropDown component (likely located in src/features/projectsV2/ProjectsMap/InterventionDropDown/)
  • Action: Declare an interface (e.g., InterventionDropDownProps) that includes existingIntervention with the correct type and update the component accordingly.

@mohitb35 mohitb35 merged commit d631314 into develop Feb 12, 2025
9 checks passed
@mohitb35 mohitb35 deleted the hotfix/intervention-filter branch February 12, 2025 09:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants