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.

Bugfix/pagination consistency (#10)

Carter23f2d17f6c4b
diff --git a/backend/controllers/programs.go b/backend/controllers/programs.go
index 5ce69c9..958271f 100644
--- a/backend/controllers/programs.go
+++ b/backend/controllers/programs.go
@@ -3,6 +3,7 @@ package controllers
import (
"database/sql"
"strconv"
+ "strings"
"github.com/Cawlumm/lyftr-backend/db"
"github.com/Cawlumm/lyftr-backend/middleware"
@@ -14,10 +15,29 @@ import (
func ListPrograms(c *gin.Context) {
uid := middleware.UserID(c)
- rows, err := db.DB.Query(
- `SELECT id, user_id, name, notes, created_at FROM programs WHERE user_id = ? ORDER BY created_at DESC`,
- uid,
- )
+ limit := 20
+ offset := 0
+ if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 100 {
+ limit = l
+ }
+ if o, err := strconv.Atoi(c.Query("offset")); err == nil && o >= 0 {
+ offset = o
+ }
+ q := c.Query("q")
+
+ var rows *sql.Rows
+ var err error
+ if q != "" {
+ rows, err = db.DB.Query(
+ `SELECT id, user_id, name, notes, created_at FROM programs WHERE user_id = ? AND LOWER(name) LIKE ? ORDER BY created_at DESC LIMIT ? OFFSET ?`,
+ uid, "%"+strings.ToLower(q)+"%", limit, offset,
+ )
+ } else {
+ rows, err = db.DB.Query(
+ `SELECT id, user_id, name, notes, created_at FROM programs WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?`,
+ uid, limit, offset,
+ )
+ }
if err != nil {
utils.InternalError(c)
return
diff --git a/backend/controllers/weight.go b/backend/controllers/weight.go
index fb0b613..9bfd199 100644
--- a/backend/controllers/weight.go
+++ b/backend/controllers/weight.go
@@ -18,6 +18,10 @@ func ListWeightLogs(c *gin.Context) {
if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 1000 {
limit = l
}
+ offset := 0
+ if o, err := strconv.Atoi(c.Query("offset")); err == nil && o >= 0 {
+ offset = o
+ }
q := `SELECT id, user_id, weight, notes, logged_at, created_at
FROM weight_logs WHERE user_id = ?`
@@ -48,8 +52,8 @@ func ListWeightLogs(c *gin.Context) {
args = append(args, hi)
}
}
- q += ` ORDER BY logged_at DESC LIMIT ?`
- args = append(args, limit)
+ q += ` ORDER BY logged_at DESC LIMIT ? OFFSET ?`
+ args = append(args, limit, offset)
rows, err := db.DB.Query(q, args...)
if err != nil {
diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.go
index ff77867..4e17009 100644
--- a/backend/controllers/workouts.go
+++ b/backend/controllers/workouts.go
@@ -3,6 +3,7 @@ package controllers
import (
"database/sql"
"strconv"
+ "strings"
"time"
"github.com/Cawlumm/lyftr-backend/db"
@@ -22,12 +23,23 @@ func ListWorkouts(c *gin.Context) {
if o, err := strconv.Atoi(c.Query("offset")); err == nil && o >= 0 {
offset = o
}
+ q := c.Query("q")
- rows, err := db.DB.Query(
- `SELECT id, user_id, name, notes, duration, started_at, created_at
- FROM workouts WHERE user_id = ? ORDER BY started_at DESC LIMIT ? OFFSET ?`,
- uid, limit, offset,
- )
+ var rows *sql.Rows
+ var err error
+ if q != "" {
+ rows, err = db.DB.Query(
+ `SELECT id, user_id, name, notes, duration, started_at, created_at
+ FROM workouts WHERE user_id = ? AND LOWER(name) LIKE ? ORDER BY started_at DESC LIMIT ? OFFSET ?`,
+ uid, "%"+strings.ToLower(q)+"%", limit, offset,
+ )
+ } else {
+ rows, err = db.DB.Query(
+ `SELECT id, user_id, name, notes, duration, started_at, created_at
+ FROM workouts WHERE user_id = ? ORDER BY started_at DESC LIMIT ? OFFSET ?`,
+ uid, limit, offset,
+ )
+ }
if err != nil {
utils.InternalError(c)
return
diff --git a/web/e2e/programs.spec.ts b/web/e2e/programs.spec.ts
index f92f0d8..2d17f74 100644
--- a/web/e2e/programs.spec.ts
+++ b/web/e2e/programs.spec.ts
@@ -2,8 +2,10 @@ import { test, expect } from '@playwright/test'
import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'
const E2E_PROGRAM_NAME = 'Test Program E2E'
const SEED_PROGRAM_NAME = 'Seeded Test Program'
+const SEED_SEARCH_PROGRAM_NAME = 'ZZZ E2E SearchTarget Program'
let programId: number
+let searchProgramId: number
let authToken: string
test.describe('Programs', () => {
@@ -24,15 +26,29 @@ test.describe('Programs', () => {
})
const pb = await p.json()
programId = pb.data.id
+
+ const sp = await request.post(`${API}/programs`, {
+ headers: { Authorization: `Bearer ${authToken}` },
+ data: {
+ name: SEED_SEARCH_PROGRAM_NAME,
+ notes: 'Created by E2E seed for search',
+ exercises: []
+ }
+ })
+ const spb = await sp.json()
+ searchProgramId = spb.data.id
})
test.afterAll(async ({ request }) => {
const headers = { Authorization: `Bearer ${authToken}` }
- // Delete seeded program
+ // Delete seeded programs
if (programId) {
await request.delete(`${API}/programs/${programId}`, { headers })
}
+ if (searchProgramId) {
+ await request.delete(`${API}/programs/${searchProgramId}`, { headers })
+ }
// Delete any UI-created E2E programs
const list = await request.get(`${API}/programs`, { headers })
@@ -76,6 +92,35 @@ test.describe('Programs', () => {
await expect(page.getByText(E2E_PROGRAM_NAME).first()).toBeVisible()
})
+ test('search filters program list', async ({ page }) => {
+ await expect(page.getByText(SEED_SEARCH_PROGRAM_NAME).first()).toBeVisible({ timeout: 5000 })
+ const searchInput = page.getByPlaceholder(/search programs/i)
+ await searchInput.fill('SearchTarget')
+ await page.waitForTimeout(500)
+ await expect(page.getByText(SEED_SEARCH_PROGRAM_NAME).first()).toBeVisible()
+ await expect(page.getByText(SEED_PROGRAM_NAME)).not.toBeVisible()
+ })
+
+ test('clearing search restores full list', async ({ page }) => {
+ const searchInput = page.getByPlaceholder(/search programs/i)
+ await searchInput.fill('SearchTarget')
+ await page.waitForTimeout(500)
+ await expect(page.getByText(SEED_SEARCH_PROGRAM_NAME).first()).toBeVisible()
+ await searchInput.fill('')
+ await page.waitForTimeout(500)
+ await expect(page.getByText(SEED_PROGRAM_NAME)).toBeVisible()
+ await expect(page.getByText(SEED_SEARCH_PROGRAM_NAME).first()).toBeVisible()
+ })
+
+ test('search input stays focused while typing', async ({ page }) => {
+ await expect(page.getByRole('heading', { name: /programs/i })).toBeVisible()
+ const searchInput = page.getByPlaceholder(/search programs/i)
+ await searchInput.click()
+ await searchInput.type('S')
+ await page.waitForTimeout(500)
+ await expect(searchInput).toBeFocused()
+ })
+
test('program detail page loads with exercises', async ({ page }) => {
await page.goto(`/programs/${programId}`)
await expect(page.getByRole('heading')).toBeVisible()
diff --git a/web/e2e/weight.spec.ts b/web/e2e/weight.spec.ts
new file mode 100644
index 0000000..aa079fd
--- /dev/null
+++ b/web/e2e/weight.spec.ts
@@ -0,0 +1,135 @@
+import { test, expect } from '@playwright/test'
+import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'
+
+const SEED_WEIGHT_NOTE = 'E2E seed weight'
+const FORM_WEIGHT_NOTE = 'E2E form weight test'
+
+let authToken: string
+let seedWeightIds: number[] = []
+
+test.describe('Weight', () => {
+ test.beforeAll(async ({ request }) => {
+ const res = await request.post(`${API}/auth/login`, {
+ data: { email: TEST_EMAIL, password: TEST_PASSWORD }
+ })
+ authToken = (await res.json()).data.token
+ const headers = { Authorization: `Bearer ${authToken}` }
+
+ // Seed entries at -7d, -3d, and today so history and period selector have data
+ const offsets = [7, 3, 0]
+ for (const daysAgo of offsets) {
+ const date = new Date(Date.now() - daysAgo * 86400000)
+ date.setHours(12, 0, 0, 0)
+ const r = await request.post(`${API}/weight`, {
+ headers,
+ data: { weight: 175 - daysAgo, notes: SEED_WEIGHT_NOTE, logged_at: date.toISOString() }
+ })
+ const rb = await r.json()
+ if (rb.data?.id) seedWeightIds.push(rb.data.id)
+ }
+ })
+
+ test.afterAll(async ({ request }) => {
+ const headers = { Authorization: `Bearer ${authToken}` }
+
+ for (const id of seedWeightIds) {
+ await request.delete(`${API}/weight/${id}`, { headers })
+ }
+
+ // Clean up any entries the form-submit test created
+ const list = await request.get(`${API}/weight?limit=100`, { headers })
+ const lb = await list.json()
+ const toDelete = (lb.data ?? []).filter((w: any) => w.notes === FORM_WEIGHT_NOTE)
+ await Promise.all(toDelete.map((w: any) =>
+ request.delete(`${API}/weight/${w.id}`, { headers })
+ ))
+ })
+
+ test.beforeEach(async ({ page }) => {
+ await page.goto('/weight')
+ })
+
+ test('page loads with log form and history', async ({ page }) => {
+ await expect(page.getByRole('heading', { name: 'Weight', exact: true })).toBeVisible()
+ await expect(page.getByRole('button', { name: /log weight/i })).toBeVisible()
+ await expect(page.getByText(/history/i)).toBeVisible({ timeout: 5000 })
+ })
+
+ test('seeded entries appear in history list', async ({ page }) => {
+ await expect(page.getByText(/history/i)).toBeVisible({ timeout: 5000 })
+ // Weight values 175, 172, 168 lbs from seed — at least one card should show
+ const cards = page.locator('.card')
+ await expect(cards.first()).toBeVisible({ timeout: 5000 })
+ })
+
+ test('period selector switches chart range without crash', async ({ page }) => {
+ await expect(page.getByRole('heading', { name: 'Weight', exact: true })).toBeVisible()
+ for (const period of ['7d', '90d', 'All', '30d']) {
+ await page.getByRole('button', { name: period, exact: true }).click()
+ await page.waitForTimeout(300)
+ // Page should still be showing the weight heading — no crash/remount
+ await expect(page.getByRole('heading', { name: 'Weight', exact: true })).toBeVisible()
+ }
+ })
+
+ test('log weight via form adds entry to history', async ({ page }) => {
+ const testDate = new Date(Date.now() - 14 * 86400000).toISOString().split('T')[0]
+
+ await page.getByRole('button', { name: /add date.*note/i }).click()
+ await page.locator('input[type="date"]').fill(testDate)
+ await page.locator('input[placeholder*="morning"]').fill(FORM_WEIGHT_NOTE)
+
+ // Fill weight
+ const weightInput = page.locator('input[inputmode="decimal"]').first()
+ await weightInput.fill('170')
+
+ await page.getByRole('button', { name: /log weight/i }).click()
+ await page.waitForTimeout(500)
+
+ // Entry should appear in history
+ await expect(page.getByText(/history/i)).toBeVisible({ timeout: 5000 })
+ })
+
+ test('duplicate date warning appears when logging same date', async ({ page }) => {
+ // Today is already seeded — form defaults to today, submit should trigger warning
+ const weightInput = page.locator('input[inputmode="decimal"]').first()
+ await weightInput.fill('180')
+ await page.getByRole('button', { name: /log weight/i }).click()
+ await expect(page.getByText(/already logged/i)).toBeVisible({ timeout: 3000 })
+ await page.getByRole('button', { name: /cancel/i }).click()
+ await expect(page.getByText(/already logged/i)).not.toBeVisible()
+ })
+
+ test('history entry navigates to weight detail', async ({ page }) => {
+ await expect(page.getByText(/history/i)).toBeVisible({ timeout: 5000 })
+ const firstEntry = page.locator('a[href^="/weight/"]').first()
+ await expect(firstEntry).toBeVisible({ timeout: 5000 })
+ await firstEntry.click()
+ await expect(page).toHaveURL(/\/weight\/\d+/)
+ await expect(page.getByText('Weight Entry')).toBeVisible()
+ })
+
+ test('weight detail delete removes entry and returns to list', async ({ page }) => {
+ // Create a dedicated entry to delete via API so we have a known URL
+ const headers = { Authorization: `Bearer ${authToken}` }
+ const r = await page.request.post(`${API}/weight`, {
+ headers,
+ data: {
+ weight: 999,
+ notes: 'E2E delete target',
+ logged_at: new Date(Date.now() - 30 * 86400000).toISOString()
+ }
+ })
+ const { data } = await r.json()
+ const deleteId = data.id
+
+ await page.goto(`/weight/${deleteId}`)
+ await expect(page.getByText('Weight Entry')).toBeVisible()
+
+ await page.getByRole('button', { name: /delete/i }).click()
+ await expect(page.getByText(/permanently deleted/i)).toBeVisible({ timeout: 3000 })
+ await page.getByRole('button', { name: /^delete$/i }).click()
+ await page.waitForURL('/weight', { timeout: 5000 })
+ await expect(page.getByRole('heading', { name: 'Weight', exact: true })).toBeVisible()
+ })
+})
diff --git a/web/e2e/workouts.spec.ts b/web/e2e/workouts.spec.ts
index ca6a7ea..9d75bf8 100644
--- a/web/e2e/workouts.spec.ts
+++ b/web/e2e/workouts.spec.ts
@@ -2,10 +2,12 @@ import { test, expect } from '@playwright/test'
import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'
const E2E_WORKOUT_NAME = 'Test Workout E2E'
const SEED_WORKOUT_NAME = 'Seeded Test Workout'
+const SEED_SEARCH_WORKOUT_NAME = 'ZZZ E2E SearchTarget Workout'
const LAYOUT_KEY = 'lyftr_workout_layout'
const SESSION_KEY = 'lyftr_active_session'
let workoutId: number
+let searchWorkoutId: number
let authToken: string
test.describe('Workouts', () => {
@@ -27,15 +29,30 @@ test.describe('Workouts', () => {
})
const wb = await w.json()
workoutId = wb.data.id
+
+ const sw = await request.post(`${API}/workouts`, {
+ headers: { Authorization: `Bearer ${authToken}` },
+ data: {
+ name: SEED_SEARCH_WORKOUT_NAME,
+ duration: 1800,
+ started_at: new Date().toISOString(),
+ exercises: []
+ }
+ })
+ const swb = await sw.json()
+ searchWorkoutId = swb.data.id
})
test.afterAll(async ({ request }) => {
const headers = { Authorization: `Bearer ${authToken}` }
- // Delete seeded workout
+ // Delete seeded workouts
if (workoutId) {
await request.delete(`${API}/workouts/${workoutId}`, { headers })
}
+ if (searchWorkoutId) {
+ await request.delete(`${API}/workouts/${searchWorkoutId}`, { headers })
+ }
// Delete any UI-created E2E workouts
const list = await request.get(`${API}/workouts?limit=100`, { headers })
@@ -111,6 +128,35 @@ test.describe('Workouts', () => {
await expect(page.locator('.card').first()).toBeVisible()
})
+ test('search filters workout list', async ({ page }) => {
+ await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible({ timeout: 5000 })
+ const searchInput = page.getByPlaceholder(/search workouts/i)
+ await searchInput.fill('SearchTarget')
+ await page.waitForTimeout(500)
+ await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()
+ await expect(page.getByText(SEED_WORKOUT_NAME)).not.toBeVisible()
+ })
+
+ test('clearing search restores full list', async ({ page }) => {
+ const searchInput = page.getByPlaceholder(/search workouts/i)
+ await searchInput.fill('SearchTarget')
+ await page.waitForTimeout(500)
+ await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()
+ await searchInput.fill('')
+ await page.waitForTimeout(500)
+ await expect(page.getByText(SEED_WORKOUT_NAME)).toBeVisible()
+ await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()
+ })
+
+ test('search input stays focused while typing', async ({ page }) => {
+ await expect(page.getByRole('heading', { name: /workouts/i })).toBeVisible()
+ const searchInput = page.getByPlaceholder(/search workouts/i)
+ await searchInput.click()
+ await searchInput.type('S')
+ await page.waitForTimeout(500)
+ await expect(searchInput).toBeFocused()
+ })
+
test('weight unit displays consistently', async ({ page }) => {
await page.goto('/settings')
const kgButton = page.getByRole('button', { name: 'kg' })
diff --git a/web/src/components/PeriodSelector.tsx b/web/src/components/PeriodSelector.tsx
new file mode 100644
index 0000000..bc9772e
--- /dev/null
+++ b/web/src/components/PeriodSelector.tsx
@@ -0,0 +1,25 @@
+interface PeriodSelectorProps<T extends string> {
+ options: readonly T[]
+ value: T
+ onChange: (value: T) => void
+}
+
+export default function PeriodSelector<T extends string>({ options, value, onChange }: PeriodSelectorProps<T>) {
+ return (
+ <div className="flex gap-1 bg-surface-overlay rounded-lg p-1">
+ {options.map(opt => (
+ <button
+ key={opt}
+ onClick={() => onChange(opt)}
+ className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors 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>
+ )
+}
diff --git a/web/src/hooks/useServerInfiniteList.ts b/web/src/hooks/useServerInfiniteList.ts
new file mode 100644
index 0000000..fe5530a
--- /dev/null
+++ b/web/src/hooks/useServerInfiniteList.ts
@@ -0,0 +1,85 @@
+import { useState, useEffect, useRef, useCallback } from 'react'
+
+interface Options<T> {
+ fetcher: (offset: number, limit: number) => Promise<T[]>
+ pageSize?: number
+ rootMargin?: string
+ // Changing any dep resets the list and re-fetches from offset 0 (e.g. search query)
+ deps?: readonly unknown[]
+}
+
+interface Result<T> {
+ items: T[]
+ sentinelRef: React.RefObject<HTMLDivElement>
+ hasMore: boolean
+ loading: boolean
+ // True only during the very first fetch — use for full-page spinners
+ initialLoading: boolean
+ // Call after create/delete to discard loaded items and re-fetch from scratch
+ reload: () => void
+}
+
+export function useServerInfiniteList<T>({
+ fetcher,
+ pageSize = 20,
+ rootMargin = '200px',
+ deps = [],
+}: Options<T>): Result<T> {
+ const [items, setItems] = useState<T[]>([])
+ const [offset, setOffset] = useState(0)
+ const [hasMore, setHasMore] = useState(true)
+ const [loading, setLoading] = useState(false)
+ const sentinelRef = useRef<HTMLDivElement>(null)
+ // Tracks whether a fetch is in flight to prevent double-fetches
+ const fetchingRef = useRef(false)
+ // Incremented by reload() to force a reset even if deps haven't changed
+ const [resetKey, setResetKey] = useState(0)
+ // Flips true after first fetch completes — never resets — drives initialLoading
+ const initializedRef = useRef(false)
+
+ const fetchPage = useCallback(async (currentOffset: number, replace: boolean) => {
+ if (fetchingRef.current) return
+ fetchingRef.current = true
+ setLoading(true)
+ try {
+ const page = await fetcher(currentOffset, pageSize)
+ setItems(prev => replace ? page : [...prev, ...page])
+ setOffset(currentOffset + page.length)
+ setHasMore(page.length === pageSize)
+ initializedRef.current = true
+ } finally {
+ fetchingRef.current = false
+ setLoading(false)
+ }
+ }, [fetcher, pageSize])
+
+ // Reset and fetch from scratch when deps or resetKey change
+ useEffect(() => {
+ setItems([])
+ setOffset(0)
+ setHasMore(true)
+ fetchingRef.current = false
+ fetchPage(0, true)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [...deps, resetKey])
+
+ // Sentinel intersection → load next page
+ useEffect(() => {
+ const el = sentinelRef.current
+ if (!el) return
+ const obs = new IntersectionObserver(
+ entries => {
+ if (entries[0]?.isIntersecting && hasMore && !fetchingRef.current) {
+ fetchPage(offset, false)
+ }
+ },
+ { rootMargin },
+ )
+ obs.observe(el)
+ return () => obs.disconnect()
+ }, [hasMore, offset, fetchPage, rootMargin])
+
+ const reload = useCallback(() => setResetKey(k => k + 1), [])
+
+ return { items, sentinelRef, hasMore, loading, initialLoading: loading && !initializedRef.current, reload }
+}
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index cf14301..38b4cf3 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -9,6 +9,7 @@ import {
LineChart, Line, PieChart, Pie, Legend,
} from 'recharts'
import Loading from '../components/Loading'
+import PeriodSelector from '../components/PeriodSelector'
import QuickWeighInSheet from '../components/QuickWeighInSheet'
import { workoutAPI, foodAPI, weightAPI, userAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
@@ -136,6 +137,7 @@ export default function Dashboard() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [sheetOpen, setSheetOpen] = useState(false)
+ const [volumePeriod, setVolumePeriod] = useState<'7' | '14' | '30'>('7')
const wUnit = weightShort(settings.weight_unit)
useEffect(() => {
@@ -173,8 +175,8 @@ export default function Dashboard() {
const weekWorkouts = workouts.filter(w => new Date(w.started_at) >= weekStart)
const lastWorkout = workouts[0] ?? null
- // Volume chart: last 7 workouts oldest→newest
- const chartData = workouts.slice(0, 7).reverse().map(w => ({
+ // Volume chart: slice by selected period, oldest→newest
+ const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map(w => ({
date: format(new Date(w.started_at), 'M/d'),
volume: Math.round(lbsToDisplay(calcVolume(w), settings.weight_unit)),
name: w.name,
@@ -327,14 +329,16 @@ export default function Dashboard() {
{/* ── Volume trend chart ─────────────────────── */}
<div className="card p-4">
- <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center justify-between mb-3 gap-2">
<div className="flex items-center gap-2">
<TrendingUp className="w-4 h-4 text-brand-500" />
<h2 className="section-title">Volume Trend</h2>
</div>
- <span className="text-xs text-tx-muted">
- {chartData.length > 0 ? `last ${chartData.length} workouts` : ''}
- </span>
+ <PeriodSelector
+ options={['7', '14', '30'] as const}
+ value={volumePeriod}
+ onChange={setVolumePeriod}
+ />
</div>
{chartData.length === 0 ? (
diff --git a/web/src/pages/ExerciseDetail.tsx b/web/src/pages/ExerciseDetail.tsx
index c1e0935..c7baa60 100644
--- a/web/src/pages/ExerciseDetail.tsx
+++ b/web/src/pages/ExerciseDetail.tsx
@@ -1,16 +1,21 @@
-import { useState, useEffect } from 'react'
+import { useState, useEffect, useMemo } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { ArrowLeft, Dumbbell, Trophy } from 'lucide-react'
-import { format } from 'date-fns'
+import { format, subDays } from 'date-fns'
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts'
import Model, { IExerciseData } from 'react-body-highlighter'
import { exerciseAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { useSettingsStore, weightShort, lbsToDisplay } from '../stores/settings'
import { useTheme } from '../hooks/useTheme'
+import PeriodSelector from '../components/PeriodSelector'
import * as types from '../types'
import { muscleColor, muscleColorBordered, EQUIPMENT_LABEL, muscleToBodySlugs } from '../utils/exerciseUtils'
+const HISTORY_PERIODS = ['1m', '3m', '6m', 'All'] as const
+type HistoryPeriod = typeof HISTORY_PERIODS[number]
+const HISTORY_DAYS: Record<HistoryPeriod, number | null> = { '1m': 30, '3m': 90, '6m': 180, 'All': null }
+
function buildBodyData(exercise: types.Exercise): IExerciseData[] {
const primarySlugs = muscleToBodySlugs(exercise.muscle_group)
const secondarySlugs = (exercise.secondary_muscles || [])
@@ -37,6 +42,7 @@ export default function ExerciseDetail() {
const [exercise, setExercise] = useState<types.Exercise | null>(null)
const [pr, setPR] = useState<types.PersonalRecord | null>(null)
const [history, setHistory] = useState<types.ExerciseHistoryPoint[]>([])
+ const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('3m')
const [imgFailed, setImgFailed] = useState(false)
const [loading, setLoading] = useState(true)
@@ -53,7 +59,7 @@ export default function ExerciseDetail() {
Promise.all([
exercisePromise,
exerciseAPI.getPRs(id).catch(() => null),
- exerciseAPI.getHistory(id, 15).catch(() => []),
+ exerciseAPI.getHistory(id, 50).catch(() => []),
])
.then(([ex, prData, histData]) => {
setExercise(ex)
@@ -64,6 +70,13 @@ export default function ExerciseDetail() {
.finally(() => setLoading(false))
}, [exerciseId])
+ const filteredHistory = useMemo(() => {
+ const days = HISTORY_DAYS[historyPeriod]
+ if (days == null) return history
+ const cutoff = subDays(new Date(), days).getTime()
+ return history.filter(h => new Date(h.date).getTime() >= cutoff)
+ }, [history, historyPeriod])
+
const bodyColor = isDark ? '#162240' : '#e2e8f0'
const highlightColors = ['#0e7490', '#22d3ee'] // [secondary=cyan-700, primary=cyan-400]
@@ -197,15 +210,21 @@ export default function ExerciseDetail() {
{/* History chart */}
{history.length >= 2 && (() => {
- const chartData = [...history].reverse().map(h => ({
+ const chartData = [...filteredHistory].reverse().map(h => ({
date: format(new Date(h.date), 'M/d'),
weight: Math.round(lbsToDisplay(h.max_weight, wUnit)),
}))
return (
<div className="card p-4">
- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">
- Weight Progression
- </p>
+ <div className="flex items-center justify-between mb-3 gap-2">
+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">
+ Weight Progression
+ </p>
+ <PeriodSelector options={HISTORY_PERIODS} value={historyPeriod} onChange={setHistoryPeriod} />
+ </div>
+ {chartData.length < 2 ? (
+ <div className="flex items-center justify-center h-[110px] text-tx-muted text-sm">No data for this period</div>
+ ) : (
<ResponsiveContainer width="100%" height={110}>
<LineChart data={chartData}>
<XAxis
@@ -234,6 +253,7 @@ export default function ExerciseDetail() {
/>
</LineChart>
</ResponsiveContainer>
+ )}
</div>
)
})()}
diff --git a/web/src/pages/Programs.tsx b/web/src/pages/Programs.tsx
index f16a785..4af63d6 100644
--- a/web/src/pages/Programs.tsx
+++ b/web/src/pages/Programs.tsx
@@ -1,9 +1,10 @@
import { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { format } from 'date-fns'
-import { BookOpen, Plus, Dumbbell, Edit2, Trash2, AlertCircle, Search, Play, ChevronRight, MoreVertical } from 'lucide-react'
+import { BookOpen, Plus, Dumbbell, Edit2, Trash2, Search, Play, ChevronRight, MoreVertical } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import Loading from '../components/Loading'
+import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import * as types from '../types'
@@ -225,36 +226,20 @@ function ProgramCard({
export default function Programs() {
const navigate = useNavigate()
- const [programs, setPrograms] = useState<types.Program[]>([])
const [search, setSearch] = useState('')
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState<string | null>(null)
+ const [debouncedSearch, setDebouncedSearch] = useState('')
- const loadPrograms = async () => {
- try {
- const data = await programAPI.list()
- setPrograms(data || [])
- } catch (err: any) {
- setError(err.message || 'Failed to load programs')
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => { loadPrograms() }, [])
-
- const filtered = programs.filter(p => p.name.toLowerCase().includes(search.toLowerCase()))
+ useEffect(() => {
+ const t = setTimeout(() => setDebouncedSearch(search), 300)
+ return () => clearTimeout(t)
+ }, [search])
- if (loading) return <Loading />
+ const { items: programs, sentinelRef, hasMore, loading, initialLoading, reload } = useServerInfiniteList<types.Program>({
+ fetcher: (offset, limit) => programAPI.list({ offset, limit, q: debouncedSearch || undefined }),
+ deps: [debouncedSearch],
+ })
- if (error) {
- return (
- <div className="alert-error">
- <AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error}</span>
- </div>
- )
- }
+ if (initialLoading) return <Loading />
return (
<div className="space-y-5 animate-slide-up">
@@ -296,7 +281,7 @@ export default function Programs() {
</div>
<div className="space-y-2">
- {filtered.length === 0 ? (
+ {programs.length === 0 && !loading ? (
<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" />
@@ -305,14 +290,20 @@ export default function Programs() {
<p className="text-xs text-tx-muted">{search ? 'Try a different search' : 'Create a program to get started'}</p>
</div>
) : (
- filtered.map(p => (
- <ProgramCard
- key={p.id}
- program={p}
- onEdit={(id) => navigate(`/programs/${id}/edit`)}
- onDelete={(id) => setPrograms(prev => prev.filter(x => x.id !== id))}
- />
- ))
+ <>
+ {programs.map(p => (
+ <ProgramCard
+ key={p.id}
+ program={p}
+ onEdit={(id) => navigate(`/programs/${id}/edit`)}
+ onDelete={() => reload()}
+ />
+ ))}
+ <div ref={sentinelRef} />
+ {hasMore && loading && (
+ <p className="text-center text-xs text-tx-muted py-2">Loading more…</p>
+ )}
+ </>
)}
</div>
diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsx
index 4e42741..1a81e35 100644
--- a/web/src/pages/Weight.tsx
+++ b/web/src/pages/Weight.tsx
@@ -4,8 +4,9 @@ import { format, subDays } from 'date-fns'
import { Link } from 'react-router-dom'
import { HelpTip } from '../components/Tooltip'
import Loading from '../components/Loading'
+import PeriodSelector from '../components/PeriodSelector'
import WeightInput from '../components/WeightInput'
-import { useInfiniteList } from '../hooks/useInfiniteList'
+import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
import { isPositiveNumber } from '../utils/numberUtils'
import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'
import { weightAPI } from '../services/api'
@@ -207,11 +208,32 @@ export default function Weight() {
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
const [period, setPeriod] = useState<Period>('30d')
- 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)
+ // Paginated history list
+ const { items, sentinelRef, hasMore, loading: listLoading, initialLoading, reload } = useServerInfiniteList<types.WeightLog>({
+ fetcher: (offset, limit) => weightAPI.list({ offset, limit }),
+ })
+
+ // Chart data — re-fetched when period changes
+ const [chartLogs, setChartLogs] = useState<types.WeightLog[]>([])
+ const [chartLoading, setChartLoading] = useState(true)
+
+ useEffect(() => {
+ setChartLoading(true)
+ const days = PERIOD_DAYS[period]
+ const from = days != null ? format(subDays(new Date(), days), 'yyyy-MM-dd') : undefined
+ weightAPI.list({ limit: 1000, from })
+ .then(data => setChartLogs(data || []))
+ .catch(() => {})
+ .finally(() => setChartLoading(false))
+ }, [period])
+
+ useEffect(() => {
+ weightAPI.stats().then(setStats).catch(() => {})
+ }, [])
+
// Log form
const [newWeight, setNewWeight] = useState('')
const [newDate, setNewDate] = useState(todayStr())
@@ -222,46 +244,24 @@ export default function Weight() {
const duplicateWarningDismissedRef = useRef(false)
const logFormRef = useRef<HTMLFormElement>(null)
- const { visibleCount, sentinelRef, hasMore } = useInfiniteList({ total: logs.length })
-
const prefillDoneRef = useRef(false)
-
- const refresh = async () => {
- const [logData, statsData] = await Promise.all([
- weightAPI.list({ limit: 365 }),
- weightAPI.stats(),
- ])
- setLogs(logData || [])
- setStats(statsData)
- if (!prefillDoneRef.current && logData && logData.length > 0) {
- setNewWeight(String(Math.round(lbsToDisplay(logData[0].weight, settings.weight_unit))))
+ useEffect(() => {
+ if (!prefillDoneRef.current && items.length > 0) {
+ setNewWeight(String(Math.round(lbsToDisplay(items[0].weight, settings.weight_unit))))
prefillDoneRef.current = true
}
- }
-
- useEffect(() => {
- refresh()
- .catch(err => setError(err?.message || 'Failed to load weight data'))
- .finally(() => setLoading(false))
- }, [])
-
- const days = PERIOD_DAYS[period]
- const filtered = useMemo(() => {
- if (days == null) return logs
- const cutoff = subDays(new Date(), days).getTime()
- return logs.filter(l => new Date(l.logged_at).getTime() >= cutoff)
- }, [logs, days])
+ }, [items])
// Oldest → newest for the chart
const chartPoints: ChartPoint[] = useMemo(() => {
- return filtered
+ return chartLogs
.slice()
.reverse()
.map(l => {
const d = new Date(l.logged_at)
return { ts: d.getTime(), weight: lbsToDisplay(l.weight, settings.weight_unit), date: d }
})
- }, [filtered, settings.weight_unit])
+ }, [chartLogs, settings.weight_unit])
const handleLog = async (e: React.FormEvent) => {
e.preventDefault()
@@ -272,7 +272,7 @@ export default function Weight() {
return
}
- if (!duplicateWarningDismissedRef.current && logs.length > 0 && isoToDayInput(logs[0].logged_at) === newDate) {
+ if (!duplicateWarningDismissedRef.current && items.length > 0 && isoToDayInput(items[0].logged_at) === newDate) {
setShowDuplicateWarning(true)
return
}
@@ -281,46 +281,32 @@ export default function Weight() {
setError(null)
setShowDuplicateWarning(false)
- const tempId = -Date.now()
- const loggedAtIso = dayToIsoNoon(newDate)
- const trimmedNotes = newNotes.trim()
- const weightLbs = displayToLbs(w, settings.weight_unit)
- const optimistic: types.WeightLog = {
- id: tempId,
- weight: weightLbs,
- notes: trimmedNotes,
- logged_at: loggedAtIso,
- }
- setLogs(prev =>
- [optimistic, ...prev].sort(
- (a, b) => new Date(b.logged_at).getTime() - new Date(a.logged_at).getTime()
- )
- )
-
try {
const real = await weightAPI.log({
- weight: weightLbs,
- notes: trimmedNotes,
- logged_at: loggedAtIso,
+ weight: displayToLbs(w, settings.weight_unit),
+ notes: newNotes.trim(),
+ logged_at: dayToIsoNoon(newDate),
})
- setLogs(prev => prev.map(l => (l.id === tempId ? real : l)))
setNewWeight(String(Math.round(lbsToDisplay(real.weight, settings.weight_unit))))
setNewNotes('')
setNewDate(todayStr())
setShowNotes(false)
duplicateWarningDismissedRef.current = false
+ reload()
weightAPI.stats().then(setStats).catch(() => {})
+ const days = PERIOD_DAYS[period]
+ const from = days != null ? format(subDays(new Date(), days), 'yyyy-MM-dd') : undefined
+ weightAPI.list({ limit: 1000, from }).then(data => setChartLogs(data || [])).catch(() => {})
} catch (err: any) {
- setLogs(prev => prev.filter(l => l.id !== tempId))
setError(err?.response?.data?.error || 'Failed to log weight')
} finally {
setLogging(false)
}
}
- if (loading) return <Loading />
+ if (initialLoading) return <Loading />
- if (error && logs.length === 0) {
+ if (error && items.length === 0) {
return (
<div className="alert-error">
<AlertCircle className="w-5 h-5 flex-shrink-0" />
@@ -329,10 +315,9 @@ export default function Weight() {
)
}
- // Period stats are computed from the in-memory `filtered` window so the hero
- // card matches the period selector. For the "All" period we prefer the
- // server-computed stats — they don't truncate at the fetch limit (365 rows).
- const periodValues = filtered.map(l => l.weight) // raw lbs from DB
+ // Period stats computed from chartLogs (period-scoped server fetch).
+ // For "All" period prefer server-computed stats since they're not capped at 1000.
+ const periodValues = chartLogs.map(l => l.weight) // raw lbs from DB, newest first
const useServerAggregate = period === 'All' && stats != null
const currentLbs = periodValues[0] ?? stats?.latest ?? 0
const oldestLbs = periodValues[periodValues.length - 1] ?? stats?.starting ?? 0
@@ -390,8 +375,8 @@ export default function Weight() {
<Scale className="w-4 h-4 text-brand-500" />
<h2 className="section-title">Log Weight</h2>
</div>
- {logs.length > 0 && (
- <span className="text-[11px] text-tx-muted">last: {Math.round(lbsToDisplay(logs[0].weight, settings.weight_unit))} {wUnit}</span>
+ {items.length > 0 && (
+ <span className="text-[11px] text-tx-muted">last: {Math.round(lbsToDisplay(items[0].weight, settings.weight_unit))} {wUnit}</span>
)}
</div>
<form ref={logFormRef} onSubmit={handleLog} className="space-y-3">
@@ -442,11 +427,11 @@ export default function Weight() {
</button>
)}
- {showDuplicateWarning && logs.length > 0 && (
+ {showDuplicateWarning && items.length > 0 && (
<div className="flex items-start gap-3 rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-400" role="alert">
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
<div className="flex-1 min-w-0">
- <p className="font-medium">Already logged on {format(new Date(logs[0].logged_at), 'MMM d')} ({Math.round(lbsToDisplay(logs[0].weight, settings.weight_unit))} {wUnit}). Log again anyway?</p>
+ <p className="font-medium">Already logged on {format(new Date(items[0].logged_at), 'MMM d')} ({Math.round(lbsToDisplay(items[0].weight, settings.weight_unit))} {wUnit}). Log again anyway?</p>
<div className="flex gap-2 mt-2">
<button
type="button"
@@ -487,7 +472,7 @@ export default function Weight() {
{/* Current weight hero */}
<div className="card p-6 border-brand-500/20 bg-brand-500/5">
- {logs.length === 0 ? (
+ {items.length === 0 ? (
<div className="text-center py-2">
<p className="stat-label mb-1">Current Weight</p>
<p className="text-tx-muted text-sm">The scale doesn't know you exist yet. Fix that.</p>
@@ -537,21 +522,7 @@ export default function Weight() {
<div className="card p-5">
<div className="flex items-center justify-between mb-4 gap-2">
<h2 className="section-title">Trend</h2>
- <div className="flex gap-1 bg-surface-overlay rounded-lg p-1">
- {PERIODS.map(p => (
- <button
- key={p}
- onClick={() => setPeriod(p)}
- className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors duration-150 ${
- period === p
- ? 'bg-surface-raised border border-surface-border text-tx-primary shadow-card'
- : 'text-tx-muted hover:text-tx-primary'
- }`}
- >
- {p}
- </button>
- ))}
- </div>
+ <PeriodSelector options={PERIODS} value={period} onChange={setPeriod} />
</div>
{chartPoints.length === 0 ? (
@@ -568,12 +539,12 @@ export default function Weight() {
</div>
{/* History */}
- {logs.length > 0 && (
+ {items.length > 0 && (
<>
<h2 className="section-title px-1">History</h2>
<div className="space-y-2">
- {logs.slice(0, visibleCount).map((entry, i) => {
- const next = logs[i + 1]
+ {items.map((entry, i) => {
+ const next = items[i + 1]
const deltaLbs = next ? entry.weight - next.weight : 0
const displayW = lbsToDisplay(entry.weight, settings.weight_unit)
const displayDelta = lbsToDisplay(Math.abs(deltaLbs), settings.weight_unit)
@@ -613,10 +584,9 @@ export default function Weight() {
)
})}
</div>
- {hasMore && (
- <div ref={sentinelRef} className="flex justify-center py-4">
- <span className="text-xs text-tx-muted">Loading more…</span>
- </div>
+ <div ref={sentinelRef} />
+ {hasMore && listLoading && (
+ <p className="text-center text-xs text-tx-muted py-2">Loading more…</p>
)}
</>
)}
diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsx
index 69eca17..06c9b56 100644
--- a/web/src/pages/Workouts.tsx
+++ b/web/src/pages/Workouts.tsx
@@ -4,6 +4,7 @@ import { format } from 'date-fns'
import { Dumbbell, Plus, Clock, Search, AlertCircle, Edit2, Trash2, TrendingUp, ChevronRight, MoreVertical } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import Loading from '../components/Loading'
+import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, lbsToDisplay } from '../stores/settings'
import * as types from '../types'
@@ -200,34 +201,22 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on
export default function Workouts() {
const navigate = useNavigate()
- const [workouts, setWorkouts] = useState<types.Workout[]>([])
-
const [search, setSearch] = useState('')
- const [loading, setLoading] = useState(true)
+ const [debouncedSearch, setDebouncedSearch] = useState('')
const [error, setError] = useState<string | null>(null)
- const loadWorkouts = async () => {
- try {
- const data = await workoutAPI.list({ limit: 50 })
- setWorkouts(data || [])
- } catch (err: any) {
- setError(err.message || 'Failed to load workouts')
- } finally {
- setLoading(false)
- }
- }
-
+ // Debounce search so we don't fire a request on every keystroke
useEffect(() => {
- loadWorkouts()
- }, [])
+ const t = setTimeout(() => setDebouncedSearch(search), 300)
+ return () => clearTimeout(t)
+ }, [search])
- const filtered = workouts.filter(w =>
- w.name.toLowerCase().includes(search.toLowerCase())
- )
+ const { items: workouts, sentinelRef, hasMore, loading, initialLoading, reload } = useServerInfiniteList<types.Workout>({
+ fetcher: (offset, limit) => workoutAPI.list({ offset, limit, q: debouncedSearch || undefined }),
+ deps: [debouncedSearch],
+ })
- if (loading) {
- return <Loading />
- }
+ if (initialLoading) return <Loading />
if (error) {
return (
@@ -283,7 +272,7 @@ export default function Workouts() {
{/* Workout list */}
<div className="space-y-2">
- {filtered.length === 0 ? (
+ {workouts.length === 0 && !loading ? (
<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">
<Dumbbell className="w-6 h-6 text-tx-muted" />
@@ -292,10 +281,16 @@ export default function Workouts() {
<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}
- onEdit={(id) => navigate(`/workouts/${id}/edit`)}
- onDelete={(id) => setWorkouts(prev => prev.filter(x => x.id !== id))}
- />)
+ <>
+ {workouts.map(w => <WorkoutCard key={w.id} workout={w}
+ onEdit={(id) => navigate(`/workouts/${id}/edit`)}
+ onDelete={() => reload()}
+ />)}
+ <div ref={sentinelRef} />
+ {hasMore && loading && (
+ <p className="text-center text-xs text-tx-muted py-2">Loading more…</p>
+ )}
+ </>
)}
</div>
diff --git a/web/src/services/api.ts b/web/src/services/api.ts
index 498e0e8..3e4f3b9 100644
--- a/web/src/services/api.ts
+++ b/web/src/services/api.ts
@@ -61,7 +61,7 @@ export const userAPI = {
}
export const workoutAPI = {
- list: (params?: { limit?: number; offset?: number }) =>
+ list: (params?: { limit?: number; offset?: number; q?: string }) =>
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)),
@@ -97,7 +97,7 @@ export const exerciseAPI = {
export const programAPI = {
- list: () => api.get<{ data: types.Program[] }>('/programs').then(res => unwrap(res)),
+ list: (params?: { limit?: number; offset?: number; q?: string }) => api.get<{ data: types.Program[] }>('/programs', { params }).then(res => unwrap(res)),
get: (id: number) => api.get<{ data: types.Program }>(`/programs/${id}`).then(res => unwrap(res)),
create: (data: any) => api.post<{ data: types.Program }>('/programs', data).then(res => unwrap(res)),
update: (id: number, data: any) => api.put<{ data: types.Program }>(`/programs/${id}`, data).then(res => unwrap(res)),
@@ -105,7 +105,7 @@ export const programAPI = {
}
export const weightAPI = {
- list: (params?: { limit?: number; from?: string; to?: string }) =>
+ list: (params?: { limit?: number; offset?: number; from?: string; to?: string }) =>
api.get<{ data: types.WeightLog[] }>('/weight', { params }).then(res => unwrap(res)),
get: (id: number) => api.get<{ data: types.WeightLog }>(`/weight/${id}`).then(res => unwrap(res)),
log: (data: { weight: number; notes?: string; logged_at?: string }) =>