feat: Implement dynamic dashboard with tabs/cards for multi-child families
Some checks failed
CI/CD Pipeline / Lint and Test (push) Has been cancelled
CI/CD Pipeline / E2E Tests (push) Has been cancelled
CI/CD Pipeline / Build Application (push) Has been cancelled

- Create DynamicChildDashboard component with tab view (1-3 children) and card view (4+)
- Integrate with Redux viewMode selector for automatic layout switching
- Update GraphQL dashboard query to include displayColor, sortOrder, nickname
- Replace static summary with dynamic multi-child dashboard
- Add child selection handling with Redux state sync
- Implement compact metrics display for card view
- Build and test successfully
This commit is contained in:
2025-10-04 21:43:05 +00:00
parent 2747630013
commit a3cbe22592
4 changed files with 376 additions and 103 deletions

View File

@@ -9,6 +9,7 @@ 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 DynamicChildDashboard from '@/components/dashboard/DynamicChildDashboard';
import {
Restaurant,
Hotel,
@@ -28,16 +29,29 @@ import { useRealTimeActivities } from '@/hooks/useWebSocket';
import { useTranslation } from '@/hooks/useTranslation';
import { analyticsApi } from '@/lib/api/analytics';
import { useTheme } from '@mui/material/styles';
import { useDispatch, useSelector } from 'react-redux';
import { fetchChildren, selectSelectedChild } from '@/store/slices/childrenSlice';
import { AppDispatch, RootState } from '@/store/store';
export default function HomePage() {
const { t } = useTranslation('dashboard');
const theme = useTheme();
const { user, isLoading: authLoading } = useAuth();
const router = useRouter();
const dispatch = useDispatch<AppDispatch>();
const selectedChild = useSelector(selectSelectedChild);
const familyId = useSelector((state: RootState) => state.auth.user?.familyId);
const [selectedChildId, setSelectedChildId] = useState<string | null>(null);
const [predictions, setPredictions] = useState<any>(null);
const [predictionsLoading, setPredictionsLoading] = useState(false);
// Fetch children on mount
useEffect(() => {
if (familyId && !authLoading) {
dispatch(fetchChildren(familyId));
}
}, [familyId, authLoading, dispatch]);
// GraphQL query for dashboard data
const { data, loading, error, refetch } = useQuery(GET_DASHBOARD, {
variables: { childId: selectedChildId },
@@ -99,6 +113,13 @@ export default function HomePage() {
}
}, [data, selectedChildId]);
// Sync selectedChildId with Redux selectedChild
useEffect(() => {
if (selectedChild?.id && selectedChild.id !== selectedChildId) {
setSelectedChildId(selectedChild.id);
}
}, [selectedChild, selectedChildId]);
// Fetch predictions when selectedChildId changes
useEffect(() => {
const fetchPredictions = async () => {
@@ -142,10 +163,36 @@ export default function HomePage() {
// Extract data from GraphQL response
const children = data?.dashboard?.children || [];
const selectedChild = data?.dashboard?.selectedChild;
const graphqlSelectedChild = data?.dashboard?.selectedChild;
const dailySummary = data?.dashboard?.todaySummary;
const isLoading = authLoading || loading;
// Build child metrics object for DynamicChildDashboard
const childMetrics = children.reduce((acc: any, child: any) => {
// For now, use the same summary for selected child, or zero for others
// TODO: Fetch per-child summaries from backend
if (child.id === selectedChildId && dailySummary) {
acc[child.id] = {
feedingCount: dailySummary.feedingCount || 0,
sleepDuration: dailySummary.totalSleepDuration || 0,
diaperCount: dailySummary.diaperCount || 0,
medicationCount: dailySummary.medicationCount || 0,
};
} else {
acc[child.id] = {
feedingCount: 0,
sleepDuration: 0,
diaperCount: 0,
medicationCount: 0,
};
}
return acc;
}, {});
const handleChildSelect = (childId: string) => {
setSelectedChildId(childId);
};
return (
<ProtectedRoute>
<AppShell>
@@ -223,9 +270,9 @@ export default function HomePage() {
))}
</Grid>
{/* Today's Summary */}
{/* Today's Summary - Dynamic Multi-Child Dashboard */}
<Typography variant="h6" component="h2" gutterBottom fontWeight="600" sx={{ mb: 2 }}>
{selectedChild ? t('summary.titleWithChild', { childName: selectedChild.name }) : t('summary.title')}
{t('summary.title')}
</Typography>
<ErrorBoundary
isolate
@@ -233,111 +280,19 @@ export default function HomePage() {
>
{isLoading ? (
<StatGridSkeleton count={3} />
) : (
) : children.length === 0 ? (
<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')}
{t('summary.noChild')}
</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>
) : (
<DynamicChildDashboard
childMetrics={childMetrics}
onChildSelect={handleChildSelect}
/>
)}
</ErrorBoundary>

View File

@@ -0,0 +1,312 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Tabs,
Tab,
Card,
CardContent,
Avatar,
Typography,
Grid,
Chip,
Paper,
} from '@mui/material';
import { useSelector, useDispatch } from 'react-redux';
import {
childrenSelectors,
selectViewMode,
selectSelectedChild,
selectChild,
Child,
} from '@/store/slices/childrenSlice';
import { RootState } from '@/store/store';
import {
Restaurant,
Hotel,
BabyChangingStation,
MedicalServices,
} from '@mui/icons-material';
interface DashboardMetrics {
feedingCount: number;
sleepDuration: number;
diaperCount: number;
medicationCount: number;
}
interface DynamicChildDashboardProps {
childMetrics: Record<string, DashboardMetrics>;
onChildSelect: (childId: string) => void;
}
export default function DynamicChildDashboard({
childMetrics,
onChildSelect,
}: DynamicChildDashboardProps) {
const dispatch = useDispatch();
const children = useSelector((state: RootState) => childrenSelectors.selectAll(state));
const viewMode = useSelector(selectViewMode);
const selectedChild = useSelector(selectSelectedChild);
const [selectedTab, setSelectedTab] = useState<string>('');
// Initialize selected tab
useEffect(() => {
if (selectedChild?.id) {
setSelectedTab(selectedChild.id);
} else if (children.length > 0) {
const firstChildId = children[0].id;
setSelectedTab(firstChildId);
dispatch(selectChild(firstChildId));
onChildSelect(firstChildId);
}
}, [selectedChild, children, dispatch, onChildSelect]);
const handleTabChange = (_event: React.SyntheticEvent, newValue: string) => {
setSelectedTab(newValue);
dispatch(selectChild(newValue));
onChildSelect(newValue);
};
const handleCardClick = (childId: string) => {
setSelectedTab(childId);
dispatch(selectChild(childId));
onChildSelect(childId);
};
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`;
}
};
const renderMetrics = (child: Child, isCompact: boolean = false) => {
const metrics = childMetrics[child.id] || {
feedingCount: 0,
sleepDuration: 0,
diaperCount: 0,
medicationCount: 0,
};
if (isCompact) {
return (
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', mt: 1 }}>
<Chip
icon={<Restaurant sx={{ fontSize: 16 }} />}
label={`${metrics.feedingCount} feeds`}
size="small"
variant="outlined"
/>
<Chip
icon={<Hotel sx={{ fontSize: 16 }} />}
label={formatSleepHours(metrics.sleepDuration)}
size="small"
variant="outlined"
/>
<Chip
icon={<BabyChangingStation sx={{ fontSize: 16 }} />}
label={`${metrics.diaperCount} diapers`}
size="small"
variant="outlined"
/>
{metrics.medicationCount > 0 && (
<Chip
icon={<MedicalServices sx={{ fontSize: 16 }} />}
label={`${metrics.medicationCount} meds`}
size="small"
variant="outlined"
/>
)}
</Box>
);
}
return (
<Grid container spacing={2} sx={{ mt: 1 }}>
<Grid item xs={6} sm={3}>
<Box textAlign="center">
<Restaurant sx={{ fontSize: 32, color: 'primary.main', mb: 1 }} />
<Typography variant="h4" fontWeight="600">
{metrics.feedingCount}
</Typography>
<Typography variant="body2" color="text.secondary">
Feedings
</Typography>
</Box>
</Grid>
<Grid item xs={6} sm={3}>
<Box textAlign="center">
<Hotel sx={{ fontSize: 32, color: 'info.main', mb: 1 }} />
<Typography variant="h4" fontWeight="600">
{formatSleepHours(metrics.sleepDuration)}
</Typography>
<Typography variant="body2" color="text.secondary">
Sleep
</Typography>
</Box>
</Grid>
<Grid item xs={6} sm={3}>
<Box textAlign="center">
<BabyChangingStation sx={{ fontSize: 32, color: 'warning.main', mb: 1 }} />
<Typography variant="h4" fontWeight="600">
{metrics.diaperCount}
</Typography>
<Typography variant="body2" color="text.secondary">
Diapers
</Typography>
</Box>
</Grid>
<Grid item xs={6} sm={3}>
<Box textAlign="center">
<MedicalServices sx={{ fontSize: 32, color: 'error.main', mb: 1 }} />
<Typography variant="h4" fontWeight="600">
{metrics.medicationCount}
</Typography>
<Typography variant="body2" color="text.secondary">
Medications
</Typography>
</Box>
</Grid>
</Grid>
);
};
// Tab view for 1-3 children
if (viewMode === 'tabs') {
return (
<Box>
<Tabs
value={selectedTab}
onChange={handleTabChange}
variant="fullWidth"
sx={{
borderBottom: 1,
borderColor: 'divider',
mb: 3,
}}
>
{children.map((child) => (
<Tab
key={child.id}
value={child.id}
label={
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Avatar
sx={{
bgcolor: child.displayColor,
width: 32,
height: 32,
fontSize: '0.875rem',
}}
>
{child.name[0]}
</Avatar>
<Box sx={{ textAlign: 'left' }}>
<Typography variant="body2" fontWeight="600">
{child.name}
</Typography>
{child.nickname && (
<Typography variant="caption" color="text.secondary">
{child.nickname}
</Typography>
)}
</Box>
</Box>
}
sx={{
textTransform: 'none',
minHeight: 64,
}}
/>
))}
</Tabs>
{children.map((child) => (
<Box
key={child.id}
role="tabpanel"
hidden={selectedTab !== child.id}
id={`child-tabpanel-${child.id}`}
aria-labelledby={`child-tab-${child.id}`}
>
{selectedTab === child.id && (
<Paper sx={{ p: 3 }}>
{renderMetrics(child, false)}
</Paper>
)}
</Box>
))}
</Box>
);
}
// Card view for 4+ children
return (
<Box>
<Typography variant="h6" gutterBottom fontWeight="600">
Select a child to view details
</Typography>
<Grid container spacing={2}>
{children.map((child) => (
<Grid item xs={12} sm={6} md={4} key={child.id}>
<Card
sx={{
cursor: 'pointer',
border: selectedTab === child.id ? 2 : 1,
borderColor: selectedTab === child.id ? child.displayColor : 'divider',
transition: 'all 0.2s',
'&:hover': {
transform: 'translateY(-4px)',
boxShadow: 4,
},
}}
onClick={() => handleCardClick(child.id)}
>
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
<Avatar
sx={{
bgcolor: child.displayColor,
width: 48,
height: 48,
}}
>
{child.name[0]}
</Avatar>
<Box sx={{ flex: 1 }}>
<Typography variant="h6" fontWeight="600">
{child.name}
</Typography>
{child.nickname && (
<Typography variant="body2" color="text.secondary">
{child.nickname}
</Typography>
)}
</Box>
</Box>
{renderMetrics(child, true)}
</CardContent>
</Card>
</Grid>
))}
</Grid>
{/* Show detailed metrics for selected child */}
{selectedTab && (
<Paper sx={{ p: 3, mt: 3 }}>
<Typography variant="h6" gutterBottom fontWeight="600">
{children.find(c => c.id === selectedTab)?.name}'s Today
</Typography>
{renderMetrics(children.find(c => c.id === selectedTab)!, false)}
</Paper>
)}
</Box>
);
}

View File

@@ -9,6 +9,9 @@ export const GET_DASHBOARD = gql`
birthDate
gender
photoUrl
displayColor
sortOrder
nickname
}
selectedChild {
id
@@ -16,6 +19,9 @@ export const GET_DASHBOARD = gql`
birthDate
gender
photoUrl
displayColor
sortOrder
nickname
}
recentActivities {
id

File diff suppressed because one or more lines are too long