Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
feat(weight): edit endpoint, date-range filter, richer stats, tests (#3)
Carter4aa757ca43fd
diff --git a/README.md b/README.mdindex cb418ad..1970ba6 100644--- a/README.md+++ b/README.md@@ -7,51 +7,65 @@<p align="center"><a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License" /></a><img src="https://img.shields.io/badge/status-early%20beta-orange" alt="Early Beta" />- <a href="https://hub.docker.com/r/cwlumm/lyftr-backend"><img src="https://img.shields.io/docker/pulls/cwlumm/lyftr-backend?label=docker%20pulls&logo=docker&logoColor=white&color=2496ED" alt="Docker Pulls" /></a>+ <a href="https://selfh.st/weekly/2026-04-24/"><img src="https://img.shields.io/badge/Featured%20in-selfh.st%20%C2%B7%20Apr%202026-6366f1" alt="Featured in selfh.st" /></a><img src="https://img.shields.io/badge/iOS-planned-black?logo=apple&logoColor=white" alt="iOS Planned" /></p><p align="center">+ <img src="docs/screenshots/gym-mode-exercise-mobile.png" width="160" alt="Gym Mode" /><img src="docs/screenshots/dashboard-mobile.png" width="160" alt="Dashboard" />- <img src="docs/screenshots/workouts-mobile.png" width="160" alt="Workouts" />- <img src="docs/screenshots/active-workout-mobile.png" width="160" alt="Active Workout" />- <img src="docs/screenshots/gym-mode-overview-mobile.png" width="160" alt="Gym Mode Overview" />-</p>--<p align="center">- <img src="docs/screenshots/gym-mode-exercise-mobile.png" width="160" alt="Gym Mode Sets" /><img src="docs/screenshots/exercise-detail-mobile.png" width="160" alt="Exercise Detail" />- <img src="docs/screenshots/programs-mobile.png" width="160" alt="Programs" />- <img src="docs/screenshots/settings-mobile.png" width="160" alt="Settings" /></p><p align="center"><img src="docs/screenshots/dashboard-desktop.png" width="700" alt="Dashboard desktop" /></p>-<p align="center">- <img src="docs/screenshots/gym-mode-overview-desktop.png" width="700" alt="Gym Mode desktop" />-</p>-> **Early beta** — actively being built. Expect rough edges and frequent updates. Issues and feedback are welcome. The software equivalent of going to the gym for the first time.-> **First official beta release coming soon** — stay tuned. Unlike your scheduled rest day, this one won't keep getting pushed back.+> 🌐 **Live demo coming soon** — try it without spinning up Docker.++---++## Runs on++Tested and working on:++- **Raspberry Pi 4** (2 GB RAM, arm64 Docker image)+- **Any x86 VPS** — Hetzner CAX11, DigitalOcean Droplet, Oracle Free Tier+- **Synology NAS** via Docker (Container Manager)+- **Proxmox LXC** with Docker installed+- **Local machine** — Mac, Linux, Windows (WSL2)++Single SQLite file, minimal RAM, no external services required.++---++## Why Lyftr?++**Hevy and Strong** are polished apps but cloud-only, increasingly paywalled, and your data lives on someone else's server. **Wger** is self-hosted but complex to deploy and primarily web-focused. **FitNotes** is local-only with no sync or server deployment story.++Lyftr is for people who want a modern, mobile-first workout tracker that they fully own and can run on a $5 VPS or a Raspberry Pi in the corner. No subscription. No vendor lock-in. No "your export is a Pro feature."---## Features-| Feature | Web |-|---------|-----|+| Feature | Status |+|---------|--------|| Workout logging with 800+ exercise library | ✓ || Program builder — reusable workout templates | ✓ || Active workout mode — guided set-by-set flow | ✓ || Gym Mode — full-screen card layout, one exercise at a time | ✓ || Exercise detail — personal records, progression chart, muscle diagram | ✓ || Dashboard — volume trends, consistency heatmap, muscle balance | ✓ |+| Weight tracking with trend graph | ✓ |+| lbs / kg unit support across all data | ✓ || Self-hosted — all data stays on your server | ✓ || Nutrition tracking — calories and macros | In progress |-| Weight tracking with trend graph | In progress |+| PWA — installable on any device | Planned |+| Strong / Hevy CSV import | Planned |+| iOS app (Swift) | Planned |---@@ -74,6 +88,22 @@ Open `http://localhost` in your browser and create your account. If running on a---+## More Screenshots++<p align="center">+ <img src="docs/screenshots/workouts-mobile.png" width="160" alt="Workouts" />+ <img src="docs/screenshots/active-workout-mobile.png" width="160" alt="Active Workout" />+ <img src="docs/screenshots/gym-mode-overview-mobile.png" width="160" alt="Gym Mode Overview" />+ <img src="docs/screenshots/programs-mobile.png" width="160" alt="Programs" />+ <img src="docs/screenshots/settings-mobile.png" width="160" alt="Settings" />+</p>++<p align="center">+ <img src="docs/screenshots/gym-mode-overview-desktop.png" width="700" alt="Gym Mode desktop" />+</p>++---+## ConfigurationAll variables live in `.env` at the project root.@@ -97,9 +127,7 @@ On first startup, Lyftr automatically seeds 800+ exercises from [free-exercise-dThe seed runs async so the server is immediately available. Exercises appear in the UI within a few seconds.-**Re-sync exercises:**--Go to **Settings → Exercise Library** — shows current exercise count and an in-progress indicator while seeding. Hit **Re-sync** to pull the latest exercises from the source (safe upsert, existing workout data is untouched).+**Re-sync exercises:** Go to **Settings → Exercise Library** — shows current exercise count and a progress indicator while seeding. Hit **Re-sync** to pull the latest exercises (safe upsert, existing workout data is untouched).---@@ -142,10 +170,12 @@ For HTTPS, put Lyftr behind Caddy or nginx with a Let's Encrypt certificate.- [x] Active workout mode (list + gym mode layouts)- [x] Exercise detail — PRs, progression chart, muscle diagram- [x] Dashboard with charts and trends+- [x] Weight tracking with trend graph + lbs/kg support- [x] Docker deployment with E2E test pipeline- [ ] Nutrition tracking — in progress-- [ ] Weight tracking — in progress-- [ ] PWA — installable on any device+- [ ] PWA — installable on any device without an app store+- [ ] Strong / Hevy CSV import — so you don't lose years of data switching+- [ ] Apple Health / Google Fit export- [ ] iOS app (Swift)- [ ] Hosted option (no self-hosting required)diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.goindex 70d7a22..0966d04 100644--- a/backend/controllers/testhelper_test.go+++ b/backend/controllers/testhelper_test.go@@ -100,6 +100,14 @@ CREATE TABLE IF NOT EXISTS program_sets (set_number INTEGER NOT NULL DEFAULT 1,target_reps INTEGER NOT NULL DEFAULT 0,target_weight REAL NOT NULL DEFAULT 0+);+CREATE TABLE IF NOT EXISTS weight_logs (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ weight REAL NOT NULL,+ notes TEXT NOT NULL DEFAULT '',+ logged_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP);`_, err := db.DB.Exec(schema)return errdiff --git a/backend/controllers/weight.go b/backend/controllers/weight.goindex ff9c90d..fb0b613 100644--- a/backend/controllers/weight.go+++ b/backend/controllers/weight.go@@ -15,15 +15,43 @@ import (func ListWeightLogs(c *gin.Context) {uid := middleware.UserID(c)limit := 90- if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 {+ if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 1000 {limit = l}- rows, err := db.DB.Query(- `SELECT id, user_id, weight, notes, logged_at, created_at- FROM weight_logs WHERE user_id = ? ORDER BY logged_at DESC LIMIT ?`,- uid, limit,- )+ q := `SELECT id, user_id, weight, notes, logged_at, created_at+ FROM weight_logs WHERE user_id = ?`+ args := []any{uid}++ // Date params are calendar days in the user's local timezone. We don't know+ // the client's UTC offset, so for bare YYYY-MM-DD we widen the window by+ // ±12h to cover any plausible client TZ. Callers that want exact bounds can+ // pass a full RFC3339 timestamp instead.+ if from := c.Query("from"); from != "" {+ if t, exact, ok := parseDayOrTime(from); ok {+ lo := t+ if !exact {+ lo = t.Add(-12 * time.Hour)+ }+ q += ` AND logged_at >= ?`+ args = append(args, lo)+ }+ }+ if to := c.Query("to"); to != "" {+ if t, exact, ok := parseDayOrTime(to); ok {+ hi := t+ if !exact {+ // 24h of the day itself + 12h padding for west-of-UTC clocks.+ hi = t.Add(36 * time.Hour)+ }+ q += ` AND logged_at < ?`+ args = append(args, hi)+ }+ }+ q += ` ORDER BY logged_at DESC LIMIT ?`+ args = append(args, limit)++ rows, err := db.DB.Query(q, args...)if err != nil {utils.InternalError(c)return@@ -52,7 +80,10 @@ func LogWeight(c *gin.Context) {}if req.LoggedAt.IsZero() {- req.LoggedAt = time.Now()+ // .UTC() so the serialized response doesn't depend on the server's+ // timezone setting (the instant is the same either way; this keeps the+ // wire format consistent across deployments).+ req.LoggedAt = time.Now().UTC()}res, err := db.DB.Exec(@@ -66,13 +97,83 @@ func LogWeight(c *gin.Context) {id, _ := res.LastInsertId()var log models.WeightLog- db.DB.QueryRow(+ if err := db.DB.QueryRow(`SELECT id, user_id, weight, notes, logged_at, created_at FROM weight_logs WHERE id = ?`, id,- ).Scan(&log.ID, &log.UserID, &log.Weight, &log.Notes, &log.LoggedAt, &log.CreatedAt)-+ ).Scan(&log.ID, &log.UserID, &log.Weight, &log.Notes, &log.LoggedAt, &log.CreatedAt); err != nil {+ utils.InternalError(c)+ return+ }utils.Created(c, log)}+func GetWeightLog(c *gin.Context) {+ uid := middleware.UserID(c)+ lid, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil {+ utils.BadRequest(c, "invalid id")+ return+ }++ var log models.WeightLog+ if err := db.DB.QueryRow(+ `SELECT id, user_id, weight, notes, logged_at, created_at FROM weight_logs WHERE id = ? AND user_id = ?`,+ lid, uid,+ ).Scan(&log.ID, &log.UserID, &log.Weight, &log.Notes, &log.LoggedAt, &log.CreatedAt); err != nil {+ utils.NotFound(c, "log entry not found")+ return+ }+ utils.OK(c, log)+}++func UpdateWeightLog(c *gin.Context) {+ uid := middleware.UserID(c)+ lid, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil {+ utils.BadRequest(c, "invalid id")+ return+ }++ var req models.LogWeightRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ utils.BadRequest(c, err.Error())+ return+ }+ if err := validate.Struct(req); err != nil {+ utils.ValidationError(c, err)+ return+ }++ if req.LoggedAt.IsZero() {+ // .UTC() so the serialized response doesn't depend on the server's+ // timezone setting (the instant is the same either way; this keeps the+ // wire format consistent across deployments).+ req.LoggedAt = time.Now().UTC()+ }++ res, err := db.DB.Exec(+ `UPDATE weight_logs SET weight = ?, notes = ?, logged_at = ? WHERE id = ? AND user_id = ?`,+ req.Weight, req.Notes, req.LoggedAt, lid, uid,+ )+ if err != nil {+ utils.InternalError(c)+ return+ }+ n, _ := res.RowsAffected()+ if n == 0 {+ utils.NotFound(c, "log entry not found")+ return+ }++ var log models.WeightLog+ if err := db.DB.QueryRow(+ `SELECT id, user_id, weight, notes, logged_at, created_at FROM weight_logs WHERE id = ?`, lid,+ ).Scan(&log.ID, &log.UserID, &log.Weight, &log.Notes, &log.LoggedAt, &log.CreatedAt); err != nil {+ utils.InternalError(c)+ return+ }+ utils.OK(c, log)+}+func DeleteWeightLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)@@ -97,19 +198,60 @@ func DeleteWeightLog(c *gin.Context) {func GetWeightStats(c *gin.Context) {uid := middleware.UserID(c)- var latest, oldest sql.NullFloat64- var count int+ var (+ latest, oldest, minW, maxW, avgW sql.NullFloat64+ count int+ )db.DB.QueryRow(`SELECT(SELECT weight FROM weight_logs WHERE user_id = ? ORDER BY logged_at DESC LIMIT 1),(SELECT weight FROM weight_logs WHERE user_id = ? ORDER BY logged_at ASC LIMIT 1),- COUNT(*) FROM weight_logs WHERE user_id = ?`,+ MIN(weight), MAX(weight), AVG(weight), COUNT(*)+ FROM weight_logs WHERE user_id = ?`,uid, uid, uid,- ).Scan(&latest, &oldest, &count)+ ).Scan(&latest, &oldest, &minW, &maxW, &avgW, &count)++ change7 := changeOver(uid, 7)+ change30 := changeOver(uid, 30)utils.OK(c, gin.H{"latest": latest.Float64,"starting": oldest.Float64,+ "min": minW.Float64,+ "max": maxW.Float64,+ "avg": avgW.Float64,"total_entries": count,+ "change_7d": change7,+ "change_30d": change30,})}++// parseDayOrTime accepts either a full RFC3339 timestamp or a bare YYYY-MM-DD.+// Returns the parsed time, whether the input was an exact timestamp (so callers+// know not to widen the window), and parse success.+func parseDayOrTime(s string) (t time.Time, exact bool, ok bool) {+ if v, err := time.Parse(time.RFC3339, s); err == nil {+ return v, true, true+ }+ if v, err := time.Parse("2006-01-02", s); err == nil {+ return v, false, true+ }+ return time.Time{}, false, false+}++// changeOver returns latest weight minus the earliest weight within the last+// `days` days. Returns 0 when there are fewer than two entries in the window.+func changeOver(uid int64, days int) float64 {+ cutoff := time.Now().UTC().AddDate(0, 0, -days)+ var latest, earliest sql.NullFloat64+ db.DB.QueryRow(+ `SELECT+ (SELECT weight FROM weight_logs WHERE user_id = ? AND logged_at >= ? ORDER BY logged_at DESC LIMIT 1),+ (SELECT weight FROM weight_logs WHERE user_id = ? AND logged_at >= ? ORDER BY logged_at ASC LIMIT 1)`,+ uid, cutoff, uid, cutoff,+ ).Scan(&latest, &earliest)+ if !latest.Valid || !earliest.Valid {+ return 0+ }+ return latest.Float64 - earliest.Float64+}diff --git a/backend/controllers/weight_test.go b/backend/controllers/weight_test.gonew file mode 100644index 0000000..8348d07--- /dev/null+++ b/backend/controllers/weight_test.go@@ -0,0 +1,318 @@+package controllers++import (+ "fmt"+ "net/http"+ "testing"+ "time"++ "github.com/Cawlumm/lyftr-backend/db"+)++func insertWeightLog(t *testing.T, uid int64, weight float64, loggedAt time.Time) int64 {+ t.Helper()+ res, err := db.DB.Exec(+ `INSERT INTO weight_logs (user_id, weight, notes, logged_at) VALUES (?, ?, '', ?)`,+ uid, weight, loggedAt,+ )+ if err != nil {+ t.Fatalf("insert weight log: %v", err)+ }+ id, _ := res.LastInsertId()+ return id+}++func TestListWeightLogs_empty(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodGet, "/api/v1/weight", nil)+ ListWeightLogs(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data, ok := resp["data"].([]any)+ if !ok || len(data) != 0 {+ t.Fatalf("expected empty list, got %v", resp["data"])+ }+}++func TestListWeightLogs_orderedDescAndScopedByUser(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other, _ := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")+ otherUID, _ := other.LastInsertId()++ now := time.Now()+ insertWeightLog(t, uid, 180.0, now.AddDate(0, 0, -2))+ insertWeightLog(t, uid, 181.5, now.AddDate(0, 0, -1))+ insertWeightLog(t, uid, 179.0, now)+ insertWeightLog(t, otherUID, 999.0, now)++ c, w := newContext(uid, http.MethodGet, "/api/v1/weight", nil)+ ListWeightLogs(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 3 {+ t.Fatalf("expected 3 entries (own only), got %d", len(data))+ }+ first := data[0].(map[string]any)+ if first["weight"].(float64) != 179.0 {+ t.Errorf("expected newest first (179.0), got %v", first["weight"])+ }+}++func TestListWeightLogs_dateRange(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ now := time.Now()+ insertWeightLog(t, uid, 180.0, now.AddDate(0, 0, -10))+ insertWeightLog(t, uid, 181.0, now.AddDate(0, 0, -5))+ insertWeightLog(t, uid, 182.0, now)++ from := now.AddDate(0, 0, -7).Format("2006-01-02")+ to := now.Format("2006-01-02")+ c, w := newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/weight?from=%s&to=%s", from, to), nil)+ ListWeightLogs(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 2 {+ t.Fatalf("expected 2 entries within range, got %d", len(data))+ }+}++// Regression: a YYYY-MM-DD `to` should include entries logged late on that+// day for users in west-of-UTC timezones. Their `${date}T12:00:00` local+// stored as UTC ends up several hours after UTC midnight, which a naive+// "parse as UTC + 24h" would have excluded.+func TestListWeightLogs_dateRangeWestTimezone(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ // Simulate a user in UTC-7 logging "2026-04-25 noon local" — stored as+ // 2026-04-25T19:00:00Z. A naive parser interpreting `to=2026-04-25` as+ // UTC midnight + 24h would treat the cutoff as 2026-04-25T00:00:00Z+ // and miss this entry.+ loggedAt := time.Date(2026, 4, 25, 19, 0, 0, 0, time.UTC)+ insertWeightLog(t, uid, 175.0, loggedAt)++ c, w := newContext(uid, http.MethodGet, "/api/v1/weight?from=2026-04-25&to=2026-04-25", nil)+ ListWeightLogs(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected 1 entry across TZ-padded day, got %d", len(data))+ }+}++// Regression: an RFC3339 timestamp must be honored exactly without any TZ+// padding. Callers that pass precise bounds expect exclusive control.+func TestListWeightLogs_dateRangeExactRFC3339(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ insertWeightLog(t, uid, 175.0, time.Date(2026, 4, 25, 10, 0, 0, 0, time.UTC))+ insertWeightLog(t, uid, 176.0, time.Date(2026, 4, 25, 14, 0, 0, 0, time.UTC))++ c, w := newContext(uid, http.MethodGet,+ "/api/v1/weight?from=2026-04-25T12:00:00Z&to=2026-04-25T15:00:00Z", nil)+ ListWeightLogs(c)++ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected 1 entry within exact window, got %d", len(data))+ }+ first := data[0].(map[string]any)+ if first["weight"].(float64) != 176.0 {+ t.Errorf("expected the 14:00 entry, got %v", first["weight"])+ }+}++func TestLogWeight_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{"weight": 185.5, "notes": "morning"}+ c, w := newContext(uid, http.MethodPost, "/api/v1/weight", body)+ LogWeight(c)++ if w.Code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["weight"].(float64) != 185.5 {+ t.Errorf("expected weight 185.5, got %v", data["weight"])+ }+ if data["notes"].(string) != "morning" {+ t.Errorf("expected notes preserved, got %v", data["notes"])+ }+}++func TestLogWeight_rejectsNonPositive(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{"weight": 0}+ c, w := newContext(uid, http.MethodPost, "/api/v1/weight", body)+ LogWeight(c)++ if w.Code == http.StatusCreated {+ t.Fatal("expected validation error for weight=0, got 201")+ }+}++func TestLogWeight_rejectsImplausiblyLarge(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{"weight": 9999}+ c, w := newContext(uid, http.MethodPost, "/api/v1/weight", body)+ LogWeight(c)++ if w.Code == http.StatusCreated {+ t.Fatal("expected validation error for weight=9999, got 201")+ }+}++func TestUpdateWeightLog_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ id := insertWeightLog(t, uid, 180.0, time.Now())++ body := map[string]any{"weight": 178.0, "notes": "after run"}+ c, w := newContext(uid, http.MethodPatch, "/api/v1/weight/"+fmt.Sprint(id), body)+ setParam(c, "id", fmt.Sprint(id))+ UpdateWeightLog(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["weight"].(float64) != 178.0 {+ t.Errorf("expected updated weight 178.0, got %v", data["weight"])+ }+ if data["notes"].(string) != "after run" {+ t.Errorf("expected updated notes, got %v", data["notes"])+ }+}++func TestUpdateWeightLog_ownershipEnforced(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other, _ := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")+ otherUID, _ := other.LastInsertId()+ id := insertWeightLog(t, otherUID, 200.0, time.Now())++ body := map[string]any{"weight": 100.0}+ c, w := newContext(uid, http.MethodPatch, "/api/v1/weight/"+fmt.Sprint(id), body)+ setParam(c, "id", fmt.Sprint(id))+ UpdateWeightLog(c)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for cross-user update, got %d", w.Code)+ }+ var weight float64+ db.DB.QueryRow(`SELECT weight FROM weight_logs WHERE id = ?`, id).Scan(&weight)+ if weight != 200.0 {+ t.Fatalf("expected unchanged weight 200.0, got %v", weight)+ }+}++func TestDeleteWeightLog_ownershipEnforced(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other, _ := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")+ otherUID, _ := other.LastInsertId()+ id := insertWeightLog(t, otherUID, 200.0, time.Now())++ c, w := newContext(uid, http.MethodDelete, "/api/v1/weight/"+fmt.Sprint(id), nil)+ setParam(c, "id", fmt.Sprint(id))+ DeleteWeightLog(c)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)+ }+ var count int+ db.DB.QueryRow(`SELECT COUNT(*) FROM weight_logs WHERE id = ?`, id).Scan(&count)+ if count != 1 {+ t.Fatal("entry was deleted by wrong user")+ }+}++func TestGetWeightStats_richFields(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ now := time.Now()+ insertWeightLog(t, uid, 180.0, now.AddDate(0, 0, -40))+ insertWeightLog(t, uid, 178.0, now.AddDate(0, 0, -20))+ insertWeightLog(t, uid, 176.0, now.AddDate(0, 0, -5))+ insertWeightLog(t, uid, 175.0, now.AddDate(0, 0, -1))++ c, w := newContext(uid, http.MethodGet, "/api/v1/weight/stats", nil)+ GetWeightStats(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)++ if data["latest"].(float64) != 175.0 {+ t.Errorf("latest: expected 175.0, got %v", data["latest"])+ }+ if data["starting"].(float64) != 180.0 {+ t.Errorf("starting: expected 180.0, got %v", data["starting"])+ }+ if data["min"].(float64) != 175.0 {+ t.Errorf("min: expected 175.0, got %v", data["min"])+ }+ if data["max"].(float64) != 180.0 {+ t.Errorf("max: expected 180.0, got %v", data["max"])+ }+ if data["total_entries"].(float64) != 4 {+ t.Errorf("total_entries: expected 4, got %v", data["total_entries"])+ }+ // 7d window contains entries at -5d and -1d, so change_7d = 175 - 176 = -1+ if got := data["change_7d"].(float64); got != -1.0 {+ t.Errorf("change_7d: expected -1.0, got %v", got)+ }+ // 30d window contains -20, -5, -1, so change_30d = 175 - 178 = -3+ if got := data["change_30d"].(float64); got != -3.0 {+ t.Errorf("change_30d: expected -3.0, got %v", got)+ }+}++func TestGetWeightStats_noData(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodGet, "/api/v1/weight/stats", nil)+ GetWeightStats(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["total_entries"].(float64) != 0 {+ t.Errorf("expected total_entries=0, got %v", data["total_entries"])+ }+ if data["change_7d"].(float64) != 0 {+ t.Errorf("expected change_7d=0 with no data, got %v", data["change_7d"])+ }+}diff --git a/backend/models/models.go b/backend/models/models.goindex f75dd98..137956c 100644--- a/backend/models/models.go+++ b/backend/models/models.go@@ -57,7 +57,7 @@ type Set struct {WorkoutExerciseID int64 `json:"workout_exercise_id" db:"workout_exercise_id"`SetNumber int `json:"set_number" db:"set_number"`Reps int `json:"reps,omitempty" db:"reps"`- Weight float64 `json:"weight,omitempty" db:"weight"` // stored in kg+ Weight float64 `json:"weight,omitempty" db:"weight"` // raw value in user's preferred unit (lbs or kg)Duration int `json:"duration,omitempty" db:"duration"` // seconds, for timed setsDistance float64 `json:"distance,omitempty" db:"distance"` // metersRPE float64 `json:"rpe,omitempty" db:"rpe"`@@ -67,7 +67,7 @@ type Set struct {type WeightLog struct {ID int64 `json:"id" db:"id"`UserID int64 `json:"user_id" db:"user_id"`- Weight float64 `json:"weight" db:"weight"` // stored in kg+ Weight float64 `json:"weight" db:"weight"` // raw value in user's preferred unit (lbs or kg)Notes string `json:"notes,omitempty" db:"notes"`LoggedAt time.Time `json:"logged_at" db:"logged_at"`CreatedAt time.Time `json:"created_at" db:"created_at"`@@ -137,7 +137,7 @@ type CreateSetReq struct {}type LogWeightRequest struct {- Weight float64 `json:"weight" validate:"required,gt=0"`+ Weight float64 `json:"weight" validate:"required,gt=0,lte=2000"`Notes string `json:"notes"`LoggedAt time.Time `json:"logged_at"`}diff --git a/backend/routes/routes.go b/backend/routes/routes.goindex eb6990a..d488bff 100644--- a/backend/routes/routes.go+++ b/backend/routes/routes.go@@ -54,8 +54,10 @@ func Setup(r *gin.Engine) {// Weightprotected.GET("weight", controllers.ListWeightLogs)protected.POST("weight", controllers.LogWeight)- protected.DELETE("weight/:id", controllers.DeleteWeightLog)protected.GET("weight/stats", controllers.GetWeightStats)+ protected.GET("weight/:id", controllers.GetWeightLog)+ protected.PATCH("weight/:id", controllers.UpdateWeightLog)+ protected.DELETE("weight/:id", controllers.DeleteWeightLog)// Foodprotected.GET("food", controllers.ListFoodLogs)diff --git a/web/src/App.tsx b/web/src/App.tsxindex 6a44047..467a3e8 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -18,6 +18,7 @@ import WorkoutDetail from './pages/WorkoutDetail'import ProgramDetail from './pages/ProgramDetail'import Food from './pages/Food'import Weight from './pages/Weight'+import WeightDetail from './pages/WeightDetail'import Settings from './pages/Settings'import Login from './pages/Login'import Register from './pages/Register'@@ -60,6 +61,7 @@ function App() {<Route path="/exercises/:exerciseId" element={<ExerciseDetail />} /><Route path="/food" element={<Food />} /><Route path="/weight" element={<Weight />} />+ <Route path="/weight/:id" element={<WeightDetail />} /><Route path="/settings" element={<Settings />} /></Route>) : (diff --git a/web/src/components/AddProgramModal.tsx b/web/src/components/AddProgramModal.tsxindex d49934c..838b308 100644--- a/web/src/components/AddProgramModal.tsx+++ b/web/src/components/AddProgramModal.tsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { createPortal } from 'react-dom'import { Plus, X, Trash2, AlertCircle, BookOpen, FileText, Zap, Target } from 'lucide-react'import { programAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'import ExercisePicker from './ExercisePicker'import * as types from '../types'@@ -82,7 +82,14 @@ export default function AddProgramModal({ isOpen, onClose, onSuccess }: Props) {setLoading(true)try {- await programAPI.create(formData)+ const payload = {+ ...formData,+ exercises: formData.exercises.map(ex => ({+ ...ex,+ sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),+ })),+ }+ await programAPI.create(payload)setFormData({ name: '', notes: '', exercises: [] })setPickerExercises({})onSuccess()diff --git a/web/src/components/AddWorkoutModal.tsx b/web/src/components/AddWorkoutModal.tsxindex be7af5f..985d8ec 100644--- a/web/src/components/AddWorkoutModal.tsx+++ b/web/src/components/AddWorkoutModal.tsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { createPortal } from 'react-dom'import { Plus, X, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge, BookOpen } from 'lucide-react'import { workoutAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'import ExercisePicker from './ExercisePicker'import ProgramPicker from './ProgramPicker'import * as types from '../types'@@ -133,7 +133,10 @@ export default function AddWorkoutModal({ isOpen, onClose, onSuccess }: Props) {name: formData.name,notes: formData.notes,duration: formData.duration,- exercises: formData.exercises,+ exercises: formData.exercises.map(ex => ({+ ...ex,+ sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),+ })),started_at: new Date().toISOString(),})setFormData({ name: '', notes: '', duration: 0, exercises: [] })diff --git a/web/src/components/EditProgramModal.tsx b/web/src/components/EditProgramModal.tsxindex 3ef8b6d..9341c00 100644--- a/web/src/components/EditProgramModal.tsx+++ b/web/src/components/EditProgramModal.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'import { createPortal } from 'react-dom'import { Plus, X, Trash2, AlertCircle, BookOpen, FileText, Zap, Target } from 'lucide-react'import { programAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'import ExercisePicker from './ExercisePicker'import * as types from '../types'@@ -51,7 +51,7 @@ export default function EditProgramModal({ isOpen, onClose, onSuccess, programIdsets: (ex.sets || []).map(s => ({set_number: s.set_number,target_reps: s.target_reps,- target_weight: s.target_weight,+ target_weight: lbsToDisplay(s.target_weight, settings.weight_unit),})),})),})@@ -105,7 +105,14 @@ export default function EditProgramModal({ isOpen, onClose, onSuccess, programIdsetLoading(true)try {- await programAPI.update(programId, formData)+ const payload = {+ ...formData,+ exercises: formData.exercises.map(ex => ({+ ...ex,+ sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),+ })),+ }+ await programAPI.update(programId, payload)onSuccess()onClose()} catch (err: any) {diff --git a/web/src/components/EditWeightModal.tsx b/web/src/components/EditWeightModal.tsxnew file mode 100644index 0000000..e12f284--- /dev/null+++ b/web/src/components/EditWeightModal.tsx@@ -0,0 +1,159 @@+import { useState, useEffect } from 'react'+import { createPortal } from 'react-dom'+import { X, Scale, AlertCircle, Save } from 'lucide-react'+import { weightAPI } from '../services/api'+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'+import { useBodyScrollLock } from '../hooks/useBodyScrollLock'+import { useEscapeKey } from '../hooks/useEscapeKey'+import { isPositiveNumber } from '../utils/numberUtils'+import { dayToIsoNoon, isoToDayInput, todayStr } from '../utils/dateUtils'+import * as types from '../types'++interface Props {+ isOpen: boolean+ onClose: () => void+ onSuccess: () => void+ log: types.WeightLog | null+}++export default function EditWeightModal({ isOpen, onClose, onSuccess, log }: Props) {+ const { settings } = useSettingsStore()+ const wUnit = weightShort(settings.weight_unit)++ const [weight, setWeight] = useState('')+ const [loggedAt, setLoggedAt] = useState('')+ const [notes, setNotes] = useState('')+ const [saving, setSaving] = useState(false)+ const [error, setError] = useState('')++ useEffect(() => {+ if (!isOpen || !log) return+ setWeight(String(Math.round(lbsToDisplay(log.weight, settings.weight_unit))))+ setLoggedAt(isoToDayInput(log.logged_at))+ setNotes(log.notes ?? '')+ setError('')+ }, [isOpen, log])++ const handleClose = () => { setError(''); onClose() }++ useBodyScrollLock(isOpen && !!log)+ useEscapeKey(isOpen && !!log, handleClose)++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault()+ if (!log || saving) return+ const w = parseFloat(weight)+ if (!Number.isFinite(w) || w <= 0) {+ setError('Enter a valid weight')+ return+ }+ setSaving(true)+ setError('')+ try {+ await weightAPI.update(log.id, {+ weight: displayToLbs(w, settings.weight_unit),+ notes: notes.trim(),+ logged_at: dayToIsoNoon(loggedAt),+ })+ onSuccess()+ onClose()+ } catch (err: any) {+ setError(err?.response?.data?.error || 'Failed to save')+ } finally {+ setSaving(false)+ }+ }++ if (!isOpen || !log) return null++ return createPortal((+ <div+ className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4"+ onClick={handleClose}+ >+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="ewm-title"+ className="bg-surface-base border border-surface-border rounded-2xl w-full max-h-[90vh] sm:max-w-md overflow-y-auto"+ onClick={e => e.stopPropagation()}+ >+ <div className="sticky top-0 border-b border-surface-border bg-surface-base px-5 py-4 flex items-center justify-between">+ <div className="flex items-center gap-2">+ <Scale className="w-4 h-4 text-brand-500" />+ <h2 id="ewm-title" className="font-display font-bold text-xl text-tx-primary">Edit Weight</h2>+ </div>+ <button onClick={handleClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">+ <X className="w-5 h-5 text-tx-muted" />+ </button>+ </div>++ <form onSubmit={handleSubmit} className="p-5 space-y-4">+ {error && (+ <div className="alert-error" role="alert" aria-live="polite">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ <span>{error}</span>+ </div>+ )}++ <div>+ <label className="label">Weight</label>+ <div className="relative mt-1">+ <input+ type="number"+ value={weight}+ onChange={e => setWeight(e.target.value)}+ step="0.1"+ min="0"+ className="input pr-10"+ autoFocus+ />+ <span className="absolute right-3.5 top-1/2 -translate-y-1/2 text-xs text-tx-muted">{wUnit}</span>+ </div>+ </div>++ <div>+ <label className="label">Date</label>+ <input+ type="date"+ value={loggedAt}+ onChange={e => setLoggedAt(e.target.value)}+ className="input mt-1"+ max={todayStr()}+ />+ </div>++ <div>+ <label className="label">Notes <span className="text-tx-muted font-normal">(optional)</span></label>+ <input+ type="text"+ value={notes}+ onChange={e => setNotes(e.target.value)}+ placeholder="e.g., after run, post-meal"+ className="input mt-1"+ maxLength={200}+ />+ </div>++ <div className="flex items-center justify-end gap-2 pt-2">+ <button+ type="button"+ onClick={handleClose}+ className="px-4 py-2 text-sm bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium"+ >+ Cancel+ </button>+ <button+ type="submit"+ disabled={!isPositiveNumber(weight) || saving}+ className="btn-primary btn-md"+ >+ <Save className="w-4 h-4" />+ {saving ? 'Saving…' : 'Save'}+ </button>+ </div>+ </form>+ </div>+ </div>+ ), document.body)+}diff --git a/web/src/components/EditWorkoutModal.tsx b/web/src/components/EditWorkoutModal.tsxindex befdcfb..6002fb5 100644--- a/web/src/components/EditWorkoutModal.tsx+++ b/web/src/components/EditWorkoutModal.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'import { createPortal } from 'react-dom'import { Plus, X, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge } from 'lucide-react'import { workoutAPI, exerciseAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'import ExercisePicker from './ExercisePicker'import * as types from '../types'@@ -73,7 +73,7 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutIdsets: (ex.sets || []).map(s => ({set_number: s.set_number,reps: s.reps,- weight: s.weight,+ weight: lbsToDisplay(s.weight, settings.weight_unit),})),})),})@@ -149,7 +149,10 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutIdname: formData.name,notes: formData.notes,duration: formData.duration,- exercises: formData.exercises,+ exercises: formData.exercises.map(ex => ({+ ...ex,+ sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),+ })),started_at: originalStartedAt || new Date().toISOString(),})onSuccess()diff --git a/web/src/components/QuickWeighInSheet.tsx b/web/src/components/QuickWeighInSheet.tsxnew file mode 100644index 0000000..9af6294--- /dev/null+++ b/web/src/components/QuickWeighInSheet.tsx@@ -0,0 +1,208 @@+import { useState, useEffect, useRef } from 'react'+import { createPortal } from 'react-dom'+import { X, Scale, Save, AlertCircle, Calendar, FileText } from 'lucide-react'+import { weightAPI } from '../services/api'+import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'+import { useBodyScrollLock } from '../hooks/useBodyScrollLock'+import { useEscapeKey } from '../hooks/useEscapeKey'+import { isPositiveNumber } from '../utils/numberUtils'+import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'+import WeightInput from './WeightInput'+import * as types from '../types'++interface Props {+ isOpen: boolean+ lastValue: number | null+ lastLog?: types.WeightLog | null+ onClose: () => void+ onSuccess: (log: types.WeightLog) => void+}++export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose, onSuccess }: Props) {+ const { settings } = useSettingsStore()+ const wUnit = weightShort(settings.weight_unit)++ const [value, setValue] = useState('')+ const [date, setDate] = useState(todayStr())+ const [notes, setNotes] = useState('')+ const [showExtras, setShowExtras] = useState(false)+ const [saving, setSaving] = useState(false)+ const [error, setError] = useState('')+ const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)+ const duplicateWarningDismissedRef = useRef(false)+ const formRef = useRef<HTMLFormElement>(null)++ useEffect(() => {+ if (!isOpen) return+ setValue(lastValue && lastValue > 0 ? String(lastValue) : '')+ setDate(todayStr())+ setNotes('')+ setShowExtras(false)+ setError('')+ setSaving(false)+ setShowDuplicateWarning(false)+ duplicateWarningDismissedRef.current = false+ }, [isOpen, lastValue])++ const handleClose = () => { setError(''); onClose() }++ useBodyScrollLock(isOpen)+ useEscapeKey(isOpen, handleClose)++ if (!isOpen) return null++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault()+ if (saving) return+ const w = parseFloat(value)+ if (!Number.isFinite(w) || w <= 0) {+ setError('Enter a valid weight')+ return+ }++ if (!duplicateWarningDismissedRef.current && lastLog && isoToDayInput(lastLog.logged_at) === date) {+ setShowDuplicateWarning(true)+ return+ }++ setSaving(true)+ setError('')+ setShowDuplicateWarning(false)+ try {+ const log = await weightAPI.log({+ weight: displayToLbs(w, settings.weight_unit),+ notes: notes.trim(),+ logged_at: dayToIsoNoon(date),+ })+ onSuccess(log)+ onClose()+ } catch (err: any) {+ setError(err?.response?.data?.error || 'Failed to save')+ setSaving(false)+ }+ }++ return createPortal((+ <div+ className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4"+ onClick={handleClose}+ >+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="qws-title"+ className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-md max-h-[90vh] overflow-y-auto animate-slide-up"+ onClick={e => e.stopPropagation()}+ >+ {/* Drag handle — mobile only */}+ <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mt-3 mb-1 sm:hidden" />++ {/* Header */}+ <div className="flex items-center justify-between px-5 py-4 border-b border-surface-border">+ <div className="flex items-center gap-2">+ <div className="w-8 h-8 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center">+ <Scale className="w-4 h-4 text-brand-500" />+ </div>+ <h2 id="qws-title" className="font-display font-bold text-lg text-tx-primary">Log Weight</h2>+ </div>+ <button onClick={handleClose} className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors">+ <X className="w-5 h-5 text-tx-muted" />+ </button>+ </div>++ <form ref={formRef} onSubmit={handleSubmit} className="p-5 space-y-4">+ {error && (+ <div className="alert-error" role="alert" aria-live="polite">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ <span>{error}</span>+ </div>+ )}++ {showDuplicateWarning && lastLog && (+ <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 today ({Math.round(lastValue ?? 0)} {wUnit}). Log again anyway?</p>+ <div className="flex gap-2 mt-2">+ <button+ type="button"+ onClick={() => setShowDuplicateWarning(false)}+ className="px-3 py-1 rounded-lg text-xs font-medium bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={() => {+ duplicateWarningDismissedRef.current = true+ setShowDuplicateWarning(false)+ formRef.current?.requestSubmit()+ }}+ className="px-3 py-1 rounded-lg text-xs font-medium bg-amber-500/20 border border-amber-500/30 text-amber-300 hover:bg-amber-500/30 transition-colors"+ >+ Log Anyway+ </button>+ </div>+ </div>+ </div>+ )}++ <WeightInput+ value={value}+ onChange={setValue}+ unit={wUnit}+ autoFocus+ size="lg"+ />++ {!showExtras ? (+ <button+ type="button"+ onClick={() => setShowExtras(true)}+ className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex items-center gap-1"+ >+ + Change date or add a note+ </button>+ ) : (+ <div className="space-y-3 pt-1">+ <div>+ <label className="label">+ <Calendar className="w-3 h-3" /> Date+ </label>+ <input+ type="date"+ value={date}+ onChange={e => setDate(e.target.value)}+ max={todayStr()}+ className="input mt-1"+ />+ </div>+ <div>+ <label className="label">+ <FileText className="w-3 h-3" /> Note <span className="text-tx-muted font-normal normal-case tracking-normal">(optional)</span>+ </label>+ <input+ type="text"+ value={notes}+ onChange={e => setNotes(e.target.value)}+ placeholder="e.g., morning, post-workout"+ maxLength={200}+ className="input mt-1"+ />+ </div>+ </div>+ )}++ <button+ type="submit"+ disabled={!isPositiveNumber(value) || saving}+ className="btn-primary btn-lg w-full"+ >+ <Save className="w-4 h-4" />+ {saving ? 'Saving…' : 'Save'}+ </button>+ </form>+ </div>+ </div>+ ), document.body)+}diff --git a/web/src/components/WeightInput.tsx b/web/src/components/WeightInput.tsxnew file mode 100644index 0000000..0f0a86b--- /dev/null+++ b/web/src/components/WeightInput.tsx@@ -0,0 +1,70 @@+import { Minus, Plus } from 'lucide-react'++interface Props {+ value: string+ onChange: (next: string) => void+ unit: string+ step?: number+ autoFocus?: boolean+ size?: 'md' | 'lg'+}++const STEP_DEFAULT = 0.5++export default function WeightInput({+ value,+ onChange,+ unit,+ step = STEP_DEFAULT,+ autoFocus = false,+ size = 'md',+}: Props) {+ const adjust = (delta: number) => {+ const current = parseFloat(value)+ const base = Number.isFinite(current) ? current : 0+ const next = Math.max(0, +(base + delta).toFixed(1))+ onChange(String(next))+ }++ const inputSize = size === 'lg'+ ? 'text-3xl py-4 font-display font-bold'+ : 'text-base py-2.5'+ const buttonSize = size === 'lg' ? 'p-4' : 'p-2.5'+ const iconSize = size === 'lg' ? 'w-6 h-6' : 'w-4 h-4'++ return (+ <div className="flex items-stretch gap-2">+ <button+ type="button"+ onClick={() => adjust(-step)}+ className={`${buttonSize} bg-surface-overlay border border-surface-border rounded-lg text-tx-secondary hover:bg-surface-muted active:scale-95 transition-all flex items-center justify-center flex-shrink-0`}+ aria-label={`Decrease by ${step}`}+ >+ <Minus className={iconSize} />+ </button>+ <div className="relative flex-1 min-w-0">+ <input+ type="number"+ inputMode="decimal"+ enterKeyHint="done"+ value={value}+ onChange={e => onChange(e.target.value)}+ step={step}+ min="0"+ autoFocus={autoFocus}+ className={`input ${inputSize} pr-12 text-center w-full tabular-nums`}+ placeholder="0.0"+ />+ <span className="absolute right-3.5 top-1/2 -translate-y-1/2 text-xs text-tx-muted">{unit}</span>+ </div>+ <button+ type="button"+ onClick={() => adjust(step)}+ className={`${buttonSize} bg-surface-overlay border border-surface-border rounded-lg text-tx-secondary hover:bg-surface-muted active:scale-95 transition-all flex items-center justify-center flex-shrink-0`}+ aria-label={`Increase by ${step}`}+ >+ <Plus className={iconSize} />+ </button>+ </div>+ )+}diff --git a/web/src/hooks/useBodyScrollLock.ts b/web/src/hooks/useBodyScrollLock.tsnew file mode 100644index 0000000..4177beb--- /dev/null+++ b/web/src/hooks/useBodyScrollLock.ts@@ -0,0 +1,29 @@+import { useEffect } from 'react'++/**+ * Lock body scroll while `active` is true. Restores the previous overflow+ * value on cleanup, and ref-counts across multiple concurrent locks so+ * stacked modals don't fight each other.+ *+ * Use this in any modal/sheet/drawer when it's open so the page underneath+ * doesn't scroll on touch devices.+ */+let lockCount = 0+let prevOverflow = ''++export function useBodyScrollLock(active: boolean) {+ useEffect(() => {+ if (!active) return+ if (lockCount === 0) {+ prevOverflow = document.body.style.overflow+ document.body.style.overflow = 'hidden'+ }+ lockCount+++ return () => {+ lockCount--+ if (lockCount === 0) {+ document.body.style.overflow = prevOverflow+ }+ }+ }, [active])+}diff --git a/web/src/hooks/useEscapeKey.ts b/web/src/hooks/useEscapeKey.tsnew file mode 100644index 0000000..1f47fdf--- /dev/null+++ b/web/src/hooks/useEscapeKey.ts@@ -0,0 +1,19 @@+import { useEffect } from 'react'++/**+ * Calls `onEscape` when the user presses Escape, but only while `active` is+ * true. Use in any modal/sheet/drawer for keyboard dismissal.+ */+export function useEscapeKey(active: boolean, onEscape: () => void) {+ useEffect(() => {+ if (!active) return+ const handler = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.stopPropagation()+ onEscape()+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [active, onEscape])+}diff --git a/web/src/hooks/useInfiniteList.ts b/web/src/hooks/useInfiniteList.tsnew file mode 100644index 0000000..ae62197--- /dev/null+++ b/web/src/hooks/useInfiniteList.ts@@ -0,0 +1,68 @@+import { useState, useEffect, useRef } from 'react'++interface Options {+ /**+ * Total length of the underlying list. The hook clamps `visibleCount` so it+ * never exceeds this and resets paging when the list shrinks (e.g. deletes).+ */+ total: number+ /**+ * How many items to reveal per page. Default 30.+ */+ pageSize?: number+ /**+ * Pixel margin around the viewport at which the sentinel is considered+ * "visible" — letting the next page load before the user reaches the very+ * end. Default 200px.+ */+ rootMargin?: string+}++/**+ * Generic frontend-only infinite-scroll for an already-fetched list.+ *+ * Use this when the data is already in memory (e.g. a single API call returned+ * the full list, or a reasonable upper bound) and you just want to render in+ * pages so the DOM stays light. Attach `sentinelRef` to a placeholder element+ * at the bottom of the list — when it scrolls into view, `visibleCount` bumps+ * by `pageSize`.+ *+ * For server-side cursor pagination, pair this with a separate fetcher that+ * appends to the underlying list when `visibleCount` approaches `total`.+ *+ * Returns:+ * - visibleCount: number of items to render (use `list.slice(0, visibleCount)`)+ * - sentinelRef: ref to attach to the bottom-of-list sentinel element+ * - hasMore: whether there are still hidden items+ */+export function useInfiniteList({ total, pageSize = 30, rootMargin = '200px' }: Options) {+ const [visibleCount, setVisibleCount] = useState(pageSize)+ const sentinelRef = useRef<HTMLDivElement | null>(null)++ // Bump on intersection.+ useEffect(() => {+ const el = sentinelRef.current+ if (!el) return+ const obs = new IntersectionObserver(+ entries => {+ if (entries[0]?.isIntersecting) {+ setVisibleCount(c => Math.min(c + pageSize, total))+ }+ },+ { rootMargin },+ )+ obs.observe(el)+ return () => obs.disconnect()+ }, [total, pageSize, rootMargin])++ // Clamp when the list shrinks.+ useEffect(() => {+ setVisibleCount(c => Math.max(pageSize, Math.min(c, total)))+ }, [total, pageSize])++ return {+ visibleCount,+ sentinelRef,+ hasMore: visibleCount < total,+ }+}diff --git a/web/src/index.css b/web/src/index.cssindex 79480e5..a253138 100644--- a/web/src/index.css+++ b/web/src/index.css@@ -75,8 +75,9 @@/* Inputs */.input {+ /* text-base (16px) is the minimum to prevent iOS Safari auto-zoom on focus. */@apply w-full px-3.5 py-2.5 bg-surface-overlay border border-surface-border rounded-lg- text-tx-primary placeholder-tx-muted text-sm+ text-tx-primary placeholder-tx-muted text-basefocus:outline-none focus:ring-1 focus:ring-brand-500 focus:border-brand-500transition-colors duration-150;}diff --git a/web/src/pages/ActiveWorkout.tsx b/web/src/pages/ActiveWorkout.tsxindex 5c606b1..d4b71b5 100644--- a/web/src/pages/ActiveWorkout.tsx+++ b/web/src/pages/ActiveWorkout.tsx@@ -6,7 +6,7 @@ import {AlertCircle, ChevronRight, ChevronLeft, Info,} from 'lucide-react'import { useWorkoutSession } from '../stores/workoutSession'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'import { workoutAPI } from '../services/api'import * as types from '../types'import { muscleColor } from '../utils/exerciseUtils'@@ -350,9 +350,9 @@ export default function ActiveWorkout() {<inputtype="number"inputMode="decimal"- value={set.actual_weight || ''}- onChange={e => updateSet(exIdx, setIdx, 'actual_weight', Number(e.target.value) || 0)}- placeholder={set.target_weight > 0 ? String(set.target_weight) : '—'}+ value={set.actual_weight ? lbsToDisplay(set.actual_weight, wUnit) : ''}+ onChange={e => updateSet(exIdx, setIdx, 'actual_weight', displayToLbs(Number(e.target.value) || 0, wUnit))}+ placeholder={set.target_weight > 0 ? String(lbsToDisplay(set.target_weight, wUnit)) : '—'}className={`input text-base text-center py-3 w-full pr-7 transition-opacity ${set.completed ? 'opacity-40' : ''}`}disabled={set.completed}step="0.5"diff --git a/web/src/pages/AddProgram.tsx b/web/src/pages/AddProgram.tsxindex 0bdde10..a391338 100644--- a/web/src/pages/AddProgram.tsx+++ b/web/src/pages/AddProgram.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'import { useNavigate } from 'react-router-dom'import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target } from 'lucide-react'import { programAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'import ExercisePicker from '../components/ExercisePicker'import * as types from '../types'@@ -77,7 +77,14 @@ export default function AddProgram() {if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }setLoading(true)try {- await programAPI.create(formData)+ const payload = {+ ...formData,+ exercises: formData.exercises.map(ex => ({+ ...ex,+ sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),+ })),+ }+ await programAPI.create(payload)navigate('/programs')} catch (err: any) {setError(err.response?.data?.error || 'Failed to create program')diff --git a/web/src/pages/AddWorkout.tsx b/web/src/pages/AddWorkout.tsxindex 59b7df5..69de48f 100644--- a/web/src/pages/AddWorkout.tsx+++ b/web/src/pages/AddWorkout.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'import { useNavigate } from 'react-router-dom'import { Plus, ArrowLeft, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge, BookOpen, CalendarDays } from 'lucide-react'import { workoutAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'import ExercisePicker from '../components/ExercisePicker'import ProgramPicker from '../components/ProgramPicker'import * as types from '../types'@@ -79,7 +79,16 @@ export default function AddWorkout() {if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }setLoading(true)try {- await workoutAPI.create({ ...formData, duration: formData.duration * 60, started_at: new Date(formData.date).toISOString() })+ const payload = {+ ...formData,+ duration: formData.duration * 60,+ started_at: new Date(formData.date).toISOString(),+ exercises: formData.exercises.map(ex => ({+ ...ex,+ sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),+ })),+ }+ await workoutAPI.create(payload)navigate('/workouts')} catch (err: any) {setError(err.response?.data?.error || 'Failed to create workout')diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsxindex 929fa54..cf14301 100644--- a/web/src/pages/Dashboard.tsx+++ b/web/src/pages/Dashboard.tsx@@ -2,17 +2,18 @@ import { useState, useEffect } from 'react'import { format, startOfWeek, isSameDay, eachDayOfInterval, endOfWeek, subWeeks } from 'date-fns'import {Dumbbell, Flame, ArrowRight, Beef,- AlertCircle, Play, Timer, TrendingUp, Scale, Activity,+ AlertCircle, Play, Timer, TrendingUp, Scale, Activity, Plus,} from 'lucide-react'import {BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell,LineChart, Line, PieChart, Pie, Legend,} from 'recharts'import Loading from '../components/Loading'+import QuickWeighInSheet from '../components/QuickWeighInSheet'import { workoutAPI, foodAPI, weightAPI, userAPI } from '../services/api'import { useWorkoutSession } from '../stores/workoutSession'import { useAuthStore } from '../stores/auth'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay } from '../stores/settings'import { useNavigate, Link } from 'react-router-dom'import * as types from '../types'import { muscleColor } from '../utils/exerciseUtils'@@ -130,9 +131,11 @@ export default function Dashboard() {const [workouts, setWorkouts] = useState<types.Workout[]>([])const [food, setFood] = useState<types.DailyStats>(DEFAULT_FOOD)const [weightLogs, setWeightLogs] = useState<types.WeightLog[]>([])+ const [weightStats, setWeightStats] = useState<types.WeightStats | null>(null)const [settings, setSettings] = useState<types.UserSettings>(storedSettings)const [loading, setLoading] = useState(true)const [error, setError] = useState<string | null>(null)+ const [sheetOpen, setSheetOpen] = useState(false)const wUnit = weightShort(settings.weight_unit)useEffect(() => {@@ -140,12 +143,14 @@ export default function Dashboard() {workoutAPI.list({ limit: 84 }), // 12 weeks × 7 days maxfoodAPI.stats(format(TODAY, 'yyyy-MM-dd')).catch(() => DEFAULT_FOOD),weightAPI.list({ limit: 14 }).catch(() => []),+ weightAPI.stats().catch(() => null),userAPI.getSettings().catch(() => DEFAULT_SETTINGS),])- .then(([ws, fs, wl, s]) => {+ .then(([ws, fs, wl, wst, s]) => {setWorkouts(ws || [])setFood(fs || DEFAULT_FOOD)setWeightLogs(wl || [])+ setWeightStats(wst)setSettings(s || DEFAULT_SETTINGS)}).catch(err => setError(err.message || 'Failed to load'))@@ -171,7 +176,7 @@ export default function Dashboard() {// Volume chart: last 7 workouts oldest→newestconst chartData = workouts.slice(0, 7).reverse().map(w => ({date: format(new Date(w.started_at), 'M/d'),- volume: Math.round(calcVolume(w)),+ volume: Math.round(lbsToDisplay(calcVolume(w), settings.weight_unit)),name: w.name,}))@@ -236,7 +241,7 @@ export default function Dashboard() {// Weight sparklineconst sparkData = [...weightLogs].reverse().map(l => ({date: format(new Date(l.logged_at), 'M/d'),- weight: l.weight,+ weight: Math.round(lbsToDisplay(l.weight, settings.weight_unit)),}))const username = user?.email?.split('@')[0] ?? 'there'@@ -464,7 +469,7 @@ export default function Dashboard() {{lastWorkout ? (() => {const exs = lastWorkout.exercises ?? []const totalSets = exs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)- const totalVolume = Math.round(calcVolume(lastWorkout))+ const totalVolume = Math.round(lbsToDisplay(calcVolume(lastWorkout), settings.weight_unit))const mins = Math.round(lastWorkout.duration / 60)return (<div className="card p-4 overflow-hidden min-w-0 cursor-pointer active:scale-[0.99] transition-transform"@@ -513,7 +518,7 @@ export default function Dashboard() {</div>{best && (<span className="text-xs text-tx-muted tabular-nums flex-shrink-0">- {sets.length}×{best.weight > 0 ? ` ${best.weight}${wUnit}` : ' BW'}+ {sets.length}×{best.weight > 0 ? ` ${Math.round(lbsToDisplay(best.weight, settings.weight_unit))}${wUnit}` : ' BW'}</span>)}</div>@@ -672,39 +677,94 @@ export default function Dashboard() {)}</div>- {/* ── Weight sparkline ───────────────────────── */}- {weightLogs.length >= 2 && (- <div className="card p-4">- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Scale className="w-4 h-4 text-brand-500" />- <h2 className="section-title">Weight</h2>- </div>- <div className="text-right">- <p className="text-sm font-bold text-tx-primary">{weightLogs[0].weight} {wUnit}</p>- {(() => {- const delta = weightLogs[0].weight - weightLogs[weightLogs.length - 1].weight- return (- <p className={`text-xs ${delta <= 0 ? 'text-brand-400' : 'text-tx-muted'}`}>- {delta <= 0 ? '↓' : '↑'}{Math.abs(delta).toFixed(1)} {wUnit}- </p>- )- })()}- </div>- </div>- <div className="w-full min-w-0">- <ResponsiveContainer width="100%" height={56}>- <LineChart data={sparkData}>- <Line dataKey="weight" dot={false} stroke="#6366f1" strokeWidth={2} type="monotone" />- <Tooltip- contentStyle={TOOLTIP_STYLE}- formatter={(v: number) => [`${v} ${wUnit}`, 'Weight']}- />- </LineChart>- </ResponsiveContainer>+ {/* ── Weight quick-log card ──────────────────── */}+ <div className="card p-4">+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <Scale className="w-4 h-4 text-brand-500" />+ <h2 className="section-title">Weight</h2></div>+ <Link to="/weight" className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex items-center gap-0.5">+ View <ArrowRight className="w-3 h-3" />+ </Link></div>- )}++ {weightLogs.length === 0 ? (+ <button+ type="button"+ onClick={() => setSheetOpen(true)}+ className="w-full flex items-center gap-3 p-3 bg-brand-500/5 border border-dashed border-brand-500/30 rounded-xl hover:bg-brand-500/10 transition-colors text-left"+ >+ <div className="w-9 h-9 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">+ <Plus className="w-4 h-4 text-brand-500" />+ </div>+ <div className="min-w-0">+ <p className="text-sm font-semibold text-tx-primary">Log your first weight</p>+ <p className="text-xs text-tx-muted">Tap to start tracking</p>+ </div>+ </button>+ ) : (+ <button+ type="button"+ onClick={() => setSheetOpen(true)}+ className="w-full text-left active:scale-[0.99] transition-transform"+ aria-label="Log weight"+ >+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-baseline gap-1.5">+ <span className="text-2xl font-bold text-tx-primary tabular-nums leading-none">+ {Math.round(lbsToDisplay(weightLogs[0].weight, settings.weight_unit))}+ </span>+ <span className="text-sm text-tx-muted">{wUnit}</span>+ </div>+ <div className="flex items-center gap-2">+ {(() => {+ const delta = weightStats?.change_7d ?? 0+ if (delta === 0) {+ return <span className="text-xs text-tx-muted">7d · no change</span>+ }+ return (+ <span className={`text-xs tabular-nums ${delta < 0 ? 'text-success-400' : 'text-error-400'}`}>+ 7d · {delta < 0 ? '↓' : '↑'}{Math.abs(Math.round(lbsToDisplay(delta, settings.weight_unit)))} {wUnit}+ </span>+ )+ })()}+ <span className="w-7 h-7 rounded-lg bg-brand-500 hover:bg-brand-600 flex items-center justify-center text-white shadow-sm">+ <Plus className="w-4 h-4" />+ </span>+ </div>+ </div>+ {weightLogs.length >= 2 && (+ <div className="w-full min-w-0">+ <ResponsiveContainer width="100%" height={48}>+ <LineChart data={sparkData}>+ <Line dataKey="weight" dot={false} stroke="#6366f1" strokeWidth={2} type="monotone" />+ <Tooltip+ contentStyle={TOOLTIP_STYLE}+ formatter={(v: number) => [`${v} ${wUnit}`, 'Weight']}+ />+ </LineChart>+ </ResponsiveContainer>+ </div>+ )}+ </button>+ )}+ </div>++ <QuickWeighInSheet+ isOpen={sheetOpen}+ lastValue={weightLogs[0] ? Math.round(lbsToDisplay(weightLogs[0].weight, settings.weight_unit)) : null}+ lastLog={weightLogs[0] ?? null}+ onClose={() => setSheetOpen(false)}+ onSuccess={(log) => {+ setWeightLogs(prev =>+ [log, ...prev].sort(+ (a, b) => new Date(b.logged_at).getTime() - new Date(a.logged_at).getTime()+ )+ )+ weightAPI.stats().then(setWeightStats).catch(() => {})+ }}+ /></div>)diff --git a/web/src/pages/EditProgram.tsx b/web/src/pages/EditProgram.tsxindex 6059e6d..95d9a61 100644--- a/web/src/pages/EditProgram.tsx+++ b/web/src/pages/EditProgram.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'import { useNavigate, useParams } from 'react-router-dom'import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target, Dumbbell } from 'lucide-react'import { programAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'import ExercisePicker from '../components/ExercisePicker'import * as types from '../types'@@ -47,7 +47,7 @@ export default function EditProgram() {sets: (ex.sets || []).map(s => ({set_number: s.set_number,target_reps: s.target_reps,- target_weight: s.target_weight,+ target_weight: lbsToDisplay(s.target_weight, settings.weight_unit),})),})),})@@ -100,7 +100,14 @@ export default function EditProgram() {if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }setLoading(true)try {- await programAPI.update(Number(id), formData)+ const payload = {+ ...formData,+ exercises: formData.exercises.map(ex => ({+ ...ex,+ sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),+ })),+ }+ await programAPI.update(Number(id), payload)navigate('/programs')} catch (err: any) {setError(err.response?.data?.error || 'Failed to update program')diff --git a/web/src/pages/EditWorkout.tsx b/web/src/pages/EditWorkout.tsxindex 9feb3f6..17cb340 100644--- a/web/src/pages/EditWorkout.tsx+++ b/web/src/pages/EditWorkout.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'import { useNavigate, useParams } from 'react-router-dom'import { Plus, ArrowLeft, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge } from 'lucide-react'import { workoutAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'import ExercisePicker from '../components/ExercisePicker'import * as types from '../types'@@ -44,7 +44,7 @@ export default function EditWorkout() {exercises: (workout.exercises || []).map(ex => ({exercise_id: ex.exercise_id,notes: ex.notes || '',- sets: (ex.sets || []).map(s => ({ set_number: s.set_number, reps: s.reps, weight: s.weight })),+ sets: (ex.sets || []).map(s => ({ set_number: s.set_number, reps: s.reps, weight: lbsToDisplay(s.weight, settings.weight_unit) })),})),})})@@ -91,7 +91,16 @@ export default function EditWorkout() {if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }setLoading(true)try {- await workoutAPI.update(Number(id), { ...formData, duration: formData.duration * 60, started_at: originalStartedAt || new Date().toISOString() })+ const payload = {+ ...formData,+ duration: formData.duration * 60,+ started_at: originalStartedAt || new Date().toISOString(),+ exercises: formData.exercises.map(ex => ({+ ...ex,+ sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),+ })),+ }+ await workoutAPI.update(Number(id), payload)navigate('/workouts')} catch (err: any) {setError(err.response?.data?.error || 'Failed to update workout')diff --git a/web/src/pages/ExerciseDetail.tsx b/web/src/pages/ExerciseDetail.tsxindex 6f591f4..c1e0935 100644--- a/web/src/pages/ExerciseDetail.tsx+++ b/web/src/pages/ExerciseDetail.tsx@@ -6,7 +6,7 @@ import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recimport Model, { IExerciseData } from 'react-body-highlighter'import { exerciseAPI } from '../services/api'import { useWorkoutSession } from '../stores/workoutSession'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay } from '../stores/settings'import { useTheme } from '../hooks/useTheme'import * as types from '../types'import { muscleColor, muscleColorBordered, EQUIPMENT_LABEL, muscleToBodySlugs } from '../utils/exerciseUtils'@@ -186,11 +186,11 @@ export default function ExerciseDetail() {<p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">Your Best</p></div><div className="flex items-end gap-2">- <span className="text-2xl font-bold text-tx-primary tabular-nums">{pr.weight}</span>+ <span className="text-2xl font-bold text-tx-primary tabular-nums">{Math.round(lbsToDisplay(pr.weight, wUnit))}</span><span className="text-sm text-tx-muted mb-0.5">{wUnit} × {pr.reps} reps</span></div><p className="text-xs text-tx-muted mt-1">- Est. 1RM: {Math.round(pr.estimated_1rm)} {wUnit} · {format(new Date(pr.date), 'MMM d, yyyy')}+ Est. 1RM: {Math.round(lbsToDisplay(pr.estimated_1rm, wUnit))} {wUnit} · {format(new Date(pr.date), 'MMM d, yyyy')}</p></div>)}@@ -199,7 +199,7 @@ export default function ExerciseDetail() {{history.length >= 2 && (() => {const chartData = [...history].reverse().map(h => ({date: format(new Date(h.date), 'M/d'),- weight: Math.round(h.max_weight * 10) / 10,+ weight: Math.round(lbsToDisplay(h.max_weight, wUnit)),}))return (<div className="card p-4">diff --git a/web/src/pages/ProgramDetail.tsx b/web/src/pages/ProgramDetail.tsxindex 8a210c5..0a81b10 100644--- a/web/src/pages/ProgramDetail.tsx+++ b/web/src/pages/ProgramDetail.tsx@@ -7,7 +7,7 @@ import {} from 'lucide-react'import { programAPI } from '../services/api'import { useWorkoutSession } from '../stores/workoutSession'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay } from '../stores/settings'import * as types from '../types'import { muscleColor } from '../utils/exerciseUtils'@@ -193,7 +193,8 @@ export default function ProgramDetail() {<div className="space-y-2">{exs.map((ex) => {const sets = ex.sets ?? []- const maxTarget = sets.length > 0 ? Math.max(...sets.map(s => s.target_weight || 0)) : 0+ const maxTargetLbs = sets.length > 0 ? Math.max(...sets.map(s => s.target_weight || 0)) : 0+ const maxTarget = Math.round(lbsToDisplay(maxTargetLbs, wUnit))return (<button@@ -232,12 +233,12 @@ export default function ProgramDetail() {{sets.length > 0 && (<div className="flex flex-wrap gap-1.5 px-4 pb-4 border-t border-surface-border/50 pt-3">{sets.map((set, i) => {- const isBest = set.target_weight === maxTarget && maxTarget > 0+ const isBest = set.target_weight === maxTargetLbs && maxTargetLbs > 0return (<div key={i} className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${isBest ? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25' : 'bg-surface-raised text-tx-secondary'}`}>- {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${set.target_weight} ${wUnit}` : 'BW'}+ {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${Math.round(lbsToDisplay(set.target_weight, wUnit))} ${wUnit}` : 'BW'}</div>)})}diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsxindex 2ea3214..4e42741 100644--- a/web/src/pages/Weight.tsx+++ b/web/src/pages/Weight.tsx@@ -1,80 +1,326 @@-import { useState, useEffect } from 'react'-import { TrendingDown, TrendingUp, Plus, Calendar, Info, AlertCircle } from 'lucide-react'+import { useState, useEffect, useMemo, useRef } from 'react'+import { TrendingDown, TrendingUp, Minus, Plus, Calendar, Sunrise, AlertCircle, ChevronRight, Scale, Activity, ArrowDown, ArrowUp, X } from 'lucide-react'import { format, subDays } from 'date-fns'+import { Link } from 'react-router-dom'import { HelpTip } from '../components/Tooltip'import Loading from '../components/Loading'+import WeightInput from '../components/WeightInput'+import { useInfiniteList } from '../hooks/useInfiniteList'+import { isPositiveNumber } from '../utils/numberUtils'+import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'import { weightAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'import * as types from '../types'const PERIODS = ['7d', '30d', '90d', 'All'] as consttype Period = typeof PERIODS[number]-const getPeriodDays = (p: Period) => {- const map: Record<Period, number> = { '7d': 7, '30d': 30, '90d': 90, 'All': 999 }- return map[p]+const PERIOD_DAYS: Record<Period, number | null> = { '7d': 7, '30d': 30, '90d': 90, 'All': null }++interface ChartPoint {+ ts: number+ weight: number+ date: Date+}++const W = 400+const H = 200+const PL = 40, PR = 8, PT = 22, PB = 30++// Catmull-rom → cubic bezier for smooth organic curves+function smoothPath(pts: [number, number][]): string {+ if (pts.length < 2) return ''+ if (pts.length === 2)+ return `M${pts[0][0].toFixed(1)},${pts[0][1].toFixed(1)} L${pts[1][0].toFixed(1)},${pts[1][1].toFixed(1)}`+ let d = `M${pts[0][0].toFixed(1)},${pts[0][1].toFixed(1)}`+ for (let i = 0; i < pts.length - 1; i++) {+ const p0 = pts[i - 1] ?? pts[i]+ const p1 = pts[i]+ const p2 = pts[i + 1]+ const p3 = pts[i + 2] ?? p2+ const cp1x = p1[0] + (p2[0] - p0[0]) / 6+ const cp1y = p1[1] + (p2[1] - p0[1]) / 6+ const cp2x = p2[0] - (p3[0] - p1[0]) / 6+ const cp2y = p2[1] - (p3[1] - p1[1]) / 6+ d += ` C${cp1x.toFixed(1)},${cp1y.toFixed(1)} ${cp2x.toFixed(1)},${cp2y.toFixed(1)} ${p2[0].toFixed(1)},${p2[1].toFixed(1)}`+ }+ return d+}++function TrendChart({ points, wUnit }: { points: ChartPoint[]; wUnit: string }) {+ const [activeIdx, setActiveIdx] = useState<number | null>(null)++ const layout = useMemo(() => {+ if (points.length < 2) return null+ const ys = points.map(p => p.weight)+ const xs = points.map(p => p.ts)+ const xMin = Math.min(...xs), xMax = Math.max(...xs)+ const yMin = Math.min(...ys), yMax = Math.max(...ys)+ const yPad = Math.max((yMax - yMin) * 0.22, 1)+ const yLo = yMin - yPad, yHi = yMax + yPad+ const xRange = xMax - xMin || 1++ const xAt = (ts: number) => PL + ((ts - xMin) / xRange) * (W - PL - PR)+ const yAt = (v: number) => PT + (1 - (v - yLo) / (yHi - yLo)) * (H - PT - PB)++ const wPts: [number, number][] = points.map(p => [xAt(p.ts), yAt(p.weight)])++ // 3 y-axis ticks evenly spaced in visible range+ const ticks = [0, 0.5, 1].map(f => ({+ label: Math.round(yLo + f * (yHi - yLo)).toString(),+ y: yAt(yLo + f * (yHi - yLo)),+ }))++ return { xAt, yAt, wPts, ticks }+ }, [points])++ if (!layout) return null++ const { wPts, ticks } = layout+ const linePath = smoothPath(wPts)+ const last = wPts[wPts.length - 1]+ const areaPath = `${linePath} L${last[0].toFixed(1)},${(H - PB).toFixed(1)} L${wPts[0][0].toFixed(1)},${(H - PB).toFixed(1)} Z`++ const activeXY = activeIdx != null ? wPts[activeIdx] : null+ const activePoint = activeIdx != null ? points[activeIdx] : null++ const handlePointerMove = (e: React.PointerEvent<SVGRectElement>) => {+ const rect = e.currentTarget.getBoundingClientRect()+ const x = PL + ((e.clientX - rect.left) / rect.width) * (W - PL - PR)+ let best = 0, bestDist = Infinity+ wPts.forEach(([px], i) => {+ const d = Math.abs(px - x)+ if (d < bestDist) { bestDist = d; best = i }+ })+ setActiveIdx(best)+ }++ // Callout: flip left if dot near right edge, flip below if dot near top+ const calloutFlipH = last[0] > W * 0.65+ const calloutFlipV = last[1] < PT + 30+ const calloutLabel = String(Math.round(points[points.length - 1].weight))+ const calloutW = calloutLabel.length * 9 + 16+ const calloutX = calloutFlipH ? last[0] - calloutW - 8 : last[0] + 8+ const calloutY = calloutFlipV ? last[1] + 10 : last[1] - 28++ const tooltipLeft = activeXY ? (activeXY[0] / W) * 100 : 0+ const flipTooltip = activeXY ? activeXY[0] > W * 0.6 : false++ return (+ <div className="relative w-full select-none">+ {activePoint && activeXY && (+ <div+ className="absolute pointer-events-none z-10 top-0"+ style={{+ left: `${tooltipLeft}%`,+ transform: flipTooltip ? 'translateX(-100%) translateX(-8px)' : 'translateX(8px)',+ }}+ >+ <div className="bg-surface-raised border border-surface-border rounded-xl px-3 py-2 shadow-card text-xs whitespace-nowrap">+ <p className="font-bold tabular-nums text-tx-primary text-sm">+ {Math.round(activePoint.weight)} <span className="font-normal text-tx-muted">{wUnit}</span>+ </p>+ <p className="text-tx-muted mt-0.5">{format(activePoint.date, 'MMM d, yyyy')}</p>+ </div>+ </div>+ )}++ <svg viewBox={`0 0 ${W} ${H}`} className="w-full h-auto overflow-visible">+ <defs>+ <linearGradient id="wGrad" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor="#6366f1" stopOpacity={0.3} />+ <stop offset="70%" stopColor="#6366f1" stopOpacity={0.06} />+ <stop offset="100%" stopColor="#6366f1" stopOpacity={0} />+ </linearGradient>+ </defs>++ {/* Subtle grid lines */}+ {ticks.map(t => (+ <line key={t.label} x1={PL} y1={t.y} x2={W - PR} y2={t.y}+ stroke="#6366f1" strokeOpacity={0.08} strokeWidth={1} strokeDasharray="4 4" />+ ))}++ {/* Y-axis tick labels */}+ {ticks.map(t => (+ <text key={`y-${t.label}`} x={PL - 6} y={t.y + 5}+ fontSize={13} textAnchor="end" fill="var(--color-tx-muted)" fillOpacity={0.65}>+ {t.label}+ </text>+ ))}++ {/* Area fill */}+ <path d={areaPath} fill="url(#wGrad)" />++ {/* Active vertical rule */}+ {activeXY && (+ <line x1={activeXY[0]} y1={PT - 4} x2={activeXY[0]} y2={H - PB}+ stroke="#6366f1" strokeOpacity={0.3} strokeWidth={1} />+ )}++ {/* Main bezier line */}+ <path d={linePath} fill="none" stroke="#6366f1" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" />++ {/* Persistent callout on latest point (hidden while interacting) */}+ {!activeXY && (+ <>+ <circle cx={last[0]} cy={last[1]} r={8} fill="#6366f1" fillOpacity={0.14} />+ <circle cx={last[0]} cy={last[1]} r={4} fill="#6366f1" />+ <rect x={calloutX} y={calloutY} width={calloutW} height={22} rx={6}+ fill="#6366f1" fillOpacity={0.18} />+ <text x={calloutX + calloutW / 2} y={calloutY + 15}+ fontSize={13} fontWeight="700" textAnchor="middle" fill="#818cf8">+ {calloutLabel}+ </text>+ </>+ )}++ {/* Active dot */}+ {activeXY && (+ <>+ <circle cx={activeXY[0]} cy={activeXY[1]} r={8} fill="#6366f1" fillOpacity={0.15} />+ <circle cx={activeXY[0]} cy={activeXY[1]} r={4} fill="#6366f1" />+ </>+ )}++ {/* Date range labels */}+ <text x={PL} y={H - 10} fontSize={12} fill="var(--color-tx-muted)" fillOpacity={0.6} textAnchor="start">+ {format(points[0].date, 'MMM d')}+ </text>+ <text x={W - PR} y={H - 10} fontSize={12} fill="var(--color-tx-muted)" fillOpacity={0.6} textAnchor="end">+ {format(points[points.length - 1].date, 'MMM d')}+ </text>++ {/* Hit area — only over chart region, not y-axis */}+ <rect+ x={PL} y={0} width={W - PL - PR} height={H - PB}+ fill="transparent"+ style={{ cursor: 'crosshair', touchAction: 'pan-y' }}+ onPointerMove={handlePointerMove}+ onPointerLeave={() => setActiveIdx(null)}+ />+ </svg>+ </div>+ )}export default function Weight() {const { settings } = useSettingsStore()const wUnit = weightShort(settings.weight_unit)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)++ // Log form+ const [newWeight, setNewWeight] = useState('')+ const [newDate, setNewDate] = useState(todayStr())+ const [newNotes, setNewNotes] = useState('')const [logging, setLogging] = useState(false)+ const [showNotes, setShowNotes] = useState(false)+ const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)+ const duplicateWarningDismissedRef = useRef(false)+ const logFormRef = useRef<HTMLFormElement>(null)- 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)- }+ 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))))+ prefillDoneRef.current = true}- load()+ }++ useEffect(() => {+ refresh()+ .catch(err => setError(err?.message || 'Failed to load weight data'))+ .finally(() => setLoading(false))}, [])- 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 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])++ // Oldest → newest for the chart+ const chartPoints: ChartPoint[] = useMemo(() => {+ return filtered+ .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])++ const handleLog = async (e: React.FormEvent) => {+ e.preventDefault()+ if (logging) return+ const w = parseFloat(newWeight)+ if (!Number.isFinite(w) || w <= 0) {+ setError('Enter a valid weight')+ return+ }++ if (!duplicateWarningDismissedRef.current && logs.length > 0 && isoToDayInput(logs[0].logged_at) === newDate) {+ setShowDuplicateWarning(true)+ return+ }- const handleLog = async () => {- if (!newWeight) returnsetLogging(true)+ 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 {- await weightAPI.log({ weight: parseFloat(newWeight) })- setNewWeight('')- const [logData, statsData] = await Promise.all([- weightAPI.list({ limit: 100 }),- weightAPI.stats(),- ])- setLogs(logData || [])- setStats(statsData)+ const real = await weightAPI.log({+ weight: weightLbs,+ notes: trimmedNotes,+ logged_at: loggedAtIso,+ })+ 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+ weightAPI.stats().then(setStats).catch(() => {})} catch (err: any) {- setError(err.message || 'Failed to log weight')+ 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 (loading) return <Loading />- if (error) {+ if (error && logs.length === 0) {return (<div className="alert-error"><AlertCircle className="w-5 h-5 flex-shrink-0" />@@ -83,13 +329,39 @@ export default function Weight() {)}- 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+ // 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+ const useServerAggregate = period === 'All' && stats != null+ const currentLbs = periodValues[0] ?? stats?.latest ?? 0+ const oldestLbs = periodValues[periodValues.length - 1] ?? stats?.starting ?? 0+ const changeLbs = currentLbs - oldestLbs+ const avgLbs = useServerAggregate+ ? (stats!.avg ?? 0)+ : (periodValues.length > 0 ? periodValues.reduce((a, b) => a + b, 0) / periodValues.length : 0)+ const minLbs = useServerAggregate+ ? (stats!.min ?? 0)+ : (periodValues.length > 0 ? Math.min(...periodValues) : 0)+ const maxLbs = useServerAggregate+ ? (stats!.max ?? 0)+ : (periodValues.length > 0 ? Math.max(...periodValues) : 0)++ const current = lbsToDisplay(currentLbs, settings.weight_unit)+ const change = Math.round(lbsToDisplay(changeLbs, settings.weight_unit))+ const avg = Math.round(lbsToDisplay(avgLbs, settings.weight_unit))+ const min = Math.round(lbsToDisplay(minLbs, settings.weight_unit))+ const max = Math.round(lbsToDisplay(maxLbs, settings.weight_unit))++ const trendIcon = change === 0 ? Minus : change < 0 ? TrendingDown : TrendingUp+ const TrendIcon = trendIcon+ const trendClass =+ change === 0+ ? 'bg-surface-muted border-surface-border text-tx-muted'+ : change < 0+ ? 'bg-success-500/10 border-success-500/20 text-success-400'+ : 'bg-error-500/10 border-error-500/20 text-error-400'+ const changeWord = change === 0 ? 'no change' : change < 0 ? 'lost' : 'gained'return (<div className="space-y-5 animate-slide-up">@@ -104,12 +376,121 @@ export default function Weight() {</span></div>+ {error && (+ <div className="alert-error" role="alert" aria-live="polite">+ <AlertCircle className="w-5 h-5 flex-shrink-0" />+ <span>{error}</span>+ </div>+ )}++ {/* Quick log — at top of page so entry is reachable on first paint */}+ <div className="card p-5">+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-2">+ <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>+ )}+ </div>+ <form ref={logFormRef} onSubmit={handleLog} className="space-y-3">+ <WeightInput+ value={newWeight}+ onChange={setNewWeight}+ unit={wUnit}+ size="lg"+ />++ {showNotes ? (+ <div className="space-y-2 bg-surface-overlay border border-surface-border rounded-xl p-3">+ <div className="flex items-center justify-between mb-1">+ <span className="text-xs font-medium text-tx-secondary">Date & note</span>+ <button+ type="button"+ onClick={() => setShowNotes(false)}+ className="p-1 hover:bg-surface-muted rounded-lg transition-colors"+ aria-label="Collapse"+ >+ <X className="w-3.5 h-3.5 text-tx-muted" />+ </button>+ </div>+ <input+ type="date"+ value={newDate}+ onChange={e => setNewDate(e.target.value)}+ max={todayStr()}+ className="input"+ />+ <input+ type="text"+ value={newNotes}+ onChange={e => setNewNotes(e.target.value)}+ placeholder="Note — e.g. morning, post-run"+ maxLength={200}+ className="input"+ />+ </div>+ ) : (+ <button+ type="button"+ onClick={() => setShowNotes(true)}+ className="w-full flex items-center justify-center gap-2 py-2.5 text-sm text-tx-secondary bg-surface-overlay border border-surface-border rounded-xl hover:bg-surface-muted active:scale-[0.98] transition-all"+ >+ <Calendar className="w-4 h-4 text-tx-muted" />+ Add date & note+ </button>+ )}++ {showDuplicateWarning && logs.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>+ <div className="flex gap-2 mt-2">+ <button+ type="button"+ onClick={() => setShowDuplicateWarning(false)}+ className="px-3 py-1 rounded-lg text-xs font-medium bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={() => {+ duplicateWarningDismissedRef.current = true+ setShowDuplicateWarning(false)+ logFormRef.current?.requestSubmit()+ }}+ className="px-3 py-1 rounded-lg text-xs font-medium bg-amber-500/20 border border-amber-500/30 text-amber-300 hover:bg-amber-500/30 transition-colors"+ >+ Log Anyway+ </button>+ </div>+ </div>+ </div>+ )}++ <button+ type="submit"+ disabled={!isPositiveNumber(newWeight) || logging}+ className="btn-primary btn-lg w-full"+ >+ <Plus className="w-4 h-4" /> {logging ? 'Logging…' : 'Log Weight'}+ </button>+ <p className="input-help flex items-center justify-center gap-1.5 text-center">+ <Sunrise className="w-3.5 h-3.5 text-amber-400 flex-shrink-0" />+ Best logged in the morning, after the bathroom+ </p>+ </form>+ </div>+{/* Current weight hero */}<div className="card p-6 border-brand-500/20 bg-brand-500/5">{logs.length === 0 ? (<div className="text-center py-2"><p className="stat-label mb-1">Current Weight</p>- <p className="text-tx-muted text-sm">No logs yet — log your first weight below</p>+ <p className="text-tx-muted text-sm">The scale doesn't know you exist yet. Fix that.</p></div>) : (<>@@ -117,21 +498,17 @@ 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.toFixed(1)}</span>+ <span className="stat-value text-5xl">{Math.round(current)}</span><span className="text-tx-muted text-lg mb-1">{wUnit}</span></div></div>- <div className={`flex items-center gap-1.5 text-sm font-semibold px-3 py-1.5 rounded-lg ${- change < 0- ? 'bg-success-500/10 border border-success-500/20 text-success-400'- : '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).toFixed(1)} {wUnit}+ <div className={`flex items-center gap-1.5 text-sm font-semibold px-3 py-1.5 rounded-lg border ${trendClass}`}>+ <TrendIcon className="w-4 h-4" />+ {Math.abs(change)} {wUnit}</div></div><p className="text-xs text-tx-muted mt-3">- {Math.abs(change).toFixed(1)} {wUnit} {change < 0 ? 'lost' : 'gained'} over {period}+ {Math.abs(change)} {wUnit} {changeWord} over {period}</p></>)}@@ -140,16 +517,17 @@ export default function Weight() {{/* Stats row */}<div className="grid grid-cols-3 gap-3">{[- { 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' },+ { label: 'Avg', value: avg, tip: 'Average weight for selected period', icon: Activity, color: 'text-brand-400' },+ { label: 'Low', value: min, tip: 'Lowest recorded weight in period', icon: ArrowDown, color: 'text-success-400' },+ { label: 'High', value: max, tip: 'Highest recorded weight in period', icon: ArrowUp, color: 'text-error-400' },].map(s => (<div key={s.label} className="card p-4"><div className="flex items-center gap-1.5 mb-2">+ <s.icon className={`w-3.5 h-3.5 ${s.color}`} /><span className="stat-label">{s.label}</span><HelpTip content={s.tip} /></div>- <span className="stat-value text-xl">{s.value.toFixed(1)}</span>+ <span className="stat-value text-xl">{Math.round(s.value)}</span><span className="text-xs text-tx-muted ml-1">{wUnit}</span></div>))}@@ -157,14 +535,14 @@ export default function Weight() {{/* Chart + period selector */}<div className="card p-5">- <div className="flex items-center justify-between mb-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 => (<buttonkey={p}onClick={() => setPeriod(p)}- className={`px-3 py-1 rounded-md text-xs font-medium transition-colors duration-150 ${+ 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'@@ -176,92 +554,73 @@ export default function Weight() {</div></div>- {/* Mini chart */}- {filtered.length === 0 ? (- <div className="flex items-center justify-center h-24 text-tx-muted text-sm">+ {chartPoints.length === 0 ? (+ <div className="flex items-center justify-center h-44 text-tx-muted text-sm">No data for this period</div>+ ) : chartPoints.length === 1 ? (+ <div className="flex items-center justify-center h-44 text-tx-muted text-sm">+ Log another entry to see the trend+ </div>) : (- <>- <div className="flex items-end gap-1 h-24 mb-1">- {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">- <div- className="w-full bg-brand-500/20 border border-brand-500/30 rounded-sm transition-all group-hover:bg-brand-500/40"- 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.weight.toFixed(1)} {wUnit}- </div>- </div>- )- })}- </div>- <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>- </>+ <TrendChart points={chartPoints} wUnit={wUnit} />)}</div>- {/* Log weight */}- <div className="card p-5">- <h2 className="section-title mb-3">Log Today's Weight</h2>- <div className="flex gap-2">- <div className="relative flex-1">- <input- type="number"- value={newWeight}- onChange={e => setNewWeight(e.target.value)}- placeholder="185.0"- step="0.1"- className="input pr-10"- />- <span className="absolute right-3.5 top-1/2 -translate-y-1/2 text-xs text-tx-muted">{wUnit}</span>- </div>- <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">- <Info className="w-3 h-3" />- Best logged first thing in the morning, after using the bathroom- </p>- </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) => {+ <>+ <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]- const delta = next ? entry.weight - next.weight : 0+ 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)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>+ <Link+ key={entry.id}+ to={`/weight/${entry.id}`}+ className="card group active:scale-[0.99] transition-transform flex items-center p-4 gap-3"+ >+ <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">+ <Scale className="w-5 h-5 text-brand-500" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="text-sm font-semibold text-tx-primary tabular-nums">+ {Math.round(displayW)} {wUnit}+ </p>+ <p className="text-xs text-tx-muted mt-0.5">+ {format(new Date(entry.logged_at), 'MMM d, yyyy')}+ </p>+ {(deltaLbs !== 0 || entry.notes) && (+ <div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">+ {deltaLbs !== 0 && (+ <span className={`flex items-center gap-0.5 text-xs font-medium tabular-nums flex-shrink-0 ${deltaLbs < 0 ? 'text-success-400' : 'text-error-400'}`}>+ {deltaLbs < 0 ? <TrendingDown className="w-3 h-3" /> : <TrendingUp className="w-3 h-3" />}+ {Math.round(displayDelta)}+ </span>+ )}+ {deltaLbs !== 0 && entry.notes && <span className="text-tx-muted/40 text-xs flex-shrink-0">·</span>}+ {entry.notes && (+ <span className="text-xs text-tx-muted truncate">{entry.notes}</span>+ )}+ </div>)}- <span className="text-sm font-semibold text-tx-primary">{entry.weight.toFixed(1)} {wUnit}</span></div>- </div>+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />+ </Link>)})}</div>- </div>+ {hasMore && (+ <div ref={sentinelRef} className="flex justify-center py-4">+ <span className="text-xs text-tx-muted">Loading more…</span>+ </div>+ )}+ </>)}+</div>)}diff --git a/web/src/pages/WeightDetail.tsx b/web/src/pages/WeightDetail.tsxnew file mode 100644index 0000000..16f5459--- /dev/null+++ b/web/src/pages/WeightDetail.tsx@@ -0,0 +1,275 @@+import { useState, useEffect } from 'react'+import { createPortal } from 'react-dom'+import { useParams, useNavigate, Link } from 'react-router-dom'+import { format } from 'date-fns'+import { ArrowLeft, Scale, Trash2, Edit2, Save, X, AlertCircle, Loader } from 'lucide-react'+import { weightAPI } from '../services/api'+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'+import { useBodyScrollLock } from '../hooks/useBodyScrollLock'+import { useEscapeKey } from '../hooks/useEscapeKey'+import { isPositiveNumber } from '../utils/numberUtils'+import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'+import WeightInput from '../components/WeightInput'+import * as types from '../types'++export default function WeightDetail() {+ const { id } = useParams<{ id: string }>()+ const navigate = useNavigate()+ const { settings } = useSettingsStore()+ const wUnit = weightShort(settings.weight_unit)++ const [log, setLog] = useState<types.WeightLog | null>(null)+ const [loading, setLoading] = useState(true)+ const [error, setError] = useState<string | null>(null)++ // Edit mode+ const [editing, setEditing] = useState(false)+ const [editWeight, setEditWeight] = useState('')+ const [editDate, setEditDate] = useState('')+ const [editNotes, setEditNotes] = useState('')+ const [saving, setSaving] = useState(false)+ const [editError, setEditError] = useState('')++ // Delete confirm+ const [confirming, setConfirming] = useState(false)+ const [deleting, setDeleting] = useState(false)++ useBodyScrollLock(confirming)+ useEscapeKey(confirming, () => setConfirming(false))+ useEscapeKey(editing, () => { setEditing(false); setEditError('') })++ useEffect(() => {+ weightAPI.get(Number(id))+ .then(data => {+ setLog(data)+ setEditWeight(String(Math.round(lbsToDisplay(data.weight, settings.weight_unit))))+ setEditDate(isoToDayInput(data.logged_at))+ setEditNotes(data.notes ?? '')+ })+ .catch(err => setError(err?.response?.data?.error || 'Failed to load entry'))+ .finally(() => setLoading(false))+ }, [id])++ const startEdit = () => {+ if (!log) return+ setEditWeight(String(Math.round(lbsToDisplay(log.weight, settings.weight_unit))))+ setEditDate(isoToDayInput(log.logged_at))+ setEditNotes(log.notes ?? '')+ setEditError('')+ setEditing(true)+ }++ const handleSave = async (e: React.FormEvent) => {+ e.preventDefault()+ if (!log || saving) return+ const w = parseFloat(editWeight)+ if (!Number.isFinite(w) || w <= 0) {+ setEditError('Enter a valid weight')+ return+ }+ setSaving(true)+ setEditError('')+ try {+ const updated = await weightAPI.update(log.id, {+ weight: displayToLbs(w, settings.weight_unit),+ notes: editNotes.trim(),+ logged_at: dayToIsoNoon(editDate),+ })+ setLog(updated)+ setEditing(false)+ } catch (err: any) {+ setEditError(err?.response?.data?.error || 'Failed to save')+ } finally {+ setSaving(false)+ }+ }++ const handleDelete = async () => {+ if (!log || deleting) return+ setDeleting(true)+ try {+ await weightAPI.delete(log.id)+ navigate('/weight', { replace: true })+ } catch {+ setDeleting(false)+ setConfirming(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>+ )+ }++ if (error || !log) {+ return (+ <div className="space-y-4">+ <Link to="/weight" className="flex items-center gap-2 text-sm text-tx-muted hover:text-tx-primary transition-colors">+ <ArrowLeft className="w-4 h-4" /> Weight+ </Link>+ <div className="alert-error">+ <AlertCircle className="w-5 h-5 flex-shrink-0" />+ <span>{error || 'Entry not found'}</span>+ </div>+ </div>+ )+ }++ return (+ <div className="space-y-5 animate-slide-up max-w-2xl">+ {/* Back nav + actions */}+ <div className="flex items-center justify-between">+ <Link to="/weight" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">+ <ArrowLeft className="w-4 h-4" /> Weight+ </Link>+ {!editing && (+ <div className="flex items-center gap-1">+ <button+ onClick={startEdit}+ className="p-2 hover:bg-surface-muted rounded-lg transition-colors"+ aria-label="Edit entry"+ >+ <Edit2 className="w-4 h-4 text-brand-500" />+ </button>+ <button+ onClick={() => setConfirming(true)}+ className="p-2 hover:bg-error-500/10 rounded-lg transition-colors"+ aria-label="Delete entry"+ >+ <Trash2 className="w-4 h-4 text-error-400" />+ </button>+ </div>+ )}+ </div>++ {/* Hero card */}+ <div className="card p-6">+ <div className="flex items-start gap-4">+ <div className="w-14 h-14 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">+ <Scale className="w-7 h-7 text-brand-500" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="stat-label mb-1">Weight Entry</p>+ {editing ? (+ <p className="text-sm text-brand-400 font-medium">Editing…</p>+ ) : (+ <>+ <div className="flex items-end gap-2">+ <span className="stat-value text-5xl tabular-nums">{Math.round(lbsToDisplay(log.weight, settings.weight_unit))}</span>+ <span className="text-tx-muted text-lg mb-1">{wUnit}</span>+ </div>+ <p className="text-sm text-tx-muted mt-1">+ {format(new Date(log.logged_at), 'EEEE, MMMM d, yyyy')}+ </p>+ {log.notes && (+ <p className="text-sm text-tx-secondary mt-2 italic">"{log.notes}"</p>+ )}+ </>+ )}+ </div>+ </div>+ </div>++ {/* Edit form */}+ {editing && (+ <div className="card p-5">+ <h2 className="section-title mb-4">Edit Entry</h2>+ <form onSubmit={handleSave} className="space-y-4">+ {editError && (+ <div className="alert-error" role="alert">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ <span>{editError}</span>+ </div>+ )}++ <div>+ <label className="label">Weight</label>+ <div className="mt-1">+ <WeightInput+ value={editWeight}+ onChange={setEditWeight}+ unit={wUnit}+ size="lg"+ />+ </div>+ </div>++ <div>+ <label className="label">Date</label>+ <input+ type="date"+ value={editDate}+ onChange={e => setEditDate(e.target.value)}+ max={todayStr()}+ className="input mt-1"+ />+ </div>++ <div>+ <label className="label">Notes <span className="text-tx-muted font-normal">(optional)</span></label>+ <input+ type="text"+ value={editNotes}+ onChange={e => setEditNotes(e.target.value)}+ placeholder="e.g., morning, post-workout"+ maxLength={200}+ className="input mt-1"+ />+ </div>++ <div className="flex items-center gap-2 pt-1">+ <button+ type="button"+ onClick={() => { setEditing(false); setEditError('') }}+ className="flex-1 py-2.5 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm flex items-center justify-center gap-1.5"+ >+ <X className="w-4 h-4" /> Cancel+ </button>+ <button+ type="submit"+ disabled={!isPositiveNumber(editWeight) || saving}+ className="flex-1 btn-primary py-2.5 rounded-xl flex items-center justify-center gap-1.5"+ >+ <Save className="w-4 h-4" />+ {saving ? 'Saving…' : 'Save'}+ </button>+ </div>+ </form>+ </div>+ )}++ {/* Delete confirm — bottom sheet */}+ {confirming && createPortal(+ <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">+ <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">+ <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />+ <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Delete Entry?</h3>+ <p className="text-sm text-tx-muted mb-5">+ {format(new Date(log.logged_at), 'MMMM d, yyyy')} · {Math.round(lbsToDisplay(log.weight, settings.weight_unit))} {wUnit} will be permanently deleted.+ </p>+ <div className="flex gap-3">+ <button+ onClick={() => setConfirming(false)}+ className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm"+ >+ Cancel+ </button>+ <button+ onClick={handleDelete}+ disabled={deleting}+ className="flex-1 py-3 bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5"+ >+ <Trash2 className="w-3.5 h-3.5" />+ {deleting ? 'Deleting…' : 'Delete'}+ </button>+ </div>+ </div>+ </div>,+ document.body+ )}+ </div>+ )+}diff --git a/web/src/pages/WorkoutDetail.tsx b/web/src/pages/WorkoutDetail.tsxindex 635d5e4..e814934 100644--- a/web/src/pages/WorkoutDetail.tsx+++ b/web/src/pages/WorkoutDetail.tsx@@ -6,7 +6,7 @@ import {ArrowLeft, Clock, Dumbbell, TrendingUp, Edit2, Trash2, ChevronRight, AlertCircle, Loader,} from 'lucide-react'import { workoutAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay } from '../stores/settings'import * as types from '../types'import { muscleColor } from '../utils/exerciseUtils'@@ -17,7 +17,7 @@ function SetChip({ set, isBest, unit }: { set: types.Set; isBest: boolean; unit:? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25': 'bg-surface-raised text-tx-secondary'}`}>- {set.reps > 0 ? set.reps : '—'} × {set.weight > 0 ? `${set.weight} ${unit}` : 'BW'}+ {set.reps > 0 ? set.reps : '—'} × {set.weight > 0 ? `${Math.round(lbsToDisplay(set.weight, unit))} ${unit}` : 'BW'}</div>)}@@ -82,9 +82,10 @@ export default function WorkoutDetail() {}const exs = workout.exercises ?? []- const totalVolume = Math.round(- exs.reduce((s, ex) => s + (ex.sets ?? []).reduce((ss, set) => ss + set.reps * set.weight, 0), 0)- )+ const totalVolume = Math.round(lbsToDisplay(+ exs.reduce((s, ex) => s + (ex.sets ?? []).reduce((ss, set) => ss + set.reps * set.weight, 0), 0),+ wUnit+ ))const totalSets = exs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)const durationMin = Math.round(workout.duration / 60)@@ -192,8 +193,9 @@ export default function WorkoutDetail() {<div className="space-y-3">{exs.map((ex, idx) => {const sets = ex.sets ?? []- const maxWeight = sets.length > 0 ? Math.max(...sets.map(s => s.weight || 0)) : 0- const exVol = sets.reduce((s, set) => s + (set.reps || 0) * (set.weight || 0), 0)+ const maxWeightLbs = sets.length > 0 ? Math.max(...sets.map(s => s.weight || 0)) : 0+ const maxWeight = Math.round(lbsToDisplay(maxWeightLbs, wUnit))+ const exVol = Math.round(lbsToDisplay(sets.reduce((s, set) => s + (set.reps || 0) * (set.weight || 0), 0), wUnit))return (<button@@ -239,7 +241,7 @@ export default function WorkoutDetail() {<div className="flex flex-wrap gap-1.5 px-4 pb-4 pt-0 border-t border-surface-border/50"><div className="w-full pt-3" />{sets.map((set, i) => (- <SetChip key={i} set={set} isBest={set.weight === maxWeight && maxWeight > 0} unit={wUnit} />+ <SetChip key={i} set={set} isBest={set.weight === maxWeightLbs && maxWeightLbs > 0} unit={wUnit} />))}</div>)}diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsxindex 64c2239..69eca17 100644--- a/web/src/pages/Workouts.tsx+++ b/web/src/pages/Workouts.tsx@@ -5,7 +5,7 @@ import { Dumbbell, Plus, Clock, Search, AlertCircle, Edit2, Trash2, TrendingUp,import { useNavigate } from 'react-router-dom'import Loading from '../components/Loading'import { workoutAPI } from '../services/api'-import { useSettingsStore, weightShort } from '../stores/settings'+import { useSettingsStore, weightShort, lbsToDisplay } from '../stores/settings'import * as types from '../types'import { muscleColor } from '../utils/exerciseUtils'@@ -29,10 +29,11 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; onreturn () => document.removeEventListener('mousedown', handler)}, [])const durationMin = Math.round(workout.duration / 60)- const totalVolume = Math.round(+ const totalVolume = Math.round(lbsToDisplay(workout.exercises?.reduce((total, e) =>- total + (e.sets?.reduce((s, set) => s + (set.reps || 0) * (set.weight || 0), 0) || 0), 0) || 0- )+ total + (e.sets?.reduce((s, set) => s + (set.reps || 0) * (set.weight || 0), 0) || 0), 0) || 0,+ wUnit+ ))const handleDelete = async () => {setDeleting(true)diff --git a/web/src/services/api.ts b/web/src/services/api.tsindex dfa48f7..498e0e8 100644--- a/web/src/services/api.ts+++ b/web/src/services/api.ts@@ -105,9 +105,13 @@ export const programAPI = {}export const weightAPI = {- list: (params?: { limit?: number }) => api.get<{ data: types.WeightLog[] }>('/weight', { params }).then(res => unwrap(res)),+ list: (params?: { limit?: 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 }) =>api.post<{ data: types.WeightLog }>('/weight', data).then(res => unwrap(res)),+ update: (id: number, data: { weight: number; notes?: string; logged_at?: string }) =>+ api.patch<{ data: types.WeightLog }>(`/weight/${id}`, data).then(res => unwrap(res)),delete: (id: number) => api.delete(`/weight/${id}`),stats: () => api.get<{ data: types.WeightStats }>('/weight/stats').then(res => unwrap(res)),}diff --git a/web/src/stores/settings.ts b/web/src/stores/settings.tsindex 0a4ab17..67cd654 100644--- a/web/src/stores/settings.ts+++ b/web/src/stores/settings.ts@@ -55,3 +55,10 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({export const weightLabel = (unit: string) => unit === 'kg' ? 'kg' : 'lbs'export const weightShort = (unit: string) => unit === 'kg' ? 'kg' : 'lb'++// Backend always stores lbs. Use these helpers everywhere weight values are read/written.+export const lbsToDisplay = (lbs: number, unit: string): number =>+ unit === 'kg' ? lbs / 2.20462 : lbs++export const displayToLbs = (val: number, unit: string): number =>+ unit === 'kg' ? val * 2.20462 : valdiff --git a/web/src/types.ts b/web/src/types.tsindex 7d7917c..fcdc75b 100644--- a/web/src/types.ts+++ b/web/src/types.ts@@ -96,7 +96,12 @@ export interface DailyStats {export interface WeightStats {latest: numberstarting: number+ min: number+ max: number+ avg: numbertotal_entries: number+ change_7d: number+ change_30d: number}export interface ProgramSet {diff --git a/web/src/utils/dateUtils.ts b/web/src/utils/dateUtils.tsnew file mode 100644index 0000000..c728905--- /dev/null+++ b/web/src/utils/dateUtils.ts@@ -0,0 +1,42 @@+/**+ * Date helpers for the local-time write / UTC-store pattern used by the+ * weight feature.+ *+ * Storage convention: timestamps are persisted as UTC ISO strings.+ * Display convention: rendered in the browser's local timezone.+ * Date-only fields ("the date this entry is *for*"): we anchor at local noon+ * so the entry's calendar day is robust across all plausible timezone offsets.+ */++/** Today's calendar date as YYYY-MM-DD in the browser's local timezone. */+export const todayStr = (): string => {+ const d = new Date()+ const pad = (n: number) => String(n).padStart(2, '0')+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`+}++/**+ * Convert a YYYY-MM-DD calendar date to an ISO timestamp anchored at the+ * user's local noon, then expressed in UTC. Noon-anchoring keeps the entry+ * on the intended calendar day for every timezone within ±12h.+ *+ * Built without `new Date('YYYY-MM-DDTHH:MM:SS')` because old mobile Safari+ * (pre-iOS 14.5) parsed that as UTC instead of local; the explicit-component+ * constructor is locale-safe everywhere.+ */+export const dayToIsoNoon = (yyyyMmDd: string): string => {+ const [y, m, d] = yyyyMmDd.split('-').map(Number)+ return new Date(y, m - 1, d, 12, 0, 0, 0).toISOString()+}++/**+ * Extract a YYYY-MM-DD string in the browser's local timezone from any ISO+ * timestamp. Use this to populate `<input type="date">` fields when editing+ * an existing entry so the displayed date matches what the user originally+ * picked.+ */+export const isoToDayInput = (iso: string): string => {+ const d = new Date(iso)+ const pad = (n: number) => String(n).padStart(2, '0')+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`+}diff --git a/web/src/utils/numberUtils.ts b/web/src/utils/numberUtils.tsnew file mode 100644index 0000000..50b8335--- /dev/null+++ b/web/src/utils/numberUtils.ts@@ -0,0 +1,8 @@+/**+ * Returns true when `s` is a string that parses to a finite, strictly positive+ * number. Use for input validation: empty / NaN / "0" / "-5" all return false.+ */+export const isPositiveNumber = (s: string): boolean => {+ const n = parseFloat(s)+ return Number.isFinite(n) && n > 0+}