Refactor this code. This is for a mobile expo project. Make sure its Dynamic.
import React, { useState, useEffect, useContext } from 'react';
import {
View,
TouchableOpacity,
Text,
ActivityIndicator,
Modal,
ScrollView,
Alert,
Dimensions,
} from 'react-native';
import Svg, { Rect, Text as SvgText, G, Circle } from 'react-native-svg';
import moment from 'moment';
import { useTheme } from 'react-native-paper';
import { Picker } from '@react-native-picker/picker';
import { AuthContext } from '../context/AuthContext';
import { api } from '../services/api'; // Import the centralized Axios instance
import styles from './WorkoutHeatmap.styles'; // Import styles
const CELL_MARGIN = 4;
const NUM_COLUMNS = 7; // Days of the week
const SCREEN_PADDING = 40; // Total horizontal padding from styles.container
// Handler for month navigation
const changeMonth = (direction) => {
if (direction === 'prev') {
setCurrentMonth(currentMonth.clone().subtract(1, 'month'));
} else if (direction === 'next') {
setCurrentMonth(currentMonth.clone().add(1, 'month'));
}
};
// Function to get color based on category and data
const getColorForDate = (date, category) => {
const dateStr = date.format('YYYY-MM-DD');
const data = workoutData[category]?.[dateStr];
code
if (!data) {
return theme.colors.disabled; // No activity
}
switch (category) {
case 'Cardio':
if (data.duration <= 20) return '#AEDFF7';
if (data.duration <= 40) return '#5CB1F6';
return '#2A6EBB';
case 'StrengthTraining':
if (data.volume <= 100) return '#C2FFD8';
if (data.volume <= 200) return '#6EE7B7';
return '#118D6E';
case 'Flexibility':
if (data.duration <= 20) return '#D7B0E0';
if (data.duration <= 40) return '#A569BD';
return '#6A1B9A';
default:
return theme.colors.disabled;
}
};
// Function to check if a date has a PR
const isPR = (dateStr) => {
for (let category of selectedCategories) {
if (workoutData[category]?.[dateStr]?.PR) {
return true;
}
}
return false;
};
// Function to filter data based on selected muscle group
const filterDataByMuscleGroup = (category, dateStr) => {
if (selectedMuscleGroup === 'All') return true;
if (category !== 'StrengthTraining') return true; // Only StrengthTraining has muscle groups
return workoutData[category][dateStr]?.muscleGroup === selectedMuscleGroup;
};
// Function to accumulate data for a specific date across selected categories
const getAggregatedData = (date) => {
const dateStr = date.format('YYYY-MM-DD');
const aggregated = [];
Helper function to get category colors for tooltip indicators
*/
const getCategoryColor = (category) => {
switch (category) {
case 'Cardio':
return '#5CB1F6';
case 'StrengthTraining':
return '#6EE7B7';
case 'Flexibility':
return '#A569BD';
default:
return '#000';
}
};
/**
Helper function to format metrics text based on category
*/
const getMetricsText = (entry) => {
switch (entry.category) {
case 'Cardio':
return Duration: ${entry.data.duration}m, Calories: ${entry.data.calories};
case 'StrengthTraining':
return Volume: ${entry.data.volume}, Reps: ${entry.data.reps}, Sets: ${entry.data.sets}, Weight: ${entry.data.weight}kg, Calories: ${entry.data.calories};
case 'Flexibility':
return Duration: ${entry.data.duration}m, Calories: ${entry.data.calories};
default:
return '';
}
};
export default WorkoutHeatmap;
Certainly! Refactoring your WorkoutHeatmap component to be more dynamic and modular can improve readability, maintainability, and performance. Below is a refactored version of your code that breaks down the component into smaller, reusable components, optimizes hooks usage, and ensures dynamic behavior throughout.
MonthNavigation: Handles the display and navigation of months.
CategoryToggle: Manages toggling of workout categories.
MuscleGroupPickerComponent: Allows users to pick muscle groups when StrengthTraining is selected.
TooltipModal: Displays detailed information in a modal when a date is tapped.
Breaking these functionalities into separate components enhances readability and reusability.
Constants and Helper Functions:
Defined constants like WORKOUT_CATEGORIES and MUSCLE_GROUPS for easy management.
Extracted helper functions getCategoryColor and getMetricsText outside the main component to keep it clean.
Optimized Hooks:
Utilized useCallback for handler functions like toggleCategory, changeMonth, and handleMuscleGroupChange to prevent unnecessary re-renders.
Used useMemo for CELL_SIZE to compute it only when width changes.
Dynamic Styling:
Moved styles into a StyleSheet for better performance and maintainability.
Ensured dynamic color assignments based on the theme and workout data.
Performance Enhancements:
Avoided inline functions and styles where possible.
Used memoization to optimize expensive calculations, such as generating the date matrix and determining colors.
Accessibility:
Enhanced accessibility by adding accessibilityLabel and accessibilityRole to interactive elements.
Error Handling:
Kept robust error handling with alerts to notify users when data fetching fails.
Code Organization:
Organized code logically with clear separation between subcomponents, helper functions, and the main component.
Additional Recommendations
Type Checking: Consider using TypeScript or PropTypes for type checking to catch potential bugs early.
Unit Testing: Implement unit tests for your components to ensure they behave as expected.
Performance Monitoring: Use tools like React Native Performance Monitor to keep an eye on your app's performance.
Theming: If you have different themes, ensure that all colors and styles adapt accordingly.
This refactored version should provide a more maintainable, readable, and dynamic WorkoutHeatmap component while preserving all existing functionalities.