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

Analytic: Feature to change Air Quality standards on charts #2383

Merged
merged 2 commits into from
Jan 16, 2025

Conversation

OchiengPaul442
Copy link
Contributor

@OchiengPaul442 OchiengPaul442 commented Jan 16, 2025

Summary of Changes (What does this PR do?)

  • Added the feature to toggle and set Air Quality standards on the charts
  • Included Organizations with standards
    • NEMA AND WHO

Status of maturity (all need to be checked before merging):

  • I've tested this locally
  • I consider this code done
  • This change ready to hit production in its current state

Screenshots (optional)

image

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added a new StandardsMenu component for selecting air quality standards.
    • Enhanced chart components to dynamically display air quality standard information.
  • Improvements

    • Updated Redux state management for air quality standards.
    • Improved dropdown menu functionality with mobile and desktop support.
    • Enhanced flexibility of reference line labeling in charts.
  • Technical Updates

    • Integrated new state management for tracking air quality standards across components.

Copy link

coderabbitai bot commented Jan 16, 2025

📝 Walkthrough

Walkthrough

This pull request introduces enhancements to the air quality standards management system by adding a new StandardsMenu component and updating state management through Redux. Key changes include the integration of this dropdown menu in the ChartContainer, modifications to the MoreInsightsChart for dynamic standard values, and adjustments to the rendering of chart reference labels. These updates improve the structure and flexibility of how air quality standards are handled across the application.

Changes

File Change Summary
platform/src/common/components/Charts/ChartContainer.jsx Added StandardsMenu import and included it in dropdown content; updated button label rendering.
platform/src/common/components/Charts/MoreInsightsChart.jsx Integrated Redux useSelector for dynamic AQ standard values; updated WHO_STANDARD_VALUE calculation and label prop.
platform/src/common/components/Charts/components/StandardsMenu.jsx New component for air quality standards dropdown menu with state management and responsive design.
platform/src/common/components/Charts/components/index.jsx Updated CustomReferenceLabel to accept dynamic name prop for flexibility.
platform/src/lib/store/services/charts/ChartSlice.js Added aqStandard to initial state and setAqStandard reducer; modified setChartDataAtOnce to include aqStandard.

Possibly related PRs

Suggested Labels

ready for review

Suggested Reviewers

  • Baalmart
  • Codebmk

Poem

🌍 Standards dance in dropdown's embrace,
Redux state shifts with elegant grace.
Charts whisper tales of pollutant might,
A menu that makes complexity light! 📊
Code evolves, standards take their flight! 🚀


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3473802 and 9dea1b4.

📒 Files selected for processing (1)
  • platform/src/common/components/Charts/components/StandardsMenu.jsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • platform/src/common/components/Charts/components/StandardsMenu.jsx

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 or @coderabbitai title 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

@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: 3

🔭 Outside diff range comments (1)
platform/src/common/components/Charts/MoreInsightsChart.jsx (1)

Add PropType validation for the name prop in CustomReferenceLabel component

The component implementation correctly uses the name prop, but its PropTypes definition is missing validation for this required prop. Add the following to the PropTypes:

  • In platform/src/common/components/Charts/components/index.jsx, update CustomReferenceLabel.propTypes to include the name prop validation:
CustomReferenceLabel.propTypes = {
  viewBox: PropTypes.object,
  name: PropTypes.string.isRequired,
};
🔗 Analysis chain

Line range hint 356-361: Verify the CustomReferenceLabel component's name prop handling.

The dynamic label implementation looks good. Let's verify that the CustomReferenceLabel component properly handles the name prop.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify CustomReferenceLabel component's prop types and usage
ast-grep --pattern 'const CustomReferenceLabel = ({ name, $$ }) => {
  $$$
}'

Length of output: 79


Script:

#!/bin/bash
# First, find files containing CustomReferenceLabel
rg "CustomReferenceLabel" -l

# Then show the context around its definition
rg "CustomReferenceLabel" -B 5 -A 10

Length of output: 6460

🧹 Nitpick comments (5)
platform/src/common/components/Charts/components/StandardsMenu.jsx (3)

7-40: Consider moving air quality standards to a configuration file.

The hardcoded aqStandards array should be moved to a dedicated configuration file for better maintainability and reusability.

-const aqStandards = [
-  {
-    name: 'WHO',
-    value: {
-      pm2_5: 10,
-      pm10: 20,
-      no2: 40,
-    },
-  },
-  // ... other standards
-];

Create a new file constants/airQualityStandards.js:

export const airQualityStandards = [
  {
    name: 'WHO',
    value: {
      pm2_5: 10,
      pm10: 20,
      no2: 40,
    },
  },
  // ... other standards
];

49-68: Consider debouncing the resize event handler.

The window resize event handler should be debounced to improve performance.

