Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
import { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { BookOpen, Plus, Dumbbell, Edit2, Trash2, Search, Play, ChevronRight, MoreVertical, Moon, Sun } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import Loading from '../components/Loading'
import PageHeader from '../components/ui/PageHeader'
import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
import { ErrorState, ListError } from '../components/ui'
import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { useAsyncAction, types, formatDate, useTranslation } from '@lyftr/shared'
import {
todaysDay, dayLabel, isDayStartable, programExerciseCount, programSetCount, sessionNameForDay,
activeSessionExercisesForDay, allExercises,
} from '@lyftr/shared'
function ProgramCard({
program,
onEdit,
onDelete,
}: {
program: types.Program
onEdit: (id: number) => void
onDelete: (id: number) => void
}) {
const { t } = useTranslation()
const navigate = useNavigate()
const { session, startSession } = useWorkoutSession()
const [menuOpen, setMenuOpen] = useState(false)
const menuRef = useRef<HTMLDivElement>(null)
const portalRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const handler = (e: MouseEvent) => {
const inMenu = menuRef.current?.contains(e.target as Node)
const inPortal = portalRef.current?.contains(e.target as Node)
if (!inMenu && !inPortal) setMenuOpen(false)
}
document.addEventListener('mousedown', handler)
return () => document.removeEventListener('mousedown', handler)
}, [])
const today = todaysDay(program)
const canQuickStart = isDayStartable(today)
const handleStart = (e: React.MouseEvent) => {
e.stopPropagation()
if (session) { navigate('/workout/start'); return }
if (!canQuickStart) {
// Today's slot is a rest day (or the program has no days yet) — nothing to
// quick-start; send them to the program to pick a day manually.
navigate(`/programs/${program.id}`)
return
}
startSession(sessionNameForDay(program, today), activeSessionExercisesForDay(today), program.id, today.id)
navigate('/workout/active')
}
const [confirming, setConfirming] = useState(false)
// Was `catch { setDeleting(false); setConfirming(false) }` — the card quietly came
// back and the user was left guessing whether the tap had registered. The confirm
// stays up now and says why, which is the same rule the sheets follow.
const remove = useAsyncAction(async () => {
await programAPI.delete(program.id)
onDelete(program.id)
}, t('programs.deleteFailed'))
if (confirming) {
return (
<div className="card overflow-hidden border-error-500/30">
<div className="flex items-center justify-between p-4 bg-error-500/5">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-lg bg-error-500/10 border border-error-500/20 flex items-center justify-center flex-shrink-0">
<Trash2 className="w-4 h-4 text-error-400" />
</div>
<div>
<p className="text-sm font-semibold text-tx-primary">{t('common.card.deleteNamed', { name: program.name })}</p>
<p className="text-xs text-tx-muted">{t('common.card.cannotUndo')}</p>
{remove.error && <p className="text-xs text-error-400 mt-1">{remove.error}</p>}
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => setConfirming(false)}
className="px-3 py-1.5 text-xs bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium"
>
{t('common.cancel')}
</button>
<button
onClick={() => { void remove.run() }}
disabled={remove.busy}
className="px-3 py-1.5 text-xs bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-lg transition-colors font-medium flex items-center gap-1"
>
<Trash2 className="w-3 h-3" />
{remove.busy ? t('common.deleting') : t('common.delete')}
</button>
</div>
</div>
</div>
)
}
const totalSets = programSetCount(program)
const totalExercises = programExerciseCount(program)
const thumbnail = allExercises(program)[0]?.exercise?.image_url
const dayCount = program.days?.length ?? 0
return (
<div className="card group active:scale-[0.99] transition-transform">
<div className="flex items-center p-4 gap-3">
<button
className="flex-1 flex items-center gap-3 min-w-0 text-left"
onClick={() => navigate(`/programs/${program.id}`)}
>
{thumbnail ? (
<img
src={thumbnail}
alt=""
className="w-11 h-11 rounded-xl object-cover flex-shrink-0 bg-surface-muted"
onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
/>
) : (
<div className="w-11 h-11 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
<BookOpen className="w-5 h-5 text-brand-500" strokeWidth={2} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold text-tx-primary truncate">{program.name}</p>
<p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{formatDate(new Date(program.created_at), 'monthDayYear')}</p>
<div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">
<span className="text-xs text-tx-muted whitespace-nowrap">{t('common.count.exercises', { count: totalExercises })}</span>
<span className="text-tx-muted/40 text-xs">·</span>
<span className="text-xs text-tx-muted whitespace-nowrap">{t('common.count.sets', { count: totalSets })}</span>
{dayCount > 1 && today && (
<>
<span className="text-tx-muted/40 text-xs">·</span>
{today.is_rest_day ? (
<span className="text-xs text-tx-muted whitespace-nowrap flex items-center gap-1"><Moon className="w-3 h-3" />{t('programs.card.restToday')}</span>
) : (
// Sun, not Dumbbell — Dumbbell already means "exercises" earlier on
// this same row; Sun/Moon reads as a natural due/rest pair instead.
<span className="text-xs text-brand-400 font-medium whitespace-nowrap flex items-center gap-1"><Sun className="w-3 h-3" />{t('programs.card.today', { day: dayLabel(today, today.order_index) })}</span>
)}
</>
)}
</div>
</div>
<ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
</button>
{/* Mobile: kebab | Desktop: hover icons */}
<div className="relative flex-shrink-0" ref={menuRef}>
{/* Mobile kebab trigger */}
<button
onClick={e => { e.stopPropagation(); setMenuOpen(o => !o) }}
className={`sm:hidden p-2 rounded-lg transition-colors ${menuOpen ? 'bg-surface-muted' : 'hover:bg-surface-muted'}`}
aria-label={t('programs.card.options')}
>
<MoreVertical className="w-4 h-4 text-tx-muted" />
</button>
{/* Centered modal dropdown — portal to escape transform stacking context */}
{menuOpen && createPortal(
<>
<div
className="fixed inset-0 z-40 bg-black/40 backdrop-blur-[2px]"
onClick={e => { e.stopPropagation(); setMenuOpen(false) }}
/>
<div ref={portalRef} className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 bg-surface-overlay border border-surface-border/60 rounded-2xl shadow-2xl z-50 overflow-hidden">
<div className="px-4 pt-4 pb-3">
<p className="text-[10px] font-semibold text-tx-muted uppercase tracking-wider text-center">{t('programs.card.menuHeading')}</p>
<p className="text-sm font-semibold text-tx-primary text-center mt-0.5 truncate">{program.name}</p>
</div>
<div className="border-t border-surface-border/40 py-1.5">
<button
onClick={e => { e.stopPropagation(); setMenuOpen(false); handleStart(e) }}
className="w-full flex items-center gap-3 px-4 py-3 text-sm font-medium text-tx-primary hover:bg-surface-muted/60 active:bg-surface-muted transition-colors"
>
<div className="w-8 h-8 rounded-xl bg-brand-500/10 flex items-center justify-center flex-shrink-0">
<Play className="w-4 h-4 text-brand-500" />
</div>
{canQuickStart ? t('programs.startWorkout') : t('programs.card.viewProgram')}
</button>
<div className="mx-4 border-t border-surface-border/30" />
<button
onClick={e => { e.stopPropagation(); setMenuOpen(false); onEdit(program.id) }}
className="w-full flex items-center gap-3 px-4 py-3 text-sm font-medium text-tx-primary hover:bg-surface-muted/60 active:bg-surface-muted transition-colors"
>
<div className="w-8 h-8 rounded-xl bg-brand-500/10 flex items-center justify-center flex-shrink-0">
<Edit2 className="w-4 h-4 text-brand-500" />
</div>
{t('programs.card.editProgram')}
</button>
<div className="mx-4 border-t border-surface-border/30" />
<button
onClick={e => { e.stopPropagation(); setMenuOpen(false); setConfirming(true) }}
className="w-full flex items-center gap-3 px-4 py-3 text-sm font-medium text-error-400 hover:bg-error-500/10 active:bg-error-500/15 transition-colors"
>
<div className="w-8 h-8 rounded-xl bg-error-500/10 flex items-center justify-center flex-shrink-0">
<Trash2 className="w-4 h-4 text-error-400" />
</div>
{t('programs.card.deleteProgram')}
</button>
</div>
<div className="border-t border-surface-border/40 p-3">
<button
onClick={e => { e.stopPropagation(); setMenuOpen(false) }}
className="w-full py-2.5 text-sm font-semibold text-tx-muted bg-surface-muted/60 hover:bg-surface-muted rounded-xl transition-colors"
>
{t('common.cancel')}
</button>
</div>
</div>
</>,
document.body
)}
{/* Desktop hover icons */}
<div className="hidden sm:flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
<button onClick={handleStart}
className="p-2 hover:bg-brand-500/10 rounded-lg transition-colors" title={canQuickStart ? t('programs.card.startTitle') : t('programs.card.restDayTitle')}>
<Play className="w-4 h-4 text-brand-500" />
</button>
<button aria-label={t('programs.card.editNamed', { name: program.name })} onClick={e => { e.stopPropagation(); onEdit(program.id) }}
className="p-2 hover:bg-surface-muted rounded-lg transition-colors">
<Edit2 className="w-4 h-4 text-brand-500" />
</button>
<button aria-label={t('common.delete')} onClick={e => { e.stopPropagation(); setConfirming(true) }}
className="p-2 hover:bg-error-500/10 rounded-lg transition-colors">
<Trash2 className="w-4 h-4 text-error-400" />
</button>
</div>
</div>
</div>
</div>
)
}
export default function Programs() {
const { t } = useTranslation()
const navigate = useNavigate()
const [search, setSearch] = useState('')
const [debouncedSearch, setDebouncedSearch] = useState('')
useEffect(() => {
const t = setTimeout(() => setDebouncedSearch(search), 300)
return () => clearTimeout(t)
}, [search])
const {
items: programs, sentinelRef, hasMore, loading, initialLoading, reload,
error: listError, retry: retryList,
} = useServerInfiniteList<types.Program>({
fetcher: (offset, limit) => programAPI.list({ offset, limit, q: debouncedSearch || undefined }),
deps: [debouncedSearch],
})
if (initialLoading) return <Loading />
// Everything on this page is downstream of one request, so when it fails with nothing
// on screen the page failed — not a section of it. A section-sized error stranded among
// empty tiles and a search box that filters nothing is three dead regions and a note;
// one page-level error is the same information said once. The section-scoped ListError
// below stays for the case it is actually for: a later page failing under rows that
// did arrive.
if (listError && programs.length === 0) {
return (
<div className="space-y-5 animate-slide-up">
<PageHeader title={t('programs.title')} subtitle={t('programs.subtitle')} />
<ErrorState
size="page"
title={t('programs.list.loadFailed')}
message={listError}
onRetry={retryList}
/>
</div>
)
}
// Three separate claims these tiles used to make without having the numbers.
//
// `programs` is one page of an infinite list, so its length is what has loaded, not how
// many exist: with 25 programs on the server the Total tile read "20 programs" on a
// perfectly healthy connection. While more pages remain it is a lower bound, and says so.
//
// A failed read leaves the list empty too, and 0 then means "we never heard back"
// rather than "you have none" — indistinguishable from the empty account below it.
// No failure branch here on purpose: the early return above fires on exactly
// "listError and nothing loaded", so by this point either rows arrived or the page is
// already showing its own error. A tile-level failure state would be unreachable.
const totalLabel = hasMore ? `${programs.length}+` : programs.length.toString()
const avgLabel = programs.length === 0
? '—'
: Math.round(programs.reduce((s, p) => s + programExerciseCount(p), 0) / programs.length).toString()
return (
<div className="space-y-5 animate-slide-up">
<PageHeader
title={t('programs.title')}
subtitle={t('programs.subtitle')}
action={
<button onClick={() => navigate('/programs/new')} className="btn-primary btn-sm">
<Plus className="w-4 h-4" /> {t('programs.newProgram')}
</button>
}
/>
<div className="grid grid-cols-2 gap-3">
{[
{ label: t('programs.stats.total'), value: totalLabel, unit: t('programs.stats.totalUnit'), icon: BookOpen },
{ label: t('programs.stats.avgExercises'), value: avgLabel, unit: t('programs.stats.perProgram'), icon: Dumbbell },
].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>
</div>
<div className="flex items-end gap-1.5">
<span className="stat-value text-xl">{s.value}</span>
<span className="text-xs text-tx-muted mb-0.5">{s.unit}</span>
</div>
</div>
))}
</div>
<div className="relative">
<Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-tx-muted pointer-events-none" />
<input
value={search}
onChange={e => setSearch(e.target.value)}
className="input pl-10"
placeholder={t('programs.list.searchPlaceholder')}
/>
</div>
<div className="space-y-2">
{programs.length === 0 && !loading ? (
// A failed first page never reaches here — the early return above renders it —
// so an empty list at this point really is empty.
<div className="empty-state">
<div className="w-12 h-12 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center mb-4">
<BookOpen className="w-6 h-6 text-tx-muted" />
</div>
<p className="text-sm font-medium text-tx-primary mb-1">{t('programs.list.empty.title')}</p>
<p className="text-xs text-tx-muted">{search ? t('common.tryDifferentSearch') : t('programs.list.empty.startHint')}</p>
</div>
) : (
<>
{programs.map(p => (
<ProgramCard
key={p.id}
program={p}
onEdit={(id) => navigate(`/programs/${id}/edit`)}
onDelete={() => reload()}
/>
))}
<div ref={sentinelRef} />
{listError && <ListError subject={t('programs.list.errorSubject')} message={listError} onRetry={retryList} />}
{hasMore && loading && (
<p className="text-center text-xs text-tx-muted py-2">{t('common.loadingMore')}</p>
)}
</>
)}
</div>
</div>
)
}