**Home Page Quick Actions:** - Updated all 6 quick action cards to use dynamic theme colors - Feeding: theme.palette.primary.main - Sleep: theme.palette.secondary.main - Diaper: theme.palette.warning.main - Medical: theme.palette.error.main - Activities: theme.palette.success.main - AI Assistant: theme.palette.info.main - Cards now change color when switching between Standard/High Contrast themes **Registration Page UI Fix:** - Fixed checkbox label alignment for Terms and Privacy checkboxes - Added inline red asterisk (*) after labels for better visual indication - Used alignItems: 'flex-start' for proper multi-line label alignment - Added bottom margin (mb: 1) between checkboxes for better spacing - Asterisk now appears inline with text instead of floating separately **Files Modified:** - app/page.tsx - Theme-aware quick action colors - app/(auth)/register/page.tsx - Checkbox alignment fix 🎉 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
391 lines
16 KiB
TypeScript
391 lines
16 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useEffect, useCallback } from 'react';
|
|
import { Box, Typography, Button, Paper, CircularProgress, Grid } from '@mui/material';
|
|
import { AppShell } from '@/components/layouts/AppShell/AppShell';
|
|
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
|
|
import { EmailVerificationBanner } from '@/components/common/EmailVerificationBanner';
|
|
import { ErrorBoundary } from '@/components/common/ErrorBoundary';
|
|
import { DataErrorFallback } from '@/components/common/ErrorFallbacks';
|
|
import { NetworkStatusIndicator } from '@/components/common/NetworkStatusIndicator';
|
|
import { StatGridSkeleton } from '@/components/common/LoadingSkeletons';
|
|
import {
|
|
Restaurant,
|
|
Hotel,
|
|
BabyChangingStation,
|
|
Insights,
|
|
SmartToy,
|
|
Analytics,
|
|
MedicalServices,
|
|
} from '@mui/icons-material';
|
|
import { motion } from 'framer-motion';
|
|
import { useAuth } from '@/lib/auth/AuthContext';
|
|
import { useRouter } from 'next/navigation';
|
|
import { useQuery } from '@apollo/client/react';
|
|
import { GET_DASHBOARD } from '@/graphql/queries/dashboard';
|
|
import { format, formatDistanceToNow } from 'date-fns';
|
|
import { useRealTimeActivities } from '@/hooks/useWebSocket';
|
|
import { useTranslation } from '@/hooks/useTranslation';
|
|
import { analyticsApi } from '@/lib/api/analytics';
|
|
import { useTheme } from '@mui/material/styles';
|
|
|
|
export default function HomePage() {
|
|
const { t } = useTranslation('dashboard');
|
|
const theme = useTheme();
|
|
const { user, isLoading: authLoading } = useAuth();
|
|
const router = useRouter();
|
|
const [selectedChildId, setSelectedChildId] = useState<string | null>(null);
|
|
const [predictions, setPredictions] = useState<any>(null);
|
|
const [predictionsLoading, setPredictionsLoading] = useState(false);
|
|
|
|
// GraphQL query for dashboard data
|
|
const { data, loading, error, refetch } = useQuery(GET_DASHBOARD, {
|
|
variables: { childId: selectedChildId },
|
|
skip: authLoading || !user,
|
|
fetchPolicy: 'cache-and-network',
|
|
});
|
|
|
|
// Log GraphQL errors and data for debugging
|
|
useEffect(() => {
|
|
console.log('[HomePage] === GraphQL Debug Info ===');
|
|
console.log('[HomePage] Raw data:', data);
|
|
console.log('[HomePage] Data type:', typeof data);
|
|
console.log('[HomePage] Data keys:', data ? Object.keys(data) : 'null');
|
|
|
|
if (error) {
|
|
console.error('[HomePage] GraphQL error:', error);
|
|
console.error('[HomePage] GraphQL error details:', {
|
|
message: error.message,
|
|
networkError: error.networkError,
|
|
graphQLErrors: error.graphQLErrors,
|
|
});
|
|
}
|
|
if (data) {
|
|
console.log('[HomePage] GraphQL data:', data);
|
|
console.log('[HomePage] Dashboard data:', data.dashboard);
|
|
}
|
|
console.log('[HomePage] Query state:', {
|
|
loading,
|
|
error: !!error,
|
|
hasData: !!data,
|
|
user: !!user,
|
|
skip: authLoading || !user,
|
|
childrenCount: data?.dashboard?.children?.length || 0,
|
|
selectedChildId,
|
|
});
|
|
console.log('[HomePage] LocalStorage token:', typeof window !== 'undefined' ? localStorage.getItem('accessToken')?.substring(0, 20) : 'SSR');
|
|
}, [error, data, loading, user, authLoading, selectedChildId]);
|
|
|
|
// Real-time activity handler to refetch dashboard data
|
|
const refreshDashboard = useCallback(async () => {
|
|
if (refetch) {
|
|
console.log('[HomePage] Refreshing dashboard data...');
|
|
await refetch();
|
|
}
|
|
}, [refetch]);
|
|
|
|
// Subscribe to real-time activity updates
|
|
useRealTimeActivities(
|
|
refreshDashboard, // On activity created
|
|
refreshDashboard, // On activity updated
|
|
refreshDashboard // On activity deleted
|
|
);
|
|
|
|
// Set the first child as selected when data loads
|
|
useEffect(() => {
|
|
if (data?.dashboard?.children && data.dashboard.children.length > 0 && !selectedChildId) {
|
|
const firstChild = data.dashboard.children[0];
|
|
setSelectedChildId(firstChild.id);
|
|
}
|
|
}, [data, selectedChildId]);
|
|
|
|
// Fetch predictions when selectedChildId changes
|
|
useEffect(() => {
|
|
const fetchPredictions = async () => {
|
|
if (!selectedChildId) return;
|
|
|
|
setPredictionsLoading(true);
|
|
try {
|
|
const predictionData = await analyticsApi.getPredictions(selectedChildId);
|
|
setPredictions(predictionData);
|
|
} catch (err) {
|
|
console.error('Failed to fetch predictions:', err);
|
|
setPredictions(null);
|
|
} finally {
|
|
setPredictionsLoading(false);
|
|
}
|
|
};
|
|
|
|
fetchPredictions();
|
|
}, [selectedChildId]);
|
|
|
|
const quickActions = [
|
|
{ icon: <Restaurant />, label: t('quickActions.feeding'), color: theme.palette.primary.main, path: '/track/feeding' },
|
|
{ icon: <Hotel />, label: t('quickActions.sleep'), color: theme.palette.secondary.main, path: '/track/sleep' },
|
|
{ icon: <BabyChangingStation />, label: t('quickActions.diaper'), color: theme.palette.warning.main, path: '/track/diaper' },
|
|
{ icon: <MedicalServices />, label: t('quickActions.medical'), color: theme.palette.error.main, path: '/track/medicine' },
|
|
{ icon: <Insights />, label: t('quickActions.activities'), color: theme.palette.success.main, path: '/activities' },
|
|
{ icon: <SmartToy />, label: t('quickActions.aiAssistant'), color: theme.palette.info.main, path: '/ai-assistant' },
|
|
];
|
|
|
|
const formatSleepHours = (minutes: number) => {
|
|
const hours = Math.floor(minutes / 60);
|
|
const mins = minutes % 60;
|
|
if (hours > 0 && mins > 0) {
|
|
return `${hours}h ${mins}m`;
|
|
} else if (hours > 0) {
|
|
return `${hours}h`;
|
|
} else {
|
|
return `${mins}m`;
|
|
}
|
|
};
|
|
|
|
// Extract data from GraphQL response
|
|
const children = data?.dashboard?.children || [];
|
|
const selectedChild = data?.dashboard?.selectedChild;
|
|
const dailySummary = data?.dashboard?.todaySummary;
|
|
const isLoading = authLoading || loading;
|
|
|
|
return (
|
|
<ProtectedRoute>
|
|
<AppShell>
|
|
<NetworkStatusIndicator />
|
|
<Box>
|
|
<EmailVerificationBanner />
|
|
|
|
<motion.div
|
|
initial={{ opacity: 0, y: 20 }}
|
|
animate={{ opacity: 1, y: 0 }}
|
|
transition={{ duration: 0.5 }}
|
|
>
|
|
<Typography variant="h4" component="h1" gutterBottom fontWeight="600" sx={{ mb: 1 }}>
|
|
{user?.name ? t('welcomeBackWithName', { name: user.name }) : t('welcomeBack')} 👋
|
|
</Typography>
|
|
<Typography variant="body1" sx={{ mb: 4, color: 'text.primary' }}>
|
|
{t('subtitle')}
|
|
</Typography>
|
|
|
|
{/* Quick Actions */}
|
|
<Typography variant="h6" component="h2" gutterBottom fontWeight="600" sx={{ mb: 2 }}>
|
|
{t('quickActions.title')}
|
|
</Typography>
|
|
<Grid container spacing={2} sx={{ mb: 4 }}>
|
|
{quickActions.map((action, index) => (
|
|
<Grid size={{ xs: 6, sm: 4, md: 2 }} key={action.label}>
|
|
<motion.div
|
|
initial={{ opacity: 0, scale: 0.9 }}
|
|
animate={{ opacity: 1, scale: 1 }}
|
|
transition={{ duration: 0.3, delay: index * 0.1 }}
|
|
style={{ height: '100%' }}
|
|
>
|
|
<Paper
|
|
component="button"
|
|
onClick={() => router.push(action.path)}
|
|
onKeyDown={(e) => {
|
|
if (e.key === 'Enter' || e.key === ' ') {
|
|
e.preventDefault();
|
|
router.push(action.path);
|
|
}
|
|
}}
|
|
aria-label={t('quickActions.navigateTo', { action: action.label })}
|
|
sx={{
|
|
p: 3,
|
|
height: '140px', // Fixed height for consistency
|
|
minHeight: '140px', // Ensure minimum height
|
|
width: '100%', // Full width of grid container
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
textAlign: 'center',
|
|
cursor: 'pointer',
|
|
bgcolor: action.color,
|
|
color: 'white',
|
|
border: 'none',
|
|
transition: 'transform 0.2s',
|
|
'&:hover': {
|
|
transform: 'scale(1.05)',
|
|
},
|
|
'&:focus-visible': {
|
|
outline: '3px solid white',
|
|
outlineOffset: '-3px',
|
|
transform: 'scale(1.05)',
|
|
},
|
|
}}
|
|
>
|
|
<Box sx={{ fontSize: 48, mb: 1 }} aria-hidden="true">{action.icon}</Box>
|
|
<Typography variant="body1" fontWeight="600">
|
|
{action.label}
|
|
</Typography>
|
|
</Paper>
|
|
</motion.div>
|
|
</Grid>
|
|
))}
|
|
</Grid>
|
|
|
|
{/* Today's Summary */}
|
|
<Typography variant="h6" component="h2" gutterBottom fontWeight="600" sx={{ mb: 2 }}>
|
|
{selectedChild ? t('summary.titleWithChild', { childName: selectedChild.name }) : t('summary.title')}
|
|
</Typography>
|
|
<ErrorBoundary
|
|
isolate
|
|
fallback={<DataErrorFallback error={new Error('Failed to load summary')} />}
|
|
>
|
|
{isLoading ? (
|
|
<StatGridSkeleton count={3} />
|
|
) : (
|
|
<Paper sx={{ p: 3 }}>
|
|
{!dailySummary ? (
|
|
<Box sx={{ textAlign: 'center', py: 4 }}>
|
|
<Typography variant="body2" sx={{ color: 'rgba(0, 0, 0, 0.7)' }}>
|
|
{children.length === 0
|
|
? t('summary.noChild')
|
|
: t('summary.noActivities')}
|
|
</Typography>
|
|
</Box>
|
|
) : (
|
|
<Grid container spacing={3}>
|
|
<Grid size={{ xs: 6, sm: 3 }}>
|
|
<Box
|
|
textAlign="center"
|
|
sx={{
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
height: '120px', // Fixed height for consistency
|
|
minHeight: '120px',
|
|
width: '100%'
|
|
}}
|
|
>
|
|
<Restaurant sx={{ fontSize: 32, color: 'primary.main', mb: 1 }} aria-hidden="true" />
|
|
<Typography variant="h3" component="div" fontWeight="600" aria-label={`${dailySummary.feedingCount || 0} feedings today`}>
|
|
{dailySummary.feedingCount || 0}
|
|
</Typography>
|
|
<Typography variant="body2" sx={{ color: 'rgba(0, 0, 0, 0.7)' }}>
|
|
{t('summary.feedings')}
|
|
</Typography>
|
|
</Box>
|
|
</Grid>
|
|
<Grid size={{ xs: 6, sm: 3 }}>
|
|
<Box
|
|
textAlign="center"
|
|
sx={{
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
height: '120px', // Fixed height for consistency
|
|
minHeight: '120px',
|
|
width: '100%'
|
|
}}
|
|
>
|
|
<Hotel sx={{ fontSize: 32, color: 'info.main', mb: 1 }} aria-hidden="true" />
|
|
<Typography variant="h3" component="div" fontWeight="600" aria-label={`${dailySummary.totalSleepDuration ? formatSleepHours(dailySummary.totalSleepDuration) : '0 minutes'} sleep today`}>
|
|
{dailySummary.totalSleepDuration
|
|
? formatSleepHours(dailySummary.totalSleepDuration)
|
|
: '0m'}
|
|
</Typography>
|
|
<Typography variant="body2" sx={{ color: 'rgba(0, 0, 0, 0.7)' }}>
|
|
{t('summary.sleep')}
|
|
</Typography>
|
|
</Box>
|
|
</Grid>
|
|
<Grid size={{ xs: 6, sm: 3 }}>
|
|
<Box
|
|
textAlign="center"
|
|
sx={{
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
height: '120px', // Fixed height for consistency
|
|
minHeight: '120px',
|
|
width: '100%'
|
|
}}
|
|
>
|
|
<BabyChangingStation sx={{ fontSize: 32, color: 'warning.main', mb: 1 }} aria-hidden="true" />
|
|
<Typography variant="h3" component="div" fontWeight="600" aria-label={`${dailySummary.diaperCount || 0} diaper changes today`}>
|
|
{dailySummary.diaperCount || 0}
|
|
</Typography>
|
|
<Typography variant="body2" sx={{ color: 'rgba(0, 0, 0, 0.7)' }}>
|
|
{t('summary.diapers')}
|
|
</Typography>
|
|
</Box>
|
|
</Grid>
|
|
<Grid size={{ xs: 6, sm: 3 }}>
|
|
<Box
|
|
textAlign="center"
|
|
sx={{
|
|
display: 'flex',
|
|
flexDirection: 'column',
|
|
alignItems: 'center',
|
|
justifyContent: 'center',
|
|
height: '120px', // Fixed height for consistency
|
|
minHeight: '120px',
|
|
width: '100%'
|
|
}}
|
|
>
|
|
<MedicalServices sx={{ fontSize: 32, color: 'error.main', mb: 1 }} aria-hidden="true" />
|
|
<Typography variant="h3" component="div" fontWeight="600" aria-label={`${dailySummary.medicationCount || 0} medications today`}>
|
|
{dailySummary.medicationCount || 0}
|
|
</Typography>
|
|
<Typography variant="body2" sx={{ color: 'rgba(0, 0, 0, 0.7)' }}>
|
|
{t('summary.medications')}
|
|
</Typography>
|
|
</Box>
|
|
</Grid>
|
|
</Grid>
|
|
)}
|
|
</Paper>
|
|
)}
|
|
</ErrorBoundary>
|
|
|
|
{/* Next Predicted Activity */}
|
|
<Box sx={{ mt: 4 }}>
|
|
<Paper sx={{ p: 3, bgcolor: 'primary.light' }}>
|
|
<Typography variant="body2" sx={{ color: 'rgba(0, 0, 0, 0.7)' }} gutterBottom>
|
|
{t('predictions.title')}
|
|
</Typography>
|
|
{predictionsLoading ? (
|
|
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
|
|
<CircularProgress size={20} />
|
|
<Typography variant="body2">Loading predictions...</Typography>
|
|
</Box>
|
|
) : predictions?.sleep?.nextNapTime || predictions?.feeding?.nextFeedingTime ? (
|
|
<>
|
|
{predictions.sleep?.nextNapTime && (
|
|
<>
|
|
<Typography variant="h6" fontWeight="600" gutterBottom>
|
|
Nap time {formatDistanceToNow(new Date(predictions.sleep.nextNapTime), { addSuffix: true })}
|
|
</Typography>
|
|
<Typography variant="body2" sx={{ color: 'rgba(0, 0, 0, 0.7)' }}>
|
|
{predictions.sleep.reasoning || t('predictions.basedOnPatterns')}
|
|
</Typography>
|
|
</>
|
|
)}
|
|
{!predictions.sleep?.nextNapTime && predictions.feeding?.nextFeedingTime && (
|
|
<>
|
|
<Typography variant="h6" fontWeight="600" gutterBottom>
|
|
Feeding time {formatDistanceToNow(new Date(predictions.feeding.nextFeedingTime), { addSuffix: true })}
|
|
</Typography>
|
|
<Typography variant="body2" sx={{ color: 'rgba(0, 0, 0, 0.7)' }}>
|
|
{predictions.feeding.reasoning || t('predictions.basedOnPatterns')}
|
|
</Typography>
|
|
</>
|
|
)}
|
|
</>
|
|
) : (
|
|
<Typography variant="body1" sx={{ color: 'rgba(0, 0, 0, 0.7)' }}>
|
|
{t('predictions.notEnoughData')}
|
|
</Typography>
|
|
)}
|
|
</Paper>
|
|
</Box>
|
|
</motion.div>
|
|
</Box>
|
|
</AppShell>
|
|
</ProtectedRoute>
|
|
);
|
|
}
|