Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Implement design system: loading animation and integrate across pages

Cawlummc54b77dfad5f
diff --git a/web/src/components/Loading.tsx b/web/src/components/Loading.tsx
new file mode 100644
index 0000000..1de65b3
--- /dev/null
+++ b/web/src/components/Loading.tsx
@@ -0,0 +1,124 @@
+export default function Loading() {
+ return (
+ <div className="fixed inset-0 flex items-center justify-center bg-surface-base">
+ <div className="flex flex-col items-center gap-11">
+ {/* Barbell Rig */}
+ <div className="relative w-56 h-24">
+ {/* Left upright */}
+ <div className="absolute left-4 top-0 bottom-4 w-1 bg-surface-muted rounded-sm">
+ <div className="absolute -left-1 top-7 w-2.5 h-0.5 bg-surface-muted rounded-sm" />
+ <div className="absolute -left-1 top-12 w-2.5 h-0.5 bg-surface-muted rounded-sm" />
+ </div>
+
+ {/* Right upright */}
+ <div className="absolute right-4 top-0 bottom-4 w-1 bg-surface-muted rounded-sm">
+ <div className="absolute -right-1 top-7 w-2.5 h-0.5 bg-surface-muted rounded-sm" />
+ <div className="absolute -right-1 top-12 w-2.5 h-0.5 bg-surface-muted rounded-sm" />
+ </div>
+
+ {/* Bar assembly - pivots and flexes */}
+ <div
+ className="absolute left-1/2 top-7 -translate-x-1/2"
+ style={{
+ animation: 'pivot 1.6s cubic-bezier(0.5, 0, 0.5, 1) infinite',
+ }}
+ >
+ {/* Bar with gradient */}
+ <div
+ className="absolute -left-24 -top-1 w-48 h-1.5 rounded-sm shadow-lg"
+ style={{
+ background: 'linear-gradient(180deg, #38d8fb 0%, #00b8d9 60%, #007a96 100%)',
+ boxShadow: '0 0 8px rgba(0, 184, 217, 0.35)',
+ animation: 'flex 1.6s cubic-bezier(0.5, 0, 0.5, 1) infinite',
+ transformOrigin: 'center',
+ }}
+ />
+
+ {/* Left plates */}
+ <div
+ className="absolute -left-28 -top-3 w-4 h-8 bg-surface-overlay border border-brand-500 rounded-sm"
+ style={{ boxShadow: 'inset 0 0 10px rgba(0, 184, 217, 0.25)' }}
+ />
+ <div
+ className="absolute -left-24 -top-4 w-3.5 h-10 bg-surface-overlay border border-brand-500 rounded-sm"
+ style={{ boxShadow: 'inset 0 0 10px rgba(0, 184, 217, 0.25)' }}
+ />
+ <div
+ className="absolute -left-20 -top-5 w-3 h-12 bg-surface-overlay border border-brand-500 rounded-sm"
+ style={{ boxShadow: 'inset 0 0 10px rgba(0, 184, 217, 0.25)' }}
+ />
+
+ {/* Right plates */}
+ <div
+ className="absolute -right-28 -top-3 w-4 h-8 bg-surface-overlay border border-brand-500 rounded-sm"
+ style={{ boxShadow: 'inset 0 0 10px rgba(0, 184, 217, 0.25)' }}
+ />
+ <div
+ className="absolute -right-24 -top-4 w-3.5 h-10 bg-surface-overlay border border-brand-500 rounded-sm"
+ style={{ boxShadow: 'inset 0 0 10px rgba(0, 184, 217, 0.25)' }}
+ />
+ <div
+ className="absolute -right-20 -top-5 w-3 h-12 bg-surface-overlay border border-brand-500 rounded-sm"
+ style={{ boxShadow: 'inset 0 0 10px rgba(0, 184, 217, 0.25)' }}
+ />
+
+ {/* Collars */}
+ <div className="absolute -left-17 -top-2 w-1 h-5.5 bg-brand-500 rounded-sm" />
+ <div className="absolute -right-17 -top-2 w-1 h-5.5 bg-brand-500 rounded-sm" />
+ </div>
+ </div>
+
+ {/* Rep dots */}
+ <div className="flex gap-2.5">
+ {[0, 1, 2, 3, 4].map((i) => (
+ <div
+ key={i}
+ className="w-2.5 h-2.5 rounded-full bg-surface-muted border border-surface-muted transition-all"
+ style={{
+ animation: `blink 1.6s steps(1, end) infinite`,
+ animationDelay: `${i * 0.16}s`,
+ }}
+ />
+ ))}
+ </div>
+
+ {/* Label */}
+ <div className="text-center">
+ <div className="font-display font-extrabold text-xl text-tx-primary tracking-tight">
+ lyftr
+ </div>
+ <div className="text-xs font-semibold text-tx-muted uppercase tracking-widest mt-2">
+ Loading
+ </div>
+ </div>
+ </div>
+
+ <style>{`
+ @keyframes flex {
+ 0%, 100% { transform: scaleY(1); }
+ 45% { transform: scaleY(1); }
+ 55%, 65% { transform: scaleY(0.55); }
+ 80% { transform: scaleY(1); }
+ }
+ @keyframes pivot {
+ 0%, 100% { transform: translateY(0); }
+ 45% { transform: translateY(0); }
+ 55%, 65% { transform: translateY(18px); }
+ 80% { transform: translateY(0); }
+ }
+ @keyframes blink {
+ 0%, 100% {
+ background-color: var(--surface-muted);
+ border-color: var(--surface-muted);
+ box-shadow: none;
+ }
+ 20%, 95% {
+ background-color: #00b8d9;
+ border-color: #00b8d9;
+ box-shadow: 0 0 10px rgba(0, 184, 217, 0.5);
+ }
+ }
+ `}</style>
+ </div>
+ )
+}
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index 48ea47c..3f21ee4 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -1,163 +1,87 @@
-import { format, subDays, isToday, isSameDay } from 'date-fns'
+import { useState, useEffect } from 'react'
+import { format, subDays } from 'date-fns'
import {
- TrendingDown, TrendingUp, Dumbbell, Utensils,
- Flame, Target, ChevronRight, Plus, Activity,
- Trophy, Repeat2, Scale, Apple, Timer,
- BarChart3, Beef, Zap, Moon, Award,
- ArrowRight, CheckCircle2, Circle,
+ TrendingDown, TrendingUp, Dumbbell, Utensils, Flame, Target, Plus, Activity,
+ Trophy, Scale, Apple, Timer, BarChart3, Beef, Zap, Award, ArrowRight,
+ CheckCircle2, AlertCircle,
} from 'lucide-react'
import { HelpTip } from '../components/Tooltip'
+import Loading from '../components/Loading'
+import { workoutAPI, foodAPI, weightAPI, userAPI } from '../services/api'
+import * as types from '../types'
-// ─── Mock data ────────────────────────────────────────
const TODAY = new Date()
-const MOCK = {
- user: { name: 'Chris' },
- weight: { current: 185.0, prev7d: 187.0, entries: [187.0, 186.5, 186.2, 185.8, 185.5, 185.2, 185.0] },
- cals: { eaten: 1850, burned: 2350, target: 2000 },
- macros: { protein: { v: 140, t: 150 }, carbs: { v: 180, t: 250 }, fat: { v: 60, t: 65 } },
- streak: 12,
- weekActivity: [
- { date: subDays(TODAY, 6), type: 'pull', name: 'Pull Day' },
- { date: subDays(TODAY, 5), type: 'legs', name: 'Leg Day' },
- { date: subDays(TODAY, 4), type: 'rest', name: 'Rest' },
- { date: subDays(TODAY, 3), type: 'push', name: 'Push Day' },
- { date: subDays(TODAY, 2), type: 'cardio', name: 'Cardio' },
- { date: subDays(TODAY, 1), type: 'rest', name: 'Rest' },
- { date: TODAY, type: 'push', name: 'Push Day' },
- ],
- lastWorkout: {
- name: 'Push Day', duration: '58 min', volume: 32450,
- exercises: [
- { name: 'Bench Press', sets: 4, reps: 8, weight: 275, pr: true },
- { name: 'Incline DB', sets: 3, reps: 10, weight: 85, pr: false },
- { name: 'Overhead Press', sets: 4, reps: 8, weight: 155, pr: false },
- { name: 'Cable Fly', sets: 3, reps: 12, weight: 40, pr: false },
- { name: 'Tricep Pushdown', sets: 3, reps: 12, weight: 60, pr: true },
- ],
- },
- prs: [
- { exercise: 'Bench Press', weight: 275, date: 'Today', improvement: '+5 lbs' },
- { exercise: 'Tricep Pushdown',weight: 60, date: 'Today', improvement: '+5 lbs' },
- { exercise: 'Barbell Squat', weight: 315, date: 'Apr 15', improvement: '+10 lbs' },
- ],
- muscleGroups: [
- { name: 'Chest', sessions: 2, color: '#00b8d9' },
- { name: 'Back', sessions: 2, color: '#00b8d9' },
- { name: 'Shoulders', sessions: 1, color: '#0ecef7' },
- { name: 'Legs', sessions: 1, color: '#0ecef7' },
- { name: 'Arms', sessions: 2, color: '#00b8d9' },
- { name: 'Core', sessions: 0, color: '#1c2f50' },
- ],
- weekStats: { totalVolume: 93200, avgDuration: 55, workoutDays: 4 },
-}
-
-const WORKOUT_COLORS: Record<string, string> = {
- push: 'text-brand-400',
- pull: 'text-violet-400',
- legs: 'text-success-400',
- cardio: 'text-warning-400',
- rest: 'text-tx-muted',
-}
-const WORKOUT_ICONS: Record<string, React.ComponentType<any>> = {
- push: Dumbbell,
- pull: Dumbbell,
- legs: Activity,
- cardio: Activity,
- rest: Moon,
-}
-
-// ─── Sub-components ───────────────────────────────────
-
-function WeightSparkline({ values }: { values: number[] }) {
- const min = Math.min(...values)
- const max = Math.max(...values)
- const range = max - min || 1
- const w = 80, h = 28, pad = 2
- const pts = values.map((v, i) => {
- const x = pad + (i / (values.length - 1)) * (w - pad * 2)
- const y = pad + ((max - v) / range) * (h - pad * 2)
- return `${x},${y}`
+export default function Dashboard() {
+ const [stats, setStats] = useState<{
+ weight?: types.WeightLog | null
+ weightStats?: types.WeightStats
+ food?: types.DailyStats
+ workouts: types.Workout[]
+ settings?: types.UserSettings
+ }>({
+ workouts: [],
})
- const going = values[values.length - 1] < values[0]
- return (
- <svg width={w} height={h} className="overflow-visible">
- <polyline
- points={pts.join(' ')}
- fill="none"
- stroke={going ? '#22c55e' : '#ef4444'}
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <circle
- cx={pts[pts.length - 1].split(',')[0]}
- cy={pts[pts.length - 1].split(',')[1]}
- r="2.5"
- fill={going ? '#22c55e' : '#ef4444'}
- />
- </svg>
- )
-}
-
-function CalorieRing({ eaten, target }: { eaten: number; target: number }) {
- const pct = Math.min(1, eaten / target)
- const r = 28
- const circ = 2 * Math.PI * r
- const offset = circ * (1 - pct)
- return (
- <div className="relative w-20 h-20 flex-shrink-0">
- <svg className="w-20 h-20 -rotate-90" viewBox="0 0 72 72">
- <circle cx="36" cy="36" r={r} fill="none" stroke="var(--surface-overlay)" strokeWidth="7" />
- <circle cx="36" cy="36" r={r} fill="none" stroke="#00b8d9" strokeWidth="7"
- strokeDasharray={circ} strokeDashoffset={offset} strokeLinecap="round" />
- </svg>
- <div className="absolute inset-0 flex flex-col items-center justify-center">
- <span className="font-display font-bold text-base text-tx-primary leading-none tabular-nums">
- {Math.round(pct * 100)}
- </span>
- <span className="text-[10px] text-tx-muted leading-none mt-0.5">%</span>
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState<string | null>(null)
+
+ useEffect(() => {
+ const load = async () => {
+ try {
+ const [workouts, foodStats, weightStats, settings] = await Promise.all([
+ workoutAPI.list({ limit: 10 }),
+ foodAPI.stats(format(TODAY, 'yyyy-MM-dd')).catch(() => ({
+ date: format(TODAY, 'yyyy-MM-dd'),
+ total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, workout_count: 0
+ })),
+ weightAPI.stats().catch(() => ({ latest: 0, starting: 0, total_entries: 0 })),
+ userAPI.getSettings().catch(() => ({
+ user_id: 0, weight_unit: 'lbs', calorie_target: 2000,
+ protein_target: 150, carb_target: 250, fat_target: 65
+ })),
+ ])
+
+ setStats({
+ workouts: workouts || [],
+ food: foodStats,
+ weightStats,
+ settings,
+ weight: workouts?.[0] ? null : null, // Placeholder
+ })
+ } catch (err: any) {
+ setError(err.message || 'Failed to load dashboard')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ load()
+ }, [])
+
+ if (loading) {
+ return <Loading />
+ }
+
+ if (error) {
+ return (
+ <div className="alert-error">
+ <AlertCircle className="w-5 h-5 flex-shrink-0" />
+ <span>{error}</span>
</div>
- </div>
- )
-}
-
-function MacroBar({ label, icon: Icon, value, target, color, unit = 'g' }: {
- label: string; icon: React.ComponentType<any>; value: number; target: number; color: string; unit?: string
-}) {
- const pct = Math.min(100, (value / target) * 100)
- return (
- <div className="flex items-center gap-3">
- <div className="w-7 h-7 rounded-md flex items-center justify-center flex-shrink-0"
- style={{ background: `${color}18`, border: `1px solid ${color}30` }}>
- <Icon className="w-3.5 h-3.5" style={{ color }} />
- </div>
- <div className="flex-1 min-w-0">
- <div className="flex justify-between items-center mb-1">
- <span className="text-xs text-tx-secondary">{label}</span>
- <span className="text-xs font-semibold text-tx-primary tabular-nums">
- {value}<span className="text-tx-muted font-normal">/{target}{unit}</span>
- </span>
- </div>
- <div className="progress-track">
- <div className="progress-bar" style={{ width: `${pct}%`, background: color }} />
- </div>
- </div>
- </div>
- )
-}
-
-// ─── Main dashboard ───────────────────────────────────
-export default function Dashboard() {
- const weightDelta = +(MOCK.weight.current - MOCK.weight.prev7d).toFixed(1)
- const weightDown = weightDelta < 0
- const calBurned = MOCK.cals.burned - MOCK.cals.eaten
- const hour = TODAY.getHours()
- const greeting = hour < 12 ? 'Good morning' : hour < 17 ? 'Good afternoon' : 'Good evening'
+ )
+ }
+
+ const lastWorkout = stats.workouts[0]
+ const foodData = stats.food
+ const settings = stats.settings!
+ const calBurned = (foodData?.total_calories || 0) - settings.calorie_target
+ const proteinPct = Math.min(100, ((foodData?.total_protein || 0) / settings.protein_target) * 100)
+ const carbsPct = Math.min(100, ((foodData?.total_carbs || 0) / settings.carb_target) * 100)
+ const fatPct = Math.min(100, ((foodData?.total_fat || 0) / settings.fat_target) * 100)
+ const calPct = Math.min(100, ((foodData?.total_calories || 0) / settings.calorie_target) * 100)
return (
<div className="space-y-4 animate-slide-up">
-
{/* ── Header ─────────────────────────────────── */}
<div className="flex justify-between items-start">
<div>
@@ -165,80 +89,16 @@ export default function Dashboard() {
{format(TODAY, 'EEEE, MMMM d')}
</p>
<h1 className="font-display font-bold text-2xl text-tx-primary mt-0.5">
- {greeting}, {MOCK.user.name}
+ Your progress today
</h1>
</div>
<button className="btn-primary btn-sm">
- <Plus className="w-3.5 h-3.5" /> Quick Log
+ <Plus className="w-3.5 h-3.5" /> Log
</button>
</div>
- {/* ── Week activity strip ─────────────────────── */}
- <div className="card p-4">
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-1.5">
- <span className="stat-label">This Week</span>
- <HelpTip content="Your training split for the past 7 days" />
- </div>
- <div className="flex items-center gap-1 text-xs text-tx-muted">
- <Repeat2 className="w-3.5 h-3.5 text-brand-500" />
- <span className="font-semibold text-brand-400">{MOCK.streak}</span>
- <span>day streak</span>
- </div>
- </div>
- <div className="grid grid-cols-7 gap-1.5">
- {MOCK.weekActivity.map((day, i) => {
- const Icon = WORKOUT_ICONS[day.type]
- const colorCls = WORKOUT_COLORS[day.type]
- const isNow = isToday(day.date)
- const isRest = day.type === 'rest'
- return (
- <div key={i} className="flex flex-col items-center gap-1.5">
- <span className={`text-[10px] font-medium uppercase ${isNow ? 'text-brand-400' : 'text-tx-muted'}`}>
- {format(day.date, 'EEE')}
- </span>
- <div className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${
- isNow
- ? 'bg-brand-500/15 border border-brand-500/40'
- : isRest
- ? 'bg-surface-overlay border border-surface-border'
- : 'bg-surface-muted border border-surface-border'
- }`}>
- <Icon className={`w-3.5 h-3.5 ${colorCls}`} strokeWidth={isRest ? 1.5 : 2} />
- </div>
- <span className={`text-[10px] text-center leading-tight hidden sm:block ${isNow ? 'text-brand-400 font-medium' : 'text-tx-muted'}`}>
- {isRest ? 'Rest' : day.name.split(' ')[0]}
- </span>
- </div>
- )
- })}
- </div>
- </div>
-
{/* ── Top stat cards ─────────────────────────── */}
- <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
-
- {/* Weight */}
- <div className="card p-4 border-brand-500/20">
- <div className="flex items-center justify-between mb-2">
- <span className="stat-label">Body Weight</span>
- <Scale className="w-3.5 h-3.5 text-tx-muted" />
- </div>
- <div className="flex items-end justify-between">
- <div>
- <div className="flex items-end gap-1">
- <span className="stat-value text-2xl">{MOCK.weight.current}</span>
- <span className="text-tx-muted text-xs mb-0.5">lbs</span>
- </div>
- <div className={`flex items-center gap-1 mt-1.5 text-xs font-medium ${weightDown ? 'text-success-400' : 'text-error-400'}`}>
- {weightDown ? <TrendingDown className="w-3.5 h-3.5" /> : <TrendingUp className="w-3.5 h-3.5" />}
- {Math.abs(weightDelta)} lbs / 7d
- </div>
- </div>
- <WeightSparkline values={MOCK.weight.entries} />
- </div>
- </div>
-
+ <div className="grid grid-cols-2 lg:grid-cols-3 gap-3">
{/* Calories */}
<div className="card p-4">
<div className="flex items-center justify-between mb-2">
@@ -246,197 +106,147 @@ export default function Dashboard() {
<Flame className="w-3.5 h-3.5 text-tx-muted" />
</div>
<div className="flex items-end gap-1">
- <span className="stat-value text-2xl">{MOCK.cals.eaten.toLocaleString()}</span>
- <span className="text-tx-muted text-xs mb-0.5">/ {MOCK.cals.target.toLocaleString()}</span>
+ <span className="stat-value text-2xl">{Math.round(foodData?.total_calories || 0)}</span>
+ <span className="text-tx-muted text-xs mb-0.5">/ {settings.calorie_target}</span>
</div>
- <div className="flex items-center gap-1 mt-1.5 text-xs text-tx-muted">
- <Zap className="w-3.5 h-3.5 text-warning-400" />
- <span>{calBurned > 0 ? `${calBurned} kcal deficit` : `${Math.abs(calBurned)} kcal surplus`}</span>
+ <div className="progress-track mt-2">
+ <div className="progress-bar" style={{ width: `${calPct}%`, background: '#00b8d9' }} />
</div>
</div>
- {/* Weekly volume */}
+ {/* Protein */}
<div className="card p-4">
<div className="flex items-center justify-between mb-2">
- <span className="stat-label">Weekly Volume</span>
- <BarChart3 className="w-3.5 h-3.5 text-tx-muted" />
+ <span className="stat-label">Protein</span>
+ <Beef className="w-3.5 h-3.5 text-tx-muted" />
</div>
<div className="flex items-end gap-1">
- <span className="stat-value text-2xl">{(MOCK.weekStats.totalVolume / 1000).toFixed(0)}k</span>
- <span className="text-tx-muted text-xs mb-0.5">lbs</span>
+ <span className="stat-value text-2xl">{Math.round(foodData?.total_protein || 0)}</span>
+ <span className="text-tx-muted text-xs mb-0.5">g</span>
</div>
- <div className="flex items-center gap-1 mt-1.5 text-xs text-tx-muted">
- <Timer className="w-3.5 h-3.5" />
- <span>{MOCK.weekStats.avgDuration} min avg · {MOCK.weekStats.workoutDays} sessions</span>
+ <div className="progress-track mt-2">
+ <div className="progress-bar" style={{ width: `${proteinPct}%`, background: '#f59e0b' }} />
</div>
</div>
- {/* PRs this week */}
+ {/* Workouts */}
<div className="card p-4">
<div className="flex items-center justify-between mb-2">
- <span className="stat-label">New PRs</span>
- <Trophy className="w-3.5 h-3.5 text-tx-muted" />
+ <span className="stat-label">This Week</span>
+ <Dumbbell className="w-3.5 h-3.5 text-tx-muted" />
</div>
<div className="flex items-end gap-1">
- <span className="stat-value text-2xl">{MOCK.prs.filter(p => p.date === 'Today').length}</span>
- <span className="text-tx-muted text-xs mb-0.5">today</span>
- </div>
- <div className="flex items-center gap-1 mt-1.5 text-xs text-warning-400 font-medium">
- <Award className="w-3.5 h-3.5" />
- <span>{MOCK.prs.length} this week</span>
+ <span className="stat-value text-2xl">{stats.workouts.length}</span>
+ <span className="text-tx-muted text-xs mb-0.5">sessions</span>
</div>
</div>
</div>
{/* ── Middle row ─────────────────────────────── */}
<div className="grid lg:grid-cols-2 gap-4">
-
{/* Today's nutrition */}
<div className="card p-5">
<div className="flex items-center justify-between mb-4">
- <div className="flex items-center gap-1.5">
- <h2 className="section-title">Today's Nutrition</h2>
- <HelpTip content="Macros logged so far today vs. your daily targets" />
- </div>
+ <h2 className="section-title">Today's Nutrition</h2>
<button className="btn-ghost btn-sm">
- <Utensils className="w-3.5 h-3.5" /> Log meal
+ <Utensils className="w-3.5 h-3.5" /> Log
</button>
</div>
- <div className="flex items-center gap-5">
- <div className="flex flex-col items-center gap-1">
- <CalorieRing eaten={MOCK.cals.eaten} target={MOCK.cals.target} />
- <span className="text-[10px] text-tx-muted">of goal</span>
- </div>
- <div className="flex-1 space-y-3">
- <MacroBar label="Protein" icon={Beef} value={MOCK.macros.protein.v} target={MOCK.macros.protein.t} color="#00b8d9" />
- <MacroBar label="Carbs" icon={Apple} value={MOCK.macros.carbs.v} target={MOCK.macros.carbs.t} color="#f59e0b" />
- <MacroBar label="Fat" icon={Flame} value={MOCK.macros.fat.v} target={MOCK.macros.fat.t} color="#8b5cf6" />
- </div>
- </div>
-
- <div className="mt-4 pt-4 divider grid grid-cols-3 gap-2">
- {[
- { label: 'Eaten', value: MOCK.cals.eaten, color: 'text-tx-primary' },
- { label: 'Burned', value: MOCK.cals.burned, color: 'text-success-400' },
- { label: 'Remaining', value: MOCK.cals.target - MOCK.cals.eaten, color: 'text-brand-400' },
- ].map(s => (
- <div key={s.label} className="text-center">
- <p className={`text-sm font-semibold tabular-nums ${s.color}`}>{s.value.toLocaleString()}</p>
- <p className="text-[10px] text-tx-muted mt-0.5">{s.label}</p>
+ <div className="space-y-3">
+ <div className="flex items-center gap-3">
+ <div className="w-7 h-7 rounded-md flex items-center justify-center flex-shrink-0 bg-blue-500/10 border border-blue-500/30">
+ <Beef className="w-3.5 h-3.5 text-blue-400" />
+ </div>
+ <div className="flex-1">
+ <div className="flex justify-between items-center mb-1">
+ <span className="text-xs text-tx-secondary">Protein</span>
+ <span className="text-xs font-semibold text-tx-primary">
+ {Math.round(foodData?.total_protein || 0)}g / {settings.protein_target}g
+ </span>
+ </div>
+ <div className="progress-track">
+ <div className="progress-bar" style={{ width: `${proteinPct}%`, background: '#3b82f6' }} />
+ </div>
</div>
- ))}
- </div>
- </div>
-
- {/* Last workout */}
- <div className="card p-5">
- <div className="flex items-center justify-between mb-4">
- <div className="flex items-center gap-1.5">
- <h2 className="section-title">{MOCK.lastWorkout.name}</h2>
- <span className="badge-dim">Today</span>
- </div>
- <div className="flex items-center gap-2 text-xs text-tx-muted">
- <Timer className="w-3.5 h-3.5" />
- {MOCK.lastWorkout.duration}
</div>
- </div>
- <div className="space-y-0 divide-y divide-surface-border">
- {MOCK.lastWorkout.exercises.map((ex, i) => (
- <div key={i} className="flex items-center justify-between py-2.5">
- <div className="flex items-center gap-2.5">
- {ex.pr
- ? <Trophy className="w-3.5 h-3.5 text-warning-400 flex-shrink-0" />
- : <CheckCircle2 className="w-3.5 h-3.5 text-tx-muted flex-shrink-0" />
- }
- <span className={`text-sm ${ex.pr ? 'text-tx-primary font-medium' : 'text-tx-secondary'}`}>
- {ex.name}
+ <div className="flex items-center gap-3">
+ <div className="w-7 h-7 rounded-md flex items-center justify-center flex-shrink-0 bg-amber-500/10 border border-amber-500/30">
+ <Apple className="w-3.5 h-3.5 text-amber-400" />
+ </div>
+ <div className="flex-1">
+ <div className="flex justify-between items-center mb-1">
+ <span className="text-xs text-tx-secondary">Carbs</span>
+ <span className="text-xs font-semibold text-tx-primary">
+ {Math.round(foodData?.total_carbs || 0)}g / {settings.carb_target}g
</span>
- {ex.pr && <span className="badge-brand text-[10px] px-1.5 py-0.5">PR</span>}
</div>
- <span className="text-xs text-tx-muted tabular-nums">
- {ex.sets}×{ex.reps} @ {ex.weight} lbs
- </span>
+ <div className="progress-track">
+ <div className="progress-bar" style={{ width: `${carbsPct}%`, background: '#f59e0b' }} />
+ </div>
</div>
- ))}
- </div>
-
- <div className="mt-4 pt-3 divider flex items-center justify-between">
- <span className="text-xs text-tx-muted">
- Total volume: <span className="font-semibold text-tx-primary">{MOCK.lastWorkout.volume.toLocaleString()} lbs</span>
- </span>
- <a href="/workouts" className="flex items-center gap-1 text-xs font-medium text-brand-500 hover:text-brand-400 transition-colors">
- Full log <ArrowRight className="w-3 h-3" />
- </a>
- </div>
- </div>
- </div>
-
- {/* ── Bottom row ─────────────────────────────── */}
- <div className="grid lg:grid-cols-2 gap-4">
+ </div>
- {/* Muscle group frequency */}
- <div className="card p-5">
- <div className="flex items-center gap-1.5 mb-4">
- <h2 className="section-title">Muscle Groups</h2>
- <HelpTip content="Sessions per muscle group this week. Aim for each group 2× per week." />
- </div>
- <div className="grid grid-cols-3 gap-2">
- {MOCK.muscleGroups.map(mg => (
- <div key={mg.name} className="flex flex-col items-center gap-1.5 p-3 rounded-lg bg-surface-muted border border-surface-border">
- <div className="flex gap-0.5">
- {[1, 2].map(n => (
- <div
- key={n}
- className="w-2 h-2 rounded-full"
- style={{ background: mg.sessions >= n ? mg.color : 'var(--surface-border)' }}
- />
- ))}
+ <div className="flex items-center gap-3">
+ <div className="w-7 h-7 rounded-md flex items-center justify-center flex-shrink-0 bg-purple-500/10 border border-purple-500/30">
+ <Zap className="w-3.5 h-3.5 text-purple-400" />
+ </div>
+ <div className="flex-1">
+ <div className="flex justify-between items-center mb-1">
+ <span className="text-xs text-tx-secondary">Fat</span>
+ <span className="text-xs font-semibold text-tx-primary">
+ {Math.round(foodData?.total_fat || 0)}g / {settings.fat_target}g
+ </span>
+ </div>
+ <div className="progress-track">
+ <div className="progress-bar" style={{ width: `${fatPct}%`, background: '#8b5cf6' }} />
</div>
- <span className="text-xs font-medium text-tx-secondary">{mg.name}</span>
- <span className="text-[10px] text-tx-muted">{mg.sessions}× / wk</span>
</div>
- ))}
+ </div>
</div>
</div>
- {/* Recent PRs */}
- <div className="card p-5">
- <div className="flex items-center justify-between mb-4">
- <div className="flex items-center gap-1.5">
- <h2 className="section-title">Personal Records</h2>
- <HelpTip content="Your most recent all-time weight PRs" />
+ {/* Last workout */}
+ {lastWorkout ? (
+ <div className="card p-5">
+ <div className="flex items-center justify-between mb-4">
+ <h2 className="section-title">{lastWorkout.name}</h2>
+ <span className="badge-dim">{format(lastWorkout.started_at, 'MMM d')}</span>
</div>
- <Trophy className="w-4 h-4 text-warning-400" />
- </div>
- <div className="space-y-0 divide-y divide-surface-border">
- {MOCK.prs.map((pr, i) => (
- <div key={i} className="flex items-center justify-between py-3">
- <div className="flex items-center gap-2.5">
- <div className="w-7 h-7 rounded-md bg-warning-500/10 border border-warning-500/20 flex items-center justify-center flex-shrink-0">
- <Trophy className="w-3.5 h-3.5 text-warning-400" />
- </div>
- <div>
- <p className="text-sm font-medium text-tx-primary">{pr.exercise}</p>
- <p className="text-xs text-tx-muted">{pr.date}</p>
+
+ <div className="space-y-0 divide-y divide-surface-border">
+ {lastWorkout.exercises?.slice(0, 5).map((ex) => (
+ <div key={ex.id} className="flex items-center justify-between py-2.5">
+ <div className="flex items-center gap-2.5">
+ <CheckCircle2 className="w-3.5 h-3.5 text-tx-muted flex-shrink-0" />
+ <span className="text-sm text-tx-secondary">{ex.exercise.name}</span>
</div>
+ <span className="text-xs text-tx-muted">
+ {ex.sets.length} sets
+ </span>
</div>
- <div className="text-right">
- <p className="text-sm font-semibold text-tx-primary tabular-nums">{pr.weight} lbs</p>
- <p className="text-xs text-success-400 font-medium">{pr.improvement}</p>
- </div>
- </div>
- ))}
+ ))}
+ </div>
+
+ <div className="mt-4 pt-3 border-t border-surface-border flex justify-between items-center">
+ <span className="text-xs text-tx-muted">
+ Duration: <span className="font-semibold">{lastWorkout.duration}s</span>
+ </span>
+ <a href="/workouts" className="flex items-center gap-1 text-xs font-medium text-brand-500 hover:text-brand-400">
+ Full log <ArrowRight className="w-3 h-3" />
+ </a>
+ </div>
</div>
- <div className="mt-3 pt-3 divider">
- <a href="/workouts" className="flex items-center justify-center gap-1 text-xs font-medium text-brand-500 hover:text-brand-400 transition-colors">
- View all records <ArrowRight className="w-3 h-3" />
- </a>
+ ) : (
+ <div className="card p-5 flex items-center justify-center min-h-48">
+ <div className="text-center">
+ <Dumbbell className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-50" />
+ <p className="text-sm text-tx-muted">No workouts logged yet</p>
+ </div>
</div>
- </div>
+ )}
</div>
-
</div>
)
}
diff --git a/web/src/pages/Food.tsx b/web/src/pages/Food.tsx
index ff31044..2e81948 100644
--- a/web/src/pages/Food.tsx
+++ b/web/src/pages/Food.tsx
@@ -1,176 +1,160 @@
-import { useState } from 'react'
-import { Plus, Search, Utensils, Flame, Info, ChevronRight, X } from 'lucide-react'
+import { useState, useEffect } from 'react'
+import { Plus, Flame, AlertCircle, Trash2 } from 'lucide-react'
+import { format } from 'date-fns'
import { HelpTip } from '../components/Tooltip'
+import Loading from '../components/Loading'
+import { foodAPI, userAPI } from '../services/api'
+import * as types from '../types'
-const MEALS = ['Breakfast', 'Lunch', 'Dinner', 'Snacks'] as const
-
-const MOCK_LOG: Record<string, { id: number; name: string; cals: number; p: number; c: number; f: number; qty: string }[]> = {
- Breakfast: [
- { id: 1, name: 'Greek Yogurt', cals: 130, p: 22, c: 9, f: 0, qty: '1 cup' },
- { id: 2, name: 'Blueberries', cals: 84, p: 1, c: 21, f: 0, qty: '1 cup' },
- { id: 3, name: 'Oats', cals: 150, p: 5, c: 27, f: 3, qty: '0.5 cup' },
- ],
- Lunch: [
- { id: 4, name: 'Chicken Breast', cals: 330, p: 62, c: 0, f: 7, qty: '200g' },
- { id: 5, name: 'Brown Rice', cals: 215, p: 5, c: 45, f: 2, qty: '1 cup' },
- { id: 6, name: 'Broccoli', cals: 55, p: 4, c: 11, f: 1, qty: '1 cup' },
- ],
- Dinner: [],
- Snacks: [
- { id: 7, name: 'Protein Bar', cals: 220, p: 20, c: 25, f: 8, qty: '1 bar' },
- ],
+const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as const
+const MEAL_LABELS: Record<typeof MEALS[number], string> = {
+ breakfast: 'Breakfast', lunch: 'Lunch', dinner: 'Dinner', snacks: 'Snacks'
}
-const TOTALS = { cals: 1184, p: 119, c: 138, f: 21 }
-const TARGETS = { cals: 2000, p: 150, c: 250, f: 65 }
+export default function Food() {
+ const [logs, setLogs] = useState<types.FoodLog[]>([])
+ const [stats, setStats] = useState<types.DailyStats | null>(null)
+ const [settings, setSettings] = useState<types.UserSettings | null>(null)
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState<string | null>(null)
-function MacroChip({ label, value, target, color }: { label: string; value: number; target: number; color: string }) {
- const pct = Math.min(100, (value / target) * 100)
- return (
- <div className="flex-1">
- <div className="flex justify-between items-center mb-1.5">
- <span className="stat-label">{label}</span>
- <span className="text-xs font-semibold text-tx-primary tabular-nums">
- {value}<span className="text-tx-muted font-normal">/{target}g</span>
- </span>
- </div>
- <div className="progress-track">
- <div className="progress-bar" style={{ width: `${pct}%`, background: color }} />
- </div>
- </div>
- )
-}
+ useEffect(() => {
+ const load = async () => {
+ try {
+ const today = format(new Date(), 'yyyy-MM-dd')
+ const [logData, statsData, settingsData] = await Promise.all([
+ foodAPI.list(today),
+ foodAPI.stats(today).catch(() => ({
+ date: today,
+ total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, workout_count: 0
+ })),
+ userAPI.getSettings().catch(() => ({
+ user_id: 0, weight_unit: 'lbs', calorie_target: 2000,
+ protein_target: 150, carb_target: 250, fat_target: 65
+ })),
+ ])
+ setLogs(logData || [])
+ setStats(statsData)
+ setSettings(settingsData)
+ } catch (err: any) {
+ setError(err.message || 'Failed to load food data')
+ } finally {
+ setLoading(false)
+ }
+ }
+ load()
+ }, [])
-export default function Food() {
- const [search, setSearch] = useState('')
- const [activeAdd, setActiveAdd] = useState<string | null>(null)
+ const handleDelete = async (id: number) => {
+ try {
+ await foodAPI.delete(id)
+ setLogs(logs.filter(l => l.id !== id))
+ } catch (err: any) {
+ setError(err.message || 'Failed to delete entry')
+ }
+ }
+
+ if (loading) {
+ return <Loading />
+ }
+
+ if (!settings) {
+ return (
+ <div className="alert-error">
+ <AlertCircle className="w-5 h-5 flex-shrink-0" />
+ <span>Failed to load settings</span>
+ </div>
+ )
+ }
- const remaining = TARGETS.cals - TOTALS.cals
+ const stats_ = stats!
+ const totalCals = stats_.total_calories
+ const remaining = settings.calorie_target - totalCals
return (
<div className="space-y-5 animate-slide-up">
-
{/* Header */}
<div className="flex justify-between items-center">
<div>
<h1 className="font-display font-bold text-2xl text-tx-primary">Nutrition</h1>
<p className="text-tx-muted text-sm mt-0.5">Log meals and track your macros</p>
</div>
- <button className="btn-secondary btn-sm">
- <ChevronRight className="w-3.5 h-3.5 rotate-180" />
- Prev
+ <button className="btn-primary btn-sm">
+ <Plus className="w-3.5 h-3.5" /> Log
</button>
</div>
{/* Daily summary */}
<div className="card p-5">
<div className="flex items-center justify-between mb-5">
- <div className="flex items-center gap-1.5">
- <h2 className="section-title">Today's Summary</h2>
- <HelpTip content="All meals logged today. Targets are set in Settings." />
- </div>
+ <h2 className="section-title">Today's Summary</h2>
<div className={`flex items-center gap-1 text-xs font-medium ${remaining > 0 ? 'text-tx-muted' : 'text-warning-400'}`}>
<Flame className="w-3.5 h-3.5" />
- {remaining > 0 ? `${remaining} kcal remaining` : `${Math.abs(remaining)} kcal over`}
+ {remaining > 0 ? `${remaining.toFixed(0)} kcal left` : `${Math.abs(remaining).toFixed(0)} kcal over`}
</div>
</div>
- {/* Calorie ring placeholder + macros */}
- <div className="flex items-center gap-6">
- {/* Calorie summary */}
- <div className="text-center flex-shrink-0">
- <div className="relative w-20 h-20">
- <svg className="w-20 h-20 -rotate-90" viewBox="0 0 80 80">
- <circle cx="40" cy="40" r="32" fill="none" stroke="var(--surface-overlay)" strokeWidth="8" />
- <circle cx="40" cy="40" r="32" fill="none" stroke="#00b8d9" strokeWidth="8"
- strokeDasharray={`${2 * Math.PI * 32}`}
- strokeDashoffset={`${2 * Math.PI * 32 * (1 - TOTALS.cals / TARGETS.cals)}`}
- strokeLinecap="round"
- />
- </svg>
- <div className="absolute inset-0 flex flex-col items-center justify-center">
- <span className="font-display font-bold text-lg text-tx-primary leading-none tabular-nums">{TOTALS.cals}</span>
- <span className="text-xs text-tx-muted">kcal</span>
- </div>
- </div>
- <p className="text-xs text-tx-muted mt-1">of {TARGETS.cals}</p>
+ <div className="space-y-3">
+ <div className="flex justify-between items-center">
+ <span className="text-sm text-tx-secondary">Calories</span>
+ <span className="stat-value text-2xl">{Math.round(totalCals)} / {settings.calorie_target}</span>
+ </div>
+ <div className="progress-track">
+ <div className="progress-bar" style={{ width: `${Math.min(100, (totalCals / settings.calorie_target) * 100)}%`, background: '#00b8d9' }} />
</div>
- {/* Macro bars */}
- <div className="flex-1 space-y-3">
- <MacroChip label="Protein" value={TOTALS.p} target={TARGETS.p} color="#00b8d9" />
- <MacroChip label="Carbs" value={TOTALS.c} target={TARGETS.c} color="#f59e0b" />
- <MacroChip label="Fat" value={TOTALS.f} target={TARGETS.f} color="#8b5cf6" />
+ <div className="grid grid-cols-3 gap-3 mt-5 pt-3 border-t border-surface-border">
+ <div>
+ <p className="text-xs text-tx-muted">Protein</p>
+ <p className="stat-value text-lg">{Math.round(stats_.total_protein)}/{settings.protein_target}g</p>
+ </div>
+ <div>
+ <p className="text-xs text-tx-muted">Carbs</p>
+ <p className="stat-value text-lg">{Math.round(stats_.total_carbs)}/{settings.carb_target}g</p>
+ </div>
+ <div>
+ <p className="text-xs text-tx-muted">Fat</p>
+ <p className="stat-value text-lg">{Math.round(stats_.total_fat)}/{settings.fat_target}g</p>
+ </div>
</div>
</div>
</div>
{/* Meal sections */}
{MEALS.map(meal => {
- const entries = MOCK_LOG[meal] ?? []
- const mealCals = entries.reduce((sum, e) => sum + e.cals, 0)
- const isAdding = activeAdd === meal
+ const entries = logs.filter(l => l.meal === meal)
+ const mealCals = entries.reduce((sum, e) => sum + e.calories, 0)
return (
<div key={meal} className="card overflow-hidden">
- <div className="flex items-center justify-between px-4 py-3 border-b border-surface-border">
+ <div className="px-4 py-3 border-b border-surface-border flex justify-between items-center">
<div className="flex items-center gap-2">
- <span className="text-sm font-semibold text-tx-primary">{meal}</span>
- {mealCals > 0 && (
- <span className="badge-dim">{mealCals} kcal</span>
- )}
+ <span className="text-sm font-semibold text-tx-primary">{MEAL_LABELS[meal]}</span>
+ {mealCals > 0 && <span className="badge-dim">{Math.round(mealCals)} kcal</span>}
</div>
- <button
- onClick={() => setActiveAdd(isAdding ? null : meal)}
- className="btn-ghost btn-icon-sm"
- >
- {isAdding ? <X className="w-3.5 h-3.5" /> : <Plus className="w-3.5 h-3.5" />}
+ <button className="btn-ghost btn-icon-sm">
+ <Plus className="w-3.5 h-3.5" />
</button>
</div>
- {isAdding && (
- <div className="px-4 py-3 bg-surface-muted border-b border-surface-border animate-slide-up">
- <div className="relative">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-tx-muted pointer-events-none" />
- <input
- autoFocus
- value={search}
- onChange={e => setSearch(e.target.value)}
- className="input pl-9 py-2 text-xs"
- placeholder="Search food database…"
- />
- </div>
- <p className="input-help flex items-center gap-1 mt-2">
- <Info className="w-3 h-3" />
- Search over 300,000 foods from the USDA database
- </p>
- </div>
- )}
-
{entries.length === 0 ? (
<div className="px-4 py-6 text-center">
- <Utensils className="w-5 h-5 text-tx-muted mx-auto mb-2" />
- <p className="text-xs text-tx-muted">Nothing logged yet</p>
+ <p className="text-xs text-tx-muted">No entries</p>
</div>
) : (
<div className="divide-y divide-surface-border">
{entries.map(entry => (
- <div key={entry.id} className="flex items-center justify-between px-4 py-3 hover:bg-surface-muted transition-colors group">
+ <div key={entry.id} className="px-4 py-3 flex justify-between items-center hover:bg-surface-muted transition-colors group">
<div>
<p className="text-sm font-medium text-tx-primary">{entry.name}</p>
- <p className="text-xs text-tx-muted">{entry.qty}</p>
- </div>
- <div className="flex items-center gap-4">
- <div className="hidden sm:flex gap-3 text-xs text-tx-muted tabular-nums">
- <span>{entry.p}g P</span>
- <span>{entry.c}g C</span>
- <span>{entry.f}g F</span>
- </div>
- <span className="text-sm font-semibold text-tx-primary tabular-nums">{entry.cals}</span>
- <button className="btn-icon-sm btn-ghost opacity-0 group-hover:opacity-100 transition-opacity">
- <X className="w-3 h-3" />
- </button>
+ <p className="text-xs text-tx-muted">{Math.round(entry.calories)} kcal · {entry.servings} servings</p>
</div>
+ <button
+ onClick={() => handleDelete(entry.id)}
+ className="btn-ghost btn-icon-sm opacity-0 group-hover:opacity-100 transition-opacity"
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
</div>
))}
</div>
diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsx
index 6aec1ee..3c41824 100644
--- a/web/src/pages/Login.tsx
+++ b/web/src/pages/Login.tsx
@@ -26,16 +26,16 @@ export default function Login() {
}
}
- const handleDemoLogin = () => {
+ const handleDemoLogin = async () => {
setLoading(true)
- setTimeout(() => {
- const demoUser = { id: 1, email: '[email protected]', created_at: new Date().toISOString() }
- localStorage.setItem('access_token', 'demo-token')
- localStorage.setItem('refresh_token', 'demo-refresh')
- localStorage.setItem('user', JSON.stringify(demoUser))
- useAuthStore.setState({ user: demoUser, isAuthenticated: true, isLoading: false })
+ try {
+ await login('[email protected]', 'password123')
navigate('/')
- }, 400)
+ } catch (err: any) {
+ setError(err.response?.data?.error || 'Demo login failed')
+ } finally {
+ setLoading(false)
+ }
}
return (
diff --git a/web/src/pages/Register.tsx b/web/src/pages/Register.tsx
index 077003c..6f7098d 100644
--- a/web/src/pages/Register.tsx
+++ b/web/src/pages/Register.tsx
@@ -20,7 +20,7 @@ export default function Register() {
if (password.length < 8) { setError('Password must be at least 8 characters'); return }
setLoading(true)
try {
- await register(email, password, passwordConfirm)
+ await register(email, password)
navigate('/')
} catch (err: any) {
setError(err.response?.data?.error || 'Registration failed.')
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 99ba801..54d2c43 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -1,14 +1,14 @@
+import { useState, useEffect } from 'react'
import { useAuthStore } from '../stores/auth'
import { useTheme } from '../hooks/useTheme'
+import { userAPI } from '../services/api'
+import * as types from '../types'
import { HelpTip } from '../components/Tooltip'
import {
- User, Shield, Target, Ruler, Moon, Sun,
- Server, LogOut, Trash2, ChevronRight, Check,
+ User, Shield, Target, Moon, Sun, Server, LogOut, Trash2, ChevronRight, Check, AlertCircle, Loader,
} from 'lucide-react'
-function SettingRow({
- label, description, children
-}: { label: string; description?: string; children: React.ReactNode }) {
+function SettingRow({ label, description, children }: { label: string; description?: string; children: React.ReactNode }) {
return (
<div className="flex items-center justify-between py-4">
<div className="flex-1 mr-4">
@@ -33,52 +33,95 @@ function Section({ title, children }: { title: string; children: React.ReactNode
)
}
-function UnitToggle({ value, onChange, options }: {
- value: string; onChange: (v: string) => void; options: string[]
-}) {
- return (
- <div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">
- {options.map(opt => (
- <button
- key={opt}
- onClick={() => onChange(opt)}
- className={`px-3 py-1 rounded-md text-xs font-medium transition-all duration-150 ${
- value === opt
- ? 'bg-surface-raised border border-surface-border text-tx-primary shadow-card'
- : 'text-tx-muted hover:text-tx-primary'
- }`}
- >
- {opt}
- </button>
- ))}
- </div>
- )
-}
-
export default function Settings() {
const { user, logout } = useAuthStore()
const { theme, toggleTheme } = useTheme()
+ const [settings, setSettings] = useState<types.UserSettings | null>(null)
+ const [loading, setLoading] = useState(true)
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [success, setSuccess] = useState(false)
+
+ const [formData, setFormData] = useState({
+ weight_unit: 'lbs' as 'lbs' | 'kg',
+ calorie_target: 2000,
+ protein_target: 150,
+ carb_target: 250,
+ fat_target: 65,
+ })
+
+ useEffect(() => {
+ const load = async () => {
+ try {
+ const data = await userAPI.getSettings()
+ setSettings(data)
+ setFormData({
+ weight_unit: data.weight_unit,
+ calorie_target: data.calorie_target,
+ protein_target: data.protein_target,
+ carb_target: data.carb_target,
+ fat_target: data.fat_target,
+ })
+ } catch (err: any) {
+ setError(err.message || 'Failed to load settings')
+ } finally {
+ setLoading(false)
+ }
+ }
+ load()
+ }, [])
+
+ const handleSave = async () => {
+ setSaving(true)
+ setError(null)
+ setSuccess(false)
+ try {
+ await userAPI.updateSettings(formData)
+ setSuccess(true)
+ setTimeout(() => setSuccess(false), 3000)
+ } catch (err: any) {
+ setError(err.message || 'Failed to save settings')
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center min-h-96">
+ <Loader className="w-6 h-6 animate-spin text-brand-500" />
+ </div>
+ )
+ }
return (
<div className="space-y-5 animate-slide-up max-w-2xl">
-
{/* Header */}
<div>
<h1 className="font-display font-bold text-2xl text-tx-primary">Settings</h1>
<p className="text-tx-muted text-sm mt-0.5">Preferences and account configuration</p>
</div>
+ {error && (
+ <div className="alert-error">
+ <AlertCircle className="w-5 h-5 flex-shrink-0" />
+ <span>{error}</span>
+ </div>
+ )}
+
+ {success && (
+ <div className="alert-success">
+ <Check className="w-5 h-5 flex-shrink-0" />
+ <span>Settings saved successfully</span>
+ </div>
+ )}
+
{/* Account */}
<Section title="Account">
<SettingRow label="Email" description="Your login email address">
<span className="text-sm text-tx-muted font-mono">{user?.email}</span>
</SettingRow>
- <SettingRow label="Password" description="Change your password">
- <button className="btn-secondary btn-sm">
- Change <ChevronRight className="w-3.5 h-3.5" />
- </button>
- </SettingRow>
- <SettingRow label="Member since" description="">
+ <SettingRow label="Member since">
<span className="text-sm text-tx-muted">
{user?.created_at ? new Date(user.created_at).toLocaleDateString('en-US', { month: 'long', year: 'numeric' }) : '—'}
</span>
@@ -88,34 +131,41 @@ export default function Settings() {
{/* Appearance */}
<Section title="Appearance">
<SettingRow label="Theme" description="Interface color scheme">
- <button
- onClick={toggleTheme}
- className="btn-secondary btn-sm"
- >
+ <button onClick={toggleTheme} className="btn-secondary btn-sm">
{theme === 'dark'
? <><Moon className="w-3.5 h-3.5" /> Dark</>
- : <><Sun className="w-3.5 h-3.5" /> Light</>
+ : <><Sun className="w-3.5 h-3.5" /> Light</>
}
</button>
</SettingRow>
</Section>
- {/* Goals & units */}
+ {/* Goals & Units */}
<Section title="Goals & Units">
- <SettingRow
- label="Weight unit"
- description="Displayed across the entire app"
- >
- <UnitToggle value="lbs" onChange={() => {}} options={['lbs', 'kg']} />
+ <SettingRow label="Weight unit" description="Displayed across the entire app">
+ <div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">
+ {(['lbs', 'kg'] as const).map(unit => (
+ <button
+ key={unit}
+ onClick={() => setFormData({ ...formData, weight_unit: unit })}
+ className={`px-3 py-1 rounded-md text-xs font-medium transition-all ${
+ formData.weight_unit === unit
+ ? 'bg-surface-raised border border-surface-border text-tx-primary'
+ : 'text-tx-muted hover:text-tx-primary'
+ }`}
+ >
+ {unit}
+ </button>
+ ))}
+ </div>
</SettingRow>
- <SettingRow
- label="Calorie target"
- description="Daily calorie goal"
- >
+
+ <SettingRow label="Calorie target" description="Daily calorie goal">
<div className="flex items-center gap-2">
<input
type="number"
- defaultValue={2000}
+ value={formData.calorie_target}
+ onChange={e => setFormData({ ...formData, calorie_target: parseInt(e.target.value) || 0 })}
className="input w-24 text-right"
min={500}
max={10000}
@@ -123,73 +173,83 @@ export default function Settings() {
<span className="text-xs text-tx-muted">kcal</span>
</div>
</SettingRow>
- <SettingRow label="Protein target" description="">
+
+ <SettingRow label="Protein target" description="Daily protein goal">
<div className="flex items-center gap-2">
- <input type="number" defaultValue={150} className="input w-24 text-right" />
+ <input
+ type="number"
+ value={formData.protein_target}
+ onChange={e => setFormData({ ...formData, protein_target: parseInt(e.target.value) || 0 })}
+ className="input w-24 text-right"
+ />
<span className="text-xs text-tx-muted">g</span>
</div>
</SettingRow>
- <SettingRow label="Carb target" description="">
+
+ <SettingRow label="Carb target" description="Daily carb goal">
<div className="flex items-center gap-2">
- <input type="number" defaultValue={250} className="input w-24 text-right" />
+ <input
+ type="number"
+ value={formData.carb_target}
+ onChange={e => setFormData({ ...formData, carb_target: parseInt(e.target.value) || 0 })}
+ className="input w-24 text-right"
+ />
<span className="text-xs text-tx-muted">g</span>
</div>
</SettingRow>
- <SettingRow label="Fat target" description="">
+
+ <SettingRow label="Fat target" description="Daily fat goal">
<div className="flex items-center gap-2">
- <input type="number" defaultValue={65} className="input w-24 text-right" />
+ <input
+ type="number"
+ value={formData.fat_target}
+ onChange={e => setFormData({ ...formData, fat_target: parseInt(e.target.value) || 0 })}
+ className="input w-24 text-right"
+ />
<span className="text-xs text-tx-muted">g</span>
</div>
</SettingRow>
+
<div className="py-3 flex justify-end">
- <button className="btn-primary btn-sm">
- <Check className="w-3.5 h-3.5" /> Save goals
+ <button
+ onClick={handleSave}
+ disabled={saving}
+ className="btn-primary btn-sm"
+ >
+ <Check className="w-3.5 h-3.5" /> {saving ? 'Saving...' : 'Save'}
</button>
</div>
</Section>
{/* Server info */}
<Section title="Self-Hosted Instance">
- <SettingRow
- label="API server"
- description="Backend server this client is connected to"
- >
+ <SettingRow label="API server" description="Backend server this client is connected to">
<div className="flex items-center gap-2">
<span className="w-1.5 h-1.5 rounded-full bg-success-500 flex-shrink-0" />
<span className="text-xs font-mono text-tx-muted">localhost:3000</span>
</div>
</SettingRow>
- <SettingRow
- label="Database"
- description="Storage backend"
- >
+ <SettingRow label="Database" description="Storage backend">
<span className="badge-dim">SQLite</span>
</SettingRow>
- <SettingRow
- label="Version"
- description="lyftr backend version"
- >
+ <SettingRow label="Version" description="lyftr backend version">
<span className="text-xs text-tx-muted font-mono">v0.1.0</span>
</SettingRow>
</Section>
- {/* Danger zone */}
+ {/* Danger Zone */}
<Section title="Danger Zone">
<SettingRow label="Sign out" description="Log out of this device">
<button onClick={() => logout()} className="btn-secondary btn-sm">
<LogOut className="w-3.5 h-3.5" /> Sign out
</button>
</SettingRow>
- <SettingRow
- label="Delete account"
- description="Permanently delete all your data from this server"
- >
+ <SettingRow label="Delete account" description="Permanently delete all your data">
<button className="btn-danger btn-sm">
<Trash2 className="w-3.5 h-3.5" /> Delete
</button>
</SettingRow>
</Section>
-
</div>
)
}
diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsx
index 5335f56..8f26ae9 100644
--- a/web/src/pages/Weight.tsx
+++ b/web/src/pages/Weight.tsx
@@ -1,36 +1,95 @@
-import { useState } from 'react'
-import { TrendingDown, TrendingUp, Plus, Calendar, Info } from 'lucide-react'
+import { useState, useEffect } from 'react'
+import { TrendingDown, TrendingUp, Plus, Calendar, Info, AlertCircle } from 'lucide-react'
+import { format, subDays } from 'date-fns'
import { HelpTip } from '../components/Tooltip'
+import Loading from '../components/Loading'
+import { weightAPI } from '../services/api'
+import * as types from '../types'
const PERIODS = ['7d', '30d', '90d', 'All'] as const
type Period = typeof PERIODS[number]
-const MOCK_ENTRIES = [
- { date: 'Apr 18', value: 185.0 },
- { date: 'Apr 17', value: 185.2 },
- { date: 'Apr 16', value: 185.5 },
- { date: 'Apr 15', value: 186.0 },
- { date: 'Apr 14', value: 186.2 },
- { date: 'Apr 13', value: 186.5 },
- { date: 'Apr 12', value: 187.0 },
-]
-
-const avg = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length
+const getPeriodDays = (p: Period) => {
+ const map: Record<Period, number> = { '7d': 7, '30d': 30, '90d': 90, 'All': 999 }
+ return map[p]
+}
export default function Weight() {
const [period, setPeriod] = useState<Period>('30d')
const [newWeight, setNewWeight] = useState('')
+ const [logs, setLogs] = useState<types.WeightLog[]>([])
+ const [stats, setStats] = useState<types.WeightStats | null>(null)
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState<string | null>(null)
+ const [logging, setLogging] = useState(false)
+
+ useEffect(() => {
+ const load = async () => {
+ try {
+ const [logData, statsData] = await Promise.all([
+ weightAPI.list({ limit: 100 }),
+ weightAPI.stats(),
+ ])
+ setLogs(logData || [])
+ setStats(statsData)
+ } catch (err: any) {
+ setError(err.message || 'Failed to load weight data')
+ } finally {
+ setLoading(false)
+ }
+ }
+ load()
+ }, [])
+
+ const daysToShow = getPeriodDays(period)
+ const filtered = logs.filter(l => {
+ const logDate = new Date(l.logged_at)
+ const daysDiff = Math.floor((Date.now() - logDate.getTime()) / (1000 * 60 * 60 * 24))
+ return daysDiff <= daysToShow
+ })
+
+ const handleLog = async () => {
+ if (!newWeight) return
+ setLogging(true)
+ try {
+ await weightAPI.log({ weight: parseFloat(newWeight) })
+ setNewWeight('')
+ const [logData, statsData] = await Promise.all([
+ weightAPI.list({ limit: 100 }),
+ weightAPI.stats(),
+ ])
+ setLogs(logData || [])
+ setStats(statsData)
+ } catch (err: any) {
+ setError(err.message || 'Failed to log weight')
+ } finally {
+ setLogging(false)
+ }
+ }
- const values = MOCK_ENTRIES.map(e => e.value)
- const current = values[0]
- const change = +(current - values[values.length - 1]).toFixed(1)
- const average = +avg(values).toFixed(1)
- const min = Math.min(...values)
- const max = Math.max(...values)
+ if (loading) {
+ return <Loading />
+ }
+
+ if (error) {
+ return (
+ <div className="alert-error">
+ <AlertCircle className="w-5 h-5 flex-shrink-0" />
+ <span>{error}</span>
+ </div>
+ )
+ }
+
+ const values = filtered.map(l => l.weight)
+ const current = values[0] || stats?.latest || 0
+ const oldest = values[values.length - 1] || stats?.starting || 0
+ const change = +(current - oldest).toFixed(1)
+ const avg = values.length > 0 ? +(values.reduce((a, b) => a + b, 0) / values.length).toFixed(1) : 0
+ const min = values.length > 0 ? Math.min(...values) : 0
+ const max = values.length > 0 ? Math.max(...values) : 0
return (
<div className="space-y-5 animate-slide-up">
-
{/* Header */}
<div className="flex justify-between items-center">
<div>
@@ -48,7 +107,7 @@ export default function Weight() {
<div>
<p className="stat-label mb-2">Current Weight</p>
<div className="flex items-end gap-2">
- <span className="stat-value text-5xl">{current}</span>
+ <span className="stat-value text-5xl">{current.toFixed(1)}</span>
<span className="text-tx-muted text-lg mb-1">lbs</span>
</div>
</div>
@@ -58,39 +117,36 @@ export default function Weight() {
: 'bg-error-500/10 border border-error-500/20 text-error-400'
}`}>
{change < 0 ? <TrendingDown className="w-4 h-4" /> : <TrendingUp className="w-4 h-4" />}
- {Math.abs(change)} lbs
+ {Math.abs(change).toFixed(1)} lbs
</div>
</div>
<p className="text-xs text-tx-muted mt-3">
- {Math.abs(change)} lbs {change < 0 ? 'lost' : 'gained'} over {period}
+ {Math.abs(change).toFixed(1)} lbs {change < 0 ? 'lost' : 'gained'} over {period}
</p>
</div>
{/* Stats row */}
<div className="grid grid-cols-3 gap-3">
{[
- { label: 'Average', value: average, tip: 'Rolling average weight for selected period' },
- { label: 'Lowest', value: min, tip: 'Lowest recorded weight in selected period' },
- { label: 'Highest', value: max, tip: 'Highest recorded weight in selected period' },
+ { label: 'Average', value: avg, tip: 'Average weight for selected period' },
+ { label: 'Lowest', value: min, tip: 'Lowest recorded weight' },
+ { label: 'Highest', value: max, tip: 'Highest recorded weight' },
].map(s => (
<div key={s.label} className="card p-4">
<div className="flex items-center gap-1.5 mb-2">
<span className="stat-label">{s.label}</span>
<HelpTip content={s.tip} />
</div>
- <span className="stat-value text-xl">{s.value}</span>
+ <span className="stat-value text-xl">{s.value.toFixed(1)}</span>
<span className="text-xs text-tx-muted ml-1">lbs</span>
</div>
))}
</div>
- {/* Chart placeholder + period selector */}
+ {/* Chart + period selector */}
<div className="card p-5">
<div className="flex items-center justify-between mb-5">
- <div className="flex items-center gap-1.5">
- <h2 className="section-title">Trend</h2>
- <HelpTip content="Smoothed rolling average — individual daily fluctuations are normal" />
- </div>
+ <h2 className="section-title">Trend</h2>
<div className="flex gap-1 bg-surface-overlay rounded-lg p-1">
{PERIODS.map(p => (
<button
@@ -108,10 +164,10 @@ export default function Weight() {
</div>
</div>
- {/* Mini chart — visual weight trend using div bars */}
+ {/* Mini chart */}
<div className="flex items-end gap-1 h-24 mb-1">
- {MOCK_ENTRIES.slice().reverse().map((entry, i) => {
- const pct = ((entry.value - min) / (max - min || 1)) * 100
+ {filtered.slice().reverse().map((entry, i) => {
+ const pct = max > min ? ((entry.weight - min) / (max - min)) * 100 : 50
const height = 20 + pct * 0.8
return (
<div key={i} className="flex-1 flex flex-col items-center gap-1 group relative">
@@ -120,23 +176,23 @@ export default function Weight() {
style={{ height: `${height}%` }}
/>
<div className="absolute -top-6 left-1/2 -translate-x-1/2 opacity-0 group-hover:opacity-100 transition-opacity bg-surface-overlay border border-surface-border rounded px-1.5 py-0.5 text-xs text-tx-primary whitespace-nowrap z-10">
- {entry.value} lbs
+ {entry.weight.toFixed(1)} lbs
</div>
</div>
)
})}
</div>
- <div className="flex justify-between text-xs text-tx-muted mt-1">
- <span>{MOCK_ENTRIES[MOCK_ENTRIES.length - 1].date}</span>
- <span>{MOCK_ENTRIES[0].date}</span>
- </div>
+ {filtered.length > 0 && (
+ <div className="flex justify-between text-xs text-tx-muted mt-1">
+ <span>{format(new Date(filtered[filtered.length - 1].logged_at), 'MMM d')}</span>
+ <span>{format(new Date(filtered[0].logged_at), 'MMM d')}</span>
+ </div>
+ )}
</div>
{/* Log weight */}
<div className="card p-5">
- <div className="section-header">
- <h2 className="section-title">Log Today's Weight</h2>
- </div>
+ <h2 className="section-title mb-3">Log Today's Weight</h2>
<div className="flex gap-2">
<div className="relative flex-1">
<input
@@ -149,8 +205,12 @@ export default function Weight() {
/>
<span className="absolute right-3.5 top-1/2 -translate-y-1/2 text-xs text-tx-muted">lbs</span>
</div>
- <button className="btn-primary btn-md" disabled={!newWeight}>
- <Plus className="w-4 h-4" /> Log
+ <button
+ onClick={handleLog}
+ disabled={!newWeight || logging}
+ className="btn-primary btn-md"
+ >
+ <Plus className="w-4 h-4" /> {logging ? 'Logging...' : 'Log'}
</button>
</div>
<p className="input-help flex items-center gap-1 mt-2">
@@ -159,30 +219,31 @@ export default function Weight() {
</p>
</div>
- {/* Log entries */}
- <div className="card p-5">
- <h2 className="section-title mb-4">History</h2>
- <div className="space-y-0 divide-y divide-surface-border">
- {MOCK_ENTRIES.map((entry, i) => (
- <div key={i} className="flex items-center justify-between py-3">
- <span className="text-sm text-tx-secondary">{entry.date}</span>
- <div className="flex items-center gap-3">
- {i < MOCK_ENTRIES.length - 1 && (
- <span className={`text-xs font-medium ${
- entry.value < MOCK_ENTRIES[i + 1].value ? 'text-success-400' : 'text-error-400'
- }`}>
- {entry.value < MOCK_ENTRIES[i + 1].value ? '↓' : '↑'}
- {Math.abs(+(entry.value - MOCK_ENTRIES[i + 1].value).toFixed(1))}
- </span>
- )}
- <span className="text-sm font-semibold text-tx-primary tabular-nums">
- {entry.value} lbs
- </span>
- </div>
- </div>
- ))}
+ {/* History */}
+ {logs.length > 0 && (
+ <div className="card p-5">
+ <h2 className="section-title mb-4">History</h2>
+ <div className="space-y-0 divide-y divide-surface-border">
+ {logs.slice(0, 20).map((entry, i) => {
+ const next = logs[i + 1]
+ const delta = next ? entry.weight - next.weight : 0
+ return (
+ <div key={entry.id} className="flex items-center justify-between py-3">
+ <span className="text-sm text-tx-secondary">{format(new Date(entry.logged_at), 'MMM d')}</span>
+ <div className="flex items-center gap-3">
+ {delta !== 0 && (
+ <span className={`text-xs font-medium ${delta < 0 ? 'text-success-400' : 'text-error-400'}`}>
+ {delta < 0 ? '↓' : '↑'}{Math.abs(delta).toFixed(1)}
+ </span>
+ )}
+ <span className="text-sm font-semibold text-tx-primary">{entry.weight.toFixed(1)} lbs</span>
+ </div>
+ </div>
+ )
+ })}
+ </div>
</div>
- </div>
+ )}
</div>
)
}
diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsx
index 5c0955c..5ff2330 100644
--- a/web/src/pages/Workouts.tsx
+++ b/web/src/pages/Workouts.tsx
@@ -1,41 +1,14 @@
-import { useState } from 'react'
-import { Dumbbell, Plus, ChevronRight, BarChart2, Clock, Weight, Search, Filter, Info } from 'lucide-react'
-import { HelpTip, Tooltip } from '../components/Tooltip'
+import { useState, useEffect } from 'react'
+import { format } from 'date-fns'
+import { Dumbbell, Plus, ChevronRight, BarChart2, Clock, Weight, Search, AlertCircle } from 'lucide-react'
+import { HelpTip } from '../components/Tooltip'
+import Loading from '../components/Loading'
+import { workoutAPI } from '../services/api'
+import * as types from '../types'
-const MOCK_WORKOUTS = [
- {
- id: 1, date: 'Today', name: 'Push Day',
- exercises: [
- { name: 'Bench Press', sets: 4, reps: 8, weight: 275 },
- { name: 'Incline Dumbbell', sets: 3, reps: 10, weight: 85 },
- { name: 'Cable Fly', sets: 3, reps: 12, weight: 40 },
- { name: 'Overhead Press', sets: 4, reps: 8, weight: 155 },
- { name: 'Tricep Pushdown', sets: 3, reps: 12, weight: 60 },
- ],
- duration: '58 min', volume: 32450,
- },
- {
- id: 2, date: 'Yesterday', name: 'Cardio',
- exercises: [
- { name: 'Treadmill Run', sets: 1, reps: 1, weight: 0 },
- ],
- duration: '45 min', volume: 0,
- },
- {
- id: 3, date: 'Apr 16', name: 'Pull Day',
- exercises: [
- { name: 'Barbell Row', sets: 4, reps: 8, weight: 225 },
- { name: 'Lat Pulldown', sets: 3, reps: 10, weight: 140 },
- { name: 'Seated Cable Row',sets: 3, reps: 12, weight: 120 },
- { name: 'Face Pull', sets: 3, reps: 15, weight: 50 },
- { name: 'Barbell Curl', sets: 3, reps: 10, weight: 95 },
- ],
- duration: '62 min', volume: 28100,
- },
-]
-
-function WorkoutCard({ workout }: { workout: typeof MOCK_WORKOUTS[0] }) {
+function WorkoutCard({ workout }: { workout: types.Workout }) {
const [open, setOpen] = useState(false)
+ const durationMin = Math.round(workout.duration / 60)
return (
<div className="card overflow-hidden">
@@ -49,21 +22,16 @@ function WorkoutCard({ workout }: { workout: typeof MOCK_WORKOUTS[0] }) {
</div>
<div className="text-left">
<p className="text-sm font-semibold text-tx-primary">{workout.name}</p>
- <p className="text-xs text-tx-muted">{workout.date}</p>
+ <p className="text-xs text-tx-muted">{format(new Date(workout.started_at), 'MMM d, yyyy')}</p>
</div>
</div>
<div className="flex items-center gap-4">
<div className="hidden sm:flex items-center gap-4 text-xs text-tx-muted">
<span className="flex items-center gap-1">
- <Clock className="w-3.5 h-3.5" /> {workout.duration}
+ <Clock className="w-3.5 h-3.5" /> {durationMin} min
</span>
- {workout.volume > 0 && (
- <span className="flex items-center gap-1">
- <Weight className="w-3.5 h-3.5" /> {workout.volume.toLocaleString()} lbs
- </span>
- )}
<span className="flex items-center gap-1">
- <BarChart2 className="w-3.5 h-3.5" /> {workout.exercises.length} exercises
+ <BarChart2 className="w-3.5 h-3.5" /> {workout.exercises?.length || 0} exercises
</span>
</div>
<ChevronRight className={`w-4 h-4 text-tx-muted transition-transform duration-200 ${open ? 'rotate-90' : ''}`} />
@@ -75,22 +43,24 @@ function WorkoutCard({ workout }: { workout: typeof MOCK_WORKOUTS[0] }) {
<div className="px-4 py-2">
<div className="grid grid-cols-4 text-xs text-tx-muted uppercase tracking-wider py-2 border-b border-surface-border">
<span className="col-span-2">Exercise</span>
- <span className="text-right">Sets × Reps</span>
- <span className="text-right">Weight</span>
+ <span className="text-right">Sets</span>
+ <span className="text-right">Avg Weight</span>
</div>
- {workout.exercises.map((ex, i) => (
- <div key={i} className="grid grid-cols-4 text-sm py-2.5 border-b border-surface-border last:border-0">
- <span className="col-span-2 text-tx-primary font-medium">{ex.name}</span>
- <span className="text-right text-tx-secondary tabular-nums">{ex.sets} × {ex.reps}</span>
- <span className="text-right text-tx-muted tabular-nums">
- {ex.weight > 0 ? `${ex.weight} lbs` : '—'}
- </span>
- </div>
- ))}
+ {workout.exercises?.map((ex) => {
+ const avgWeight = ex.sets?.length > 0
+ ? (ex.sets.reduce((sum, s) => sum + (s.weight || 0), 0) / ex.sets.length).toFixed(0)
+ : '—'
+ return (
+ <div key={ex.id} className="grid grid-cols-4 text-sm py-2.5 border-b border-surface-border last:border-0">
+ <span className="col-span-2 text-tx-primary font-medium">{ex.exercise.name}</span>
+ <span className="text-right text-tx-secondary tabular-nums">{ex.sets?.length || 0}</span>
+ <span className="text-right text-tx-muted tabular-nums">{avgWeight} lbs</span>
+ </div>
+ )
+ })}
</div>
<div className="flex justify-end gap-2 px-4 py-3 bg-surface-muted">
- <button className="btn-ghost btn-sm">Duplicate</button>
- <button className="btn-secondary btn-sm">Edit</button>
+ <button className="btn-ghost btn-sm">Details</button>
</div>
</div>
)}
@@ -99,17 +69,44 @@ function WorkoutCard({ workout }: { workout: typeof MOCK_WORKOUTS[0] }) {
}
export default function Workouts() {
+ const [workouts, setWorkouts] = useState<types.Workout[]>([])
const [search, setSearch] = useState('')
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState<string | null>(null)
+
+ useEffect(() => {
+ const load = async () => {
+ try {
+ const data = await workoutAPI.list({ limit: 50 })
+ setWorkouts(data || [])
+ } catch (err: any) {
+ setError(err.message || 'Failed to load workouts')
+ } finally {
+ setLoading(false)
+ }
+ }
+ load()
+ }, [])
- const filtered = MOCK_WORKOUTS.filter(w =>
+ const filtered = workouts.filter(w =>
w.name.toLowerCase().includes(search.toLowerCase())
)
- const weekVolume = MOCK_WORKOUTS.reduce((sum, w) => sum + w.volume, 0)
+ if (loading) {
+ return <Loading />
+ }
+
+ if (error) {
+ return (
+ <div className="alert-error">
+ <AlertCircle className="w-5 h-5 flex-shrink-0" />
+ <span>{error}</span>
+ </div>
+ )
+ }
return (
<div className="space-y-5 animate-slide-up">
-
{/* Header */}
<div className="flex justify-between items-center">
<div>
@@ -121,17 +118,16 @@ export default function Workouts() {
</button>
</div>
- {/* This week summary */}
+ {/* Summary */}
<div className="grid grid-cols-3 gap-3">
{[
- { label: 'Sessions', value: '3', unit: 'this week', icon: Dumbbell, tip: 'Total workouts logged this week' },
- { label: 'Total Volume',value: weekVolume.toLocaleString(), unit: 'lbs lifted', icon: Weight, tip: 'Sum of sets × reps × weight across all exercises' },
- { label: 'Avg Duration',value: '55', unit: 'min / session', icon: Clock, tip: 'Average workout duration this week' },
+ { label: 'Total', value: workouts.length.toString(), unit: 'workouts', icon: Dumbbell },
+ { label: 'This Month', value: workouts.filter(w => new Date(w.started_at).getMonth() === new Date().getMonth()).length.toString(), unit: 'sessions', icon: Clock },
+ { label: 'Avg Duration', value: workouts.length > 0 ? Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60).toString() : '0', unit: 'min', icon: Clock },
].map(s => (
<div key={s.label} className="card p-4">
<div className="flex items-center gap-1.5 mb-2">
<span className="stat-label">{s.label}</span>
- <HelpTip content={s.tip} />
</div>
<div className="flex items-end gap-1.5">
<span className="stat-value text-xl">{s.value}</span>
@@ -160,7 +156,7 @@ export default function Workouts() {
<Dumbbell className="w-6 h-6 text-tx-muted" />
</div>
<p className="text-sm font-medium text-tx-primary mb-1">No workouts found</p>
- <p className="text-xs text-tx-muted">Try a different search or log a new workout.</p>
+ <p className="text-xs text-tx-muted">{search ? 'Try a different search' : 'Log a workout to get started'}</p>
</div>
) : (
filtered.map(w => <WorkoutCard key={w.id} workout={w} />)
diff --git a/web/src/services/api.ts b/web/src/services/api.ts
index b141ad5..4f91c5a 100644
--- a/web/src/services/api.ts
+++ b/web/src/services/api.ts
@@ -1,90 +1,87 @@
import axios, { AxiosInstance } from 'axios'
import * as types from '../types'
-const API_BASE = (import.meta.env.VITE_API_URL as string) || 'http://localhost:3000/api'
+const API_BASE = (import.meta.env.VITE_API_URL as string) || 'http://localhost:3000/api/v1'
const api: AxiosInstance = axios.create({
baseURL: API_BASE,
- headers: {
- 'Content-Type': 'application/json',
- },
+ headers: { 'Content-Type': 'application/json' },
})
api.interceptors.request.use((config) => {
const token = localStorage.getItem('access_token')
- if (token) {
- config.headers.Authorization = `Bearer ${token}`
- }
+ if (token) config.headers.Authorization = `Bearer ${token}`
return config
})
api.interceptors.response.use(
(response) => response,
async (error) => {
- const originalRequest = error.config
-
- if (error.response?.status === 401 && !originalRequest._retry) {
- originalRequest._retry = true
+ const original = error.config
+ if (error.response?.status === 401 && !original._retry) {
+ original._retry = true
try {
const refreshToken = localStorage.getItem('refresh_token')
- const response = await axios.post(`${API_BASE}/auth/refresh`, { refresh_token: refreshToken })
- localStorage.setItem('access_token', response.data.access_token)
- originalRequest.headers.Authorization = `Bearer ${response.data.access_token}`
- return api(originalRequest)
+ const res = await axios.post(`${API_BASE}/auth/refresh`, { refresh_token: refreshToken })
+ const newToken = res.data.data.token
+ localStorage.setItem('access_token', newToken)
+ original.headers.Authorization = `Bearer ${newToken}`
+ if (res.data.data.refresh_token) {
+ localStorage.setItem('refresh_token', res.data.data.refresh_token)
+ }
+ return api(original)
} catch {
localStorage.removeItem('access_token')
localStorage.removeItem('refresh_token')
+ localStorage.removeItem('user')
window.location.href = '/login'
}
}
-
return Promise.reject(error)
}
)
+const unwrap = <T>(res: { data: { data: T } }) => res.data.data
+
export const authAPI = {
- login: (data: types.LoginRequest) => api.post<types.AuthResponse>('/auth/login', data),
- register: (data: types.RegisterRequest) => api.post<types.AuthResponse>('/auth/register', data),
- logout: () => api.post('/auth/logout'),
+ login: (data: types.LoginRequest) => api.post<{ data: types.AuthResponse }>('/auth/login', data).then(res => unwrap(res)),
+ register: (data: types.RegisterRequest) => api.post<{ data: types.AuthResponse }>('/auth/register', data).then(res => unwrap(res)),
+}
+
+export const userAPI = {
+ me: () => api.get<{ data: types.User }>('/me').then(res => unwrap(res)),
+ getSettings: () => api.get<{ data: types.UserSettings }>('/settings').then(res => unwrap(res)),
+ updateSettings: (data: Partial<types.UserSettings>) => api.put<{ data: types.UserSettings }>('/settings', data).then(res => unwrap(res)),
+ deleteAccount: () => api.delete('/me'),
}
export const workoutAPI = {
- list: (params?: { start_date?: string; end_date?: string }) =>
- api.get<types.Workout[]>('/workouts', { params }),
- get: (id: number) => api.get<types.Workout>(`/workouts/${id}`),
- create: (data: Omit<types.Workout, 'id' | 'created_at'>) =>
- api.post<types.Workout>('/workouts', data),
- update: (id: number, data: Partial<types.Workout>) =>
- api.put<types.Workout>(`/workouts/${id}`, data),
+ list: (params?: { limit?: number; offset?: number }) =>
+ api.get<{ data: types.Workout[] }>('/workouts', { params }).then(res => unwrap(res)),
+ get: (id: number) => api.get<{ data: types.Workout }>(`/workouts/${id}`).then(res => unwrap(res)),
+ create: (data: any) => api.post<{ data: types.Workout }>('/workouts', data).then(res => unwrap(res)),
delete: (id: number) => api.delete(`/workouts/${id}`),
}
export const exerciseAPI = {
- list: () => api.get<types.Exercise[]>('/exercises'),
- search: (q: string) => api.get<types.Exercise[]>('/exercises', { params: { q } }),
-}
-
-export const foodAPI = {
- list: (date: string) => api.get<types.FoodLog[]>('/food-logs', { params: { date } }),
- search: (q: string) => api.get<any>('/food-search', { params: { q } }),
- create: (data: Omit<types.FoodLog, 'id'>) => api.post<types.FoodLog>('/food-logs', data),
- update: (id: number, data: Partial<types.FoodLog>) =>
- api.put<types.FoodLog>(`/food-logs/${id}`, data),
- delete: (id: number) => api.delete(`/food-logs/${id}`),
+ list: (params?: { q?: string; muscle_group?: string; category?: string; equipment?: string }) =>
+ api.get<{ data: types.Exercise[] }>('/exercises', { params }).then(res => unwrap(res)),
+ get: (id: number) => api.get<{ data: types.Exercise }>(`/exercises/${id}`).then(res => unwrap(res)),
}
export const weightAPI = {
- list: (params?: { start_date?: string; end_date?: string }) =>
- api.get<types.Weight[]>('/weight', { params }),
- create: (data: Omit<types.Weight, 'id'>) => api.post<types.Weight>('/weight', data),
- update: (id: number, data: Partial<types.Weight>) =>
- api.put<types.Weight>(`/weight/${id}`, data),
+ list: (params?: { limit?: number }) => api.get<{ data: types.WeightLog[] }>('/weight', { params }).then(res => unwrap(res)),
+ log: (data: { weight: number; notes?: string; logged_at?: string }) =>
+ api.post<{ data: types.WeightLog }>('/weight', data).then(res => unwrap(res)),
delete: (id: number) => api.delete(`/weight/${id}`),
+ stats: () => api.get<{ data: types.WeightStats }>('/weight/stats').then(res => unwrap(res)),
}
-export const userAPI = {
- getProfile: () => api.get<types.User>('/user'),
- updateProfile: (data: Partial<types.User>) => api.put<types.User>('/user', data),
+export const foodAPI = {
+ list: (date?: string) => api.get<{ data: types.FoodLog[] }>('/food', { params: { date } }).then(res => unwrap(res)),
+ log: (data: any) => api.post<{ data: types.FoodLog }>('/food', data).then(res => unwrap(res)),
+ delete: (id: number) => api.delete(`/food/${id}`),
+ stats: (date?: string) => api.get<{ data: types.DailyStats }>('/food/stats', { params: { date } }).then(res => unwrap(res)),
}
export default api
diff --git a/web/src/stores/auth.ts b/web/src/stores/auth.ts
index 0161deb..875b6ef 100644
--- a/web/src/stores/auth.ts
+++ b/web/src/stores/auth.ts
@@ -7,19 +7,16 @@ interface AuthStore {
isAuthenticated: boolean
isLoading: boolean
error: string | null
-
- login: (email: string, password: string) => Promise<void>
- register: (email: string, password: string, passwordConfirm: string) => Promise<void>
- logout: () => Promise<void>
- setUser: (user: types.User | null) => void
+ login: (email: string, password: string) => Promise<void>
+ register: (email: string, password: string) => Promise<void>
+ logout: () => void
clearError: () => void
}
export const useAuthStore = create<AuthStore>((set) => {
- // Hydrate from localStorage on init
- const token = localStorage.getItem('access_token')
+ const token = localStorage.getItem('access_token')
const userStr = localStorage.getItem('user')
- const user = userStr ? JSON.parse(userStr) : null
+ const user = userStr ? JSON.parse(userStr) : null
return {
user,
@@ -27,55 +24,41 @@ export const useAuthStore = create<AuthStore>((set) => {
isLoading: false,
error: null,
- login: async (email: string, password: string) => {
+ login: async (email, password) => {
set({ isLoading: true, error: null })
try {
- const response = await authAPI.login({ email, password })
- localStorage.setItem('access_token', response.data.access_token)
- localStorage.setItem('refresh_token', response.data.refresh_token)
- localStorage.setItem('user', JSON.stringify(response.data.user))
- set({ user: response.data.user, isAuthenticated: true, isLoading: false })
- } catch (error: any) {
- const message = error.response?.data?.error || 'Login failed'
- set({ error: message, isLoading: false })
- throw error
+ const data = await authAPI.login({ email, password })
+ localStorage.setItem('access_token', data.token)
+ localStorage.setItem('refresh_token', data.refresh_token)
+ localStorage.setItem('user', JSON.stringify(data.user))
+ set({ user: data.user, isAuthenticated: true, isLoading: false })
+ } catch (err: any) {
+ set({ error: err.response?.data?.error || 'Login failed', isLoading: false })
+ throw err
}
},
- register: async (email: string, password: string, passwordConfirm: string) => {
+ register: async (email, password) => {
set({ isLoading: true, error: null })
try {
- const response = await authAPI.register({ email, password, password_confirm: passwordConfirm })
- localStorage.setItem('access_token', response.data.access_token)
- localStorage.setItem('refresh_token', response.data.refresh_token)
- localStorage.setItem('user', JSON.stringify(response.data.user))
- set({ user: response.data.user, isAuthenticated: true, isLoading: false })
- } catch (error: any) {
- const message = error.response?.data?.error || 'Registration failed'
- set({ error: message, isLoading: false })
- throw error
+ const data = await authAPI.register({ email, password })
+ localStorage.setItem('access_token', data.token)
+ localStorage.setItem('refresh_token', data.refresh_token)
+ localStorage.setItem('user', JSON.stringify(data.user))
+ set({ user: data.user, isAuthenticated: true, isLoading: false })
+ } catch (err: any) {
+ set({ error: err.response?.data?.error || 'Registration failed', isLoading: false })
+ throw err
}
},
- logout: async () => {
- try {
- await authAPI.logout()
- } catch {
- // Continue logout even if API call fails
- }
+ logout: () => {
localStorage.removeItem('access_token')
localStorage.removeItem('refresh_token')
localStorage.removeItem('user')
set({ user: null, isAuthenticated: false, error: null })
},
- setUser: (user) => {
- set({ user })
- if (user) {
- localStorage.setItem('user', JSON.stringify(user))
- }
- },
-
clearError: () => set({ error: null }),
}
})
diff --git a/web/src/types.ts b/web/src/types.ts
index 1b5c531..3864b91 100644
--- a/web/src/types.ts
+++ b/web/src/types.ts
@@ -2,66 +2,104 @@ export interface User {
id: number
email: string
created_at: string
+ updated_at?: string
}
-export interface Workout {
- id: number
- date: string
- exercises: WorkoutExercise[]
- created_at: string
+export interface UserSettings {
+ user_id: number
+ weight_unit: 'lbs' | 'kg'
+ calorie_target: number
+ protein_target: number
+ carb_target: number
+ fat_target: number
}
-export interface WorkoutExercise {
+export interface Exercise {
id: number
- exercise_id: number
name: string
- sets: Set[]
- notes?: string
+ muscle_group: string
+ secondary_muscles: string[]
+ category: string
+ equipment: string
+ description: string
+ image_url?: string
+ video_url?: string
}
export interface Set {
+ id?: number
+ set_number: number
reps: number
weight: number
+ duration?: number
+ distance?: number
+ rpe?: number
+ is_warmup?: boolean
}
-export interface Exercise {
+export interface WorkoutExercise {
+ id?: number
+ workout_id?: number
+ exercise_id: number
+ order_index?: number
+ notes?: string
+ exercise: Exercise
+ sets: Set[]
+}
+
+export interface Workout {
id: number
+ user_id?: number
name: string
- category: 'push' | 'pull' | 'legs' | 'cardio' | 'other'
- equipment?: string
- muscle_groups: string[]
+ notes?: string
+ duration: number
+ started_at: string
+ created_at: string
+ exercises: WorkoutExercise[]
+}
+
+export interface WeightLog {
+ id: number
+ user_id?: number
+ weight: number
+ notes?: string
+ logged_at: string
+ created_at?: string
}
export interface FoodLog {
id: number
- date: string
- food_name: string
+ user_id?: number
+ name: string
+ meal: 'breakfast' | 'lunch' | 'dinner' | 'snacks'
calories: number
protein: number
carbs: number
fat: number
- quantity: number
- unit: string
+ servings: number
+ serving_size?: string
+ barcode?: string
+ logged_at: string
+ created_at?: string
}
-export interface Weight {
- id: number
+export interface DailyStats {
date: string
- value: number
+ total_calories: number
+ total_protein: number
+ total_carbs: number
+ total_fat: number
+ workout_count: number
}
-export interface DailyStats {
- date: string
- weight?: number
- calories: number
- protein: number
- carbs: number
- fat: number
- workouts: number
+export interface WeightStats {
+ latest: number
+ starting: number
+ total_entries: number
}
export interface AuthResponse {
- access_token: string
+ token: string
refresh_token: string
user: User
}
@@ -74,5 +112,4 @@ export interface LoginRequest {
export interface RegisterRequest {
email: string
password: string
- password_confirm: string
}