Integrating a comprehensive Calendar Workout/Exercise Heatmap into your ProfileScreen involves several steps. Below, I'll guide you through creating a modular and scalable implementation in React Native, adhering to your detailed specifications.
1. Overview
- Heatmap Structure: We'll use a dedicated
WorkoutHeatmap component that supports multiple layers (Cardio, Strength Training, Flexibility/Recovery).
- Data Handling: Ensure that workout data is structured appropriately and available within the
AuthContext or another relevant context/provider.
- Visualization: We'll utilize libraries like
@ptomasroos/react-native-multi-carousel for the calendar structure and customize it to display heatmaps. Alternatively, using SVGs with react-native-svg can offer more flexibility.
For this implementation, we'll create a simplified version using basic React Native components and react-native-svg for customization. You can enhance it further with more sophisticated libraries as needed.
2. Dependencies
First, install necessary dependencies:
npm install react-native-svg
or
yarn add react-native-svg
3. Structure Overview
- ProfileScreen.js: The main profile screen where the heatmap will be integrated.
- WorkoutHeatmap.js: A new component responsible for rendering the calendar heatmap.
- heatmapUtils.js: Utility functions for processing workout data.
4. Implementing the Heatmap
4.1. WorkoutHeatmap Component
Create a new file components/WorkoutHeatmap.js:
// components/WorkoutHeatmap.js
import React, { useState } from 'react';
import { View, StyleSheet, Dimensions, TouchableOpacity, Text, Picker } from 'react-native';
import Svg, { Rect, Text as SvgText } from 'react-native-svg';
import moment from 'moment';
import { useTheme } from 'react-native-paper';
import { getWorkoutData } from '../utils/heatmapUtils'; // Assume this fetches and processes workout data
const { width } = Dimensions.get('window');
const CELL_SIZE = 30;
const CELL_MARGIN = 4;
const NUM_COLUMNS = 7; // Days of the week
const categories = ['Cardio', 'StrengthTraining', 'Flexibility'];
const WorkoutHeatmap = () => {
const theme = useTheme();
const [selectedCategory, setSelectedCategory] = useState('Cardio');
// Generate a matrix for the current month
const startOfMonth = moment().startOf('month').startOf('week');
const endOfMonth = moment().endOf('month').endOf('week');
const dateMatrix = [];
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');
}
dateMatrix.push(week);
}
// Fetch workout data
const workoutData = getWorkoutData(); // Should return data structured by date and category
// Helper function to determine color based on data
const getColorForDate = (date) => {
const dateStr = date.format('YYYY-MM-DD');
const data = workoutData[selectedCategory][dateStr];
if (!data) {
return theme.colors.disabled; // No activity
}
// Determine color based on category and data
switch (selectedCategory) {
case 'Cardio':
// Example: duration mapping
if (data.duration <= 20) return '#AEDFF7';
if (data.duration <= 40) return '#5CB1F6';
return '#2A6EBB';
case 'StrengthTraining':
// Example: volume mapping
if (data.volume <= 50) return '#C2FFD8';
if (data.volume <= 100) return '#6EE7B7';
return '#118D6E';
case 'Flexibility':
// Example: duration mapping
if (data.duration <= 20) return '#D7B0E0';
if (data.duration <= 40) return '#A569BD';
return '#6A1B9A';
default:
return theme.colors.disabled;
}
};
return (
<View style={styles.container}>
{/* Category Picker */}
<View style={styles.pickerContainer}>
<Text style={[styles.pickerLabel, { color: theme.colors.text }]}>Category:</Text>
<Picker
selectedValue={selectedCategory}
style={[styles.picker, { color: theme.colors.text }]}
onValueChange={(itemValue) => setSelectedCategory(itemValue)}
>
{categories.map((cat) => (
<Picker.Item label={cat} value={cat} key={cat} />
))}
</Picker>
</View>
{/* Month and Year */}
<Text style={[styles.monthLabel, { color: theme.colors.text }]}>
{moment().format('MMMM YYYY')}
</Text>
{/* Calendar Heatmap */}
<Svg width={width} height={(CELL_SIZE + CELL_MARGIN) * dateMatrix.length + 20}>
{dateMatrix.map((week, weekIndex) =>
week.map((date, dayIndex) => {
const x = dayIndex * (CELL_SIZE + CELL_MARGIN);
const y = weekIndex * (CELL_SIZE + CELL_MARGIN);
const color = getColorForDate(date);
const isCurrentMonth = date.month() === moment().month();
return (
<TouchableOpacity
key={date.format('YYYY-MM-DD')}
onPress={() => {
// Handle onPress, e.g., show details
console.log(`Selected date: ${date.format('YYYY-MM-DD')}`);
}}
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 ? color : 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>
</TouchableOpacity>
);
})
)}
</Svg>
</View>
);
};
const styles = StyleSheet.create({
container: {
marginVertical: 20,
alignItems: 'center',
},
pickerContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
},
pickerLabel: {
marginRight: 10,
fontSize: 16,
},
picker: {
height: 50,
width: 150,
},
monthLabel: {
fontSize: 18,
marginBottom: 10,
},
});
export default WorkoutHeatmap;
4.2. Utility Functions
Create a utility file utils/heatmapUtils.js to process workout data:
// utils/heatmapUtils.js
import moment from 'moment';
/**
* Sample function to fetch and process workout data.
* In a real app, this would fetch from an API or local storage.
*/
export const getWorkoutData = () => {
// Sample data structure
// {
// Cardio: { '2023-10-01': { duration: 30, calories: 300 }, ... },
// StrengthTraining: { '2023-10-01': { volume: 80, calories: 200 }, ... },
// Flexibility: { '2023-10-01': { duration: 20, calories: 150 }, ... },
// }
// For demonstration, generate random data for the current month
const currentMonth = moment().month();
const currentYear = moment().year();
const daysInMonth = moment().daysInMonth();
const categories = ['Cardio', 'StrengthTraining', 'Flexibility'];
const workoutData = {
Cardio: {},
StrengthTraining: {},
Flexibility: {},
};
for (let day = 1; day <= daysInMonth; day++) {
const date = moment({ year: currentYear, month: currentMonth, day }).format('YYYY-MM-DD');
// Randomly decide if the user worked out on this day
if (Math.random() > 0.3) {
// Cardio
if (Math.random() > 0.5) {
workoutData.Cardio[date] = {
duration: Math.floor(Math.random() * 60) + 10, // 10-70 minutes
calories: Math.floor(Math.random() * 500) + 100, // 100-600 calories
};
}
// Strength Training
if (Math.random() > 0.5) {
workoutData.StrengthTraining[date] = {
volume: Math.floor(Math.random() * 200) + 50, // 50-250
calories: Math.floor(Math.random() * 400) + 100, // 100-500 calories
};
}
// Flexibility
if (Math.random() > 0.5) {
workoutData.Flexibility[date] = {
duration: Math.floor(Math.random() * 60) + 10, // 10-70 minutes
calories: Math.floor(Math.random() * 200) + 50, // 50-250 calories
};
}
}
}
return workoutData;
};
Note: Replace the getWorkoutData function with real data fetching logic as per your application's architecture.
4.3. Integrate WorkoutHeatmap into ProfileScreen
Update your ProfileScreen.js to include the WorkoutHeatmap component.
// screens/ProfileScreen.js
import React, { useContext } from 'react';
import { View, StyleSheet, ScrollView, ActivityIndicator, TouchableOpacity } from 'react-native';
import { Title, Caption, Text } from 'react-native-paper';
import { AuthContext } from '../context/AuthContext';
import { useTheme } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import WorkoutHeatmap from '../components/WorkoutHeatmap'; // Import the Heatmap component
const ProfileScreen = ({ navigation }) => {
const { user, loading } = useContext(AuthContext);
const theme = useTheme(); // Access the current theme
/**
* If the app is still loading user data, show a loading indicator
*/
if (loading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={theme.colors.primary} />
</View>
);
}
/**
* If no user is logged in, prompt the user to log in
*/
if (!user) {
return (
<View style={styles.container}>
<Text>No user data available. Please log in.</Text>
{/* Assume there's a Login button or navigation here */}
</View>
);
}
/**
* Render the user's profile information along with the workout heatmap
*/
return (
<ScrollView
contentContainerStyle={[styles.container, { backgroundColor: theme.colors.background }]}
>
{/* User Information Section with Hamburger Menu */}
<View style={styles.userInfoSection}>
<View>
{user.name ? (
<Title style={[styles.title, { color: theme.colors.text }]}>{user.name}</Title>
) : (
<Title style={[styles.title, { color: theme.colors.text }]}>User ID: {user.id}</Title>
)}
{user.email && (
<Caption style={[styles.caption, { color: theme.colors.text }]}>{user.email}</Caption>
)}
</View>
{/* Hamburger Menu Button */}
<TouchableOpacity
onPress={() => navigation.navigate('Settings')}
accessibilityLabel="Open Settings"
accessibilityRole="button"
>
<Icon name="menu" size={28} color={theme.colors.primary} />
</TouchableOpacity>
</View>
{/* Workout Heatmap Section */}
<WorkoutHeatmap />
{/* Additional Profile Information can be added here */}
{/* Removed Logout Button from here */}
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flexGrow: 1,
padding: 20,
},
userInfoSection: {
paddingHorizontal: 20,
paddingVertical: 20, // Adjusted padding for alignment
flexDirection: 'row', // Align items horizontally
justifyContent: 'space-between', // Space between user info and button
alignItems: 'center', // Vertically center the items
backgroundColor: 'transparent',
},
title: {
fontSize: 26,
fontWeight: 'bold',
},
caption: {
fontSize: 16,
lineHeight: 16,
marginTop: 5,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default ProfileScreen;
5. Enhancements and Customizations
The provided implementation offers a foundational structure for the heatmap. To align it more closely with your detailed plan, consider the following enhancements:
5.1. Multiple Layered Heatmaps
Implement toggling between categories or stacking them:
- Toggle Buttons: Add buttons or switches to allow users to select multiple categories simultaneously.
- Color Overlays: When multiple categories are active, consider blending colors or using patterns to represent overlaps.
// Update categories and Picker to allow multiple selections
const allCategories = ['Cardio', 'StrengthTraining', 'Flexibility'];
const [selectedCategories, setSelectedCategories] = useState(['Cardio']); // Array of selected categories
// Handle selection logic in the picker or use checkboxes
5.2. Data Overlays
Display metrics within each heatmap cell:
- SVG Text: Utilize
SvgText elements to overlay data like duration, calories, PRs, etc.
<SvgText
x={x + CELL_SIZE / 2}
y={y + CELL_SIZE / 2 + 4}
fontSize={10}
fill={theme.colors.text}
textAnchor="middle"
>
{date.date()}
</SvgText>
{data.duration && (
<SvgText
x={x + CELL_SIZE / 2}
y={y + CELL_SIZE / 2 + 15}
fontSize={8}
fill={theme.colors.text}
textAnchor="middle"
>
{data.duration}m
</SvgText>
)}
5.3. Responsive Timeframes
Allow users to view heatmaps on daily, weekly, or monthly bases:
- Date Picker: Implement a date picker or segmented control to switch timeframes.
- Rendering Logic: Adjust the
WorkoutHeatmap component to render based on the selected timeframe.
5.4. Personal Records (PRs)
Identify and mark PRs in the heatmap:
- PR Data: Ensure PRs are part of your workout data.
- Special Symbols: Overlay stars or other icons on cells that represent PRs.
{data.isPR && (
<SvgText
x={x + CELL_SIZE - 5}
y={y + 5}
fontSize={10}
fill="gold"
textAnchor="end"
>
★
</SvgText>
)}
5.5. Accessibility Enhancements
Ensure that the heatmap is accessible:
- Accessible Labels: Provide meaningful accessibility labels for each cell.
- Dynamic Font Sizes: Allow text within cells to scale based on user settings.
5.6. Advanced Insights
Implement weekly summaries and monthly progress reports:
- Aggregation: Compute total workout time, calories burned, etc., and display them above or below the heatmap.
- Charts: Use additional visualization components like bar charts or line graphs for trends.
6. Complete Example with Basic Heatmap Integration
For a more complete example, here's how your project structure might look:
project/
│
├── components/
│ └── WorkoutHeatmap.js
├── utils/
│ └── heatmapUtils.js
├── context/
│ └── AuthContext.js
├── screens/
│ └── ProfileScreen.js
├── App.js
├── package.json
└── ...
Ensure that your AuthContext provides necessary user and workout data. The WorkoutHeatmap accesses this data via utility functions or directly through context.
7. Final Thoughts
Implementing a feature-rich calendar workout/exercise heatmap requires careful consideration of data structure, UI design, and user interactions. The above approach provides a scalable foundation, which you can expand based on specific requirements such as multiple heatmap layers, detailed data overlays, and advanced insights.
Feel free to enhance the visual appeal using additional libraries or custom SVG designs, and ensure that the performance remains optimal, especially when dealing with large datasets or complex visualizations.