diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e49b77..f0bbccb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,31 @@ All notable changes to the POWR project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +# Changelog - March 22, 2025 + +## Added +- Enhanced Profile Tab with new features + - Implemented tabbed interface with Overview, Activity, Progress, and Settings + - Added Terms of Service modal with comprehensive content + - Created dedicated settings screen with improved organization + - Added dark mode toggle in settings + - Implemented proper text visibility in both light and dark modes + - Added Nostr publishing settings with clear explanations + - Created analytics service for workout progress tracking + - Added progress visualization with charts and statistics + - Implemented activity feed for personal workout history + +## Fixed +- Dark mode text visibility issues + - Added explicit text-foreground classes to ensure visibility + - Updated button variants to use purple for better contrast + - Fixed modal content visibility in dark mode + - Improved component styling for consistent appearance +- TypeScript errors in navigation + - Fixed router.push path format in SettingsDrawer + - Updated import paths for better type safety + - Improved component props typing + # Changelog - March 20, 2025 ## Improved diff --git a/app/(tabs)/_layout.tsx b/app/(tabs)/_layout.tsx index 469e934..2e4183b 100644 --- a/app/(tabs)/_layout.tsx +++ b/app/(tabs)/_layout.tsx @@ -51,7 +51,7 @@ export default function TabLayout() { options={{ title: 'Profile', tabBarIcon: ({ color, size }) => ( - + ), }} /> @@ -97,4 +97,4 @@ export default function TabLayout() { ); -} \ No newline at end of file +} diff --git a/app/(tabs)/history/calendar.tsx b/app/(tabs)/history/calendar.tsx index 0afc910..d94262e 100644 --- a/app/(tabs)/history/calendar.tsx +++ b/app/(tabs)/history/calendar.tsx @@ -7,7 +7,7 @@ import { Workout } from '@/types/workout'; import { format, isSameDay } from 'date-fns'; import { Card, CardContent } from '@/components/ui/card'; import { cn } from '@/lib/utils'; -import { WorkoutHistoryService } from '@/lib/db/services/WorkoutHIstoryService'; +import { WorkoutHistoryService } from '@/lib/db/services/WorkoutHistoryService'; import WorkoutCard from '@/components/workout/WorkoutCard'; import { ChevronLeft, ChevronRight, Calendar } from 'lucide-react-native'; @@ -378,4 +378,4 @@ export default function CalendarScreen() { ); -} \ No newline at end of file +} diff --git a/app/(tabs)/history/workoutHistory.tsx b/app/(tabs)/history/workoutHistory.tsx index b52ca2e..697c284 100644 --- a/app/(tabs)/history/workoutHistory.tsx +++ b/app/(tabs)/history/workoutHistory.tsx @@ -5,7 +5,7 @@ import { Text } from '@/components/ui/text'; import { useSQLiteContext } from 'expo-sqlite'; import { Workout } from '@/types/workout'; import { format } from 'date-fns'; -import { WorkoutHistoryService } from '@/lib/db/services/WorkoutHIstoryService'; +import { WorkoutHistoryService } from '@/lib/db/services/WorkoutHistoryService'; import WorkoutCard from '@/components/workout/WorkoutCard'; // Mock data for when database tables aren't yet created @@ -157,4 +157,4 @@ export default function HistoryScreen() { ); -} \ No newline at end of file +} diff --git a/app/(tabs)/profile.tsx b/app/(tabs)/profile.tsx deleted file mode 100644 index 7e1e744..0000000 --- a/app/(tabs)/profile.tsx +++ /dev/null @@ -1,191 +0,0 @@ -// app/(tabs)/profile.tsx -import { View, ScrollView, ImageBackground } from 'react-native'; -import { useState, useEffect } from 'react'; -import { Settings, LogIn, Bell } from 'lucide-react-native'; -import { H1 } from '@/components/ui/typography'; -import { Button } from '@/components/ui/button'; -import { Text } from '@/components/ui/text'; -import Header from '@/components/Header'; -import { useSafeAreaInsets } from 'react-native-safe-area-context'; -import { TabScreen } from '@/components/layout/TabScreen'; -import UserAvatar from '@/components/UserAvatar'; -import { useNDKCurrentUser } from '@/lib/hooks/useNDK'; -import NostrLoginSheet from '@/components/sheets/NostrLoginSheet'; - -export default function ProfileScreen() { - const insets = useSafeAreaInsets(); - const { currentUser, isAuthenticated } = useNDKCurrentUser(); - const [profileImageUrl, setProfileImageUrl] = useState(undefined); - const [bannerImageUrl, setBannerImageUrl] = useState(undefined); - const [aboutText, setAboutText] = useState(undefined); - const [isLoginSheetOpen, setIsLoginSheetOpen] = useState(false); - - const displayName = isAuthenticated - ? (currentUser?.profile?.displayName || currentUser?.profile?.name || 'Nostr User') - : 'Guest User'; - - const username = isAuthenticated - ? (currentUser?.profile?.nip05 || '@user') - : '@guest'; - - // Reset profile data when authentication state changes - useEffect(() => { - if (!isAuthenticated) { - setProfileImageUrl(undefined); - setBannerImageUrl(undefined); - setAboutText(undefined); - } - }, [isAuthenticated]); - - // Extract profile data from Nostr profile - useEffect(() => { - if (currentUser?.profile) { - console.log('Profile data:', currentUser.profile); - - // Extract image URL - const imageUrl = currentUser.profile.image || - currentUser.profile.picture || - (currentUser.profile as any).avatar || - undefined; - setProfileImageUrl(imageUrl); - - // Extract banner URL - const bannerUrl = currentUser.profile.banner || - (currentUser.profile as any).background || - undefined; - setBannerImageUrl(bannerUrl); - - // Extract about text - const about = currentUser.profile.about || - (currentUser.profile as any).description || - undefined; - setAboutText(about); - } - }, [currentUser?.profile]); - - // Show different UI when not authenticated - if (!isAuthenticated) { - return ( - -
console.log('Open notifications')} - > - - - - - - } - /> - - - -

Guest User

