Dashboard: per-widget add/delete, free placement, VO2/HRV stats, body battery graph, more widgets
Build and push images / validate (push) Successful in 3s
Build and push images / build-frontend (push) Successful in 9s
Build and push images / build-backend (push) Successful in 6s
Build and push images / build-worker (push) Successful in 5s

- VO2 max and HRV status now available as top-bar stat widgets
- Edit mode can add (palette) and remove (x) individual widgets
- Body Battery widget shows todays intraday graph (fixed collapsing height)
- compactType disabled so widgets stay put and align along top edges (no jumping up)
- New optional widgets: cycling, stress, active calories, floors, VO2 trend, sleep stages, weight trend

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 23:20:25 +01:00
parent 8ed47d6042
commit 491660fc6b
+265 -209
View File
@@ -1,5 +1,5 @@
import { Link, useNavigate } from 'react-router-dom'
import { useQuery, useMutation } from '@tanstack/react-query'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useMemo, useState, useEffect, useRef } from 'react'
import {
BarChart, Bar, AreaChart, Area, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
@@ -20,6 +20,7 @@ import { BB_INFERRED_COLOR, BB_INFERRED_LABEL, bbLevelColor, inferBBType } from
const Grid = WidthProvider(GridLayout)
const MEDALS = { 1: '🥇', 2: '🥈', 3: '🥉' }
const tooltipStyle = { background: '#111827', border: '1px solid #374151', borderRadius: 8, fontSize: 12, color: '#fff' }
const HRV_PALETTE = {
balanced: 'text-green-400 bg-green-400/10 border-green-400/30',
@@ -28,31 +29,59 @@ const HRV_PALETTE = {
poor: 'text-red-400 bg-red-400/10 border-red-400/30',
}
// Widget registry + default grid positions (12-col grid). minW/minH keep widgets usable.
const WIDGETS = [
{ id: 'stats', default: { x: 0, y: 0, w: 12, h: 1 }, minW: 4, minH: 1 },
{ id: 'weekly', default: { x: 0, y: 1, w: 6, h: 3 }, minW: 4, minH: 2 },
{ id: 'bodyBattery', default: { x: 6, y: 1, w: 3, h: 3 }, minW: 3, minH: 2 },
{ id: 'vo2max', default: { x: 9, y: 1, w: 3, h: 3 }, minW: 2, minH: 2 },
{ id: 'sleep', default: { x: 0, y: 4, w: 5, h: 3 }, minW: 3, minH: 2 },
{ id: 'hrv', default: { x: 5, y: 4, w: 3, h: 2 }, minW: 2, minH: 2 },
{ id: 'featured', default: { x: 0, y: 7, w: 8, h: 5 }, minW: 4, minH: 3 },
{ id: 'recent', default: { x: 8, y: 7, w: 4, h: 5 }, minW: 3, minH: 3 },
{ id: 'prs', default: { x: 0, y: 12, w: 12, h: 2 }, minW: 4, minH: 2 },
]
// Merge a saved layout with the registry: keep saved positions for known widgets,
// fall back to defaults for any widget the saved layout doesn't include (e.g. new ones).
function buildLayout(saved) {
const byId = Object.fromEntries((saved || []).map(l => [l.i, l]))
return WIDGETS.map(w => {
const s = byId[w.id]
const pos = s ? { x: s.x, y: s.y, w: s.w, h: s.h } : w.default
return { i: w.id, ...pos, minW: w.minW, minH: w.minH }
})
// Compact single-stat widgets. val(health, ytdStats) → display string.
const STAT_DEFS = {
stat_steps: { label: 'Steps today', accent: 'green', sub: 'goal 10,000', val: h => h.steps != null ? h.steps.toLocaleString() : '--' },
stat_resting_hr: { label: 'Resting HR', accent: 'red', val: h => formatHeartRate(h.resting_hr) },
stat_sleep: { label: 'Sleep', accent: 'default', val: h => formatSleep(h.sleep_duration_s) },
stat_vo2max: { label: 'VO₂ max', accent: 'blue', val: h => h.vo2max != null ? h.vo2max.toFixed(1) : '--', sub: h => h.fitness_age != null ? `fitness age ${h.fitness_age}` : undefined },
stat_hrv: { label: 'HRV status', accent: 'purple', val: h => h.hrv_nightly_avg != null ? `${Math.round(h.hrv_nightly_avg)} ms` : '--', sub: h => h.hrv_status || undefined },
stat_running: { label: 'Running this year', accent: 'blue', val: (h, y) => y ? `${y.running_km.toFixed(0)} km` : '--' },
stat_cycling: { label: 'Cycling this year', accent: 'orange', val: (h, y) => y ? `${y.cycling_km.toFixed(0)} km` : '--' },
stat_stress: { label: 'Stress', accent: 'purple', val: h => h.avg_stress != null ? Math.round(h.avg_stress) : '--' },
stat_calories: { label: 'Active calories', accent: 'orange', val: h => h.active_calories != null ? Math.round(h.active_calories).toLocaleString() : '--' },
stat_floors: { label: 'Floors climbed', accent: 'green', val: h => h.floors_climbed != null ? h.floors_climbed : '--' },
}
// ── Widgets ──────────────────────────────────────────────────────────────────
// Full widget registry: size defaults + palette label. Stats inherit from STAT_DEFS.
const WIDGETS = {
...Object.fromEntries(Object.entries(STAT_DEFS).map(([id, d]) => [id, { label: d.label, w: 2, h: 1, minW: 2, minH: 1 }])),
weekly: { label: 'Weekly distance', w: 6, h: 3, minW: 4, minH: 2 },
bodyBattery: { label: 'Body Battery', w: 4, h: 3, minW: 3, minH: 2 },
vo2maxTrend: { label: 'VO₂ max trend', w: 3, h: 3, minW: 2, minH: 2 },
sleepDetail: { label: 'Sleep stages', w: 5, h: 3, minW: 3, minH: 2 },
weight: { label: 'Weight trend', w: 3, h: 3, minW: 2, minH: 2 },
featured: { label: 'Latest activity', w: 8, h: 5, minW: 4, minH: 3 },
recent: { label: 'Recent activities', w: 4, h: 5, minW: 3, minH: 3 },
prs: { label: 'Running PRs', w: 12, h: 2, minW: 4, minH: 2 },
}
// Default arrangement (used for new users and to migrate pre-redesign layouts).
const DEFAULT_LAYOUT = [
{ i: 'stat_steps', x: 0, y: 0, w: 2, h: 1 },
{ i: 'stat_resting_hr', x: 2, y: 0, w: 2, h: 1 },
{ i: 'stat_sleep', x: 4, y: 0, w: 2, h: 1 },
{ i: 'stat_vo2max', x: 6, y: 0, w: 2, h: 1 },
{ i: 'stat_hrv', x: 8, y: 0, w: 2, h: 1 },
{ i: 'stat_running', x: 10, y: 0, w: 2, h: 1 },
{ i: 'weekly', x: 0, y: 1, w: 6, h: 3 },
{ i: 'bodyBattery', x: 6, y: 1, w: 4, h: 3 },
{ i: 'featured', x: 0, y: 4, w: 8, h: 5 },
{ i: 'recent', x: 8, y: 4, w: 4, h: 5 },
{ i: 'prs', x: 0, y: 9, w: 12, h: 2 },
]
const attachMins = (lay) =>
lay.filter(l => WIDGETS[l.i]).map(l => ({ ...l, minW: WIDGETS[l.i].minW, minH: WIDGETS[l.i].minH }))
function buildLayout(saved) {
const known = (saved || []).filter(l => WIDGETS[l.i])
// Migrate old layouts (no stat_* widgets) or empty/missing to the new default.
const hasStats = known.some(l => l.i.startsWith('stat_'))
return attachMins(known.length && hasStats ? known : DEFAULT_LAYOUT)
}
// ── Reusable card shell ──────────────────────────────────────────────────────
function Card({ title, viewHref, children, className = '' }) {
return (
@@ -77,25 +106,15 @@ function Stat({ label, value }) {
)
}
function StatsRow({ health, ytdStats }) {
return (
<div className="grid grid-cols-2 sm:grid-cols-5 gap-3 h-full">
<StatCard label="Steps today" value={health.steps != null ? health.steps.toLocaleString() : '--'} accent="green" sub="goal 10,000" />
<StatCard label="Running this year" value={ytdStats ? `${ytdStats.running_km.toFixed(0)} km` : '--'} accent="blue" />
<StatCard label="Cycling this year" value={ytdStats ? `${ytdStats.cycling_km.toFixed(0)} km` : '--'} accent="orange" />
<StatCard label="Resting HR" value={formatHeartRate(health.resting_hr)} accent="red" />
<StatCard label="Sleep" value={formatSleep(health.sleep_duration_s)} />
</div>
)
}
// ── Chart widgets ────────────────────────────────────────────────────────────
function MiniBodyBattery({ bb, hires, sleepStart, sleepEnd }) {
const raw = (hires?.length ? hires : bb?.values || []).map(([ts, level]) => ({ ts, level }))
function BodyBatteryToday({ bb, hires, sleepStart, sleepEnd }) {
const raw = (hires?.length ? hires : bb?.values || []).map(([ts, level]) => ({ t: ts, level }))
const sleepStartMs = sleepStart ? new Date(sleepStart).getTime() : null
const sleepEndMs = sleepEnd ? new Date(sleepEnd).getTime() : null
const data = raw.map((d, i) => ({
...d,
type: inferBBType(d.ts, d.level, i > 0 ? raw[i - 1].level : null, sleepStartMs, sleepEndMs),
type: inferBBType(d.t, d.level, i > 0 ? raw[i - 1].level : null, sleepStartMs, sleepEndMs),
}))
const charged = bb?.charged, drained = bb?.drained, end_level = bb?.end_level
const peak = data.length ? Math.max(...data.map(d => d.level)) : end_level
@@ -104,84 +123,114 @@ function MiniBodyBattery({ bb, hires, sleepStart, sleepEnd }) {
return (
<Card title="Body Battery" viewHref="/health">
<div className="flex items-baseline gap-3 flex-wrap">
{peak != null && (
<span className="text-3xl font-bold" style={{ color: bbLevelColor(peak) }}>{Math.round(peak)}</span>
<div className="flex flex-col h-full">
<div className="flex items-baseline gap-3 flex-wrap">
{peak != null && <span className="text-3xl font-bold" style={{ color: bbLevelColor(peak) }}>{Math.round(peak)}</span>}
{charged != null && <span className="text-sm font-semibold text-green-400">+{charged}</span>}
{drained != null && <span className="text-sm font-semibold text-orange-400">-{drained}</span>}
{end_level != null && <span className="text-xs text-gray-500">now {Math.round(end_level)}</span>}
</div>
{hasGraph ? (
<>
<div className="flex-1 min-h-0 mt-2">
<ResponsiveContainer width="100%" height="100%" minHeight={80}>
<BarChart data={data} margin={{ top: 2, right: 4, bottom: 0, left: 0 }} barCategoryGap={0}>
<XAxis dataKey="t" tick={{ fontSize: 9, fill: '#6b7280' }} axisLine={false} tickLine={false}
tickFormatter={ts => format(new Date(ts), 'HH:mm')}
interval={Math.max(1, Math.floor(data.length / 6))} />
<YAxis domain={[0, 100]} tick={{ fontSize: 9, fill: '#6b7280' }} axisLine={false} tickLine={false}
width={26} ticks={[0, 50, 100]} />
<Tooltip contentStyle={tooltipStyle} itemStyle={{ color: '#fff' }} labelStyle={{ color: '#fff' }}
labelFormatter={ts => format(new Date(ts), 'HH:mm')} formatter={v => [`${Math.round(v)}%`, 'Battery']} />
<Bar dataKey="level" isAnimationActive={false} radius={0}>
{data.map((d, i) => <Cell key={i} fill={BB_INFERRED_COLOR[d.type]} />)}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
<div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
{presentTypes.map(type => (
<div key={type} className="flex items-center gap-1">
<div className="w-2 h-2 rounded-sm" style={{ backgroundColor: BB_INFERRED_COLOR[type] }} />
<span className="text-xs text-gray-500">{BB_INFERRED_LABEL[type]}</span>
</div>
))}
</div>
</>
) : (
<p className="text-xs text-gray-600 mt-3">No body battery data today</p>
)}
{charged != null && <span className="text-sm font-semibold text-green-400">+{charged}</span>}
{drained != null && <span className="text-sm font-semibold text-orange-400">-{drained}</span>}
{end_level != null && <span className="text-xs text-gray-500">now {Math.round(end_level)}</span>}
</div>
{hasGraph ? (
<>
<div className="mt-3 flex-1 min-h-0">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 2, right: 0, bottom: 0, left: 0 }} barCategoryGap={0}>
<YAxis domain={[0, 100]} hide />
<Tooltip
contentStyle={{ background: '#111827', border: '1px solid #374151', borderRadius: 6, fontSize: 11, color: '#fff' }}
itemStyle={{ color: '#fff' }} labelStyle={{ color: '#fff' }}
labelFormatter={ts => format(new Date(ts), 'HH:mm')}
formatter={v => [`${Math.round(v)}%`, 'Battery']}
/>
<Bar dataKey="level" isAnimationActive={false} radius={0}>
{data.map((d, i) => <Cell key={i} fill={BB_INFERRED_COLOR[d.type]} />)}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
<div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
{presentTypes.map(type => (
<div key={type} className="flex items-center gap-1">
<div className="w-2 h-2 rounded-sm" style={{ backgroundColor: BB_INFERRED_COLOR[type] }} />
<span className="text-xs text-gray-500">{BB_INFERRED_LABEL[type]}</span>
</div>
))}
</div>
</>
) : (
<p className="text-xs text-gray-600 mt-3">No body battery data today</p>
)}
</Card>
)
}
function Vo2MaxWidget({ health, recentHealth }) {
function Sparkline({ data, dataKey, color, gradId, fmt }) {
return (
<ResponsiveContainer width="100%" height="100%" minHeight={60}>
<AreaChart data={data} margin={{ top: 4, right: 2, bottom: 0, left: 0 }}>
<defs>
<linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.3} />
<stop offset="95%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
<YAxis domain={['dataMin - 1', 'dataMax + 1']} hide />
<Tooltip contentStyle={tooltipStyle} labelFormatter={d => format(new Date(d), 'MMM d')}
formatter={v => [fmt ? fmt(v) : v, '']} />
<Area type="monotone" dataKey={dataKey} stroke={color} strokeWidth={2} fill={`url(#${gradId})`}
dot={false} connectNulls isAnimationActive={false} />
</AreaChart>
</ResponsiveContainer>
)
}
function Vo2MaxTrend({ health, recentHealth }) {
const series = useMemo(
() => [...(recentHealth || [])]
.filter(d => d.vo2max != null)
() => [...(recentHealth || [])].filter(d => d.vo2max != null)
.sort((a, b) => new Date(a.date) - new Date(b.date))
.map(d => ({ date: d.date, v: d.vo2max })),
[recentHealth],
)
return (
<Card title="VO₂ Max" viewHref="/health">
<div className="flex items-baseline gap-2">
<span className="text-3xl font-bold text-blue-400">{health.vo2max != null ? health.vo2max.toFixed(1) : '--'}</span>
<span className="text-xs text-gray-500">ml/kg/min</span>
</div>
{health.fitness_age != null && (
<p className="text-xs text-gray-500 mt-0.5">Fitness age {health.fitness_age}</p>
)}
{series.length >= 2 && (
<div className="flex-1 min-h-0 mt-2">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={series} margin={{ top: 4, right: 2, bottom: 0, left: 0 }}>
<defs>
<linearGradient id="grad-dash-vo2" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
</linearGradient>
</defs>
<YAxis domain={['dataMin - 1', 'dataMax + 1']} hide />
<Tooltip contentStyle={{ background: '#111827', border: '1px solid #374151', borderRadius: 6, fontSize: 11 }}
labelFormatter={d => format(new Date(d), 'MMM d')} formatter={v => [v.toFixed(1), 'VO₂ max']} />
<Area type="monotone" dataKey="v" stroke="#3b82f6" strokeWidth={2} fill="url(#grad-dash-vo2)"
dot={false} connectNulls isAnimationActive={false} />
</AreaChart>
</ResponsiveContainer>
<div className="flex flex-col h-full">
<div className="flex items-baseline gap-2">
<span className="text-3xl font-bold text-blue-400">{health.vo2max != null ? health.vo2max.toFixed(1) : '--'}</span>
<span className="text-xs text-gray-500">ml/kg/min</span>
</div>
)}
{health.fitness_age != null && <p className="text-xs text-gray-500 mt-0.5">Fitness age {health.fitness_age}</p>}
<div className="flex-1 min-h-0 mt-2">
{series.length >= 2
? <Sparkline data={series} dataKey="v" color="#3b82f6" gradId="grad-dash-vo2" fmt={v => v.toFixed(1)} />
: <p className="text-xs text-gray-600">Not enough history</p>}
</div>
</div>
</Card>
)
}
function WeightMini({ recentHealth }) {
const series = useMemo(
() => [...(recentHealth || [])].filter(d => d.weight_kg != null)
.sort((a, b) => new Date(a.date) - new Date(b.date))
.map(d => ({ date: d.date, w: +d.weight_kg.toFixed(2) })),
[recentHealth],
)
const latest = series.length ? series[series.length - 1].w : null
return (
<Card title="Weight" viewHref="/health">
<div className="flex flex-col h-full">
<div className="flex items-baseline gap-2">
<span className="text-3xl font-bold text-emerald-300">{latest != null ? latest.toFixed(1) : '--'}</span>
<span className="text-xs text-gray-500">kg</span>
</div>
<div className="flex-1 min-h-0 mt-2">
{series.length >= 2
? <Sparkline data={series} dataKey="w" color="#34d399" gradId="grad-dash-weight" fmt={v => `${v.toFixed(1)} kg`} />
: <p className="text-xs text-gray-600">Not enough history</p>}
</div>
</div>
</Card>
)
}
@@ -193,7 +242,7 @@ const SLEEP_STAGES = [
{ key: 'sleep_awake_s', label: 'Awake', color: '#6b7280' },
]
function SleepMini({ health }) {
function SleepDetail({ health }) {
const total = SLEEP_STAGES.reduce((s, st) => s + (health[st.key] || 0), 0)
return (
<Card title="Sleep" viewHref="/health">
@@ -229,60 +278,39 @@ function SleepMini({ health }) {
)
}
function HrvWidget({ health }) {
const status = health.hrv_status
const cls = status ? (HRV_PALETTE[status.toLowerCase()] || 'text-gray-400 bg-gray-400/10 border-gray-400/30') : null
return (
<Card title="HRV status" viewHref="/health">
<div className="flex flex-col items-start justify-center h-full gap-2">
<div className="flex items-baseline gap-2">
<span className="text-3xl font-bold text-violet-300">{health.hrv_nightly_avg != null ? Math.round(health.hrv_nightly_avg) : '--'}</span>
<span className="text-xs text-gray-500">ms</span>
</div>
{status
? <span className={`text-xs px-2 py-0.5 rounded-full border ${cls}`}>{status}</span>
: <span className="text-xs text-gray-600">No HRV status</span>}
</div>
</Card>
)
}
function WeeklyChart({ activities }) {
const navigate = useNavigate()
if (!activities?.length) return (
<div className="flex items-center justify-center h-full text-gray-600 text-sm">No activities yet</div>
)
const now = new Date()
const weeks = eachWeekOfInterval({ start: subWeeks(startOfWeek(now), 7), end: startOfWeek(now) })
const data = weeks.map(weekStart => {
const weekEnd = addDays(weekStart, 7)
const km = activities
.filter(a => { const t = new Date(a.start_time); return t >= weekStart && t < weekEnd })
.reduce((s, a) => s + (a.distance_m || 0) / 1000, 0)
return {
week: format(weekStart, 'MMM d'),
km: parseFloat(km.toFixed(2)),
weekStartISO: format(weekStart, 'yyyy-MM-dd'),
weekEndISO: format(weekEnd, 'yyyy-MM-dd'),
}
})
const handleBarClick = (entry) => {
const p = entry?.activePayload?.[0]?.payload
if (p) navigate(`/activities?from=${p.weekStartISO}&to=${p.weekEndISO}`)
}
const data = useMemo(() => {
if (!activities?.length) return []
const now = new Date()
const weeks = eachWeekOfInterval({ start: subWeeks(startOfWeek(now), 7), end: startOfWeek(now) })
return weeks.map(weekStart => {
const weekEnd = addDays(weekStart, 7)
const km = activities
.filter(a => { const t = new Date(a.start_time); return t >= weekStart && t < weekEnd })
.reduce((s, a) => s + (a.distance_m || 0) / 1000, 0)
return { week: format(weekStart, 'MMM d'), km: parseFloat(km.toFixed(2)), weekStartISO: format(weekStart, 'yyyy-MM-dd'), weekEndISO: format(weekEnd, 'yyyy-MM-dd') }
})
}, [activities])
return (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 4, right: 4, bottom: 4, left: 0 }} barSize={20}
onClick={handleBarClick} style={{ cursor: 'pointer' }}>
<CartesianGrid strokeDasharray="3 3" stroke="#1f2937" vertical={false} />
<XAxis dataKey="week" tick={{ fontSize: 10, fill: '#6b7280' }} axisLine={false} tickLine={false} />
<YAxis tick={{ fontSize: 10, fill: '#6b7280' }} axisLine={false} tickLine={false} width={28}
tickFormatter={v => `${v.toFixed(0)}`} />
<Tooltip contentStyle={{ background: '#111827', border: '1px solid #374151', borderRadius: 8, fontSize: 12 }}
formatter={(v) => [`${v.toFixed(1)} km`, 'Distance']} cursor={{ fill: 'rgba(59,130,246,0.1)' }} />
<Bar dataKey="km" fill="#3b82f6" radius={[3, 3, 0, 0]} isAnimationActive={false} />
</BarChart>
</ResponsiveContainer>
<Card title="Weekly distance (km)">
{data.length ? (
<ResponsiveContainer width="100%" height="100%" minHeight={100}>
<BarChart data={data} margin={{ top: 4, right: 4, bottom: 4, left: 0 }} barSize={20}
onClick={e => { const p = e?.activePayload?.[0]?.payload; if (p) navigate(`/activities?from=${p.weekStartISO}&to=${p.weekEndISO}`) }}
style={{ cursor: 'pointer' }}>
<CartesianGrid strokeDasharray="3 3" stroke="#1f2937" vertical={false} />
<XAxis dataKey="week" tick={{ fontSize: 10, fill: '#6b7280' }} axisLine={false} tickLine={false} />
<YAxis tick={{ fontSize: 10, fill: '#6b7280' }} axisLine={false} tickLine={false} width={28} tickFormatter={v => `${v.toFixed(0)}`} />
<Tooltip contentStyle={tooltipStyle} formatter={(v) => [`${v.toFixed(1)} km`, 'Distance']} cursor={{ fill: 'rgba(59,130,246,0.1)' }} />
<Bar dataKey="km" fill="#3b82f6" radius={[3, 3, 0, 0]} isAnimationActive={false} />
</BarChart>
</ResponsiveContainer>
) : (
<div className="flex items-center justify-center h-full text-gray-600 text-sm">No activities yet</div>
)}
</Card>
)
}
@@ -296,9 +324,7 @@ function FeaturedActivity({ activity, segments }) {
<div className="flex items-center gap-2 min-w-0">
<span className="text-xl">{sportIcon(activity.sport_type)}</span>
<div className="min-w-0">
<Link to={`/activities/${activity.id}`} className="text-sm font-semibold text-white hover:text-blue-400 transition-colors truncate block">
{activity.name}
</Link>
<Link to={`/activities/${activity.id}`} className="text-sm font-semibold text-white hover:text-blue-400 transition-colors truncate block">{activity.name}</Link>
<p className="text-xs text-gray-500">{formatDate(activity.start_time)}</p>
</div>
</div>
@@ -330,15 +356,11 @@ function FeaturedActivity({ activity, segments }) {
return (
<div key={seg.segment_id} className="flex items-center gap-2 text-sm">
<span className="flex-1 text-gray-300 text-xs truncate">{seg.name}</span>
<span className={`font-mono text-xs ${isPodium ? 'text-yellow-400 font-semibold' : 'text-gray-200'}`}>
{formatDuration(seg.duration_s)}
</span>
<span className={`font-mono text-xs ${isPodium ? 'text-yellow-400 font-semibold' : 'text-gray-200'}`}>{formatDuration(seg.duration_s)}</span>
<span className="w-8 text-right text-xs">
{isPodium
? <span title={`#${seg.rank} of ${seg.effort_count}`}>{MEDALS[seg.rank]}</span>
: delta != null
? <span className="text-red-400 font-mono">+{formatDuration(delta)}</span>
: <span className="text-gray-700">--</span>}
{isPodium ? <span title={`#${seg.rank} of ${seg.effort_count}`}>{MEDALS[seg.rank]}</span>
: delta != null ? <span className="text-red-400 font-mono">+{formatDuration(delta)}</span>
: <span className="text-gray-700">--</span>}
</span>
</div>
)
@@ -369,9 +391,7 @@ function RecentActivities({ activities }) {
</Link>
))}
{!activities?.length && (
<p className="text-gray-600 text-sm text-center py-8">
No activities yet <Link to="/upload" className="text-blue-400 hover:underline">import some data</Link>
</p>
<p className="text-gray-600 text-sm text-center py-8">No activities yet <Link to="/upload" className="text-blue-400 hover:underline">import some data</Link></p>
)}
</div>
</Card>
@@ -404,18 +424,14 @@ export default function DashboardPage() {
queryKey: ['activities-recent'],
queryFn: () => api.get('/activities/', { params: { per_page: 10 } }).then(r => r.data),
})
const { data: allActivities } = useQuery({
queryKey: ['activities-all-chart'],
queryFn: () =>
api.get('/activities/', { params: { per_page: 100, from_date: subDays(new Date(), 60).toISOString() } }).then(r => r.data),
queryFn: () => api.get('/activities/', { params: { per_page: 100, from_date: subDays(new Date(), 60).toISOString() } }).then(r => r.data),
})
const { data: recentHealth } = useQuery({
queryKey: ['health-metrics', 'dash'],
queryFn: () => api.get('/health-metrics/', { params: { limit: 365 } }).then(r => r.data),
})
const { data: profile } = useQuery({
queryKey: ['profile'],
queryFn: () => api.get('/profile/').then(r => r.data),
@@ -431,7 +447,6 @@ export default function DashboardPage() {
sleep_duration_s: pick('sleep_duration_s'),
sleep_start: latest.sleep_start ?? null,
sleep_end: latest.sleep_end ?? null,
// Sleep stages + score for the latest night (same row as sleep_start).
sleep_deep_s: latest.sleep_deep_s ?? null,
sleep_rem_s: latest.sleep_rem_s ?? null,
sleep_light_s: latest.sleep_light_s ?? null,
@@ -443,6 +458,8 @@ export default function DashboardPage() {
vo2max: pick('vo2max'),
fitness_age: pick('fitness_age'),
avg_stress: pick('avg_stress'),
active_calories: pick('active_calories'),
floors_climbed: pick('floors_climbed'),
}
}, [recentHealth])
@@ -451,17 +468,14 @@ export default function DashboardPage() {
queryFn: () => api.get('/health-metrics/intraday', { params: { date: health.date } }).then(r => r.data),
enabled: !!health.date,
})
const { data: records } = useQuery({
queryKey: ['records-running'],
queryFn: () => api.get('/records/', { params: { sport_type: 'running' } }).then(r => r.data),
})
const { data: ytdStats } = useQuery({
queryKey: ['ytd-stats'],
queryFn: () => api.get('/activities/stats/ytd').then(r => r.data),
})
const featured = recentActivities?.[0]
const { data: featuredSegments } = useQuery({
queryKey: ['activity-segments', featured?.id],
@@ -471,11 +485,11 @@ export default function DashboardPage() {
// ── Layout state ──────────────────────────────────────────────────────────
const [editMode, setEditMode] = useState(false)
const [addOpen, setAddOpen] = useState(false)
const [layout, setLayout] = useState(() => buildLayout(null))
const saveTimer = useRef(null)
const loadedRef = useRef(false)
// Apply the saved layout once the profile loads.
useEffect(() => {
if (profile && !loadedRef.current) {
loadedRef.current = true
@@ -483,48 +497,84 @@ export default function DashboardPage() {
}
}, [profile])
const qc = useQueryClient()
const stripLayout = (lay) => lay.map(({ i, x, y, w, h }) => ({ i, x, y, w, h }))
const saveLayout = useMutation({
mutationFn: (lay) =>
api.put('/profile/dashboard-layout', { layout: lay.map(({ i, x, y, w, h }) => ({ i, x, y, w, h })) }),
mutationFn: (lay) => api.put('/profile/dashboard-layout', { layout: stripLayout(lay) }),
// Keep the cached profile in sync so re-mounting the page doesn't revert the layout.
onSuccess: (_d, lay) => qc.setQueryData(['profile'], p => (p ? { ...p, dashboard_layout: stripLayout(lay) } : p)),
})
const persist = (lay) => { clearTimeout(saveTimer.current); saveLayout.mutate(lay) }
const handleLayoutChange = (next) => {
setLayout(next)
const withMins = attachMins(next)
setLayout(withMins)
if (editMode) {
clearTimeout(saveTimer.current)
saveTimer.current = setTimeout(() => saveLayout.mutate(next), 700)
saveTimer.current = setTimeout(() => saveLayout.mutate(withMins), 700)
}
}
const finishEditing = () => {
clearTimeout(saveTimer.current)
saveLayout.mutate(layout)
setEditMode(false)
const addWidget = (id) => {
if (layout.some(l => l.i === id)) { setAddOpen(false); return }
const maxY = layout.reduce((m, l) => Math.max(m, l.y + l.h), 0)
const def = WIDGETS[id]
const next = attachMins([...layout, { i: id, x: 0, y: maxY, w: def.w, h: def.h }])
setLayout(next); persist(next); setAddOpen(false)
}
const removeWidget = (id) => { const next = layout.filter(l => l.i !== id); setLayout(next); persist(next) }
const finishEditing = () => { persist(layout); setEditMode(false); setAddOpen(false) }
const resetLayout = () => { const def = attachMins(DEFAULT_LAYOUT); setLayout(def); persist(def) }
const renderWidget = (id) => {
if (STAT_DEFS[id]) {
const d = STAT_DEFS[id]
return <StatCard label={d.label} accent={d.accent} value={d.val(health, ytdStats)}
sub={typeof d.sub === 'function' ? d.sub(health) : d.sub} />
}
switch (id) {
case 'weekly': return <WeeklyChart activities={allActivities} />
case 'bodyBattery': return <BodyBatteryToday bb={intraday?.body_battery} hires={intraday?.body_battery_hires} sleepStart={health.sleep_start} sleepEnd={health.sleep_end} />
case 'vo2maxTrend': return <Vo2MaxTrend health={health} recentHealth={recentHealth} />
case 'sleepDetail': return <SleepDetail health={health} />
case 'weight': return <WeightMini recentHealth={recentHealth} />
case 'featured': return <FeaturedActivity activity={featured} segments={featuredSegments} />
case 'recent': return <RecentActivities activities={recentActivities} />
case 'prs': return <RunningPRs records={records} />
default: return null
}
}
const resetLayout = () => {
const def = buildLayout(null)
setLayout(def)
saveLayout.mutate(def)
}
const WIDGET_CONTENT = {
stats: <StatsRow health={health} ytdStats={ytdStats} />,
weekly: <Card title="Weekly distance (km)"><WeeklyChart activities={allActivities} /></Card>,
bodyBattery: <MiniBodyBattery bb={intraday?.body_battery} hires={intraday?.body_battery_hires} sleepStart={health.sleep_start} sleepEnd={health.sleep_end} />,
vo2max: <Vo2MaxWidget health={health} recentHealth={recentHealth} />,
sleep: <SleepMini health={health} />,
hrv: <HrvWidget health={health} />,
featured: <FeaturedActivity activity={featured} segments={featuredSegments} />,
recent: <RecentActivities activities={recentActivities} />,
prs: <RunningPRs records={records} />,
}
const presentIds = new Set(layout.map(l => l.i))
const available = Object.keys(WIDGETS).filter(id => !presentIds.has(id))
return (
<div className="p-6">
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-bold text-white">Dashboard</h1>
<div className="flex items-center gap-3">
{editMode && (
<div className="relative">
<button onClick={() => setAddOpen(o => !o)}
className="text-sm font-medium px-3 py-1.5 rounded-lg bg-gray-800 hover:bg-gray-700 text-gray-200 transition-colors">
+ Add widget
</button>
{addOpen && (
<div className="absolute right-0 mt-1 w-56 max-h-80 overflow-auto bg-gray-900 border border-gray-700 rounded-lg shadow-xl z-50 py-1">
{available.length === 0
? <p className="text-xs text-gray-500 px-3 py-2">All widgets are on the dashboard</p>
: available.map(id => (
<button key={id} onClick={() => addWidget(id)}
className="block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-3 py-1.5 transition-colors">
{WIDGETS[id].label}
</button>
))}
</div>
)}
</div>
)}
{editMode && (
<button onClick={resetLayout} className="text-xs text-gray-400 hover:text-white transition-colors">Reset layout</button>
)}
@@ -540,7 +590,7 @@ export default function DashboardPage() {
</div>
{editMode && (
<p className="text-xs text-gray-500 mb-3">Drag widgets to move them, or drag a corner to resize. Changes save automatically.</p>
<p className="text-xs text-gray-500 mb-3">Drag to move, drag a corner to resize, or remove a widget with . Add widgets from the menu. Changes save automatically.</p>
)}
<Grid
@@ -552,13 +602,19 @@ export default function DashboardPage() {
isDraggable={editMode}
isResizable={editMode}
onLayoutChange={handleLayoutChange}
compactType="vertical"
compactType={null}
preventCollision={false}
draggableCancel=".widget-delete"
>
{WIDGETS.map(w => (
<div key={w.id}
className={`rounded-xl ${editMode ? 'ring-2 ring-blue-500/40 cursor-move' : ''}`}>
{layout.filter(l => WIDGETS[l.i]).map(l => (
<div key={l.i} className={`rounded-xl relative ${editMode ? 'ring-2 ring-blue-500/40 cursor-move' : ''}`}>
{editMode && (
<button onClick={() => removeWidget(l.i)}
className="widget-delete absolute -top-2 -right-2 z-20 w-6 h-6 flex items-center justify-center rounded-full bg-red-600 hover:bg-red-500 text-white text-xs shadow-lg"
title="Remove widget"></button>
)}
<div className={`h-full ${editMode ? 'pointer-events-none select-none' : ''}`}>
{WIDGET_CONTENT[w.id]}
{renderWidget(l.i)}
</div>
</div>
))}