-
-
Notifications
You must be signed in to change notification settings - Fork 68
Aditya-Feat: Add filters to Issues Breakdown Chart in BM Dashboard #4324
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
Open
Aditya-gam
wants to merge
19
commits into
development
Choose a base branch
from
Aditya-feature/add-filters-to-issues-breakdown-chart
base: development
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Aditya-Feat: Add filters to Issues Breakdown Chart in BM Dashboard #4324
Aditya-gam
wants to merge
19
commits into
development
from
Aditya-feature/add-filters-to-issues-breakdown-chart
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add comprehensive state management for filtering functionality in the Issues Breakdown Chart component. This establishes the foundation for implementing multi-dimensional filtering capabilities. Changes: - Add filter state variables for projects, date range, and issue types * selectedProjects: array to store selected project IDs * startDate: string for start date filter (YYYY-MM-DD format) * endDate: string for end date filter (YYYY-MM-DD format) * selectedIssueTypes: array to store selected issue type filters - Add state for available filter options * availableIssueTypes: stores fetched issue type options * availableProjects: stores available project list for selection - Preserve all existing functionality and states * Maintains data, loading, error, and darkMode states * No changes to existing data fetching or rendering logic
Add API integration to fetch available issue types for filter dropdown. This populates the availableIssueTypes state that will be used for the Issue Type filter UI in subsequent steps. Changes: - Add new useEffect hook that runs on component mount - Fetch issue types from /api/issues/types endpoint - Extract and store issueTypes from response.data.issueTypes - Implement graceful error handling * Falls back to empty array if fetch fails * Non-blocking: chart continues to work without filters * Errors don't affect primary chart functionality Implementation details: - Follows existing async/await pattern used in fetchData - Validates response data structure before setting state - Uses consistent endpoint format with REACT_APP_APIENDPOINT - Matches project code style and conventions
Implement flexible project data fetching that prioritizes Redux store and falls back to API when needed. This populates the availableProjects state for the Project filter dropdown in subsequent steps. Changes: - Add Redux selector for project data * Checks state.bmProjects first * Falls back to state.allProjects?.projects * Defaults to empty array if neither exists - Add useEffect hook with hybrid data strategy * Primary: Use Redux store if projects available * Fallback: Fetch from /projects API endpoint * Dependencies: Re-runs when reduxProjects changes - Implement graceful error handling * Falls back to empty array if API fetch fails * Non-blocking: chart continues to work without filters * Errors don't affect primary chart functionality Implementation details: - Follows existing async/await pattern used in other fetches - Validates data structure before setting state (Array.isArray check) - Uses consistent endpoint format with REACT_APP_APIENDPOINT - Reactive to Redux state changes via dependency array - Matches project code style and conventions Benefits: - Efficient: Reuses existing Redux data when available - Resilient: API fallback ensures data availability - Performance: Avoids unnecessary API calls when data exists in store
…cing Implement complete filter integration with the API endpoint, including query parameter construction, debounced requests, and enhanced error handling. This enables dynamic chart updates based on filter selections. Changes: - Add useRef hook for debouncing timeout management * Stores timeout reference to prevent memory leaks * Allows cleanup of pending timeouts - Refactor fetchData function to accept filters parameter * Build query string using URLSearchParams * Add projects filter as comma-separated project IDs * Add startDate and endDate in YYYY-MM-DD format * Add issueTypes filter as comma-separated strings * Construct clean URL with conditional query string - Enhance error handling for validation errors * Specifically handle 400 status errors * Extract user-friendly messages from API response * Check err.response.data?.error and err.response.data?.message * Fallback to generic message for unexpected error formats * Preserve existing error handling for other status codes - Update useEffect hook with filter integration * Add all filter states to dependency array * Implement 300ms debouncing to prevent excessive API calls * Clear existing timeout before setting new one * Include cleanup function to prevent memory leaks * Auto-fetch data when any filter changes Implementation details: - Uses URLSearchParams for query string building (standard pattern) - Debouncing improves performance and reduces server load - Proper cleanup prevents memory leaks on unmount - Validation error handling provides better UX - Follows React best practices and project conventions Benefits: - Performance: Debouncing reduces unnecessary API calls - UX: User-friendly error messages for validation issues - Reliability: Proper cleanup prevents memory leaks - Maintainability: Clean, readable query string construction
Implement robust data processing function to normalize API responses into the chart's fixed three-category structure. This ensures consistent data format regardless of API response variations and handles diverse property naming conventions. Changes: - Add processChartData function for data normalization * Validates input data (null/array checks) * Extracts projectId and projectName with fallbacks * Initializes all three issue types to 0 by default * Returns empty array for invalid input - Implement two-phase property matching strategy Phase 1 - Exact matches: * Checks for equipmentIssues, laborIssues, materialIssues * Handles materialsIssues variant (plural) * Tracks matched keys to prevent double-counting Phase 2 - Pattern matching for unmapped properties: * Equipment patterns: equipment, tool, machine * Labor patterns: labor, labour * Material patterns: material, supply, resource * Skips project metadata (_id, name, projectId, projectName) * Only processes properties not matched in Phase 1 - Integrate processChartData into fetchData * Processes API response before setting state (line 173) * Ensures chart always receives normalized data structure * Maintains backward compatibility with existing API format Edge case handling: - Empty/null API data returns empty array - Missing properties default to 0 - Non-numeric values coerced to number or default to 0 - Zero values skipped in pattern matching (optimization) - Prevents accumulation if exact match already found Implementation details: - Uses Set for efficient matched key tracking - Case-insensitive pattern matching (toLowerCase) - Additive accumulation for pattern matches - Comprehensive JSDoc documentation - Follows project code style and conventions Benefits: - Flexibility: Handles various API response formats - Reliability: Consistent output structure guaranteed - Maintainability: Clear separation of data transformation logic - Performance: Efficient tracking prevents double-counting - Extensibility: Easy to add new pattern matching rules
Implement project filter dropdown using react-select with multi-selection
capability, dark mode support, and comprehensive styling. This provides
users with an intuitive interface to filter issue data by projects.
Changes - Component (IssuesBreakdownChart.jsx):
- Add react-select import for multi-select dropdown
- Create filters section between legend and chart
* Positioned using filtersRow container
* Wrapped in filterGroup for consistent layout
- Implement react-select multi-select dropdown
* isMulti prop enables multiple project selection
* classNamePrefix="customSelect" for custom styling
* Maps availableProjects to option objects:
{ value: project._id || project.projectId,
label: project.name || project.projectName }
* Handles different property name conventions
- Add onChange handler for filter updates
* Updates selectedProjects state with array of IDs
* Extracts values from selected options
* Handles null/undefined (sets empty array)
* Triggers debounced API call via state change
- Implement comprehensive dark mode styling
* Control: #2c3344 background, #364156 border
* Menu: #2c3344 background matching control
* Options: #0d55b3 selected, #364156 focused
* Multi-value tags: #375071 background
* Hover states: #0d55b3 with white text
* Text colors: #e0e0e0 normal, #fff selected
- Add light mode styling
* Multi-value tags: #e2e7ee background
* Consistent font sizing (14px menu, 12px tags)
* Hover states match project patterns
- User experience features
* Placeholder: "Select Projects"
* isClearable for quick deselection
* isDisabled when no projects available
* Proper label association (htmlFor/id)
* Minimum height 38px for consistency
Changes - Styles (IssueBreakdownChart.module.css):
- Add .filtersRow class
* Flex container with 24px gap
* flex-wrap for responsive layout
* 24px top margin, 20px bottom margin
* Full width
- Add .filterGroup class
* Flex column layout for label + control
* min-width: 250px for usability
* flex: 1 for equal distribution
- Add .filterLabel class
* 14px font size, 600 weight
* 8px bottom margin for spacing
* Uses var(--text-color) for theme support
Implementation details:
- Follows patterns from ToolsHorizontalBarChart and ProjectRiskProfileOverview
- Handles property name variations (_id vs projectId, name vs projectName)
- Dark mode colors match project design system
- Value extraction uses controlled component pattern
- Filter state changes trigger existing debounced fetch logic
Benefits:
- UX: Intuitive multi-select with clear visual feedback
- Accessibility: Proper label associations and disabled states
- Consistency: Matches existing project filter patterns
- Theme support: Seamless dark/light mode switching
- Responsive: Flexible layout adapts to container width
Implement comprehensive filter UI with project multi-select and date range
inputs. Includes validation logic, dark mode support, and accessibility
features for an enhanced user experience.
Changes - JavaScript (IssuesBreakdownChart.jsx):
- Import react-select for multi-select dropdown functionality
- Add date change handlers with cross-validation
* handleStartDateChange: Updates startDate, adjusts endDate if invalid
* handleEndDateChange: Updates endDate, adjusts startDate if invalid
* Ensures endDate >= startDate bidirectionally
- Implement Project Filter UI
* Uses react-select with isMulti for multiple project selection
* Maps availableProjects to {value, label} option format
* Handles different property names (_id/projectId, name/projectName)
* Controlled component synced with selectedProjects state
* onChange updates selectedProjects with array of IDs
* Features: isClearable, disabled when no projects available
* Placeholder: "Select Projects"
- Implement Date Range Filter UI
* Two native HTML <input type="date"> elements
* Start Date and End Date with "to" separator
* Format: YYYY-MM-DD (native date input standard)
* HTML validation: min attribute on endDate tied to startDate
* JavaScript validation in handlers for cross-field logic
- Dark mode styling for react-select
* Control, menu, option backgrounds (#2c3344, #364156)
* Selected state (#0d55b3), focused state (#364156)
* Multi-value tags with appropriate colors (#375071)
* Hover states for remove buttons
* Light mode styling for standard appearance
- Add filters section layout
* Positioned between legend and chart container
* Uses filtersRow container with flex layout
* Two filterGroup sections (Project, Date Range)
Changes - CSS (IssueBreakdownChart.module.css):
- .filtersRow: Flex container with 24px gap, flex-wrap support
- .filterGroup: Column layout, min-width 250px, flex: 1
- .filterLabel: 14px font, 600 weight, 8px bottom margin
- .datePickerGroup: Flex container with 8px gap for inputs
- .datePicker: Native date input styling
* Flex: 1 for equal width distribution
* Border, padding, border-radius consistent with design
* CSS variables for theme support
* Min-height: 38px matches react-select height
- .datePicker:focus: Focus states
* Primary color border
* Box shadow for visual feedback
- .dateSeparator: "to" text styling, nowrap
Accessibility features:
- Proper label association with htmlFor and id attributes
- aria-label on both date inputs ("Start date", "End date")
- Semantic HTML structure
- Keyboard navigation support (native inputs and react-select)
Validation approach:
- HTML min attribute prevents invalid selection in date picker
- JavaScript handlers ensure data consistency in state
- Bidirectional validation (start adjusts end, end adjusts start)
Implementation details:
- Follows patterns from ToolsHorizontalBarChart.jsx
- Follows patterns from ProjectRiskProfileOverview.jsx
- Consistent with project's react-select usage patterns
- Dark mode colors match project theme standards
- CSS variables enable automatic theme switching
Benefits:
- UX: Intuitive multi-select and date range controls
- Accessibility: ARIA labels and semantic HTML
- Consistency: Matches existing project UI patterns
- Validation: Prevents invalid date ranges
- Theming: Full dark/light mode support
Implement issue type filter UI with a fixed set of three issue categories,
including display name to API property name mapping. This completes the
full filtering suite for the Issues Breakdown Chart.
Changes:
- Add FIXED_ISSUE_TYPES constant
* Array with three fixed display names:
- 'Equipment Issues'
- 'Labor Issues'
- 'Materials Issues'
* Does not use availableIssueTypes from API
* Ensures filter options match chart categories exactly
- Add ISSUE_TYPE_MAPPING constant
* Maps user-friendly display names to API property names
* 'Equipment Issues' → 'equipmentIssues'
* 'Labor Issues' → 'laborIssues'
* 'Materials Issues' → 'materialIssues'
* Enables seamless translation between UI and API
- Update fetchData function with display name mapping
* Maps selected display names to API property names before sending
* Uses ISSUE_TYPE_MAPPING for translation
* Filters out undefined values with .filter(Boolean)
* Only appends issueTypes param if valid mapped values exist
* Prevents sending invalid or empty issue type filters
- Add Issue Type Filter UI
* Positioned in filtersRow after Date Range Filter
* Uses react-select with isMulti for multiple selection
* Options derived from FIXED_ISSUE_TYPES (not from API)
* Controlled component synced with selectedIssueTypes state
* onChange updates state with array of display names
* Handles null/undefined gracefully (defaults to empty array)
- Dark mode styling for Issue Type Filter
* Control, menu, option backgrounds (#2c3344, #364156)
* Selected state (#0d55b3), focused state (#364156)
* Multi-value tags (#375071 dark, #e2e7ee light)
* Hover states for remove buttons
* Placeholder color (#aaaaaa)
* Consistent with Project Filter styling
- Filter integration
* Placeholder: "Select Issue Types"
* isClearable for easy deselection
* No isDisabled prop (always available)
* Triggers debounced API call via useEffect hook
* Works seamlessly with other filters
Accessibility features:
- Proper label association (htmlFor="issue-type-filter")
- Semantic HTML structure
- Keyboard navigation support via react-select
- Clear visual feedback for selection
Design decisions:
- Fixed types ensure consistency with chart structure
- Display names provide better UX than camelCase property names
- Mapping layer separates UI concerns from API concerns
- No dependency on API /issues/types endpoint for filter options
- Filter always shows three options regardless of data availability
Implementation details:
- Follows established react-select patterns in codebase
- Matches styling of Project Filter for visual consistency
- Integrates with existing debounced filter system
- No new CSS classes required (reuses existing layout)
Benefits:
- UX: User-friendly display names instead of technical property names
- Consistency: Filter options always match chart categories
- Maintainability: Clear separation between display and API layers
- Reliability: No dependency on external API for filter options
- Integration: Works seamlessly with existing filter architecture
…lity
Implement Issue Type multi-select filter with fixed categories and a
Reset Filters button to clear all active filters. Includes display name
to API property mapping and complete dark mode support.
Changes - JavaScript (IssuesBreakdownChart.jsx):
- Add fixed issue type constants
* FIXED_ISSUE_TYPES: ['Equipment Issues', 'Labor Issues', 'Materials Issues']
* Uses fixed array instead of API-fetched types
* Ensures consistency with chart's three-category structure
- Add display name to API property name mapping
* ISSUE_TYPE_MAPPING: Maps display names to API properties
* 'Equipment Issues' → 'equipmentIssues'
* 'Labor Issues' → 'laborIssues'
* 'Materials Issues' → 'materialIssues'
- Implement handleResetFilters function
* Clears selectedProjects (sets to [])
* Clears startDate (sets to null)
* Clears endDate (sets to null)
* Clears selectedIssueTypes (sets to [])
* Triggers automatic data refetch via useEffect hook
- Update fetchData with issue type mapping
* Maps display names to API property names before sending request
* Uses ISSUE_TYPE_MAPPING for transformation
* Filters out undefined values with filter(Boolean)
* Only appends issueTypes if valid mapped values exist
- Implement Issue Type Filter UI
* Uses react-select with isMulti for multiple selection
* Options from FIXED_ISSUE_TYPES (not API-fetched)
* Controlled component synced with selectedIssueTypes state
* onChange updates selectedIssueTypes with display names
* Features: isClearable for clearing selections
* Placeholder: "Select Issue Types"
* Positioned in filtersRow after Date Range Filter
- Add Reset Filters button UI
* Positioned after filtersRow in resetButtonContainer
* onClick triggers handleResetFilters
* Button text: "Reset Filters"
* Type: "button" (prevents form submission)
- Dark mode styling for Issue Type select and Reset button
* react-select styling matches Project filter pattern
* Control, menu, option backgrounds (#2c3344, #364156)
* Selected state (#0d55b3), focused state (#364156)
* Multi-value tags (#375071) with hover states
* Reset button colors: #DE6A6A (dark) / #f44336 (light)
* Reset button text: #0d1b2a (dark) / white (light)
Changes - CSS (IssueBreakdownChart.module.css):
- .resetButtonContainer: Right-aligned flex container
* display: flex, justify-content: flex-end
* margin-top: 16px, margin-bottom: 8px
* width: 100% for full container width
- .resetButton: Button styling with transitions
* padding: 8px 16px, border-radius: 6px
* font-weight: 500, font-size: 14px
* cursor: pointer, no border
* transition: all 0.3s ease for smooth animations
- .resetButton:hover: Hover state effects
* opacity: 0.9 for subtle darkening
* transform: translateY(-1px) for lift effect
- .resetButton:active: Active state
* transform: translateY(0) returns to normal position
Accessibility features:
- Proper label association with htmlFor and id ("issue-type-filter")
- Keyboard navigation support via react-select
- Button type="button" prevents unintended form submission
- Semantic HTML structure maintained
Data flow:
1. User selects issue types (display names stored in state)
2. Display names mapped to API properties in fetchData
3. API receives property names (equipmentIssues, laborIssues, etc.)
4. Response processed by processChartData
5. Chart displays filtered data
Reset flow:
1. User clicks Reset Filters button
2. handleResetFilters clears all filter states
3. useEffect detects state changes (dependency array)
4. fetchData called with empty filters (300ms debounce)
5. Chart updates to show all unfiltered data
Implementation details:
- Follows patterns from InteractiveMap.jsx (red reset button)
- Consistent with project's react-select usage patterns
- Display name mapping ensures API compatibility
- Fixed types ensure chart consistency
- Dark mode colors match project theme standards
Benefits:
- UX: Easy filter reset with single click
- Consistency: Fixed types align with chart structure
- Maintainability: Centralized display-to-API mapping
- Flexibility: Can filter by specific issue categories
- Theming: Complete dark/light mode support
- Automatic: Reset triggers refetch without manual action
…ates Implement comprehensive responsive design with multiple breakpoints and enhance interactive states for filter controls. Ensures optimal viewing experience across all device sizes while maintaining accessibility. Changes: Enhanced Interactive States: - Date picker hover state * Border color transition on hover * Smooth 0.2s ease transition - Date picker focus state * Primary color border (#0d55b3) * Accessible box shadow (2px rgba) * Removes default outline for custom styling - Reset button states * Box shadow for depth (2px 4px default) * Hover: Lift effect with translateY(-1px) and enhanced shadow * Active: Pressed state with translateY(0) and reduced shadow * Focus: Accessibility outline with primary color shadow * Smooth 0.3s transition for all state changes Layout Enhancements: - filtersRow alignment * Added align-items: flex-start for consistent alignment * Maintains existing flex-wrap and gap - Reset button container * Flex layout with justify-content: flex-end * Proper margin-top (16px) and margin-bottom (8px) * Full width for proper alignment Responsive Design - Tablet (≤1024px): - Reduced gap in filtersRow (24px → 16px) - Reduced filterGroup min-width (250px → 200px) - Maintains horizontal layout Responsive Design - Mobile (≤768px): - Container padding reduced (32px → 20px) - Heading font size reduced (36px → 28px) - filtersRow switches to vertical layout (flex-direction: column) - Filter groups take full width (100%) - Date pickers maintain horizontal layout - Reset button centered with max-width (200px) - Chart height reduced (500px → 400px) - Adjusted margins and gaps for compact layout Responsive Design - Small Mobile (≤480px): - Container padding reduced further (20px → 16px) - Heading font size reduced (28px → 24px) - Legend adjustments: * Gap reduced (24px → 16px) * Left-aligned (justify-content: flex-start) * Label font size reduced (22px → 18px) - Filter label font size reduced (14px → 13px) - Date picker group wraps (flex-wrap: wrap) - Date separator takes full width with centered text - Chart height reduced (400px → 350px) CSS Architecture: - Uses CSS variables for theme support - Transition properties for smooth state changes - Mobile-first responsive approach with progressive enhancement - Maintains existing styles, adds enhancements only Benefits: - Responsive: Optimal layout on all screen sizes - Performance: CSS-only transitions, no JavaScript overhead - Accessibility: Proper focus states and keyboard navigation - UX: Smooth transitions and intuitive interactive states - Maintainability: Clear breakpoint organization and comments - Consistency: Follows project's CSS patterns and variable usage Testing Considerations: - Tablet: Horizontal filters with reduced spacing - Mobile: Vertical filters, centered reset button - Small mobile: Optimized spacing, wrapped date separator - All sizes: Chart remains functional and readable
Implement robust error handling, loading states, and empty states with
user-friendly UI feedback. Removes early returns and adds conditional
rendering for all application states.
Changes - JavaScript (IssuesBreakdownChart.jsx):
1. Import Loading component
* Uses common Loading component from components/common/Loading
* Supports dark mode prop
2. Enhanced error handling in fetchData
* Date validation: Prevents startDate > endDate
* Early validation return with error message
* 400 validation errors: User-friendly messages from API
* HTTP errors: Status code and message display
* Network errors: Connection error messaging
* Generic errors: Fallback error messages
* Clears data array on error (line 264)
3. Filter parameter handling
* Empty project array: Omits projects param (fetches all)
* Empty issue types array: Omits issueTypes param (fetches all)
* Conditional parameter appending (lines 201, 214)
4. Issue type mapping in filters
* Maps display names to API property names
* Uses ISSUE_TYPE_MAPPING constant
* Filters out undefined values (line 218)
5. Response validation
* Checks for valid response and response.data
* Sets error and clears data if invalid
* Prevents rendering errors from invalid responses
6. Removed early returns
* No early return for loading state
* No early return for error state
* No early return for empty data
* All states handled in conditional render
7. Added conditional rendering in chartContainer
* Loading state: Loading component + message
* Error state: Error icon + error message
* Empty state: Chart icon + helpful message
* Data state: ResponsiveContainer with BarChart
8. Error message banner
* Displays above filters when error exists
* Uses role="alert" for accessibility
* Font Awesome exclamation-circle icon
* Positioned before chartContainer
9. Loading state UI
* Centered Loading component
* "Loading issue statistics..." message
* Consistent with project patterns
10. Empty state UI
* Chart icon (fa-chart-bar)
* "No data available" primary message
* "Try adjusting your filters..." subtext
* Helpful user guidance
11. Error state UI in chart area
* Warning icon (fa-exclamation-triangle)
* Error message display
* Consistent error styling
Changes - CSS (IssueBreakdownChart.module.css):
1. .errorMessage
* Error banner above filters
* Semi-transparent red background (rgba)
* Red border and text (#f44336)
* Padding: 12px 16px
* Border-radius: 6px
* Icon sizing: 16px
2. .chartContainer enhancements
* Display: flex for centering
* Align-items: center
* Justify-content: center
* Enables centered state displays
3. .loadingContainer
* Flex column layout
* Centered alignment and justification
* Gap: 16px between Loading and text
* Padding: 40px
* Full width and height
4. .loadingText
* Color: var(--text-color, #666)
* Font-size: 16px
* Font-weight: 500
5. .errorContainer
* Flex column layout
* Centered alignment
* Gap: 12px
* Padding: 40px
* Text-align: center
* Icon styling: 48px, red (#f44336), 70% opacity
6. .errorText
* Color: var(--text-color, #333)
* Font-size: 16px
* Font-weight: 500
7. .emptyContainer
* Flex column layout
* Centered alignment
* Gap: 12px
* Padding: 40px
* Text-align: center
* Icon styling: 48px, muted color (#999), 50% opacity
8. .emptyText
* Color: var(--text-color, #666)
* Font-size: 18px
* Font-weight: 500
9. .emptySubtext
* Color: var(--text-color, #999)
* Font-size: 14px
* Margin-top: 4px
Edge Cases Handled:
- Invalid date ranges: Validated before API call
- Empty filter arrays: Omits parameters (fetches all data)
- Network errors: Clear messaging to user
- API validation errors: User-friendly error display
- Invalid API responses: Graceful fallback
- No data returned: Empty state with guidance
- Loading delays: Loading indicator with message
Accessibility Features:
- role="alert" on error messages
- aria-hidden="true" on decorative icons
- Semantic error messaging
- Clear visual feedback for all states
Benefits:
- UX: Clear feedback for all application states
- Reliability: Handles all error scenarios gracefully
- Accessibility: ARIA roles and semantic HTML
- Maintainability: Centralized state rendering logic
- Resilience: Never crashes on invalid data
- User Guidance: Helpful messages in empty/error states
…cellation
Implement comprehensive performance optimizations using React hooks to
prevent unnecessary re-renders, memoize expensive computations, and
properly clean up pending API requests on unmount.
Changes:
1. Import React optimization hooks
* Added useCallback for memoizing functions
* Added useMemo for memoizing computed values
2. Add AbortController for request cancellation
* Added abortControllerRef to track pending requests
* Cancels previous request before starting new one
* Cleanup on component unmount
* Prevents memory leaks from pending requests
3. Memoize processChartData with useCallback
* Empty dependency array (pure function)
* Prevents recreation on every render
* Stable reference for fetchData dependency
4. Memoize date change handlers with useCallback
* handleStartDateChange: Uses functional setState
* handleEndDateChange: Uses functional setState
* Empty dependency arrays (no external dependencies)
* Prevents unnecessary child component re-renders
5. Memoize handleResetFilters with useCallback
* Empty dependency array
* Stable function reference
* Prevents re-renders when passed as prop
6. Memoize fetchData with useCallback
* Dependency: [processChartData]
* Integrates AbortController for cancellation
* Cancels pending request before new request
* Creates new AbortController per request
* Passes signal to httpService.get
* Checks if aborted before state updates
* Skips error setting if request aborted
* Handles AbortError gracefully
* Only updates loading state if not aborted
7. Add cleanup useEffect for unmount
* Cancels pending API request (abortControllerRef)
* Clears pending debounce timeout (debounceTimeoutRef)
* Prevents memory leaks
* Empty dependency array (runs once on unmount)
8. Update debounced fetch useEffect
* Added fetchData to dependency array
* Properly responds to memoized function changes
9. Memoize react-select options with useMemo
* projectOptions: Depends on [availableProjects]
* selectedProjectValues: Depends on [availableProjects, selectedProjects]
* issueTypeOptions: Empty deps (FIXED_ISSUE_TYPES is constant)
* selectedIssueTypeValues: Depends on [selectedIssueTypes]
* Prevents expensive array mapping on every render
10. Create memoized onChange handlers
* handleProjectChange: useCallback with empty deps
* handleIssueTypeChange: useCallback with empty deps
* Stable function references
* Prevents react-select from detecting changes
11. Update Select components
* Use memoized projectOptions instead of inline mapping
* Use memoized selectedProjectValues instead of inline filtering
* Use memoized handleProjectChange instead of inline function
* Use memoized issueTypeOptions instead of inline mapping
* Use memoized selectedIssueTypeValues instead of inline mapping
* Use memoized handleIssueTypeChange instead of inline function
12. Enhanced COLORS constant documentation
* Added JSDoc comment explaining fixed nature
* Clarifies colors work in both light/dark modes
* Prevents accidental modification
Implementation Details:
- AbortController pattern:
* Store controller in ref
* Abort previous before creating new
* Pass signal to fetch request
* Check aborted state before updates
* Handle AbortError in catch block
- Functional setState pattern:
* Used in date handlers to avoid dependency arrays
* Prevents stale closure issues
* Cleaner dependency management
- useMemo optimization:
* Only recomputes when dependencies change
* Prevents expensive .map() operations
* Reduces garbage collection pressure
- useCallback optimization:
* Prevents function recreation
* Maintains referential equality
* Reduces child component re-renders
Performance Benefits:
- Prevents unnecessary re-renders of react-select components
- Reduces expensive array mapping operations
- Eliminates stale API requests on rapid filter changes
- Prevents memory leaks from unmounted components
- Improves responsiveness during filter interactions
- Reduces garbage collection overhead
- Optimizes React reconciliation process
Memory Management:
- Properly cancels pending requests on unmount
- Clears debounce timers on cleanup
- No memory leaks from pending operations
- Efficient reference management with refs
Testing Considerations:
- Rapid filter changes should cancel previous requests
- Component unmount should cancel pending requests
- No console errors from aborted requests
- Smooth UI interaction without jank
- Stable behavior across multiple filter changes
… response mapping
- Fixed API response mapping to use correct property names with spaces
('Equipment Issues', 'Labor Issues', 'Materials Issues')
- Changed issue type filter to work client-side by conditionally rendering bars
instead of sending filter parameters to API
- Removed unnecessary API call to fetch available issue types
- Simplified processChartData function to directly map API response properties
- Issue type filter now shows/hides specific bars while keeping all projects visible
- Removed unused availableIssueTypes state variable
The filter now correctly displays only selected issue type bars for all projects,
matching the intended behavior where the backend pre-aggregates all issue types
into three fixed categories.
…e filters - Fixed date picker inputs to use proper dark mode colors (#2c3344 background, #e0e0e0 text) - Applied :global(.dark-mode) selectors in CSS Modules for proper scoping - Enhanced calendar icon visibility with invert(1) brightness(1.5) filter - Increased icon opacity to 1 and added brighter hover state (brightness 1.8) - Improved date separator 'to' text contrast with #e0e0e0 color - Added dark-mode class to component container for CSS selector matching - Applied !important flags to ensure dark mode styles override defaults - Set color-scheme: dark to help browser adapt native controls
- Fix 'no data available' message visibility in dark mode - Add dark mode styling for chart background (#253342) - Update grid lines color for dark mode (rgba(255,255,255,0.1)) - Update all text colors (axis labels, tooltips, loading, error states) - Improve error message visibility with lighter red (#ff6b6b) - Apply consistent color scheme matching project standards (#1b2a41, #ffffff, #d1d5db) All dark mode colors now align with the project's established theme.
- Change endpoint from /projects to /bm/projectsNames?withIssuesOnly=true - Ensures project filter dropdown only shows projects with actual issue data - Improves UX by preventing selection of projects without issues - All selected projects will now have corresponding data in the chart
- Add flex-basis (300px) to prevent filter overlap at all screen sizes - Add new breakpoint at 1280px to handle medium screens smoothly - Add breakpoint at 900px for small tablets - Fix overlap issue at ~1155px width where issue type filter overlapped date range - Ensure consistent wrapping behavior across all screen sizes - Adjust flex properties for better responsive behavior The filters now properly wrap to new lines before overlapping, ensuring a consistent and responsive layout from 1280px down to mobile sizes.
Root cause: overflow-x: hidden was clipping Date Range and Issue Type filters on screens < 768px, making them invisible while only showing Project filter. Changes: - Reduced base min-width from 280px to 250px for better wrapping - Removed overflow-x: hidden from .container and .inner (was clipping content) - Added 900px breakpoint for smooth transition to 2-column layout - Changed flex properties from '1 1 100%' to '1 1 auto' for better flexibility - Updated date picker widths from '100%' to 'auto' with flex: 1 - Added flex-shrink: 0 to date separator to prevent collapse - Changed date separator width from '100%' to 'auto' at 480px Result: - All three filters now visible at all screen sizes - No overflow or clipping issues - Smooth responsive behavior from desktop to mobile - Filters properly wrap without being cut off
✅ Deploy Preview for highestgoodnetwork-dev ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
…cting getSelectStyles utility function
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.



Description
This PR adds three dynamic filters (Project, Date Range, and Issue Type) to the Issues Breakdown Chart in the BM Dashboard, allowing users to filter and view issue statistics by different criteria.

Related PRs (if any):
Improves the issues chart built in the PR #3606 + PR #1438.
This PR is the Frontend PR for the backend PR #1879.
Main changes explained:
Update
src/components/BMDashboard/WeeklyProjectSummary/IssuesBreakdownChart.jsxCreate
src/components/BMDashboard/WeeklyProjectSummary/IssueBreakdownChart.module.css:global(.dark-mode)selectorsHow to test:
Aditya-feature/add-filters-to-issues-breakdown-chartrm -rf node_modules && yarn cache cleanyarn installand start the app:yarn start:localTest Project Filter:
Test Date Range Filter:
Test Issue Type Filter:
Test Combined Filters:
Test Reset Button:
Test Dark Mode:
Test Responsive Design:
Screenshots or videos of changes:
Light Mode:

Dark Mode:

Test Video:
TestVideo.mov
Note:
/api/issues/breakdown. Issue Type filter is applied client-side only.