- Not logged in - - Login with your Nostr private key to view and manage your profile. - - -
-
- - {/* NostrLoginSheet */} - setIsLoginSheetOpen(false)} - /> - - ); - } - - return ( - -
- - - {/* Banner Image */} - - {bannerImageUrl ? ( - - - - ) : ( - - )} - - - {/* Profile Avatar and Name - positioned to overlap the banner */} - - -

{displayName}

- {username} - - {/* About section */} - {aboutText && ( - - {aboutText} - - )} -
- - {/* Stats */} - - - 24 - Workouts - - - 12 - Templates - - - 3 - Programs - - - - - - - - -
- - ); -} \ No newline at end of file diff --git a/app/(tabs)/profile/_layout.tsx b/app/(tabs)/profile/_layout.tsx new file mode 100644 index 0000000..0e1fcf9 --- /dev/null +++ b/app/(tabs)/profile/_layout.tsx @@ -0,0 +1,86 @@ +// app/(tabs)/profile/_layout.tsx +import React, { useState } from 'react'; +import { View } from 'react-native'; +import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs'; +import { useTheme } from '@react-navigation/native'; +import { TabScreen } from '@/components/layout/TabScreen'; +import Header from '@/components/Header'; +import { useNDKCurrentUser } from '@/lib/hooks/useNDK'; +import NostrLoginSheet from '@/components/sheets/NostrLoginSheet'; +import OverviewScreen from './overview'; +import ActivityScreen from './activity'; +import ProgressScreen from './progress'; +import SettingsScreen from './settings'; +import type { CustomTheme } from '@/lib/theme'; + +const Tab = createMaterialTopTabNavigator(); + +export default function ProfileTabLayout() { + const theme = useTheme() as CustomTheme; + const { isAuthenticated } = useNDKCurrentUser(); + const [isLoginSheetOpen, setIsLoginSheetOpen] = useState(false); + + return ( + +
+ + + + + + + + + + + + {/* NostrLoginSheet */} + setIsLoginSheetOpen(false)} + /> + + ); +} diff --git a/app/(tabs)/profile/activity.tsx b/app/(tabs)/profile/activity.tsx new file mode 100644 index 0000000..d99508a --- /dev/null +++ b/app/(tabs)/profile/activity.tsx @@ -0,0 +1,217 @@ +// app/(tabs)/profile/activity.tsx +import React, { useState, useEffect } from 'react'; +import { View, ScrollView, Pressable } from 'react-native'; +import { Text } from '@/components/ui/text'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent } from '@/components/ui/card'; +import { useNDKCurrentUser } from '@/lib/hooks/useNDK'; +import { ActivityIndicator } from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import NostrLoginSheet from '@/components/sheets/NostrLoginSheet'; +import { useRouter } from 'expo-router'; +import { useAnalytics } from '@/lib/hooks/useAnalytics'; +import { PersonalRecord } from '@/lib/services/AnalyticsService'; +import { formatDistanceToNow } from 'date-fns'; +import { useWorkouts } from '@/lib/hooks/useWorkouts'; +import { useTemplates } from '@/lib/hooks/useTemplates'; +import WorkoutCard from '@/components/workout/WorkoutCard'; +import { Dumbbell, BarChart2, Award, Calendar } from 'lucide-react-native'; + +export default function ActivityScreen() { + const insets = useSafeAreaInsets(); + const router = useRouter(); + const { isAuthenticated } = useNDKCurrentUser(); + const analytics = useAnalytics(); + const { workouts, loading: workoutsLoading } = useWorkouts(); + const { templates, loading: templatesLoading } = useTemplates(); + const [isLoginSheetOpen, setIsLoginSheetOpen] = useState(false); + const [records, setRecords] = useState([]); + const [loading, setLoading] = useState(true); + + // Stats + const completedWorkouts = workouts?.filter(w => w.isCompleted)?.length || 0; + const totalTemplates = templates?.length || 0; + const totalPrograms = 0; // Placeholder for programs count + + // Load personal records + useEffect(() => { + async function loadRecords() { + if (!isAuthenticated) return; + + try { + setLoading(true); + const personalRecords = await analytics.getPersonalRecords(undefined, 3); + setRecords(personalRecords); + } catch (error) { + console.error('Error loading personal records:', error); + } finally { + setLoading(false); + } + } + + loadRecords(); + }, [isAuthenticated, analytics]); + + // Show different UI when not authenticated + if (!isAuthenticated) { + return ( + + + Login with your Nostr private key to view your activity and stats. + + + + {/* NostrLoginSheet */} + setIsLoginSheetOpen(false)} + /> + + ); + } + + if (loading || workoutsLoading || templatesLoading) { + return ( + + + + ); + } + + return ( + + {/* Stats Cards - Row 1 */} + + + + + + {completedWorkouts} + Workouts + + + + + + + + + {totalTemplates} + Templates + + + + + + {/* Stats Cards - Row 2 */} + + + + + + {totalPrograms} + Programs + + + + + + + + + {records.length} + PRs + + + + + + {/* Personal Records */} + + + + Personal Records + router.push('/profile/progress')}> + View All + + + + {records.length === 0 ? ( + + No personal records yet. Complete more workouts to see your progress. + + ) : ( + records.map((record) => ( + + {record.exerciseName} + {record.value} {record.unit} × {record.reps} reps + + {formatDistanceToNow(new Date(record.date), { addSuffix: true })} + + + )) + )} + + + + {/* Recent Workouts */} + + + + Recent Workouts + router.push('/history/workoutHistory')}> + View All + + + + {workouts && workouts.length > 0 ? ( + workouts + .filter(workout => workout.isCompleted) + .slice(0, 2) + .map(workout => ( + + + + )) + ) : ( + + No recent workouts. Complete a workout to see it here. + + )} + + + + {/* Quick Actions */} + + + + + + ); +} diff --git a/app/(tabs)/profile/overview.tsx b/app/(tabs)/profile/overview.tsx new file mode 100644 index 0000000..3575f5f --- /dev/null +++ b/app/(tabs)/profile/overview.tsx @@ -0,0 +1,259 @@ +// app/(tabs)/profile/overview.tsx +import React, { useState, useCallback } from 'react'; +import { View, FlatList, RefreshControl, Pressable, TouchableOpacity, ImageBackground } from 'react-native'; +import { Text } from '@/components/ui/text'; +import { Button } from '@/components/ui/button'; +import { useNDKCurrentUser } from '@/lib/hooks/useNDK'; +import { ActivityIndicator } from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import NostrLoginSheet from '@/components/sheets/NostrLoginSheet'; +import EnhancedSocialPost from '@/components/social/EnhancedSocialPost'; +import EmptyFeed from '@/components/social/EmptyFeed'; +import { useUserActivityFeed } from '@/lib/hooks/useFeedHooks'; +import { AnyFeedEntry } from '@/types/feed'; +import UserAvatar from '@/components/UserAvatar'; +import { useRouter } from 'expo-router'; +import { QrCode, Mail, Copy } from 'lucide-react-native'; +import { useTheme } from '@react-navigation/native'; +import type { CustomTheme } from '@/lib/theme'; +import { Alert } from 'react-native'; + +// Define the conversion function for feed items +function convertToLegacyFeedItem(entry: AnyFeedEntry) { + return { + id: entry.eventId, + type: entry.type, + originalEvent: entry.event!, + parsedContent: entry.content!, + createdAt: (entry.timestamp || Date.now()) / 1000 + }; +} + +export default function OverviewScreen() { + const insets = useSafeAreaInsets(); + const router = useRouter(); + const theme = useTheme() as CustomTheme; + const { currentUser, isAuthenticated } = useNDKCurrentUser(); + const [isLoginSheetOpen, setIsLoginSheetOpen] = useState(false); + const { + entries, + loading, + resetFeed, + hasContent + } = useUserActivityFeed(); + + const [isRefreshing, setIsRefreshing] = useState(false); + + // Profile data + const profileImageUrl = currentUser?.profile?.image || + currentUser?.profile?.picture || + (currentUser?.profile as any)?.avatar; + + const bannerImageUrl = currentUser?.profile?.banner || + (currentUser?.profile as any)?.background; + + const displayName = isAuthenticated + ? (currentUser?.profile?.displayName || currentUser?.profile?.name || 'Nostr User') + : 'Guest User'; + + const username = isAuthenticated + ? (currentUser?.profile?.nip05 || '@user') + : '@guest'; + + const aboutText = currentUser?.profile?.about || + (currentUser?.profile as any)?.description; + + const pubkey = currentUser?.pubkey; + + // Handle refresh + const handleRefresh = useCallback(async () => { + setIsRefreshing(true); + try { + await resetFeed(); + // Add a slight delay to ensure the UI updates + await new Promise(resolve => setTimeout(resolve, 300)); + } catch (error) { + console.error('Error refreshing feed:', error); + } finally { + setIsRefreshing(false); + } + }, [resetFeed]); + + // Handle post selection + const handlePostPress = useCallback((entry: AnyFeedEntry) => { + // Just log the entry info for now + console.log(`Selected ${entry.type}:`, entry); + }, []); + + // Copy pubkey to clipboard + const copyPubkey = useCallback(() => { + if (pubkey) { + // Simple alert instead of clipboard functionality + Alert.alert('Pubkey', pubkey, [ + { text: 'OK' } + ]); + console.log('Pubkey shown to user'); + } + }, [pubkey]); + + // Show QR code alert + const showQRCode = useCallback(() => { + Alert.alert('QR Code', 'QR Code functionality will be implemented soon', [ + { text: 'OK' } + ]); + }, []); + + // Memoize render item function + const renderItem = useCallback(({ item }: { item: AnyFeedEntry }) => ( + handlePostPress(item)} + /> + ), [handlePostPress]); + + // Show different UI when not authenticated + if (!isAuthenticated) { + return ( + + + Login with your Nostr private key to view your profile and posts. + + + + {/* NostrLoginSheet */} + setIsLoginSheetOpen(false)} + /> + + ); + } + + // Profile header component + const ProfileHeader = useCallback(() => ( + + {/* Banner Image */} + + {bannerImageUrl ? ( + + + + ) : ( + + )} + + + + + {/* Left side - Avatar */} + + + {/* Action buttons - positioned to the right */} + + + + + + + + + + router.push('/profile/settings')} + > + Edit Profile + + + + + {/* Profile info */} + + {displayName} + {username} + + {/* Follower stats */} + + + + 2,003 + following + + + + + + 4,764 + followers + + + + + {/* About text */} + {aboutText && ( + {aboutText} + )} + + + {/* Divider */} + + + + ), [displayName, username, profileImageUrl, aboutText, pubkey, theme.colors.text, router, showQRCode, copyPubkey]); + + if (loading && entries.length === 0) { + return ( + + + + ); + } + + return ( + + item.id} + renderItem={renderItem} + refreshControl={ + + } + ListHeaderComponent={} + ListEmptyComponent={ + + + + } + contentContainerStyle={{ + paddingBottom: insets.bottom + 20, + flexGrow: entries.length === 0 ? 1 : undefined + }} + /> + + ); +} diff --git a/app/(tabs)/profile/progress.tsx b/app/(tabs)/profile/progress.tsx new file mode 100644 index 0000000..c28de83 --- /dev/null +++ b/app/(tabs)/profile/progress.tsx @@ -0,0 +1,248 @@ +// app/(tabs)/profile/progress.tsx +import React, { useState, useEffect } from 'react'; +import { View, ScrollView } from 'react-native'; +import { Text } from '@/components/ui/text'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent } from '@/components/ui/card'; +import { useNDKCurrentUser } from '@/lib/hooks/useNDK'; +import { ActivityIndicator } from 'react-native'; +import { useAnalytics } from '@/lib/hooks/useAnalytics'; +import { WorkoutStats, PersonalRecord } from '@/lib/services/AnalyticsService'; + +// Period selector component +function PeriodSelector({ period, setPeriod }: { + period: 'week' | 'month' | 'year' | 'all', + setPeriod: (period: 'week' | 'month' | 'year' | 'all') => void +}) { + return ( + + + + + + + ); +} + +// Format duration in hours and minutes +function formatDuration(milliseconds: number): string { + const hours = Math.floor(milliseconds / (1000 * 60 * 60)); + const minutes = Math.floor((milliseconds % (1000 * 60 * 60)) / (1000 * 60)); + return `${hours}h ${minutes}m`; +} + +export default function ProgressScreen() { + const { isAuthenticated } = useNDKCurrentUser(); + const analytics = useAnalytics(); + const [period, setPeriod] = useState<'week' | 'month' | 'year' | 'all'>('month'); + const [loading, setLoading] = useState(true); + const [stats, setStats] = useState(null); + const [records, setRecords] = useState([]); + + // Load workout statistics when period changes + useEffect(() => { + async function loadStats() { + if (!isAuthenticated) return; + + try { + setLoading(true); + const workoutStats = await analytics.getWorkoutStats(period); + setStats(workoutStats); + + // Load personal records + const personalRecords = await analytics.getPersonalRecords(undefined, 5); + setRecords(personalRecords); + } catch (error) { + console.error('Error loading analytics data:', error); + } finally { + setLoading(false); + } + } + + loadStats(); + }, [isAuthenticated, period, analytics]); + + // Workout frequency chart + const WorkoutFrequencyChart = () => { + const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; + + return ( + + Workout Frequency Chart + + {stats?.frequencyByDay.map((count, index) => ( + + + {days[index]} + + ))} + + + ); + }; + + // Exercise distribution chart + const ExerciseDistributionChart = () => { + // Sample exercise names for demonstration + const exerciseNames = [ + 'Bench Press', 'Squat', 'Deadlift', 'Pull-up', 'Shoulder Press' + ]; + + // Convert exercise distribution to percentages + const exerciseDistribution = stats?.exerciseDistribution || {}; + const total = Object.values(exerciseDistribution).reduce((sum, count) => sum + count, 0) || 1; + const percentages = Object.entries(exerciseDistribution).reduce((acc, [id, count]) => { + acc[id] = Math.round((count / total) * 100); + return acc; + }, {} as Record); + + // Take top 5 exercises + const topExercises = Object.entries(percentages) + .sort(([, a], [, b]) => b - a) + .slice(0, 5); + + return ( + + Exercise Distribution + + {topExercises.map(([id, percentage], index) => ( + + + + {exerciseNames[index % exerciseNames.length].substring(0, 8)} + + + ))} + + + ); + }; + + if (!isAuthenticated) { + return ( + + + Log in to view your progress + + + ); + } + + if (loading) { + return ( + + + + ); + } + + return ( + + + + {/* Workout Summary */} + + + Workout Summary + Workouts: {stats?.workoutCount || 0} + Total Time: {formatDuration(stats?.totalDuration || 0)} + Total Volume: {(stats?.totalVolume || 0).toLocaleString()} lb + + + + {/* Workout Frequency Chart */} + + + Workout Frequency + + + + + {/* Muscle Group Distribution */} + + + Exercise Distribution + + + + + {/* Personal Records */} + + + Personal Records + {records.length === 0 ? ( + + No personal records yet. Complete more workouts to see your progress. + + ) : ( + records.map((record) => ( + + {record.exerciseName} + {record.value} {record.unit} × {record.reps} reps + + {new Date(record.date).toLocaleDateString()} + + {record.previousRecord && ( + + Previous: {record.previousRecord.value} {record.unit} + + )} + + )) + )} + + + + {/* Note about future implementation */} + + + + Note: This is a placeholder UI. In the future, this tab will display real analytics based on your workout history. + + + + + ); +} diff --git a/app/(tabs)/profile/settings.tsx b/app/(tabs)/profile/settings.tsx new file mode 100644 index 0000000..5ede01c --- /dev/null +++ b/app/(tabs)/profile/settings.tsx @@ -0,0 +1,149 @@ +// app/(tabs)/profile/settings.tsx +import React, { useState } from 'react'; +import { View, ScrollView, Switch, TouchableOpacity } from 'react-native'; +import { Text } from '@/components/ui/text'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent } from '@/components/ui/card'; +import { useNDKCurrentUser, useNDKAuth } from '@/lib/hooks/useNDK'; +import { ActivityIndicator } from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import NostrLoginSheet from '@/components/sheets/NostrLoginSheet'; +import TermsOfServiceModal from '@/components/TermsOfServiceModal'; +import { useTheme } from '@react-navigation/native'; +import type { CustomTheme } from '@/lib/theme'; +import { useColorScheme } from '@/lib/theme/useColorScheme'; +import { ChevronRight } from 'lucide-react-native'; + +export default function SettingsScreen() { + const insets = useSafeAreaInsets(); + const theme = useTheme() as CustomTheme; + const { colorScheme, toggleColorScheme } = useColorScheme(); + const { currentUser, isAuthenticated } = useNDKCurrentUser(); + const { logout } = useNDKAuth(); + const [isLoginSheetOpen, setIsLoginSheetOpen] = useState(false); + const [isTermsModalVisible, setIsTermsModalVisible] = useState(false); + + // Show different UI when not authenticated + if (!isAuthenticated) { + return ( + + + Login with your Nostr private key to access settings. + + + + {/* NostrLoginSheet */} + setIsLoginSheetOpen(false)} + /> + + ); + } + + return ( + + {/* Account Settings */} + + + Account Settings + + + Nostr Publishing + Public + + + + Local Storage + Enabled + + + + Connected Relays + 5 + + + + + {/* App Settings */} + + + App Settings + + + Dark Mode + + + + + Notifications + + + + + Units + Metric (kg) + + + + + {/* About */} + + + About + + + Version + 1.0.0 + + + setIsTermsModalVisible(true)} + > + Terms of Service + + View + + + + + + {/* Terms of Service Modal */} + setIsTermsModalVisible(false)} + /> + + + {/* Logout Button */} + + + + + ); +} diff --git a/app/(tabs)/profile/terms.tsx b/app/(tabs)/profile/terms.tsx new file mode 100644 index 0000000..9301587 --- /dev/null +++ b/app/(tabs)/profile/terms.tsx @@ -0,0 +1,75 @@ +// app/(tabs)/profile/terms.tsx +import React from 'react'; +import { View, ScrollView, TouchableOpacity } from 'react-native'; +import { Text } from '@/components/ui/text'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import { format } from 'date-fns'; +import { ChevronLeft } from 'lucide-react-native'; +import { useRouter } from 'expo-router'; + +export default function TermsOfServiceScreen() { + const insets = useSafeAreaInsets(); + const router = useRouter(); + const currentDate = format(new Date(), 'MMMM d, yyyy'); + + return ( + + + router.back()} + className="mr-4 p-2" + > + + + Terms of Service + + + + POWR App Terms of Service + + + POWR is a local-first fitness tracking application that integrates with the Nostr protocol. + + + Data Storage and Privacy + + • POWR stores your workout data, exercise templates, and preferences locally on your device. + • We do not collect, store, or track any personal data on our servers. + • Any content you choose to publish to Nostr relays (such as workouts or templates) will be publicly available to anyone with access to those relays. Think of Nostr posts as public broadcasts. + • Your private keys are stored locally on your device and are never transmitted to us. + + + User Responsibility + + • You are responsible for safeguarding your private keys. + • You are solely responsible for any content you publish to Nostr relays. + • Exercise caution when sharing personal information through public Nostr posts. + + + Fitness Disclaimer + + • POWR provides fitness tracking tools, not medical advice. Consult a healthcare professional before starting any fitness program. + • You are solely responsible for any injuries or health issues that may result from exercises tracked using this app. + + + Changes to Terms + + We may update these terms from time to time. Continued use of the app constitutes acceptance of any changes. + + + + Last Updated: {currentDate} + + + + ); +} diff --git a/components/SettingsDrawer.tsx b/components/SettingsDrawer.tsx index 08e7e70..0bd7b12 100644 --- a/components/SettingsDrawer.tsx +++ b/components/SettingsDrawer.tsx @@ -101,7 +101,7 @@ export default function SettingsDrawer() { // Go to the profile tab which should have login functionality closeDrawer(); setTimeout(() => { - router.push("/(tabs)/profile"); + router.push("/"); }, 300); }; @@ -531,4 +531,4 @@ const styles = StyleSheet.create({ padding: 16, paddingBottom: Platform.OS === 'ios' ? 16 : 16, }, -}); \ No newline at end of file +}); diff --git a/components/TermsOfServiceModal.tsx b/components/TermsOfServiceModal.tsx new file mode 100644 index 0000000..23b5437 --- /dev/null +++ b/components/TermsOfServiceModal.tsx @@ -0,0 +1,173 @@ +// components/TermsOfServiceModal.tsx +import React from 'react'; +import { View, ScrollView, Modal, TouchableOpacity, StyleSheet, Text } from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import { format } from 'date-fns'; +import { X } from 'lucide-react-native'; +import { Button } from '@/components/ui/button'; +import { useColorScheme } from '@/lib/theme/useColorScheme'; + +interface TermsOfServiceModalProps { + visible: boolean; + onClose: () => void; +} + +export default function TermsOfServiceModal({ visible, onClose }: TermsOfServiceModalProps) { + const insets = useSafeAreaInsets(); + const { isDarkColorScheme } = useColorScheme(); + const currentDate = format(new Date(), 'MMMM d, yyyy'); + + const textColor = isDarkColorScheme ? '#FFFFFF' : '#000000'; + const backgroundColor = isDarkColorScheme ? '#1c1c1e' : '#FFFFFF'; + const mutedTextColor = isDarkColorScheme ? '#A1A1A1' : '#6B7280'; + + return ( + + + + + Terms of Service + + + + + + + + POWR App Terms of Service + + + + POWR is a local-first fitness tracking application that integrates with the Nostr protocol. + + + + Data Storage and Privacy + + + • POWR stores your workout data, exercise templates, and preferences locally on your device. + + + • We do not collect, store, or track any personal data on our servers. + + + • Any content you choose to publish to Nostr relays (such as workouts or templates) will be publicly available to anyone with access to those relays. Think of Nostr posts as public broadcasts. + + + • Your private keys are stored locally on your device and are never transmitted to us. + + + + User Responsibility + + + • You are responsible for safeguarding your private keys. + + + • You are solely responsible for any content you publish to Nostr relays. + + + • Exercise caution when sharing personal information through public Nostr posts. + + + + Fitness Disclaimer + + + • POWR provides fitness tracking tools, not medical advice. Consult a healthcare professional before starting any fitness program. + + + • You are solely responsible for any injuries or health issues that may result from exercises tracked using this app. + + + + Changes to Terms + + + We may update these terms from time to time. Continued use of the app constitutes acceptance of any changes. + + + + Last Updated: {currentDate} + + + + + + + + ); +} + +const styles = StyleSheet.create({ + modalContainer: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + backgroundColor: 'rgba(0, 0, 0, 0.7)', + }, + modalContent: { + width: '90%', + maxHeight: '80%', + borderRadius: 12, + padding: 20, + shadowColor: '#000', + shadowOffset: { width: 0, height: 2 }, + shadowOpacity: 0.25, + shadowRadius: 3.84, + elevation: 5, + }, + header: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + marginBottom: 16, + }, + title: { + fontSize: 20, + fontWeight: 'bold', + }, + closeButton: { + padding: 4, + }, + scrollView: { + flex: 1, + marginBottom: 16, + }, + heading: { + fontSize: 18, + fontWeight: 'bold', + marginTop: 16, + marginBottom: 8, + }, + sectionTitle: { + fontSize: 16, + fontWeight: '600', + marginTop: 16, + marginBottom: 8, + }, + paragraph: { + marginBottom: 16, + lineHeight: 20, + }, + bulletPoint: { + marginBottom: 8, + lineHeight: 20, + }, + lastUpdated: { + fontSize: 12, + marginTop: 16, + marginBottom: 8, + }, +}); diff --git a/components/sheets/TermsOfServiceSheet.tsx b/components/sheets/TermsOfServiceSheet.tsx new file mode 100644 index 0000000..97cf69a --- /dev/null +++ b/components/sheets/TermsOfServiceSheet.tsx @@ -0,0 +1,175 @@ +// components/sheets/TermsOfServiceSheet.tsx +import React from 'react'; +import { View, ScrollView, Modal, TouchableOpacity, StyleSheet } from 'react-native'; +import { Text } from '@/components/ui/text'; +import { Button } from '@/components/ui/button'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import { format } from 'date-fns'; +import { X } from 'lucide-react-native'; +import { useColorScheme } from '@/lib/theme/useColorScheme'; + +interface TermsOfServiceSheetProps { + open: boolean; + onClose: () => void; +} + +export default function TermsOfServiceSheet({ open, onClose }: TermsOfServiceSheetProps) { + const insets = useSafeAreaInsets(); + const { isDarkColorScheme } = useColorScheme(); + const currentDate = format(new Date(), 'MMMM d, yyyy'); + + if (!open) return null; + + return ( + + + + + Terms of Service + + + + + + + + POWR App Terms of Service + + + + POWR is a local-first fitness tracking application that integrates with the Nostr protocol. + + + + Data Storage and Privacy + + + • POWR stores your workout data, exercise templates, and preferences locally on your device. + + + • We do not collect, store, or track any personal data on our servers. + + + • Any content you choose to publish to Nostr relays (such as workouts or templates) will be publicly available to anyone with access to those relays. Think of Nostr posts as public broadcasts. + + + • Your private keys are stored locally on your device and are never transmitted to us. + + + + User Responsibility + + + • You are responsible for safeguarding your private keys. + + + • You are solely responsible for any content you publish to Nostr relays. + + + • Exercise caution when sharing personal information through public Nostr posts. + + + + Fitness Disclaimer + + + • POWR provides fitness tracking tools, not medical advice. Consult a healthcare professional before starting any fitness program. + + + • You are solely responsible for any injuries or health issues that may result from exercises tracked using this app. + + + + Changes to Terms + + + We may update these terms from time to time. Continued use of the app constitutes acceptance of any changes. + + + + Last Updated: {currentDate} + + + + + + + + ); +} + +const styles = StyleSheet.create({ + modalContainer: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + backgroundColor: 'rgba(0, 0, 0, 0.7)', + }, + modalContent: { + width: '90%', + maxHeight: '80%', + borderRadius: 12, + padding: 20, + shadowColor: '#000', + shadowOffset: { width: 0, height: 2 }, + shadowOpacity: 0.25, + shadowRadius: 3.84, + elevation: 5, + }, + header: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + marginBottom: 16, + }, + title: { + fontSize: 20, + fontWeight: 'bold', + }, + closeButton: { + padding: 4, + }, + scrollView: { + flex: 1, + marginBottom: 16, + }, + heading: { + fontSize: 18, + fontWeight: 'bold', + marginTop: 16, + marginBottom: 8, + }, + sectionTitle: { + fontSize: 16, + fontWeight: '600', + marginTop: 16, + marginBottom: 8, + }, + paragraph: { + marginBottom: 16, + lineHeight: 20, + }, + bulletPoint: { + marginBottom: 8, + lineHeight: 20, + }, + lastUpdated: { + fontSize: 12, + marginTop: 16, + marginBottom: 8, + }, +}); diff --git a/docs/design/ProfileTab/ProfileTabEnhancementDesignDoc.md b/docs/design/ProfileTab/ProfileTabEnhancementDesignDoc.md new file mode 100644 index 0000000..ab69ca2 --- /dev/null +++ b/docs/design/ProfileTab/ProfileTabEnhancementDesignDoc.md @@ -0,0 +1,147 @@ +# Profile Tab Enhancement Design Document + +## Overview + +This document outlines the design and implementation of the enhanced Profile tab for the POWR app. The enhancement includes a tabbed interface with separate screens for profile overview, activity feed, progress analytics, and settings. + +## Motivation + +The original Profile tab was limited to displaying basic user information. With the growing social and analytics features of the app, we need a more comprehensive profile experience that: + +1. Showcases the user's identity and achievements +2. Displays workout activity in a social feed format +3. Provides analytics and progress tracking +4. Offers easy access to settings and preferences + +By moving analytics and progress tracking to the Profile tab, we create a more cohesive user experience that focuses on personal growth and achievement. + +## Design + +### Tab Structure + +The enhanced Profile tab is organized into four sub-tabs: + +1. **Overview**: Displays user profile information, stats summary, and quick access to recent records and activity +2. **Activity**: Shows a chronological feed of the user's workout posts +3. **Progress**: Provides analytics and progress tracking with charts and personal records +4. **Settings**: Contains profile editing, privacy controls, and app preferences + +### Navigation + +The tabs are implemented using Expo Router's `Tabs` component, with appropriate icons for each tab: + +- Overview: User icon +- Activity: Activity icon +- Progress: BarChart2 icon +- Settings: Settings icon + +### Data Flow + +The Profile tab components interact with several services: + +1. **NDK Services**: For user profile data and authentication +2. **WorkoutService**: For accessing workout history +3. **AnalyticsService**: For calculating statistics and progress metrics + +## Implementation Details + +### New Components and Files + +1. **Tab Layout**: + - `app/(tabs)/profile/_layout.tsx`: Defines the tab structure and navigation + +2. **Tab Screens**: + - `app/(tabs)/profile/overview.tsx`: Profile information and summary + - `app/(tabs)/profile/activity.tsx`: Workout activity feed + - `app/(tabs)/profile/progress.tsx`: Analytics and progress tracking + - `app/(tabs)/profile/settings.tsx`: User settings and preferences + +3. **Services**: + - `lib/services/AnalyticsService.ts`: Service for calculating workout statistics and progress data + - `lib/hooks/useAnalytics.ts`: React hook for accessing the analytics service + +### Analytics Service + +The AnalyticsService provides methods for: + +1. **Workout Statistics**: Calculate aggregate statistics like total workouts, duration, volume, etc. +2. **Exercise Progress**: Track progress for specific exercises over time +3. **Personal Records**: Identify and track personal records for exercises + +The service is designed to work with both local and Nostr-based workout data, providing a unified view of the user's progress. + +### Authentication Integration + +The Profile tab is integrated with the Nostr authentication system: + +- Unauthenticated users see a login prompt in the Overview tab +- All tabs show appropriate UI for unauthenticated users +- The NostrLoginSheet is accessible from the Overview tab + +## User Experience + +### Overview Tab + +The Overview tab provides a comprehensive view of the user's profile: + +- Profile picture and banner image +- Display name and username +- About/bio text +- Summary statistics (workouts, templates, programs) +- Recent personal records +- Recent activity +- Quick actions for profile management + +### Activity Tab + +The Activity tab displays the user's workout posts in a chronological feed: + +- Each post shows the workout details +- Posts are formatted similar to the social feed +- Empty state for users with no activity + +### Progress Tab + +The Progress tab visualizes the user's fitness journey: + +- Period selector (week, month, year, all-time) +- Workout summary statistics +- Workout frequency chart +- Exercise distribution chart +- Personal records list +- Empty states for users with no data + +### Settings Tab + +The Settings tab provides access to user preferences: + +- Profile information editing +- Privacy settings +- Notification preferences +- Account management + +## Future Enhancements + +1. **Workout Streaks**: Track and display workout consistency +2. **Goal Setting**: Allow users to set and track fitness goals +3. **Comparison Analytics**: Compare current performance with past periods +4. **Social Integration**: Show followers/following counts and management +5. **Achievement Badges**: Gamification elements for workout milestones + +## Technical Considerations + +### Performance + +- The AnalyticsService uses caching to minimize recalculations +- Data is loaded asynchronously to keep the UI responsive +- Charts and visualizations use efficient rendering techniques + +### Data Privacy + +- Analytics are calculated locally on the device +- Sharing controls allow users to decide what data is public +- Personal records can be selectively shared + +## Conclusion + +The enhanced Profile tab transforms the user experience by providing a comprehensive view of the user's identity, activity, and progress. By centralizing these features in the Profile tab, we create a more intuitive and engaging experience that encourages users to track their fitness journey and celebrate their achievements. diff --git a/docs/design/WorkoutTab/HistoryTabEnhancementDesignDoc.md b/docs/design/WorkoutTab/HistoryTabEnhancementDesignDoc.md new file mode 100644 index 0000000..5b80727 --- /dev/null +++ b/docs/design/WorkoutTab/HistoryTabEnhancementDesignDoc.md @@ -0,0 +1,368 @@ +# History Tab Enhancement Design Document + +## Problem Statement +The current History tab provides basic workout tracking but lacks filtering, detailed views, and improved visualization features that would help users better navigate and understand their training history. Additionally, the app needs to better integrate with Nostr for workout sharing and synchronization across devices. Analytics and progress tracking features, which were initially considered for the History tab, have been moved to the Profile tab as they better align with documenting personal growth. + +## Requirements + +### Functional Requirements +- Enhanced workout history browsing with filtering and sorting +- Detailed workout view with complete exercise and set information +- Calendar view with improved visualization and interaction +- Export and sharing capabilities for workout data +- Search functionality across workout history +- Differentiation between local and Nostr-published workouts +- Ability to publish local workouts to Nostr +- Display of Nostr workouts not stored locally +- Integration with Profile tab for analytics and progress tracking + +### Non-Functional Requirements +- Performance optimization for large workout histories +- Responsive UI that works across device sizes +- Offline functionality for viewing history without network +- Consistent design language with the rest of the app +- Accessibility compliance +- Efficient data synchronization with Nostr relays + +## Design Decisions + +### 1. Tab Structure Enhancement +Keep the existing History/Calendar structure, focusing on enhancing these views with better filtering, search, and visualization. + +Rationale: +- Maintains simplicity of individual views +- Follows established patterns in fitness apps +- Allows specialized UI for each view type +- Analytics and progress tracking will be moved to the Profile tab for better user context + +### 2. Data Aggregation Strategy +Implement a dedicated analytics service that pre-processes workout data for visualization. This service will be shared with the Profile tab's analytics features. + +Rationale: +- Improves performance by avoiding repeated calculations +- Enables complex trend analysis without UI lag +- Separates presentation logic from data processing +- Supports both history visualization and profile analytics + +### 3. History Visualization Approach +Focus on providing clear, chronological views of workout history with rich filtering and search capabilities. + +Rationale: +- Users need to quickly find specific past workouts +- Calendar view provides temporal context for training patterns +- Filtering by exercise, type, and other attributes enables targeted review +- Integration with Profile tab analytics provides deeper insights when needed + +### 4. Nostr Integration Strategy +Implement a tiered approach to Nostr integration, starting with basic publishing capabilities in the MVP and expanding to full synchronization in future versions. + +Rationale: +- Allows for incremental development and testing +- Prioritizes most valuable features for initial release +- Addresses core user needs first +- Builds foundation for more advanced features + +## Technical Design + +### Core Components + +```typescript +// Enhanced history service + +// Enhanced workout history service +interface EnhancedWorkoutHistoryService extends WorkoutHistoryService { + searchWorkouts(query: string): Promise; + filterWorkouts(filters: WorkoutFilters): Promise; + getWorkoutsByExercise(exerciseId: string): Promise; + exportWorkoutHistory(format: 'csv' | 'json'): Promise; + getWorkoutStreak(): Promise; + + // Nostr integration methods + getWorkoutSyncStatus(workoutId: string): Promise<{ + isLocal: boolean; + isPublished: boolean; + eventId?: string; + relayCount?: number; + }>; + publishWorkoutToNostr(workoutId: string): Promise; // Returns event ID +} + +// Nostr workout service (for future expansion) +interface NostrWorkoutHistoryService { + // Fetch workouts from relays that aren't in local DB + fetchNostrOnlyWorkouts(since?: Date): Promise; + + // Merge local and Nostr workouts with deduplication + getMergedWorkoutHistory(): Promise; + + // Import a Nostr workout into local DB + importNostrWorkoutToLocal(eventId: string): Promise; +} + +// New data structures +interface WorkoutStats { + period: string; + workoutCount: number; + totalVolume: number; + totalDuration: number; + averageIntensity: number; + exerciseDistribution: Record; +} + +interface ProgressPoint { + date: number; + value: number; + workoutId: string; +} + +interface WorkoutFilters { + type?: TemplateType[]; + dateRange?: { start: Date; end: Date }; + exercises?: string[]; + tags?: string[]; + source?: ('local' | 'nostr' | 'both')[]; +} + +// Enhanced WorkoutCard props +interface EnhancedWorkoutCardProps extends WorkoutCardProps { + source: 'local' | 'nostr' | 'both'; + publishStatus?: { + isPublished: boolean; + relayCount: number; + lastPublished?: number; + }; + onShare?: () => void; + onImport?: () => void; +} +``` + +### Database Schema Updates + +```sql +-- Fix typo in service name first (WorkoutHIstoryService -> WorkoutHistoryService) + +-- Add Nostr-related fields to completed_workouts table +ALTER TABLE completed_workouts ADD COLUMN nostr_event_id TEXT; +ALTER TABLE completed_workouts ADD COLUMN nostr_published_at INTEGER; +ALTER TABLE completed_workouts ADD COLUMN nostr_relay_count INTEGER DEFAULT 0; +ALTER TABLE completed_workouts ADD COLUMN source TEXT DEFAULT 'local'; + +-- Create table for tracking Nostr-only workouts (future expansion) +CREATE TABLE IF NOT EXISTS nostr_workouts ( + event_id TEXT PRIMARY KEY, + pubkey TEXT NOT NULL, + content TEXT NOT NULL, + created_at INTEGER NOT NULL, + kind INTEGER NOT NULL, + tags TEXT NOT NULL, + sig TEXT NOT NULL, + last_seen INTEGER NOT NULL, + relay_count INTEGER NOT NULL +); +``` + +### Integration Points +- SQLite database for local storage +- Chart libraries for data visualization +- Share API for exporting workout data +- Nostr integration for social sharing and sync +- Calendar API for date handling +- NDK for Nostr relay communication + +## Implementation Plan + +### Phase 1: Foundation & Enhanced History View +1. Fix typo in WorkoutHistoryService filename +2. Implement workout detail view navigation +3. Add filtering and sorting to history list +4. Enhance WorkoutCard with more metrics +5. Implement search functionality +6. Add basic Nostr status indicators (local vs. published) +7. Improve calendar visualization with heatmap +8. Add day summary popups to calendar + +### Phase 2: Nostr Integration (MVP) +1. Update database schema to track Nostr event IDs and publication status +2. Implement visual indicators for workout source/status +3. Add basic publishing functionality for local workouts +4. Add filtering by source (local/published) + +### Phase 3: Export & Sharing +1. Add workout export functionality +2. Implement social sharing features +3. Create printable workout reports +4. Add data backup options + +### Phase 4: Integration with Profile Analytics +1. Implement data sharing with Profile tab analytics +2. Add navigation links to relevant analytics from workout details +3. Ensure consistent data representation between History and Profile tabs + +### Future Phases: Advanced Nostr Integration +1. Create NostrWorkoutHistoryService for fetching Nostr-only workouts +2. Implement workout importing functionality +3. Add background sync for Nostr workouts +4. Implement batch operations for publishing/importing +5. Add cross-device synchronization + +## UI Mockups + +### History Tab with Source Indicators + +``` +┌─────────────────────────────────────────┐ +│ HISTORY │ +├─────────────────────────────────────────┤ +│ ┌─────────────────────────────────────┐ │ +│ │ MARCH 2025 │ │ +│ │ │ │ +│ │ ┌─────────────────────────────────┐ │ │ +│ │ │ Push Day 1 🔄 > │ │ │ +│ │ │ Friday, Mar 7 │ │ │ +│ │ │ ⏱️ 1h 47m ⚖️ 9239 lb 🔄 120 │ │ │ +│ │ │ │ │ │ +│ │ │ Bench Press │ │ │ +│ │ │ Incline Dumbbell Press │ │ │ +│ │ │ Tricep Pushdown │ │ │ +│ │ └─────────────────────────────────┘ │ │ +│ │ │ │ +│ │ ┌─────────────────────────────────┐ │ │ +│ │ │ Pull Day 1 📱 > │ │ │ +│ │ │ Wednesday, Mar 5 │ │ │ +│ │ │ ⏱️ 1h 36m ⚖️ 1396 lb 🔄 95 │ │ │ +│ │ │ │ │ │ +│ │ │ Lat Pulldown │ │ │ +│ │ │ Seated Row │ │ │ +│ │ │ Bicep Curl │ │ │ +│ │ └─────────────────────────────────┘ │ │ +│ │ │ │ +│ └─────────────────────────────────────┘ │ +│ │ +│ ┌─────────────────────────────────────┐ │ +│ │ FEBRUARY 2025 │ │ +│ │ │ │ +│ │ ┌─────────────────────────────────┐ │ │ +│ │ │ Leg Day 1 ☁️ > │ │ │ +│ │ │ Monday, Feb 28 │ │ │ +│ │ │ ⏱️ 1h 15m ⚖️ 8750 lb 🔄 87 │ │ │ +│ │ │ │ │ │ +│ │ │ Squat │ │ │ +│ │ │ Leg Press │ │ │ +│ │ │ Leg Extension │ │ │ +│ │ └─────────────────────────────────┘ │ │ +└─────────────────────────────────────────┘ + +Legend: +🔄 - Local only +📱 - Published to Nostr +☁️ - From Nostr (not stored locally) +``` + +### Workout Detail View with Sharing + +``` +┌─────────────────────────────────────────┐ +│ < WORKOUT DETAILS │ +├─────────────────────────────────────────┤ +│ Push Day 1 │ +│ Friday, March 7, 2025 │ +│ │ +│ ⏱️ 1h 47m ⚖️ 9239 lb 🔄 120 reps │ +│ │ +│ ┌─────────────────────────────────────┐ │ +│ │ EXERCISES │ │ +│ │ │ │ +│ │ Bench Press │ │ +│ │ 135 lb × 12 │ │ +│ │ 185 lb × 10 │ │ +│ │ 205 lb × 8 │ │ +│ │ 225 lb × 6 │ │ +│ │ │ │ +│ │ Incline Dumbbell Press │ │ +│ │ 50 lb × 12 │ │ +│ │ 60 lb × 10 │ │ +│ │ 70 lb × 8 │ │ +│ │ │ │ +│ │ Tricep Pushdown │ │ +│ │ 50 lb × 15 │ │ +│ │ 60 lb × 12 │ │ +│ │ 70 lb × 10 │ │ +│ └─────────────────────────────────────┘ │ +│ │ +│ ┌─────────────────────────────────────┐ │ +│ │ NOTES │ │ +│ │ Felt strong today. Increased bench │ │ +│ │ press weight by 10 lbs. │ │ +│ └─────────────────────────────────────┘ │ +│ │ +│ ┌─────────────────────────────────────┐ │ +│ │ 🔄 Local Only │ │ +│ │ │ │ +│ │ [Publish to Nostr] │ │ +│ └─────────────────────────────────────┘ │ +│ │ +│ [Export Workout] │ +└─────────────────────────────────────────┘ +``` + +Note: Analytics Dashboard and Progress Tracking features have been moved to the Profile tab. See the Profile Tab Enhancement Design Document for details on these features. + +## Testing Strategy + +### Unit Tests +- Service method tests for data processing +- Component rendering tests +- Filter and search algorithm tests +- Chart data preparation tests +- Nostr event creation and parsing tests + +### Integration Tests +- End-to-end workout flow tests +- Database read/write performance tests +- UI interaction tests +- Cross-tab navigation tests +- Nostr publishing and retrieval tests + +## Future Considerations + +### Potential Enhancements +- AI-powered workout insights and recommendations +- Advanced periodization analysis +- Integration with wearable devices for additional metrics +- Video playback of recorded exercises +- Community benchmarking and anonymous comparisons +- Full cross-device synchronization via Nostr +- Collaborative workouts with friends + +### Known Limitations +- Performance may degrade with very large workout histories +- Complex analytics require significant processing +- Limited by available device storage +- Some features require online connectivity +- Nostr relay availability affects sync reliability + +## Integration with Profile Tab + +The History tab will integrate with the Profile tab's analytics and progress tracking features to provide a cohesive user experience: + +### Data Flow +- The same underlying workout data will power both History views and Profile analytics +- The analytics service will process workout data for both tabs +- Changes in one area will be reflected in the other + +### Navigation Integration +- Workout detail views will include links to relevant analytics in the Profile tab +- The Profile tab's progress tracking will link back to relevant historical workouts +- Consistent data visualization will be used across both tabs + +### User Experience +- Users will use the History tab for finding and reviewing specific workouts +- Users will use the Profile tab for analyzing trends and tracking progress +- The separation provides clearer context for each activity while maintaining data consistency + +## References +- [Workout Data Flow Specification](../WorkoutTab/WorkoutDataFlowSpec.md) +- [Nostr Exercise NIP](../nostr-exercise-nip.md) +- [WorkoutHistoryService implementation](../../../lib/db/services/WorkoutHistoryService.ts) +- [NDK documentation](https://github.com/nostr-dev-kit/ndk) +- [Profile Tab Enhancement Design Document](../ProfileTab/ProfileTabEnhancementDesignDoc.md) diff --git a/lib/hooks/useAnalytics.ts b/lib/hooks/useAnalytics.ts new file mode 100644 index 0000000..440e32d --- /dev/null +++ b/lib/hooks/useAnalytics.ts @@ -0,0 +1,49 @@ +// lib/hooks/useAnalytics.ts +import { useEffect, useMemo } from 'react'; +import { analyticsService } from '@/lib/services/AnalyticsService'; +import { useWorkoutService } from '@/components/DatabaseProvider'; + +/** + * Hook to provide access to the analytics service + * This hook ensures the analytics service is properly initialized with + * the necessary database services + */ +export function useAnalytics() { + const workoutService = useWorkoutService(); + + // Initialize the analytics service with the necessary services + useEffect(() => { + analyticsService.setWorkoutService(workoutService); + + // We could also set the NostrWorkoutService here if needed + // analyticsService.setNostrWorkoutService(nostrWorkoutService); + + return () => { + // Clear the cache when the component unmounts + analyticsService.invalidateCache(); + }; + }, [workoutService]); + + // Create a memoized object with the analytics methods + const analytics = useMemo(() => ({ + // Workout statistics + getWorkoutStats: (period: 'week' | 'month' | 'year' | 'all') => + analyticsService.getWorkoutStats(period), + + // Exercise progress + getExerciseProgress: ( + exerciseId: string, + metric: 'weight' | 'reps' | 'volume', + period: 'month' | 'year' | 'all' + ) => analyticsService.getExerciseProgress(exerciseId, metric, period), + + // Personal records + getPersonalRecords: (exerciseIds?: string[], limit?: number) => + analyticsService.getPersonalRecords(exerciseIds, limit), + + // Cache management + invalidateCache: () => analyticsService.invalidateCache() + }), []); + + return analytics; +} diff --git a/lib/hooks/useFeedHooks.ts b/lib/hooks/useFeedHooks.ts index dbe2f88..617c559 100644 --- a/lib/hooks/useFeedHooks.ts +++ b/lib/hooks/useFeedHooks.ts @@ -285,6 +285,61 @@ export function usePOWRFeed(options: FeedOptions = {}) { * Hook for the Global tab in the social feed * Shows all workout-related content */ +/** + * Hook for the user's own activity feed + * Shows only the user's own posts and workouts + */ +export function useUserActivityFeed(options: FeedOptions = {}) { + const { currentUser } = useNDKCurrentUser(); + const { ndk } = useNDK(); + + // Create filters for user's own content + const userFilters = useMemo(() => { + if (!currentUser?.pubkey) return []; + + return [ + { + kinds: [1] as any[], // Social posts + authors: [currentUser.pubkey], + limit: 30 + }, + { + kinds: [30023] as any[], // Articles + authors: [currentUser.pubkey], + limit: 20 + }, + { + kinds: [1301, 33401, 33402] as any[], // Workout-specific content + authors: [currentUser.pubkey], + limit: 30 + } + ]; + }, [currentUser?.pubkey]); + + // Use feed events hook + const feed = useFeedEvents( + currentUser?.pubkey ? userFilters : false, + { + subId: 'user-activity-feed', + feedType: 'user-activity', + ...options + } + ); + + // Feed monitor for auto-refresh + const monitor = useFeedMonitor({ + onRefresh: async () => { + return feed.resetFeed(); + } + }); + + return { + ...feed, + ...monitor, + hasContent: feed.entries.length > 0 + }; +} + export function useGlobalFeed(options: FeedOptions = {}) { // Global filters - focus on workout content const globalFilters = useMemo(() => [ @@ -324,4 +379,4 @@ export function useGlobalFeed(options: FeedOptions = {}) { ...feed, ...monitor }; -} \ No newline at end of file +} diff --git a/lib/services/AnalyticsService.ts b/lib/services/AnalyticsService.ts new file mode 100644 index 0000000..bc59649 --- /dev/null +++ b/lib/services/AnalyticsService.ts @@ -0,0 +1,313 @@ +// lib/services/AnalyticsService.ts +import { Workout } from '@/types/workout'; +import { WorkoutService } from '@/lib/db/services/WorkoutService'; +import { NostrWorkoutService } from '@/lib/db/services/NostrWorkoutService'; + +/** + * Workout statistics data structure + */ +export interface WorkoutStats { + workoutCount: number; + totalDuration: number; // in milliseconds + totalVolume: number; + averageIntensity: number; + exerciseDistribution: Record; + frequencyByDay: number[]; // 0 = Sunday, 6 = Saturday +} + +/** + * Progress point for tracking exercise progress + */ +export interface ProgressPoint { + date: number; // timestamp + value: number; + workoutId: string; +} + +/** + * Personal record data structure + */ +export interface PersonalRecord { + id: string; + exerciseId: string; + exerciseName: string; + value: number; + unit: string; + reps: number; + date: number; // timestamp + workoutId: string; + previousRecord?: { + value: number; + date: number; + }; +} + +/** + * Service for calculating workout analytics and progress data + */ +export class AnalyticsService { + private workoutService: WorkoutService | null = null; + private nostrWorkoutService: NostrWorkoutService | null = null; + private cache = new Map(); + + // Set the workout service (called from React components) + setWorkoutService(service: WorkoutService): void { + this.workoutService = service; + } + + // Set the Nostr workout service (called from React components) + setNostrWorkoutService(service: NostrWorkoutService): void { + this.nostrWorkoutService = service; + } + + /** + * Get workout statistics for a given period + */ + async getWorkoutStats(period: 'week' | 'month' | 'year' | 'all'): Promise { + const cacheKey = `stats-${period}`; + if (this.cache.has(cacheKey)) return this.cache.get(cacheKey); + + // Get workouts for the period + const workouts = await this.getWorkoutsForPeriod(period); + + // Calculate statistics + const stats: WorkoutStats = { + workoutCount: workouts.length, + totalDuration: 0, + totalVolume: 0, + averageIntensity: 0, + exerciseDistribution: {}, + frequencyByDay: [0, 0, 0, 0, 0, 0, 0], + }; + + // Process workouts + workouts.forEach(workout => { + // Add duration + stats.totalDuration += (workout.endTime || Date.now()) - workout.startTime; + + // Add volume + stats.totalVolume += workout.totalVolume || 0; + + // Track frequency by day + const day = new Date(workout.startTime).getDay(); + stats.frequencyByDay[day]++; + + // Track exercise distribution + workout.exercises?.forEach(exercise => { + const exerciseId = exercise.id; + stats.exerciseDistribution[exerciseId] = (stats.exerciseDistribution[exerciseId] || 0) + 1; + }); + }); + + // Calculate average intensity + stats.averageIntensity = workouts.length > 0 + ? workouts.reduce((sum, workout) => sum + (workout.averageRpe || 0), 0) / workouts.length + : 0; + + this.cache.set(cacheKey, stats); + return stats; + } + + /** + * Get progress for a specific exercise + */ + async getExerciseProgress( + exerciseId: string, + metric: 'weight' | 'reps' | 'volume', + period: 'month' | 'year' | 'all' + ): Promise { + const cacheKey = `progress-${exerciseId}-${metric}-${period}`; + if (this.cache.has(cacheKey)) return this.cache.get(cacheKey); + + // Get workouts for the period + const workouts = await this.getWorkoutsForPeriod(period); + + // Filter workouts that contain the exercise + const relevantWorkouts = workouts.filter(workout => + workout.exercises?.some(exercise => + exercise.id === exerciseId || exercise.exerciseId === exerciseId + ) + ); + + // Extract progress points + const progressPoints: ProgressPoint[] = []; + + relevantWorkouts.forEach(workout => { + const exercise = workout.exercises?.find(e => + e.id === exerciseId || e.exerciseId === exerciseId + ); + + if (!exercise) return; + + let value = 0; + + switch (metric) { + case 'weight': + // Find the maximum weight used in any set + value = Math.max(...exercise.sets.map(set => set.weight || 0)); + break; + case 'reps': + // Find the maximum reps in any set + value = Math.max(...exercise.sets.map(set => set.reps || 0)); + break; + case 'volume': + // Calculate total volume (weight * reps) for the exercise + value = exercise.sets.reduce((sum, set) => + sum + ((set.weight || 0) * (set.reps || 0)), 0); + break; + } + + progressPoints.push({ + date: workout.startTime, + value, + workoutId: workout.id + }); + }); + + // Sort by date + progressPoints.sort((a, b) => a.date - b.date); + + this.cache.set(cacheKey, progressPoints); + return progressPoints; + } + + /** + * Get personal records for exercises + */ + async getPersonalRecords( + exerciseIds?: string[], + limit?: number + ): Promise { + const cacheKey = `records-${exerciseIds?.join('-') || 'all'}-${limit || 'all'}`; + if (this.cache.has(cacheKey)) return this.cache.get(cacheKey); + + // Get all workouts + const workouts = await this.getWorkoutsForPeriod('all'); + + // Track personal records by exercise + const recordsByExercise = new Map(); + const previousRecords = new Map(); + + // Process workouts in chronological order + workouts.sort((a, b) => a.startTime - b.startTime); + + workouts.forEach(workout => { + workout.exercises?.forEach(exercise => { + // Skip if we're filtering by exerciseIds and this one isn't included + if (exerciseIds && !exerciseIds.includes(exercise.id) && + !exerciseIds.includes(exercise.exerciseId || '')) { + return; + } + + // Find the maximum weight used in any set + const maxWeightSet = exercise.sets.reduce((max, set) => { + if (!set.weight) return max; + if (!max || set.weight > max.weight) { + return { weight: set.weight, reps: set.reps || 0 }; + } + return max; + }, null as { weight: number; reps: number } | null); + + if (!maxWeightSet) return; + + const exerciseId = exercise.exerciseId || exercise.id; + const currentRecord = recordsByExercise.get(exerciseId); + + // Check if this is a new record + if (!currentRecord || maxWeightSet.weight > currentRecord.value) { + // Save the previous record + if (currentRecord) { + previousRecords.set(exerciseId, { + value: currentRecord.value, + date: currentRecord.date + }); + } + + // Create new record + recordsByExercise.set(exerciseId, { + id: `pr-${exerciseId}-${workout.id}`, + exerciseId, + exerciseName: exercise.title, + value: maxWeightSet.weight, + unit: 'lb', + reps: maxWeightSet.reps, + date: workout.startTime, + workoutId: workout.id, + previousRecord: previousRecords.get(exerciseId) + }); + } + }); + }); + + // Convert to array and sort by date (most recent first) + let records = Array.from(recordsByExercise.values()) + .sort((a, b) => b.date - a.date); + + // Apply limit if specified + if (limit) { + records = records.slice(0, limit); + } + + this.cache.set(cacheKey, records); + return records; + } + + /** + * Helper method to get workouts for a period + */ + private async getWorkoutsForPeriod(period: 'week' | 'month' | 'year' | 'all'): Promise { + const now = new Date(); + let startDate: Date; + + switch (period) { + case 'week': + startDate = new Date(now); + startDate.setDate(now.getDate() - 7); + break; + case 'month': + startDate = new Date(now); + startDate.setMonth(now.getMonth() - 1); + break; + case 'year': + startDate = new Date(now); + startDate.setFullYear(now.getFullYear() - 1); + break; + case 'all': + default: + startDate = new Date(0); // Beginning of time + break; + } + + // Get workouts from both local and Nostr sources + let localWorkouts: Workout[] = []; + if (this.workoutService) { + localWorkouts = await this.workoutService.getWorkoutsByDateRange(startDate.getTime(), now.getTime()); + } + + // In a real implementation, we would also fetch Nostr workouts + // const nostrWorkouts = await this.nostrWorkoutService?.getWorkoutsByDateRange(startDate.getTime(), now.getTime()); + const nostrWorkouts: Workout[] = []; + + // Combine and deduplicate workouts + const allWorkouts = [...localWorkouts]; + + // Add Nostr workouts that aren't already in local workouts + for (const nostrWorkout of nostrWorkouts) { + if (!allWorkouts.some(w => w.id === nostrWorkout.id)) { + allWorkouts.push(nostrWorkout); + } + } + + return allWorkouts.sort((a, b) => b.startTime - a.startTime); + } + + /** + * Invalidate cache when new workouts are added + */ + invalidateCache(): void { + this.cache.clear(); + } +} + +// Create a singleton instance +export const analyticsService = new AnalyticsService(); diff --git a/types/feed.ts b/types/feed.ts index f2dac62..a1fb0f2 100644 --- a/types/feed.ts +++ b/types/feed.ts @@ -61,7 +61,7 @@ export type UpdateEntryFn = (id: string, updater: (entry: AnyFeedEntry) => AnyFe // Feed filter options export interface FeedFilterOptions { - feedType: 'following' | 'powr' | 'global'; + feedType: 'following' | 'powr' | 'global' | 'user-activity'; since?: number; until?: number; limit?: number; @@ -78,5 +78,5 @@ export interface FeedOptions { enabled?: boolean; filterFn?: FeedEntryFilterFn; sortFn?: (a: AnyFeedEntry, b: AnyFeedEntry) => number; - feedType?: 'following' | 'powr' | 'global'; // Added this property -} \ No newline at end of file + feedType?: 'following' | 'powr' | 'global' | 'user-activity'; // Added this property +}