+import { debounce } from 'lodash';

 useEffect(() => {
   const handleClickOutside = (event) => {
     if (menuRef.current && !menuRef.current.contains(event.target)) {
       setIsOpen(false);
     }
   };

-  const handleResize = () => {
+  const handleResize = debounce(() => {
     setIsMobile(window.innerWidth < 640);
-  };
+  }, 250);

   document.addEventListener('mousedown', handleClickOutside);
   window.addEventListener('resize', handleResize);
   handleResize();

   return () => {
     document.removeEventListener('mousedown', handleClickOutside);
     window.removeEventListener('resize', handleResize);
+    handleResize.cancel();
   };
 }, []);

106-117: Consider using CSS classes for transitions.

Move transition styles to CSS classes for better maintainability and performance.

+// Add to your CSS file
+.standards-menu {
+  @apply absolute bg-white shadow-md p-1 border border-gray-200 rounded-md transition-all duration-200 ease-in-out overflow-hidden z-10;
+}
+
+.standards-menu--mobile {
+  @apply left-0 right-0 top-full mt-1;
+}
+
+.standards-menu--desktop {
+  @apply right-full top-0 mt-0;
+}

-<div
-  className={`
-    absolute bg-white shadow-md p-1 border border-gray-200 rounded-md
-    transition-all duration-200 ease-in-out overflow-hidden z-10
-    ${isOpen ? 'opacity-100 visible' : 'opacity-0 invisible'}
-    ${isMobile ? 'left-0 right-0 top-full mt-1' : 'right-full top-0 mt-0'}
-  `}
+<div
+  className={`
+    standards-menu
+    ${isOpen ? 'opacity-100 visible' : 'opacity-0 invisible'}
+    ${isMobile ? 'standards-menu--mobile' : 'standards-menu--desktop'}
+  `}
platform/src/lib/store/services/charts/ChartSlice.js (1)

26-33: Consider using TypeScript or PropTypes for better type safety.

The aqStandard object structure should be type-safe to prevent runtime errors.

// If using TypeScript:
interface AQStandard {
  name: string;
  value: {
    pm2_5: number;
    pm10: number;
    no2: number;
  };
}

// If using PropTypes:
import PropTypes from 'prop-types';

const aqStandardShape = {
  name: PropTypes.string.isRequired,
  value: PropTypes.shape({
    pm2_5: PropTypes.number.isRequired,
    pm10: PropTypes.number.isRequired,
    no2: PropTypes.number.isRequired,
  }).isRequired,
};
platform/src/common/components/Charts/MoreInsightsChart.jsx (1)

166-167: Consider adding input validation for the standard value.

While the implementation is correct, consider adding validation to ensure the standard value is non-negative and within an expected range.

-  () => aqStandard.value[pollutantType] || 0,
+  () => {
+    const value = aqStandard.value[pollutantType];
+    return typeof value === 'number' && value >= 0 ? value : 0;
+  },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cd14846 and 3473802.

📒 Files selected for processing (5)
  • platform/src/common/components/Charts/ChartContainer.jsx (4 hunks)
  • platform/src/common/components/Charts/MoreInsightsChart.jsx (5 hunks)
  • platform/src/common/components/Charts/components/StandardsMenu.jsx (1 hunks)
  • platform/src/common/components/Charts/components/index.jsx (2 hunks)
  • platform/src/lib/store/services/charts/ChartSlice.js (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-push-deploy-analytics-platform-preview
  • GitHub Check: test-analytics-platform-changes
🔇 Additional comments (3)
platform/src/common/components/Charts/ChartContainer.jsx (1)

159-159: LGTM! Clean and consistent UI improvements.

The changes improve text wrapping and component organization in the dropdown menu.

Also applies to: 170-174, 183-183, 185-185

platform/src/common/components/Charts/MoreInsightsChart.jsx (2)

384-384: LGTM! Proper dependency management.

The addition of aqStandard.name to the dependencies array is correct and necessary for proper memoization.


29-29: LGTM! Clean integration of Redux state management.

The addition of Redux state management for air quality standards is well-implemented. The selector follows best practices and is properly placed at the component level.

Let's verify the Redux state structure:

Also applies to: 63-63

✅ Verification successful

Verified: Redux state integration is properly implemented

The useSelector hook correctly accesses the aqStandard state from the chart slice, which is properly structured with name and pollutant values. The state management follows Redux best practices and is consistently used across components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the Redux state structure for air quality standards
ast-grep --pattern 'const initialState = {
  $$$
  aqStandard: {
    $$$
  }
  $$$
}'

Length of output: 87


Script:

#!/bin/bash
# Find potential Redux slice files
fd -e js -e ts -e jsx -e tsx | grep -i "slice\|reducer"

# Search for aqStandard in state definitions
rg -l "aqStandard" --type js --type ts --type jsx --type tsx

# Look for Redux state initialization patterns
ast-grep --pattern 'createSlice({
  $$$
})'

Length of output: 66996


Script:

#!/bin/bash
# Search for aqStandard in state definitions and usages
rg -t js -t jsx -t ts -t tsx "aqStandard" -A 2 -B 2

# Search for selector patterns related to aqStandard
rg -t js -t jsx -t ts -t tsx "useSelector.*aqStandard" -A 2 -B 2

