Certainly! Here's a refactored version of your WorkoutHeatmap component for your Expo mobile app. The refactoring focuses on enhancing modularity, readability, and performance while ensuring dynamic behavior. Key improvements include:
-
Component Breakdown: The main component is split into smaller, reusable components such as MonthNavigation, CategoryToggle, MuscleGroupPicker, HeatmapGrid, and TooltipModal. This enhances readability and maintainability.
-
Custom Hooks: Logic related to fetching and processing workout data is encapsulated within custom hooks (useDateMatrix and useWorkoutData), promoting separation of concerns.
-
Memoization: Utilizes useMemo and React.memo to prevent unnecessary re-renders, optimizing performance.
-
Dynamic Configurations: Constants like workoutCategories and muscleGroups are defined outside the component, making them easily adjustable or injectable via props if needed in the future.
-
Accessibility Enhancements: Improved accessibility labels and roles for better support with screen readers.
-
Error Handling: Enhanced error handling with user feedback through alerts.
-
Styling Consistency: Ensures that styling is consistently applied and easily adjustable via the styles import.
Below is the refactored code:
// frontend/Components/WorkoutHeatmap.js
import React, { useState, useEffect, useContext, useMemo } 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
// Constants
const CELL_MARGIN = 4;
const NUM_COLUMNS = 7; // Days of the week
const SCREEN_PADDING = 40; // Total horizontal padding from styles.container
const WORKOUT_CATEGORIES = ['Cardio', 'StrengthTraining', 'Flexibility'];
const MUSCLE_GROUPS = [
'All',
'Chest',
'Shoulders',
'Back',
'Arms',
'Legs',
'Quads',
'Hamstrings',
'Calves',
'Glutes',
'Abs',
'Obliques',
'Lower Back',
];
// Helper Functions
const getCategoryColor = (category) => {
switch (category) {
case 'Cardio':
return '#5CB1F6';
case 'StrengthTraining':
return '#6EE7B7';
case 'Flexibility':
return '#A569BD';
default:
return '#000';
}
};
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 '';
}
};
// Custom Hooks
const useDateMatrix = (currentMonth) => {
const [dateMatrix, setDateMatrix] = useState([]);
useEffect(() => {
const startOfMonth = currentMonth.clone().startOf('month').startOf('week');
const endOfMonth = currentMonth.clone().endOf('month').endOf('week');
const matrix = [];
let currentDate = startOfMonth.clone();
while (currentDate.isBefore(endOfMonth)) {
const week = [];
for (let i = 0; i < 7; i++) {
week.push(currentDate.clone());
currentDate.add(1, 'day');
}
matrix.push(week);
}
setDateMatrix(matrix);
}, [currentMonth]);
return dateMatrix;
};
const useWorkoutData = (user, currentMonth, selectedCategories, selectedMuscleGroup, authLoading) => {
const [workoutData, setWorkoutData] = useState({});
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchWorkoutData = async () => {
if (authLoading) return; // Wait until auth is loaded
if (!user) {
setWorkoutData({});
setLoading(false);
return;
}
setLoading(true);
try {
const response = await api.get('/workouts', { // Ensure endpoint is correct
params: {
userId: user.id,
month: currentMonth.format('YYYY-MM'),
categories: selectedCategories.join(','), // e.g., "Cardio,StrengthTraining"
muscleGroup: selectedMuscleGroup !== 'All' ? selectedMuscleGroup : undefined, // Optional filter
},
});
console.log('Workout Data:', response.data); // Debugging
setWorkoutData(response.data);
} catch (error) {
console.error('Error fetching workout data:', error);
Alert.alert('Error', 'Failed to fetch workout data.');
setWorkoutData({});
} finally {
setLoading(false);
}
};
fetchWorkoutData();
}, [user, currentMonth, selectedCategories, selectedMuscleGroup, authLoading]);
return { workoutData, loading };
};
// Subcomponents
const MonthNavigation = React.memo(({ currentMonth, onChangeMonth }) => {
const theme = useTheme();
return (
<View style={styles.monthNavigation}>
<TouchableOpacity
onPress={() => onChangeMonth('prev')}
accessibilityLabel="Navigate to previous month"
accessibilityRole="button"
>
<Text style={[styles.navButton, { color: theme.colors.primary }]}>←</Text>
</TouchableOpacity>
<Text style={[styles.monthLabel, { color: theme.colors.text }]}>
{currentMonth.format('MMMM YYYY')}
</Text>
<TouchableOpacity
onPress={() => onChangeMonth('next')}
accessibilityLabel="Navigate to next month"
accessibilityRole="button"
>
<Text style={[styles.navButton, { color: theme.colors.primary }]}>→</Text>
</TouchableOpacity>
</View>
);
});
const CategoryToggle = React.memo(({ categories, selectedCategories, onToggle }) => {
const theme = useTheme();
return (
<View style={styles.categoryContainer}>
{categories.map((category) => (
<TouchableOpacity
key={category}
style={[
styles.categoryButton,
{
backgroundColor: selectedCategories.includes(category)
? theme.colors.primary
: theme.colors.disabled,
},
]}
onPress={() => onToggle(category)}
accessibilityLabel={`Toggle ${category}`}
accessibilityRole="button"
>
<Text style={styles.categoryButtonText}>{category}</Text>
</TouchableOpacity>
))}
</View>
);
});
const MuscleGroupPicker = React.memo(({ selectedMuscleGroup, onSelect }) => {
const theme = useTheme();
return (
<View style={styles.pickerContainer}>
<Text style={[styles.pickerLabel, { color: theme.colors.text }]}>
Muscle Group:
</Text>
<Picker
selectedValue={selectedMuscleGroup}
style={[styles.picker, { color: theme.colors.text }]}
onValueChange={onSelect}
mode="dropdown"
>
{MUSCLE_GROUPS.map((group) => (
<Picker.Item label={group} value={group} key={group} />
))}
</Picker>
</View>
);
});
const HeatmapGrid = React.memo(
({
dateMatrix,
workoutData,
selectedCategories,
filterDataByMuscleGroup,
getAggregatedData,
isPR,
getColorForDate,
theme,
CELL_SIZE,
SCREEN_PADDING,
width,
setTooltipData,
}) => {
return (
<Svg
width={width - SCREEN_PADDING}
height={(CELL_SIZE + CELL_MARGIN) * dateMatrix.length + 40}
style={styles.heatmap}
>
{dateMatrix.map((week, weekIndex) =>
week.map((date, dayIndex) => {
const x = dayIndex * (CELL_SIZE + CELL_MARGIN);
const y = weekIndex * (CELL_SIZE + CELL_MARGIN);
const isCurrentMonth = date.month() === currentMonth.month();
const aggregatedData = getAggregatedData(date);
const dateStr = date.format('YYYY-MM-DD');
const prFlag = isPR(dateStr);
const hasData = aggregatedData.length > 0;
// Calculate color based on multiple categories
let fillColor = theme.colors.disabled;
if (hasData) {
// Prioritize Cardio > StrengthTraining > Flexibility
if (
selectedCategories.includes('Cardio') &&
workoutData.Cardio?.[dateStr] &&
filterDataByMuscleGroup('Cardio', dateStr)
) {
fillColor = getColorForDate(date, 'Cardio');
} else if (
selectedCategories.includes('StrengthTraining') &&
workoutData.StrengthTraining?.[dateStr] &&
filterDataByMuscleGroup('StrengthTraining', dateStr)
) {
fillColor = getColorForDate(date, 'StrengthTraining');
} else if (
selectedCategories.includes('Flexibility') &&
workoutData.Flexibility?.[dateStr]
) {
fillColor = getColorForDate(date, 'Flexibility');
}
}
return (
<G key={dateStr}>
<TouchableOpacity
onPress={() => {
const data = getAggregatedData(date);
setTooltipData({
date: date.format('MMMM Do YYYY'),
data,
});
}}
accessible={true}
accessibilityLabel={`Workout on ${date.format('MMMM Do YYYY')}`}
accessibilityRole="button"
>
<Rect
x={x}
y={y}
width={CELL_SIZE}
height={CELL_SIZE}
fill={isCurrentMonth ? fillColor : theme.colors.disabled}
rx={4}
ry={4}
/>
<SvgText
x={x + CELL_SIZE / 2}
y={y + CELL_SIZE / 2 + 4}
fontSize={10}
fill={theme.colors.text}
textAnchor="middle"
>
{date.date()}
</SvgText>
{prFlag && (
<Circle
cx={x + CELL_SIZE - 6}
cy={y + 6}
r={4}
fill="gold"
/>
)}
</TouchableOpacity>
</G>
);
})
)}
</Svg>
);
}
);
const TooltipModal = React.memo(({ tooltipData, onClose, theme, getCategoryColor, getMetricsText }) => {
if (!tooltipData) return null;
return (
<Modal
visible={tooltipData !== null}
transparent={true}
animationType="fade"
onRequestClose={onClose}
>
<TouchableOpacity
style={styles.modalOverlay}
activeOpacity={1}
onPressOut={onClose}
accessible={false}
>
<View style={[styles.tooltip, { backgroundColor: theme.colors.surface }]}>
<Text style={[styles.tooltipTitle, { color: theme.colors.text }]}>
{tooltipData.date}
</Text>
<ScrollView>
{tooltipData.data.map((entry, index) => (
<View key={index} style={styles.tooltipEntry}>
<View
style={[
styles.colorIndicator,
{ backgroundColor: getCategoryColor(entry.category) },
]}
/>
<Text style={[styles.tooltipText, { color: theme.colors.text }]}>
{entry.category}: {getMetricsText(entry)}
{entry.data.PR && (
<Text style={styles.prText}> ★ PR</Text>
)}
</Text>
</View>
))}
</ScrollView>
<TouchableOpacity
onPress={onClose}
style={styles.closeButton}
accessibilityLabel="Close Details"
accessibilityRole="button"
>
<Text
style={[
styles.closeButtonText,
{ color: theme.colors.primary },
]}
>
Close
</Text>
</TouchableOpacity>
</View>
</TouchableOpacity>
</Modal>
);
});
// Main Component
const WorkoutHeatmap = () => {
const theme = useTheme();
const { user, loading: authLoading } = useContext(AuthContext); // Access user and auth loading state
const [selectedCategories, setSelectedCategories] = useState(WORKOUT_CATEGORIES); // Initially all selected
const [selectedMuscleGroup, setSelectedMuscleGroup] = useState('All');
const [currentMonth, setCurrentMonth] = useState(moment());
const dateMatrix = useDateMatrix(currentMonth);
const { workoutData, loading } = useWorkoutData(
user,
currentMonth,
selectedCategories,
selectedMuscleGroup,
authLoading
);
const [tooltipData, setTooltipData] = useState(null); // For displaying details on tap
const { width } = Dimensions.get('window');
const CELL_SIZE = useMemo(
() => (width - SCREEN_PADDING - (NUM_COLUMNS - 1) * CELL_MARGIN) / NUM_COLUMNS,
[width]
);
// Handlers
const toggleCategory = (category) => {
setSelectedCategories((prevCategories) =>
prevCategories.includes(category)
? prevCategories.filter((cat) => cat !== category)
: [...prevCategories, category]
);
};
const changeMonth = (direction) => {
setCurrentMonth((prevMonth) =>
direction === 'prev' ? prevMonth.clone().subtract(1, 'month') : prevMonth.clone().add(1, 'month')
);
};
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;
};
const getAggregatedData = (date) => {
const dateStr = date.format('YYYY-MM-DD');
const aggregated = [];
selectedCategories.forEach((category) => {
if (
workoutData[category]?.[dateStr] &&
filterDataByMuscleGroup(category, dateStr)
) {
aggregated.push({ category, data: workoutData[category][dateStr] });
}
});
return aggregated;
};
const isPR = (dateStr) => {
for (let category of selectedCategories) {
if (workoutData[category]?.[dateStr]?.PR) {
return true;
}
}
return false;
};
const getColorForDate = (date, category) => {
const dateStr = date.format('YYYY-MM-DD');
const data = workoutData[category]?.[dateStr];
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;
}
};
return (
<View style={styles.container}>
{/* Month Navigation */}
<MonthNavigation currentMonth={currentMonth} onChangeMonth={changeMonth} />
{/* Category Toggle Buttons */}
<CategoryToggle
categories={WORKOUT_CATEGORIES}
selectedCategories={selectedCategories}
onToggle={toggleCategory}
/>
{/* Muscle Group Picker */}
{selectedCategories.includes('StrengthTraining') && (
<MuscleGroupPicker
selectedMuscleGroup={selectedMuscleGroup}
onSelect={setSelectedMuscleGroup}
/>
)}
{/* Loading Indicator */}
{loading ? (
<ActivityIndicator size="large" color={theme.colors.primary} style={styles.loadingIndicator} />
) : (
<ScrollView
horizontal={false}
contentContainerStyle={styles.heatmapContainer}
>
{/* Calendar Heatmap */}
<HeatmapGrid
dateMatrix={dateMatrix}
workoutData={workoutData}
selectedCategories={selectedCategories}
filterDataByMuscleGroup={filterDataByMuscleGroup}
getAggregatedData={getAggregatedData}
isPR={isPR}
getColorForDate={getColorForDate}
theme={theme}
CELL_SIZE={CELL_SIZE}
SCREEN_PADDING={SCREEN_PADDING}
width={width}
setTooltipData={setTooltipData}
/>
</ScrollView>
)}
{/* Tooltip for Detailed Information */}
<TooltipModal
tooltipData={tooltipData}
onClose={() => setTooltipData(null)}
theme={theme}
getCategoryColor={getCategoryColor}
getMetricsText={getMetricsText}
/>
</View>
);
};
export default WorkoutHeatmap;
Explanation of Refactoring
-
Component Decomposition:
MonthNavigation: Handles the navigation between months.
CategoryToggle: Renders toggle buttons for workout categories.
MuscleGroupPicker: Displays a picker for selecting muscle groups when 'StrengthTraining' is selected.
HeatmapGrid: Renders the SVG heatmap grid.
TooltipModal: Shows detailed workout information in a modal.
-
Custom Hooks:
useDateMatrix: Generates the matrix of dates for the current month.
useWorkoutData: Fetches workout data based on the selected filters and handles loading states.
-
Memoization:
React.memo: Used for subcomponents to prevent unnecessary re-renders when their props haven't changed.
useMemo: Calculates CELL_SIZE only when width changes, optimizing performance.
-
Enhanced Readability and Maintainability:
- Constants are defined at the top for easy adjustments.
- Helper functions like
getCategoryColor and getMetricsText are moved outside the main component for clarity.
- Inline anonymous functions are minimized to avoid re-creating functions on every render.
-
Accessibility Improvements:
- Added appropriate
accessibilityLabel and accessibilityRole to interactive elements to improve screen reader support.
-
Error Handling and User Feedback:
- Enhanced error logging and user feedback via alerts when fetching workout data fails.
-
Styling and Theming:
- Consistently applied theming using
useTheme from react-native-paper to ensure the component adheres to the app's theme.
-
Dynamic Behavior:
- The component dynamically adjusts to the selected categories and muscle groups.
Additional Recommendations
-
TypeScript Integration:
- Consider migrating to TypeScript for type safety, which can help catch errors during development and improve code quality.
-
Testing:
- Implement unit tests for the custom hooks and subcomponents to ensure they behave as expected.
-
Performance Optimization:
- If the heatmap becomes complex, consider using virtualization libraries to handle large data sets efficiently.
-
User Experience Enhancements:
- Add animations to transitions (e.g., when changing months) for a smoother user experience.
- Provide more detailed feedback in the tooltip, such as graphs or progress indicators.
-
Caching and Data Management:
- Implement caching strategies for workout data to reduce redundant API calls, especially when navigating between months frequently.
-
Error Boundary:
- Wrap the component or its parts with an error boundary to gracefully handle unexpected errors without crashing the entire app.
By implementing these refactoring steps, your WorkoutHeatmap component becomes more modular, efficient, and easier to maintain, while also enhancing the overall user experience.