To enhance the maintainability and scalability of your Expo mobile project, it's a great idea to separate the component logic from the styling. Below, I'll guide you through separating the WorkoutHeatmap component and its styles into two distinct files. Additionally, I'll ensure the component remains dynamic and adheres to best practices for Expo projects.
Overview
-
Separate Files:
- Component File:
WorkoutHeatmap.js
- Styles File:
WorkoutHeatmap.styles.js
-
Dynamic Considerations:
- Utilize responsive design principles.
- Leverage theme properties from
react-native-paper for consistent theming.
- Ensure accessibility features are intact.
1. WorkoutHeatmap Component (WorkoutHeatmap.js)
This file will contain all the component logic and import the styles from the separate styles file.
// frontend/Components/WorkoutHeatmap.js
import React, { useState, useEffect, useContext } from 'react';
import {
View,
TouchableOpacity,
Text,
ActivityIndicator,
Modal,
ScrollView,
Alert,
} 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 { width } = Dimensions.get('window');
const CELL_SIZE = 30;
const CELL_MARGIN = 4;
const NUM_COLUMNS = 7; // Days of the week
const workoutCategories = ['Cardio', 'StrengthTraining', 'Flexibility'];
const muscleGroups = [
'All',
'Chest',
'Shoulders',
'Back',
'Arms',
'Legs',
'Quads',
'Hamstrings',
'Calves',
'Glutes',
'Abs',
'Obliques',
'Lower Back',
];
const WorkoutHeatmap = () => {
const theme = useTheme();
const { user, loading: authLoading } = useContext(AuthContext); // Access user and auth loading state
const [selectedCategories, setSelectedCategories] = useState(workoutCategories); // Initially all selected
const [selectedMuscleGroup, setSelectedMuscleGroup] = useState('All');
const [currentMonth, setCurrentMonth] = useState(moment());
const [dateMatrix, setDateMatrix] = useState([]);
const [workoutData, setWorkoutData] = useState({});
const [loading, setLoading] = useState(true);
const [tooltipData, setTooltipData] = useState(null); // For displaying details on tap
useEffect(() => {
// Generate date matrix for the current month
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]);
useEffect(() => {
// Fetch workout data whenever dependencies change
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]);
// Handler for category selection
const toggleCategory = (category) => {
if (selectedCategories.includes(category)) {
setSelectedCategories(selectedCategories.filter((cat) => cat !== category));
} else {
setSelectedCategories([...selectedCategories, category]);
}
};
// 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];
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 = [];
selectedCategories.forEach((category) => {
if (
workoutData[category]?.[dateStr] &&
filterDataByMuscleGroup(category, dateStr)
) {
aggregated.push({ category, data: workoutData[category][dateStr] });
}
});
return aggregated;
};
return (
<View style={styles.container}>
{/* Month Navigation */}
<View style={styles.monthNavigation}>
<TouchableOpacity
onPress={() => changeMonth('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={() => changeMonth('next')}
accessibilityLabel="Navigate to next month"
accessibilityRole="button"
>
<Text style={[styles.navButton, { color: theme.colors.primary }]}>→</Text>
</TouchableOpacity>
</View>
{/* Category Toggle Buttons */}
<View style={styles.categoryContainer}>
{workoutCategories.map((category) => (
<TouchableOpacity
key={category}
style={[
styles.categoryButton,
{
backgroundColor: selectedCategories.includes(category)
? theme.colors.primary
: theme.colors.disabled,
},
]}
onPress={() => toggleCategory(category)}
accessibilityLabel={`Toggle ${category}`}
accessibilityRole="button"
>
<Text style={styles.categoryButtonText}>{category}</Text>
</TouchableOpacity>
))}
</View>
{/* Muscle Group Picker */}
{selectedCategories.includes('StrengthTraining') && (
<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={(itemValue) => setSelectedMuscleGroup(itemValue)}
mode="dropdown"
>
{muscleGroups.map((group) => (
<Picker.Item label={group} value={group} key={group} />
))}
</Picker>
</View>
)}
{/* Loading Indicator */}
{loading ? (
<ActivityIndicator size="large" color={theme.colors.primary} style={styles.loadingIndicator} />
) : (
<ScrollView
horizontal={false}
contentContainerStyle={styles.heatmapContainer}
>
{/* Calendar Heatmap */}
<Svg
width={width - 40}
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 hasPR = 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>
{hasPR && (
<Circle
cx={x + CELL_SIZE - 6}
cy={y + 6}
r={4}
fill="gold"
/>
)}
</TouchableOpacity>
</G>
);
})
)}
</Svg>
</ScrollView>
)}
{/* Tooltip for Detailed Information */}
<Modal
visible={tooltipData !== null}
transparent={true}
animationType="fade"
onRequestClose={() => setTooltipData(null)}
>
{tooltipData && (
<TouchableOpacity
style={styles.modalOverlay}
activeOpacity={1}
onPressOut={() => setTooltipData(null)}
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={() => setTooltipData(null)}
style={styles.closeButton}
accessibilityLabel="Close Details"
accessibilityRole="button"
>
<Text
style={[
styles.closeButtonText,
{ color: theme.colors.primary },
]}
>
Close
</Text>
</TouchableOpacity>
</View>
</TouchableOpacity>
)}
</Modal>
</View>
);
};
/**
* 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;
2. WorkoutHeatmap Styles (WorkoutHeatmap.styles.js)
This file will house all the styling for the WorkoutHeatmap component. Using a separate styles file promotes cleaner code and easier maintenance.
// frontend/Components/WorkoutHeatmap.styles.js
import { StyleSheet, Dimensions } from 'react-native';
const { width } = Dimensions.get('window');
const CELL_SIZE = 30;
const CELL_MARGIN = 4;
const NUM_COLUMNS = 7; // Days of the week
const styles = StyleSheet.create({
container: {
marginVertical: 20,
alignItems: 'center',
paddingHorizontal: 20, // Added padding to prevent heatmap from touching screen edges
},
monthNavigation: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
},
navButton: {
fontSize: 24,
marginHorizontal: 20,
},
monthLabel: {
fontSize: 18,
fontWeight: 'bold',
},
categoryContainer: {
flexDirection: 'row',
marginBottom: 10,
justifyContent: 'center',
flexWrap: 'wrap', // Allow wrapping on smaller screens
},
categoryButton: {
paddingVertical: 6,
paddingHorizontal: 12,
borderRadius: 20,
marginHorizontal: 5,
marginVertical: 5, // Added vertical margin for better spacing when wrapping
},
categoryButtonText: {
color: '#fff',
fontSize: 14,
},
pickerContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
flexWrap: 'wrap',
justifyContent: 'center',
},
pickerLabel: {
marginRight: 10,
fontSize: 16,
},
picker: {
height: 50,
width: 150,
},
heatmapContainer: {
alignItems: 'center',
},
heatmap: {
overflow: 'visible',
},
tooltip: {
width: '80%',
maxHeight: '80%',
padding: 20,
borderRadius: 8,
elevation: 5,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
},
tooltipTitle: {
fontSize: 16,
fontWeight: 'bold',
marginBottom: 10,
textAlign: 'center',
},
tooltipEntry: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
},
colorIndicator: {
width: 12,
height: 12,
borderRadius: 6,
marginRight: 8,
},
tooltipText: {
fontSize: 14,
flex: 1,
flexWrap: 'wrap',
},
prText: {
color: 'gold',
fontWeight: 'bold',
},
closeButton: {
marginTop: 10,
alignSelf: 'flex-end',
},
closeButtonText: {
fontSize: 14,
fontWeight: 'bold',
},
modalOverlay: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.3)',
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
loadingIndicator: {
marginTop: 20,
},
});
export default styles;
3. Additional Recommendations for Dynamism
To further enhance the dynamism and responsiveness of your component within the Expo environment, consider the following:
a. Responsive Sizing
Ensure that the CELL_SIZE adapts to different screen sizes. You can calculate CELL_SIZE based on the screen width.
// Update in WorkoutHeatmap.styles.js
const { width } = Dimensions.get('window');
const NUM_COLUMNS = 7; // Days of the week
const TOTAL_MARGIN = 6 * CELL_MARGIN; // 7 columns have 6 margins
const CELL_SIZE = (width - 40 - TOTAL_MARGIN) / NUM_COLUMNS; // Adjust based on container padding
// Now, use CELL_SIZE and CELL_MARGIN in your styles if needed
b. Dark Mode Support
Since you're using react-native-paper's useTheme, your component already adapts to theme changes. Ensure that all colors, including those in the SVG elements, utilize theme properties where applicable to maintain consistency.
c. Accessibility Enhancements
While basic accessibility roles and labels are included, consider the following to improve accessibility:
- Focus Management: Ensure that interactive elements are focusable and navigable via keyboard (if applicable).
- Dynamic Type: Respect user font size preferences by using scalable units or
Text components that adapt.
d. Optimize Performance
For large data sets or complex SVG rendering, consider optimizing performance:
- Memoization: Use
React.memo or useMemo to prevent unnecessary re-renders.
- Lazy Loading: If the heatmap becomes too large, implement lazy loading or pagination.
4. Final Project Structure
Your project directory should resemble the following structure for clarity and modularity:
frontend/
├── Components/
│ ├── WorkoutHeatmap.js
│ └── WorkoutHeatmap.styles.js
├── context/
│ └── AuthContext.js
├── services/
│ └── api.js
├── ...other directories and files
5. Importing the Component
When importing the WorkoutHeatmap component elsewhere in your project, you can do so normally:
import WorkoutHeatmap from './frontend/Components/WorkoutHeatmap';
// Usage in JSX
<WorkoutHeatmap />
6. Complete Example
For completeness, here's how both files integrate together:
WorkoutHeatmap.js
import React, { /* ... */ } from 'react';
import { /* ... */ } from 'react-native';
import Svg, { /* ... */ } 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 styles from './WorkoutHeatmap.styles';
const WorkoutHeatmap = () => {
// ...component logic as shown above
};
export default WorkoutHeatmap;
WorkoutHeatmap.styles.js
import { StyleSheet, Dimensions } from 'react-native';
const { width } = Dimensions.get('window');
const CELL_MARGIN = 4;
const NUM_COLUMNS = 7;
const TOTAL_MARGIN = 6 * CELL_MARGIN;
const CELL_SIZE = (width - 40 - TOTAL_MARGIN) / NUM_COLUMNS;
const styles = StyleSheet.create({
container: {
marginVertical: 20,
alignItems: 'center',
paddingHorizontal: 20,
},
// ...rest of the styles as shown above
});
export default styles;
Conclusion
By separating the component logic from styling, you achieve cleaner, more maintainable code that's easier to manage and scale. Additionally, ensuring responsiveness and dynamic theming aligns your component with best practices for React Native and Expo projects. Feel free to further customize the styles and component logic to better fit your application's specific needs.
If you have any further questions or need additional assistance, feel free to ask!