# Look for initial state definitions containing aqStandard
ast-grep --pattern 'const initialState = {
  $$$
  aqStandard
  $$$
}'

Length of output: 247


Script:

#!/bin/bash
# Search for any mentions of aqStandard
rg "aqStandard"

# Search for useSelector pattern
rg "useSelector.*state\." -A 2 -B 2

# Look for reducer files that might contain the state
fd "reducer|slice" | xargs rg "initialState"

Length of output: 66805

Comment on lines +75 to +78
const currentStandard =
aqStandards.find((s) => s.name === selectedStandard?.name) ||
aqStandards[0];

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for missing standards.

The current standard selection logic should handle cases where the standard is not found in the array.

 const currentStandard =
-  aqStandards.find((s) => s.name === selectedStandard?.name) ||
-  aqStandards[0];
+  aqStandards.find((s) => s.name === selectedStandard?.name) ??
+  aqStandards[0] ??
+  { name: 'Unknown', value: { pm2_5: 0, pm10: 0, no2: 0 } };
📝 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
const currentStandard =
aqStandards.find((s) => s.name === selectedStandard?.name) ||
aqStandards[0];
const currentStandard =
aqStandards.find((s) => s.name === selectedStandard?.name) ??
aqStandards[0] ??
{ name: 'Unknown', value: { pm2_5: 0, pm10: 0, no2: 0 } };

Comment on lines +163 to +173
setAqStandard: (state, action) => {
const newStandard = action.payload;
if (
state.aqStandard.name !== newStandard.name ||
state.aqStandard.value.pm2_5 !== newStandard.value.pm2_5 ||
state.aqStandard.value.pm10 !== newStandard.value.pm10 ||
state.aqStandard.value.no2 !== newStandard.value.no2
) {
state.aqStandard = newStandard;
}
},
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for the air quality standard values.

The setAqStandard reducer should validate the incoming values to ensure they are within acceptable ranges.

 setAqStandard: (state, action) => {
   const newStandard = action.payload;
+  // Validate standard values
+  const isValidStandard = (standard) => {
+    if (!standard?.value) return false;
+    const { pm2_5, pm10, no2 } = standard.value;
+    return (
+      typeof pm2_5 === 'number' && pm2_5 >= 0 &&
+      typeof pm10 === 'number' && pm10 >= 0 &&
+      typeof no2 === 'number' && no2 >= 0
+    );
+  };
+
+  if (!isValidStandard(newStandard)) {
+    console.error('Invalid air quality standard values');
+    return;
+  }
+
   if (
     state.aqStandard.name !== newStandard.name ||
     state.aqStandard.value.pm2_5 !== newStandard.value.pm2_5 ||
     state.aqStandard.value.pm10 !== newStandard.value.pm10 ||
     state.aqStandard.value.no2 !== newStandard.value.no2
   ) {
     state.aqStandard = newStandard;
   }
 },
📝 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
setAqStandard: (state, action) => {
const newStandard = action.payload;
if (
state.aqStandard.name !== newStandard.name ||
state.aqStandard.value.pm2_5 !== newStandard.value.pm2_5 ||
state.aqStandard.value.pm10 !== newStandard.value.pm10 ||
state.aqStandard.value.no2 !== newStandard.value.no2
) {
state.aqStandard = newStandard;
}
},
setAqStandard: (state, action) => {
const newStandard = action.payload;
// Validate standard values
const isValidStandard = (standard) => {
if (!standard?.value) return false;
const { pm2_5, pm10, no2 } = standard.value;
return (
typeof pm2_5 === 'number' && pm2_5 >= 0 &&
typeof pm10 === 'number' && pm10 >= 0 &&
typeof no2 === 'number' && no2 >= 0
);
};
if (!isValidStandard(newStandard)) {
console.error('Invalid air quality standard values');
return;
}
if (
state.aqStandard.name !== newStandard.name ||
state.aqStandard.value.pm2_5 !== newStandard.value.pm2_5 ||
state.aqStandard.value.pm10 !== newStandard.value.pm10 ||
state.aqStandard.value.no2 !== newStandard.value.no2
) {
state.aqStandard = newStandard;
}
},

@@ -268,7 +268,7 @@ const renderCustomizedLegend = ({ payload }) => {
* @param {Object} props
*/
const CustomReferenceLabel = (props) => {
const { viewBox } = props;
const { viewBox, name } = props;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update PropTypes to include the new name prop.

The name prop should be added to the PropTypes validation.

 CustomReferenceLabel.propTypes = {
   viewBox: PropTypes.object,
+  name: PropTypes.string.isRequired,
 };

Also applies to: 283-283

Copy link
Contributor

New next-platform changes available for preview here

Copy link
Contributor

New next-platform changes available for preview here

@Baalmart Baalmart merged commit 3304936 into staging Jan 16, 2025
30 of 31 checks passed
@Baalmart Baalmart deleted the analytic-standard-impl branch January 16, 2025 12:19
@Baalmart Baalmart mentioned this pull request Jan 16, 2025
5 tasks
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.

2 participants