Skip to content

armgit / lyftr

Public Imported from GitHub
0

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

Favorites: one star, tappable anywhere (#136)

Carter2db70f9585aa
diff --git a/backend/controllers/food.go b/backend/controllers/food.go
index f40fd12..7b2d72e 100644
--- a/backend/controllers/food.go
+++ b/backend/controllers/food.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"encoding/json"
+ "errors"
"fmt"
"io"
"log"
@@ -77,6 +78,10 @@ func (h *Handler) LogFood(c *gin.Context) {
utils.BadRequest(c, "name exceeds 200 characters")
return
}
+ if len(req.Brand) > 200 {
+ utils.BadRequest(c, "brand exceeds 200 characters")
+ return
+ }
if len(req.ServingSize) > 100 {
utils.BadRequest(c, "serving_size exceeds 100 characters")
return
@@ -129,6 +134,10 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {
utils.BadRequest(c, "name exceeds 200 characters")
return
}
+ if len(req.Brand) > 200 {
+ utils.BadRequest(c, "brand exceeds 200 characters")
+ return
+ }
if len(req.ServingSize) > 100 {
utils.BadRequest(c, "serving_size exceeds 100 characters")
return
@@ -516,10 +525,23 @@ func (h *Handler) CreateSavedFood(c *gin.Context) {
return
}
- f, err := h.s.Food.CreateSaved(uid, req)
+ f, created, err := h.s.Food.CreateSaved(uid, req)
+ // Explicit, because utils.DBError treats sql.ErrNoRows as "not an error" and returns
+ // without writing anything — which would let a zero-valued row leave here as a 200.
+ if errors.Is(err, sql.ErrNoRows) {
+ utils.InternalError(c)
+ return
+ }
if utils.DBError(c, err) {
return
}
+ // 200 rather than 201 when the star was already set. Nothing was created, and
+ // answering 201 twice for the same food is how the duplicates in #115 read to a
+ // client that was checking.
+ if !created {
+ utils.OK(c, f)
+ return
+ }
utils.Created(c, f)
}
diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.go
index 225625a..a6a00c4 100644
--- a/backend/controllers/food_test.go
+++ b/backend/controllers/food_test.go
@@ -951,6 +951,87 @@ func TestCreateSavedFood_success(t *testing.T) {
}
}
+// Starring saves the unscaled food — the servings stepper scales at log time — so
+// starring the same food twice cannot express anything the first star didn't. #115 was a
+// user doing exactly that and being left with two identical rows he could not tell apart.
+func TestCreateSavedFood_isSameStarTwice(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ body := map[string]any{
+ "name": "Chicken Breast", "brand": "Tesco",
+ "calories": 165.0, "protein": 31.0, "carbs": 0.0, "fat": 3.6,
+ "fiber": 0.0, "serving_size": "100g",
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/food/saved", body)
+ th.CreateSavedFood(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("first save: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ firstID := decodeResponse(t, w)["data"].(map[string]any)["id"]
+
+ // Second save of the same food: 200, not 201 — nothing was created.
+ c2, w2 := newContext(uid, http.MethodPost, "/api/v1/food/saved", body)
+ th.CreateSavedFood(c2)
+ if w2.Code != http.StatusOK {
+ t.Fatalf("second save: expected 200, got %d: %s", w2.Code, w2.Body.String())
+ }
+ if got := decodeResponse(t, w2)["data"].(map[string]any)["id"]; got != firstID {
+ t.Errorf("second save returned id %v, want the existing row %v", got, firstID)
+ }
+
+ var count int
+ db.DB.QueryRow(`SELECT COUNT(*) FROM saved_foods WHERE user_id = ?`, uid).Scan(&count)
+ if count != 1 {
+ t.Fatalf("expected 1 saved food after saving the same one twice, got %d", count)
+ }
+}
+
+// Same name, different brand, is a different product and stays a separate favourite.
+func TestCreateSavedFood_brandDistinguishes(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ for _, brand := range []string{"Tesco", "Sainsbury's"} {
+ body := map[string]any{
+ "name": "Chicken Breast", "brand": brand,
+ "calories": 165.0, "protein": 31.0, "carbs": 0.0, "fat": 3.6,
+ }
+ c, w := newContext(uid, http.MethodPost, "/api/v1/food/saved", body)
+ th.CreateSavedFood(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("brand %q: expected 201, got %d: %s", brand, w.Code, w.Body.String())
+ }
+ }
+
+ var count int
+ db.DB.QueryRow(`SELECT COUNT(*) FROM saved_foods WHERE user_id = ?`, uid).Scan(&count)
+ if count != 2 {
+ t.Fatalf("expected 2 saved foods across two brands, got %d", count)
+ }
+}
+
+// The uniqueness is per user. One person starring a food must not stop anyone else.
+func TestCreateSavedFood_scopedPerUser(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ other := otherUser(t)
+
+ body := map[string]any{"name": "Oats", "brand": "Quaker", "calories": 389.0}
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/food/saved", body)
+ th.CreateSavedFood(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("first user: expected 201, got %d", w.Code)
+ }
+ c2, w2 := newContext(other, http.MethodPost, "/api/v1/food/saved", body)
+ th.CreateSavedFood(c2)
+ if w2.Code != http.StatusCreated {
+ t.Fatalf("second user: expected 201, got %d: %s", w2.Code, w2.Body.String())
+ }
+}
+
func TestCreateSavedFood_missingName(t *testing.T) {
setupTestDB(t)
uid := createTestUser(t)
@@ -1318,3 +1399,37 @@ func TestListFoodLogs_zoneChangeDoesNotMoveStoredDay(t *testing.T) {
}
}
}
+
+// A logged entry has to remember its brand, or Recent cannot tell a branded favourite
+// from an unbranded food of the same name. Before food_logs carried brand, starring a
+// logged item from Recent posted brand ”, which passed UNIQUE(user_id, name, brand) and
+// created a second row — the duplicate class #115 was filed for, re-entered through the
+// Recent tab.
+func TestLogFood_roundTripsBrand(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ body := map[string]any{
+ "name": "Chicken Breast", "brand": "Tesco", "meal": "lunch",
+ "calories": 165.0, "protein": 31.0, "carbs": 0.0, "fat": 3.6, "servings": 1.0,
+ }
+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)
+ th.LogFood(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := decodeResponse(t, w)["data"].(map[string]any)["brand"]; got != "Tesco" {
+ t.Fatalf("logged entry came back with brand %v, want Tesco", got)
+ }
+
+ // And it survives the read path the Recent tab is built on.
+ c2, w2 := newContext(uid, http.MethodGet, "/api/v1/food", nil)
+ th.ListFoodLogs(c2)
+ entries := decodeResponse(t, w2)["data"].([]any)
+ if len(entries) != 1 {
+ t.Fatalf("expected 1 entry, got %d", len(entries))
+ }
+ if got := entries[0].(map[string]any)["brand"]; got != "Tesco" {
+ t.Errorf("listed entry has brand %v, want Tesco", got)
+ }
+}
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index f66a402..6bf8a92 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -138,6 +138,69 @@ func alterMigrations() {
ensureIndex("idx_exercises_oedb_id", `CREATE UNIQUE INDEX IF NOT EXISTS idx_exercises_oedb_id ON exercises(oedb_id)`)
normalizeExerciseTaxonomy()
+
+ // The product a diary entry was, so it survives into Recent and can be matched
+ // against Favorites. Entries written before this default to '' — the same value the
+ // unbranded case uses, which is exactly how they already compared.
+ ensureColumn("food_logs", "brand", `ALTER TABLE food_logs ADD COLUMN brand TEXT NOT NULL DEFAULT ''`)
+
+ // Favorites is a bookmark list: starring a food saves it *unscaled* — the servings
+ // stepper scales at log time instead — so two rows with the same user/name/brand
+ // carry no information the first one didn't. They are the same star pressed twice.
+ //
+ // Both the order and the condition matter. ensureIndex is log.Fatal on failure and
+ // CREATE UNIQUE INDEX fails against a table that still holds duplicates, so creating
+ // it unconditionally would refuse to boot exactly the installs that have the bug.
+ if dedupeSavedFoods() {
+ ensureIndex("idx_saved_foods_unique",
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_saved_foods_unique ON saved_foods(user_id, name, brand)`)
+ }
+}
+
+// dedupeSavedFoods collapses duplicate stars, keeping the lowest id in each
+// (user_id, name, brand) group — the one starred first.
+//
+// Reports whether saved_foods is known to be free of duplicates, i.e. whether the
+// unique index may safely be created. False means "not now", never a reason to fail
+// the boot.
+//
+// Deleting rows in a migration deserves an argument. Nothing can edit a saved food
+// (there is no PATCH), and starring copies whichever search result was on screen, so
+// two rows sharing a user, name and brand differ at most in macros sourced from two
+// search hits for the same product. Neither is more authoritative, both render
+// identically in the list, and either one logs the same way. Keeping the earliest is
+// arbitrary but stable, and the row is one tap to recreate.
+func dedupeSavedFoods() bool {
+ done, err := hasMigrationFlag("dedupe_saved_foods")
+ if err != nil {
+ log.Printf("migrations: dedupe saved_foods flag: %v (skipping the unique index this boot)", err)
+ return false
+ }
+ if done {
+ return true
+ }
+ res, err := DB.Exec(`
+ DELETE FROM saved_foods
+ WHERE id NOT IN (
+ SELECT MIN(id) FROM saved_foods GROUP BY user_id, name, brand
+ )`)
+ if err != nil {
+ // Leave the flag unset so the next boot retries, and tell the caller not to
+ // create the index — CREATE UNIQUE INDEX would fail against the duplicates still
+ // there, and ensureIndex is log.Fatal, so a transient error on this one DELETE
+ // would stop the server starting. Running without the index is the far smaller
+ // problem: the clients still check before starring, so the worst case is the
+ // duplicate this migration exists to remove. Note the server-side guard genuinely
+ // is absent there — with no index there is no unique violation for CreateSaved to
+ // resolve, so it takes the plain insert path and answers 201.
+ log.Printf("migrations: dedupe saved_foods: %v (skipping the unique index this boot)", err)
+ return false
+ }
+ if n, _ := res.RowsAffected(); n > 0 {
+ log.Printf("migration: removed %d duplicate saved_foods row(s)", n)
+ }
+ setMigrationFlag("dedupe_saved_foods")
+ return true
}
// normalizeExerciseTaxonomy rewrites the eight taxonomy values Lyftr inherited
diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go
index b9cb4e0..19a0ea6 100644
--- a/backend/db/migrations_test.go
+++ b/backend/db/migrations_test.go
@@ -629,3 +629,117 @@ func TestNormalizeExerciseTaxonomy_RunsOnce(t *testing.T) {
t.Errorf("equipment = %q, want the migration to have skipped its second run", equipment)
}
}
+
+// The unique index added for #115 is created with ensureIndex, which is log.Fatal on
+// failure — so on any database that already holds duplicate bookmarks, getting the
+// dedupe order wrong does not produce a bad row, it stops the server booting. That is
+// precisely the set of installs that have the bug, which makes this the migration worth
+// pinning rather than trusting.
+func TestDedupeSavedFoods_collapsesDuplicatesAndIndexes(t *testing.T) {
+ setupMigrationTestDB(t)
+
+ var uid, other int64
+ for _, u := range []struct {
+ email string
+ into *int64
+ }{{"[email protected]", &uid}, {"[email protected]", &other}} {
+ res, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, 'x')`, u.email)
+ if err != nil {
+ t.Fatalf("insert user: %v", err)
+ }
+ *u.into, _ = res.LastInsertId()
+ }
+
+ // The state from the issue: the same bookmark pressed twice, plus rows that only
+ // look similar — a different brand, and another user's identical bookmark.
+ rows := []struct {
+ uid int64
+ name string
+ brand string
+ kcal float64
+ }{
+ {uid, "Chicken Breast", "Tesco", 165},
+ {uid, "Chicken Breast", "Tesco", 170}, // duplicate, differing macros
+ {uid, "Chicken Breast", "Tesco", 165}, // duplicate again
+ {uid, "Chicken Breast", "Sainsbury's", 168},
+ {uid, "Rolled Oats", "Quaker", 389},
+ {other, "Chicken Breast", "Tesco", 165},
+ }
+ for _, r := range rows {
+ if _, err := DB.Exec(
+ `INSERT INTO saved_foods (user_id, name, brand, calories) VALUES (?, ?, ?, ?)`,
+ r.uid, r.name, r.brand, r.kcal,
+ ); err != nil {
+ t.Fatalf("seed saved_food: %v", err)
+ }
+ }
+
+ alterMigrations()
+
+ var n int
+ if err := DB.QueryRow(
+ `SELECT COUNT(*) FROM saved_foods WHERE user_id = ? AND name = 'Chicken Breast' AND brand = 'Tesco'`, uid,
+ ).Scan(&n); err != nil {
+ t.Fatalf("count duplicates: %v", err)
+ }
+ if n != 1 {
+ t.Fatalf("expected the duplicates collapsed to 1 row, got %d", n)
+ }
+
+ // Earliest row wins, so the surviving macros are the first save's.
+ var kcal float64
+ DB.QueryRow(
+ `SELECT calories FROM saved_foods WHERE user_id = ? AND name = 'Chicken Breast' AND brand = 'Tesco'`, uid,
+ ).Scan(&kcal)
+ if kcal != 165 {
+ t.Errorf("kept calories %v, want the first save's 165", kcal)
+ }
+
+ // The look-alikes are untouched: a different brand is a different product, and
+ // uniqueness is per user.
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM saved_foods WHERE user_id = ?`, uid).Scan(&n); err != nil {
+ t.Fatalf("count user rows: %v", err)
+ }
+ if n != 3 {
+ t.Errorf("expected 3 rows left for the user (Tesco, Sainsbury's, Oats), got %d", n)
+ }
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM saved_foods WHERE user_id = ?`, other).Scan(&n); err != nil {
+ t.Fatalf("count other user rows: %v", err)
+ }
+ if n != 1 {
+ t.Errorf("other user's bookmark was collapsed too: %d rows", n)
+ }
+
+ // And the index now actually forbids what the migration just cleaned up.
+ if _, err := DB.Exec(
+ `INSERT INTO saved_foods (user_id, name, brand, calories) VALUES (?, 'Rolled Oats', 'Quaker', 389)`, uid,
+ ); err == nil {
+ t.Fatal("a duplicate bookmark was still insertable after the migration")
+ }
+}
+
+// alterMigrations runs on every boot; the dedupe must not fight the index on the second
+// pass, and must not touch rows that are legitimately there.
+func TestDedupeSavedFoods_isIdempotentAcrossBoots(t *testing.T) {
+ setupMigrationTestDB(t)
+
+ res, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')`)
+ if err != nil {
+ t.Fatalf("insert user: %v", err)
+ }
+ uid, _ := res.LastInsertId()
+ if _, err := DB.Exec(
+ `INSERT INTO saved_foods (user_id, name, brand, calories) VALUES (?, 'Oats', 'Quaker', 389)`, uid,
+ ); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+
+ alterMigrations()
+ alterMigrations()
+
+ var n int
+ DB.QueryRow(`SELECT COUNT(*) FROM saved_foods WHERE user_id = ?`, uid).Scan(&n)
+ if n != 1 {
+ t.Fatalf("expected the single bookmark to survive two boots, got %d rows", n)
+ }
+}
diff --git a/backend/models/models.go b/backend/models/models.go
index c5e2ce8..ddadd0a 100644
--- a/backend/models/models.go
+++ b/backend/models/models.go
@@ -133,6 +133,7 @@ type FoodLog struct {
ID int64 `json:"id" db:"id"`
UserID int64 `json:"user_id" db:"user_id"`
Name string `json:"name" db:"name"`
+ Brand string `json:"brand" db:"brand"`
Meal string `json:"meal" db:"meal"` // "breakfast", "lunch", "dinner", "snacks"
Calories float64 `json:"calories" db:"calories"`
Protein float64 `json:"protein" db:"protein"`
@@ -289,6 +290,7 @@ type LogWeightRequest struct {
type LogFoodRequest struct {
Name string `json:"name" validate:"required"`
+ Brand string `json:"brand"`
Meal string `json:"meal" validate:"required,oneof=breakfast lunch dinner snacks"`
Calories float64 `json:"calories" validate:"gte=0"`
Protein float64 `json:"protein" validate:"gte=0"`
diff --git a/backend/stores/food.go b/backend/stores/food.go
index 5a4868e..1a36d21 100644
--- a/backend/stores/food.go
+++ b/backend/stores/food.go
@@ -2,8 +2,10 @@ package stores
import (
"database/sql"
+ "errors"
"github.com/Cawlumm/lyftr-backend/models"
+ "github.com/Cawlumm/lyftr-backend/utils"
)
// FoodStore owns all SQL for food_logs and saved_foods.
@@ -20,11 +22,11 @@ const foodDay = `CASE
WHEN logged_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*' THEN substr(logged_at, 1, 10)
END`
-const foodLogSelect = `SELECT id, user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on, created_at FROM food_logs`
+const foodLogSelect = `SELECT id, user_id, name, brand, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on, created_at FROM food_logs`
func scanFoodLog(row interface{ Scan(...any) error }, f *models.FoodLog) error {
return row.Scan(
- &f.ID, &f.UserID, &f.Name, &f.Meal,
+ &f.ID, &f.UserID, &f.Name, &f.Brand, &f.Meal,
&f.Calories, &f.Protein, &f.Carbs, &f.Fat, &f.Fiber,
&f.Servings, &f.ServingSize, &f.Barcode, &f.ImageURL,
&f.LoggedAt, &f.LoggedOn, &f.CreatedAt,
@@ -67,9 +69,9 @@ func (s *FoodStore) Get(uid, id int64) (models.FoodLog, error) {
// by the controller (client-supplied when sent, else from the account zone).
func (s *FoodStore) Create(uid int64, req models.LogFoodRequest, day string) (models.FoodLog, error) {
res, err := s.db.Exec(
- `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- uid, req.Name, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,
+ `INSERT INTO food_logs (user_id, name, brand, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ uid, req.Name, req.Brand, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,
req.Servings, req.ServingSize, req.Barcode, req.ImageURL, req.LoggedAt, day,
)
if err != nil {
@@ -81,10 +83,10 @@ func (s *FoodStore) Create(uid int64, req models.LogFoodRequest, day string) (mo
func (s *FoodStore) Update(uid, id int64, req models.LogFoodRequest, day string) (models.FoodLog, error) {
res, err := s.db.Exec(
- `UPDATE food_logs SET name=?, meal=?, calories=?, protein=?, carbs=?, fat=?, fiber=?,
+ `UPDATE food_logs SET name=?, brand=?, meal=?, calories=?, protein=?, carbs=?, fat=?, fiber=?,
servings=?, serving_size=?, barcode=?, image_url=?, logged_at=?, logged_on=?
WHERE id=? AND user_id=?`,
- req.Name, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,
+ req.Name, req.Brand, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,
req.Servings, req.ServingSize, req.Barcode, req.ImageURL, req.LoggedAt, day,
id, uid,
)
@@ -178,7 +180,28 @@ func (s *FoodStore) ListSaved(uid int64) ([]models.SavedFood, error) {
return foods, rows.Err()
}
-func (s *FoodStore) CreateSaved(uid int64, req models.SaveFoodRequest) (models.SavedFood, error) {
+// CreateSaved stars a food, and is idempotent: starring something already in Favorites
+// returns the existing row rather than adding a second copy. `created` reports which
+// happened so the handler can answer 201 or 200.
+//
+// The clients already show the star as filled once a food is favourited, but that check
+// reads a list fetched when the screen opened. Two devices, or one device with a stale
+// list, would otherwise race straight into the unique index and surface a 500 for what
+// is simply "already favourited".
+func (s *FoodStore) CreateSaved(uid int64, req models.SaveFoodRequest) (models.SavedFood, bool, error) {
+ // Two attempts: the insert can lose to a concurrent star, and the read that resolves
+ // that conflict can then lose to a concurrent unstar. One retry closes both, and a
+ // second failure means the row is genuinely gone rather than contended.
+ for attempt := 0; ; attempt++ {
+ f, created, err := s.createSavedOnce(uid, req)
+ if errors.Is(err, sql.ErrNoRows) && attempt == 0 {
+ continue
+ }
+ return f, created, err
+ }
+}
+
+func (s *FoodStore) createSavedOnce(uid int64, req models.SaveFoodRequest) (f models.SavedFood, created bool, err error) {
res, err := s.db.Exec(
`INSERT INTO saved_foods (user_id, name, brand, calories, protein, carbs, fat, fiber, serving_size, barcode)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
@@ -186,12 +209,23 @@ func (s *FoodStore) CreateSaved(uid int64, req models.SaveFoodRequest) (models.S
req.ServingSize, req.Barcode,
)
if err != nil {
- return models.SavedFood{}, err
+ if !utils.IsUniqueViolation(err) {
+ return models.SavedFood{}, false, err
+ }
+ // A miss here means the row was unstarred between the insert and this read, on a
+ // pool of one connection. Surfaced as sql.ErrNoRows so CreateSaved retries the
+ // insert: returning it to the handler would be worse than useless, because
+ // utils.DBError ignores sql.ErrNoRows and the zero-valued row would ship as a
+ // 200 with id 0 — a blank favourite the clients would then render.
+ err = scanSavedFood(
+ s.db.QueryRow(savedFoodSelect+` WHERE user_id = ? AND name = ? AND brand = ?`, uid, req.Name, req.Brand),
+ &f,
+ )
+ return f, false, err
}
id, _ := res.LastInsertId()
- var f models.SavedFood
err = scanSavedFood(s.db.QueryRow(savedFoodSelect+` WHERE id = ?`, id), &f)
- return f, err
+ return f, true, err
}
func (s *FoodStore) DeleteSaved(uid, id int64) (int64, error) {
diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsx
index 527e0ea..e2193a2 100644
--- a/mobile/app/(tabs)/nutrition/log.tsx
+++ b/mobile/app/(tabs)/nutrition/log.tsx
@@ -1,25 +1,26 @@
-import { useEffect, useRef, useState } from 'react'
-import { Image, Pressable, ScrollView, View } from 'react-native'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { Image, Pressable, RefreshControl, ScrollView, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import * as Haptics from 'expo-haptics'
import {
- AlertCircle, ArrowLeft, Bookmark, BookmarkCheck, ChevronRight, Minus, Plus, Scan, Utensils, Zap,
+ AlertCircle, ArrowLeft, ChevronRight, Minus, Plus, Scan, Star, Utensils, Zap,
} from 'lucide-react-native'
import {
dayToInstant, entryDay, todayStr,
type FoodSearchResult, type SavedFood,
} from '@lyftr/shared'
import {
- AppText, Button, Card, DateInput, IconButton, Label, NumberField,
- NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, SearchField, SegmentedControl, Toggle,
+ Alert, AppText, Button, Card, DateInput, IconButton, Label, NumberField,
+ NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, SearchField, SegmentedControl,
} from '../../../src/components/ui'
import { BarcodeScanner } from '../../../src/components/nutrition/BarcodeScanner'
+import { FavoriteStar, FoodResultRow } from '../../../src/components/nutrition/FoodResultRow'
import {
MACRO_COLORS, MACRO_TEXT, MEALS, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal,
} from '../../../src/components/nutrition/nutritionMeta'
import { client } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
-import { entryToResult, savedToResult, scaleServing } from '@lyftr/shared'
+import { entryToResult, findSavedFood, savedToResult, scaleServing } from '@lyftr/shared'
type Phase = 'search' | 'detail' | 'scan'
type SearchTab = 'recent' | 'myfoods' | 'all'
@@ -28,48 +29,11 @@ const hSelect = () => Haptics.selectionAsync().catch(() => {})
const TAB_OPTIONS = [
{ value: 'recent', label: 'Recent' },
- { value: 'myfoods', label: 'My Foods' },
+ { value: 'myfoods', label: 'Favorites' },
{ value: 'all', label: 'Search' },
] as const
// Port of web/pages/LogFood.tsx — the search / detail / scan food-logging flow.
-function FoodResultRow({ item, onPress }: { item: FoodSearchResult; onPress: () => void }) {
- const { colors } = useTheme()
- return (
- <Pressable
- onPress={onPress}
- className="w-full flex-row items-center gap-3 border-b border-surface-border px-4 py-3.5 active:bg-surface-muted"
- >
- {item.image_url ? (
- <Image source={{ uri: item.image_url }} className="h-11 w-11 rounded-xl border border-surface-border" />
- ) : (
- <View className="h-11 w-11 items-center justify-center rounded-xl border border-surface-border bg-surface-muted">
- <Utensils size={20} color={colors.txMuted} />
- </View>
- )}
- <View className="min-w-0 flex-1">
- <AppText variant="bodySemibold" numberOfLines={1}>{item.name}</AppText>
- {item.brand ? <AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">{item.brand}</AppText> : null}
- <View className="mt-1 flex-row flex-wrap items-center gap-x-1.5">
- <AppText variant="caption" color="secondary" style={{ fontWeight: '600', fontVariant: ['tabular-nums'] }}>{Math.round(item.calories)} kcal</AppText>
- <Dot />
- <AppText variant="caption" style={{ color: MACRO_TEXT.protein, fontVariant: ['tabular-nums'] }}>{item.protein.toFixed(0)}g P</AppText>
- <Dot />
- <AppText variant="caption" style={{ color: MACRO_TEXT.carbs, fontVariant: ['tabular-nums'] }}>{item.carbs.toFixed(0)}g C</AppText>
- <Dot />
- <AppText variant="caption" style={{ color: MACRO_TEXT.fat, fontVariant: ['tabular-nums'] }}>{item.fat.toFixed(0)}g F</AppText>
- {item.serving_size ? (<><Dot /><AppText variant="caption" color="muted" style={{ fontSize: 10 }}>{item.serving_size}</AppText></>) : null}
- </View>
- </View>
- <ChevronRight size={16} color={colors.txMuted} />
- </Pressable>
- )
-}
-
-function Dot() {
- return <AppText variant="caption" color="muted" style={{ fontSize: 10 }}>·</AppText>
-}
-
export default function LogFood() {
const { colors, brand, accent, isDark } = useTheme()
const params = useLocalSearchParams<{ meal?: string; date?: string; edit?: string }>()
@@ -91,9 +55,79 @@ export default function LogFood() {
const [servingsStr, setServingsStr] = useState('1')
const [meal, setMeal] = useState<Meal>(initMeal)
const [date, setDate] = useState(initDate)
- const [saveToMyFoods, setSaveToMyFoods] = useState(false)
+ const [togglingFavorite, setTogglingFavorite] = useState<Set<string>>(new Set())
+ const [pulling, setPulling] = useState(false)
+
+ // Derived from the list rather than tracked, so a star tapped on any tab is reflected
+ // everywhere the same food appears — including the detail screen.
+ const favoriteOf = (item: FoodSearchResult) => findSavedFood(savedFoods, item)
+
+ // Bumped by every star/unstar. A list load captures it and discards its own result if
+ // a toggle landed while it was in flight — otherwise a pull-to-refresh issued just
+ // before a DELETE resolves comes back holding the row and puts the unstarred food back
+ // on screen, and the next tap deletes an id the server no longer has.
+ const listEpoch = useRef(0)
+
+ // Favouriting is its own action, not a side effect of logging. One tap on, one tap off,
+ // from any row or from the detail header. No confirmation: a second tap undoes it.
+ // The guard is a ref, not the state below. setState does not apply within the tick it
+ // is called in, so a burst of taps in one frame all read the same empty set and all
+ // fire — five rapid clicks sent one DELETE that worked and four that 404'd, then showed
+ // "Couldn't remove …" for an unstar that had actually succeeded. The state exists only
+ // to dim the star; the ref is what decides.
+ const inFlightFavorites = useRef<Set<string>>(new Set())
+
+ const toggleFavorite = async (item: FoodSearchResult) => {
+ const key = `${item.name}|${item.brand ?? ''}`
+ // Guard this food only. A single global flag dropped taps on *other* rows while a
+ // request was in flight, so on a slow connection every other star went dead with no
+ // feedback — indistinguishable from a broken button.
+ if (inFlightFavorites.current.has(key)) return
+ inFlightFavorites.current.add(key)
+ setTogglingFavorite(new Set(inFlightFavorites.current))
+ setFavoriteError(null)
+ listEpoch.current += 1
+ const existing = favoriteOf(item)
+ try {
+ if (existing) {
+ await client.savedFoodsAPI.delete(existing.id)
+ setSavedFoods((prev) => prev.filter((f) => f.id !== existing.id))
+ Haptics.selectionAsync().catch(() => {})
+ } else {
+ const created = await client.savedFoodsAPI.create({
+ name: item.name, brand: item.brand ?? '',
+ calories: item.calories, protein: item.protein,
+ carbs: item.carbs, fat: item.fat, fiber: item.fiber ?? 0,
+ serving_size: item.serving_size ?? '',
+ })
+ // The server answers 200 with the existing row when the food is already
+ // favourited, so `created` can be something the list already holds — after a
+ // pull-to-refresh that raced this request, for instance. Appending blind puts two
+ // rows with the same id (and the same React key) in the list.
+ // Inserted in name order rather than appended: ListSaved returns ORDER BY name,
+ // so appending parks a new favourite at the bottom until the next load and then
+ // jumps it. Plain < to match SQLite's BINARY collation rather than localeCompare,
+ // which would order differently from the server it is imitating.
+ setSavedFoods((prev) => prev.some((f) => f.id === created.id)
+ ? prev
+ : [...prev, created].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)))
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
+ }
+ } catch {
+ setFavoriteError(existing
+ ? `Couldn't remove ${item.name} from Favorites.`
+ : `Couldn't add ${item.name} to Favorites.`)
+ } finally {
+ inFlightFavorites.current.delete(key)
+ setTogglingFavorite(new Set(inFlightFavorites.current))
+ }
+ }
+
+ const isToggling = (item: FoodSearchResult) =>
+ togglingFavorite.has(`${item.name}|${item.brand ?? ''}`)
const [saving, setSaving] = useState(false)
const [saveError, setSaveError] = useState<string | null>(null)
+ const [favoriteError, setFavoriteError] = useState<string | null>(null)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -113,24 +147,41 @@ export default function LogFood() {
}).catch(() => router.replace('/nutrition'))
}, [editId])
- // Recent (today, deduped ≤10) + saved foods.
- useEffect(() => {
- client.foodAPI.list(todayStr()).then((logs) => {
- const seen = new Set<string>()
- const items: FoodSearchResult[] = []
- for (const log of logs || []) {
- const key = log.name.toLowerCase()
- if (!seen.has(key)) {
- seen.add(key)
- items.push(entryToResult(log))
- if (items.length >= 10) break
+ // Recent (today, deduped ≤10) + favourites.
+ const loadLists = useCallback(async () => {
+ const epoch = listEpoch.current
+ const apply = <T,>(set: (v: T) => void) => (v: T) => {
+ if (listEpoch.current === epoch) set(v)
+ }
+ await Promise.all([
+ client.foodAPI.list(todayStr()).then((logs) => {
+ const seen = new Set<string>()
+ const items: FoodSearchResult[] = []
+ for (const log of logs || []) {
+ const key = log.name.toLowerCase()
+ if (!seen.has(key)) {
+ seen.add(key)
+ items.push(entryToResult(log))
+ if (items.length >= 10) break
+ }
}
- }
- setRecentItems(items)
- }).catch(() => {})
- client.savedFoodsAPI.list().then(setSavedFoods).catch(() => {})
+ apply(setRecentItems)(items)
+ }).catch(() => {}),
+ client.savedFoodsAPI.list().then(apply(setSavedFoods)).catch(() => {}),
+ ])
}, [])
+ useEffect(() => { loadLists() }, [loadLists])
+
+ // Pull-to-refresh, matching the five list screens that already have it. Worth having
+ // here because both lists go stale from elsewhere: logging on another device changes
+ // Recent, and favouriting on web changes Favorites.
+ const onPullRefresh = useCallback(async () => {
+ setPulling(true)
+ await loadLists()
+ setPulling(false)
+ }, [loadLists])
+
// Debounced remote search (only on the Search tab).
useEffect(() => {
if (tab !== 'all') return
@@ -193,14 +244,6 @@ export default function LogFood() {
await client.foodAPI.update(editId, payload)
} else {
await client.foodAPI.log(payload)
- if (saveToMyFoods) {
- await client.savedFoodsAPI.create({
- name: selected.name, brand: selected.brand ?? '',
- calories: selected.calories, protein: selected.protein,
- carbs: selected.carbs, fat: selected.fat, fiber: selected.fiber ?? 0,
- serving_size: selected.serving_size ?? '',
- }).catch(() => {})
- }
}
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
// Courier the confirmation to the dashboard toast: which meal (new) or 'Updated'.
@@ -250,11 +293,39 @@ export default function LogFood() {
<AppText variant="title">Log Food</AppText>
)}
</View>
+ {/* Favouriting is decoupled from logging, so the star lives beside the food
+ rather than inside the form — you can star something without logging it,
+ and unstar it the same way. Hidden in edit mode, where `selected` is a
+ logged entry being amended rather than a food being picked. */}
+ {phase === 'detail' && selected && !editId && selected.name ? (
+ <FavoriteStar
+ size="md"
+ favorited={favoriteOf(selected) !== undefined}
+ busy={isToggling(selected)}
+ name={selected.name}
+ onPress={() => toggleFavorite(selected)}
+ />
+ ) : null}
</View>
+ {/* Outside both phases on purpose: the star is on the rows *and* in the header
+ above, so a failure has to be visible whichever one the user pressed. Sitting
+ inside the search phase meant a failed star on the detail screen said nothing
+ at all and simply snapped back to unfilled. */}
+ {favoriteError ? (
+ <View className="pb-3">
+ <Alert variant="error">{favoriteError}</Alert>
+ </View>
+ ) : null}
+
{/* ── Search phase ── */}
{phase === 'search' ? (
- <ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled" contentContainerStyle={{ paddingBottom: 32 }}>
+ <ScrollView
+ showsVerticalScrollIndicator={false}
+ keyboardShouldPersistTaps="handled"
+ contentContainerStyle={{ paddingBottom: 32 }}
+ refreshControl={<RefreshControl refreshing={pulling} onRefresh={onPullRefresh} tintColor={accent} colors={[accent]} />}
+ >
<View className="gap-4">
{/* Search + scan */}
<View className="flex-row items-center gap-2">
@@ -280,6 +351,8 @@ export default function LogFood() {
{/* Tabs */}
<SegmentedControl options={TAB_OPTIONS} value={tab} onChange={setTab} />
+ {/* Above the tab content, not inside one branch: the star is on every tab, so
+ a failure starring a search result has to be visible on the search tab. */}
{rateLimited ? (
<View className="flex-row items-center gap-2 rounded-xl border border-warning-500/20 bg-warning-500/10 px-3.5 py-3">
<AlertCircle size={16} color={isDark ? brand.warningSoft : brand.warning} />
@@ -315,15 +388,35 @@ export default function LogFood() {
recentItems.length === 0 ? (
<EmptyBlock icon={Utensils} title="No recent items today" subtitle="Search or scan to log food" />
) : (
- recentItems.map((item, i) => <FoodResultRow key={`${item.name}-${item.calories}-${i}`} item={item} onPress={() => selectResult(item)} />)
+ recentItems.map((item, i) => (
+ <FoodResultRow
+ key={`${item.name}-${item.calories}-${i}`}
+ item={item}
+ onPress={() => selectResult(item)}
+ favorited={favoriteOf(item) !== undefined}
+ onToggleFavorite={() => toggleFavorite(item)}
+ togglingFavorite={isToggling(item)}
+ />
+ ))
)
) : null}
{tab === 'myfoods' ? (
savedFoods.length === 0 ? (
- <EmptyBlock icon={Bookmark} title="No saved foods yet" subtitle="Save foods while logging to find them here" />
+ <EmptyBlock icon={Star} title="No favorites yet" subtitle="Star foods while logging to find them here" />
) : (
- savedFoods.map((sf) => <FoodResultRow key={sf.id} item={savedToResult(sf)} onPress={() => selectResult(savedToResult(sf))} />)
+ <>
+ {savedFoods.map((sf) => (
+ <FoodResultRow
+ key={sf.id}
+ item={savedToResult(sf)}
+ onPress={() => selectResult(savedToResult(sf))}
+ favorited
+ onToggleFavorite={() => toggleFavorite(savedToResult(sf))}
+ togglingFavorite={isToggling(savedToResult(sf))}
+ />
+ ))}
+ </>
)
) : null}
@@ -345,7 +438,14 @@ export default function LogFood() {
</View>
) : null}
{tab === 'all' && !searching ? searchResults.map((item, i) => (
- <FoodResultRow key={`${item.name}-${item.calories}-${i}`} item={item} onPress={() => selectResult(item)} />
+ <FoodResultRow
+ key={`${item.name}-${item.calories}-${i}`}
+ item={item}
+ onPress={() => selectResult(item)}
+ favorited={favoriteOf(item) !== undefined}
+ onToggleFavorite={() => toggleFavorite(item)}
+ togglingFavorite={isToggling(item)}
+ />
)) : null}
</Card>
</View>
@@ -475,20 +575,6 @@ export default function LogFood() {
<DateInput label="When" value={date} onChange={setDate} maximumDate={new Date()} />
</Card>
- {/* Save to My Foods — hidden in edit mode */}
- {!editId ? (
- <Pressable onPress={() => setSaveToMyFoods((v) => !v)} className="flex-row items-center gap-3">
- <Card className="flex-1 flex-row items-center gap-3">
- <View pointerEvents="none">
- <Toggle value={saveToMyFoods} onValueChange={setSaveToMyFoods} />
- </View>
- <View className="flex-row items-center gap-2">
- {saveToMyFoods ? <BookmarkCheck size={16} color={accent} /> : <Bookmark size={16} color={colors.txMuted} />}
- <AppText variant="bodySemibold" color="secondary" style={{ fontSize: 14 }}>Save to My Foods</AppText>
- </View>
- </Card>
- </Pressable>
- ) : null}
</View>
</ScrollView>
diff --git a/mobile/src/components/nutrition/FoodResultRow.test.tsx b/mobile/src/components/nutrition/FoodResultRow.test.tsx
new file mode 100644
index 0000000..367b8f3
--- /dev/null
+++ b/mobile/src/components/nutrition/FoodResultRow.test.tsx
@@ -0,0 +1,90 @@
+import { fireEvent, render, screen } from '@testing-library/react-native'
+import type { FoodSearchResult } from '@lyftr/shared'
+// The `mock` prefix is what lets a jest.mock factory close over an import — the rule is
+// jest's, and it means the async-storage mock needs no require() inside the factory.
+import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'
+import { FoodResultRow } from './FoodResultRow'
+
+// Same preamble as the programs component tests: expo-router can't load under bare jest,
+// and the ui barrel reaches it via useTheme → lib/lyftr. These sit below the imports
+// because babel-jest hoists jest.mock above them anyway — writing them first was a
+// convention, not a requirement, and it cost an import/first warning per file.
+jest.mock('expo-router', () => ({
+ router: { push: jest.fn(), navigate: jest.fn(), replace: jest.fn() },
+}))
+jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage)
+jest.mock('react-native-safe-area-context', () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
+}))
+
+const item = (overrides: Partial<FoodSearchResult> = {}): FoodSearchResult => ({
+ name: 'Chicken Breast',
+ calories: 165,
+ protein: 31,
+ carbs: 0,
+ fat: 3.6,
+ fiber: 0,
+ serving_size: '100g',
+ source: 'off',
+ ...overrides,
+})
+
+const ADD = 'Add Chicken Breast to Favorites'
+const REMOVE = 'Remove Chicken Breast from Favorites'
+
+describe('FoodResultRow', () => {
+ // The label carries the toggle state, because the fill that conveys it visually is
+ // invisible to a screen reader.
+ it('offers to add when the food is not favourited', () => {
+ render(<FoodResultRow item={item()} onPress={() => {}} favorited={false} onToggleFavorite={() => {}} />)
+ expect(screen.getByLabelText(ADD)).toBeTruthy()
+ expect(screen.queryByLabelText(REMOVE)).toBeNull()
+ })
+
+ it('offers to remove when the food is favourited', () => {
+ render(<FoodResultRow item={item()} onPress={() => {}} favorited onToggleFavorite={() => {}} />)
+ expect(screen.getByLabelText(REMOVE)).toBeTruthy()
+ expect(screen.queryByLabelText(ADD)).toBeNull()
+ })
+
+ // One tap, no confirmation sheet in between — that is the whole point of the change.
+ it('toggles on a single tap', () => {
+ const onToggleFavorite = jest.fn()
+ render(<FoodResultRow item={item()} onPress={() => {}} favorited onToggleFavorite={onToggleFavorite} />)
+ fireEvent.press(screen.getByLabelText(REMOVE))
+ expect(onToggleFavorite).toHaveBeenCalledTimes(1)
+ })
+
+ // Tapping the star must not also select the food; the row press and the star press are
+ // separate targets even though the star sits inside the row's Pressable.
+ it('does not select the food when the star is tapped', () => {
+ const onPress = jest.fn()
+ render(<FoodResultRow item={item()} onPress={onPress} favorited={false} onToggleFavorite={() => {}} />)
+ fireEvent.press(screen.getByLabelText(ADD))
+ expect(onPress).not.toHaveBeenCalled()
+ })
+
+ it('still selects the food when the row body is tapped', () => {
+ const onPress = jest.fn()
+ render(<FoodResultRow item={item()} onPress={onPress} favorited={false} onToggleFavorite={() => {}} />)
+ fireEvent.press(screen.getByText('Chicken Breast'))
+ expect(onPress).toHaveBeenCalled()
+ })
+
+ // Mid-request the star is inert, so a double tap can't fire a create and a delete for
+ // the same food and leave the list disagreeing with the server.
+ it('ignores taps while the toggle is in flight', () => {
+ const onToggleFavorite = jest.fn()
+ render(
+ <FoodResultRow
+ item={item()}
+ onPress={() => {}}
+ favorited
+ onToggleFavorite={onToggleFavorite}
+ togglingFavorite
+ />,
+ )
+ fireEvent.press(screen.getByLabelText(REMOVE))
+ expect(onToggleFavorite).not.toHaveBeenCalled()
+ })
+})
diff --git a/mobile/src/components/nutrition/FoodResultRow.tsx b/mobile/src/components/nutrition/FoodResultRow.tsx
new file mode 100644
index 0000000..8dd410e
--- /dev/null
+++ b/mobile/src/components/nutrition/FoodResultRow.tsx
@@ -0,0 +1,107 @@
+import { Image, Pressable, View } from 'react-native'
+import { ChevronRight, Star, Utensils } from 'lucide-react-native'
+import type { FoodSearchResult } from '@lyftr/shared'
+import { AppText } from '../ui'
+import { useTheme } from '../../theme/useTheme'
+import { MACRO_TEXT } from './nutritionMeta'
+
+interface Props {
+ item: FoodSearchResult
+ /** Tap the row → pick this food and go to the detail step. */
+ onPress: () => void
+ /** Filled star. */
+ favorited: boolean
+ /** Toggle the star. Every list this row appears in offers favouriting. */
+ onToggleFavorite: () => void
+ /** Star is mid-request — dimmed and inert so a double tap can't race itself. */
+ togglingFavorite?: boolean
+}
+
+// The search / Recent / Favorites result row.
+//
+// The star is the whole favourites mechanic: one tap on, one tap off, from wherever the
+// food appears. It replaces the ⋮ → ActionSheet → ConfirmSheet this row briefly had,
+// which was three interactions to undo something a second tap undoes — and which only
+// existed on the Favorites tab, so a food found by search could not be favourited at all
+// without logging it first.
+//
+// No confirmation, deliberately. A favourite is a bookmark, not a record: the row is not
+// data being destroyed, and tapping again restores it. This is what Cronometer does.
+export function FoodResultRow({
+ item, onPress, favorited, onToggleFavorite, togglingFavorite = false,
+}: Props) {
+ const { colors } = useTheme()
+
+ return (
+ <Pressable
+ onPress={onPress}
+ className="w-full flex-row items-center gap-3 border-b border-surface-border px-4 py-3.5 active:bg-surface-muted"
+ >
+ {item.image_url ? (
+ <Image source={{ uri: item.image_url }} className="h-11 w-11 rounded-xl border border-surface-border" />
+ ) : (
+ <View className="h-11 w-11 items-center justify-center rounded-xl border border-surface-border bg-surface-muted">
+ <Utensils size={20} color={colors.txMuted} />
+ </View>
+ )}
+ <View className="min-w-0 flex-1">
+ <AppText variant="bodySemibold" numberOfLines={1}>{item.name}</AppText>
+ {item.brand ? <AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">{item.brand}</AppText> : null}
+ <View className="mt-1 flex-row flex-wrap items-center gap-x-1.5">
+ <AppText variant="caption" color="secondary" style={{ fontWeight: '600', fontVariant: ['tabular-nums'] }}>{Math.round(item.calories)} kcal</AppText>
+ <Dot />
+ <AppText variant="caption" style={{ color: MACRO_TEXT.protein, fontVariant: ['tabular-nums'] }}>{item.protein.toFixed(0)}g P</AppText>
+ <Dot />
+ <AppText variant="caption" style={{ color: MACRO_TEXT.carbs, fontVariant: ['tabular-nums'] }}>{item.carbs.toFixed(0)}g C</AppText>
+ <Dot />
+ <AppText variant="caption" style={{ color: MACRO_TEXT.fat, fontVariant: ['tabular-nums'] }}>{item.fat.toFixed(0)}g F</AppText>
+ {item.serving_size ? (<><Dot /><AppText variant="caption" color="muted" style={{ fontSize: 10 }}>{item.serving_size}</AppText></>) : null}
+ </View>
+ </View>
+
+ <FavoriteStar
+ favorited={favorited}
+ busy={togglingFavorite}
+ name={item.name}
+ onPress={onToggleFavorite}
+ />
+ <ChevronRight size={16} color={colors.txMuted} />
+ </Pressable>
+ )
+}
+
+// Shared by the row and the detail screen so the two cannot drift on colour, fill or
+// wording — the label is what a screen reader announces, and "Favorite"/"Unfavorite"
+// carries the toggle state that the fill conveys visually.
+export function FavoriteStar(
+ { favorited, busy = false, name, onPress, size = 'sm' }:
+ { favorited: boolean; busy?: boolean; name: string; onPress: () => void; size?: 'sm' | 'md' },
+) {
+ const { colors, accent } = useTheme()
+ // Same box, hit slop and press feedback as ui/IconButton — written out rather than
+ // reusing it because a filled star needs an SVG `fill`, and adding a fill prop to the
+ // shared primitive for one toggle is the wrong place to put it.
+ const box = size === 'sm' ? 'w-8 h-8 rounded-lg' : 'w-10 h-10 rounded-xl'
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ selected: favorited }}
+ accessibilityLabel={favorited ? `Remove ${name} from Favorites` : `Add ${name} to Favorites`}
+ onPress={onPress}
+ disabled={busy}
+ hitSlop={8}
+ className={`items-center justify-center active:scale-95 ${box} ${busy ? 'opacity-40' : ''}`}
+ >
+ <Star
+ size={size === 'sm' ? 18 : 22}
+ color={favorited ? accent : colors.txMuted}
+ fill={favorited ? accent : 'transparent'}
+ strokeWidth={2.2}
+ />
+ </Pressable>
+ )
+}
+
+function Dot() {
+ return <AppText variant="caption" color="muted" style={{ fontSize: 10 }}>·</AppText>
+}
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index ae08a14..8df0732 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -94,6 +94,8 @@ export interface FoodLog {
id: number
user_id?: number
name: string
+ /** The product this entry was, so Recent can be matched against Favorites. '' when unbranded. */
+ brand?: string
meal: 'breakfast' | 'lunch' | 'dinner' | 'snacks'
calories: number
protein: number
diff --git a/packages/shared/src/utils/food.test.ts b/packages/shared/src/utils/food.test.ts
index 73ec7b1..8740ad4 100644
--- a/packages/shared/src/utils/food.test.ts
+++ b/packages/shared/src/utils/food.test.ts
@@ -1,4 +1,4 @@
-import { entryToResult, savedToResult, scaleServing } from './food'
+import { entryToResult, findSavedFood, savedToResult, scaleServing } from './food'
import type { FoodLog, SavedFood } from '../types'
const log = (over: Partial<FoodLog> = {}): FoodLog => ({
@@ -72,3 +72,60 @@ describe('scaleServing', () => {
expect(p).toMatchObject({ name: 'Custom entry', fiber: 0, serving_size: '', image_url: '' })
})
})
+
+const saved = (over: Partial<SavedFood> = {}): SavedFood => ({
+ id: 1, user_id: 1, name: 'Chicken Breast', brand: 'Tesco',
+ calories: 165, protein: 31, carbs: 0, fat: 3.6, fiber: 0,
+ serving_size: '100g', barcode: '', created_at: '',
+ ...over,
+} as SavedFood)
+
+// The Recent tab is built on entryToResult, and its rows are matched against Favorites
+// by name + brand. If brand doesn't survive the log round-trip, a branded favourite shows
+// an unfilled star on Recent and starring it creates a second, brandless row.
+describe('brand survives the log round-trip', () => {
+ it('entryToResult keeps the brand', () => {
+ expect(entryToResult(log({ brand: 'Tesco' } as never)).brand).toBe('Tesco')
+ })
+
+ it('scaleServing carries the brand onto the logged payload', () => {
+ const picked = savedToResult(saved({ brand: 'Fage' }))
+ expect(scaleServing(picked, 2).brand).toBe('Fage')
+ })
+
+ it('an unbranded food stays an empty string, matching what the API stores', () => {
+ expect(scaleServing({ name: 'Water', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 glass', source: 'manual' }, 1).brand).toBe('')
+ })
+})
+
+describe('findSavedFood', () => {
+ it('matches on name and brand', () => {
+ const list = [saved({ id: 7 })]
+ expect(findSavedFood(list, { name: 'Chicken Breast', brand: 'Tesco' })?.id).toBe(7)
+ })
+
+ it('treats a different brand as a different product', () => {
+ const list = [saved({ brand: 'Tesco' })]
+ expect(findSavedFood(list, { name: 'Chicken Breast', brand: "Sainsbury's" })).toBeUndefined()
+ })
+
+ // The API stores '' for an unbranded food; a search result can carry undefined. These
+ // are the same bookmark, and treating them as different is how a duplicate slips past
+ // the client check straight into the server's unique index.
+ it('treats a missing brand and an empty brand as the same', () => {
+ const list = [saved({ id: 3, brand: '' })]
+ expect(findSavedFood(list, { name: 'Chicken Breast' })?.id).toBe(3)
+ expect(findSavedFood(list, { name: 'Chicken Breast', brand: '' })?.id).toBe(3)
+ })
+
+ // Matched exactly, mirroring the server's UNIQUE index. If the client folded case and
+ // the server did not, the client would hide a bookmark the server would happily add.
+ it('does not fold case', () => {
+ const list = [saved()]
+ expect(findSavedFood(list, { name: 'chicken breast', brand: 'Tesco' })).toBeUndefined()
+ })
+
+ it('returns undefined against an empty list', () => {
+ expect(findSavedFood([], { name: 'Chicken Breast', brand: 'Tesco' })).toBeUndefined()
+ })
+})
diff --git a/packages/shared/src/utils/food.ts b/packages/shared/src/utils/food.ts
index dcdeeed..f2bf7a6 100644
--- a/packages/shared/src/utils/food.ts
+++ b/packages/shared/src/utils/food.ts
@@ -12,6 +12,7 @@ export function entryToResult(e: FoodLog): FoodSearchResult {
const s = e.servings || 1
return {
name: e.name,
+ brand: e.brand ?? '',
calories: e.calories / s,
protein: e.protein / s,
carbs: e.carbs / s,
@@ -32,6 +33,10 @@ export function entryToResult(e: FoodLog): FoodSearchResult {
export function scaleServing(r: FoodSearchResult, servings: number) {
return {
name: r.name || 'Custom entry',
+ // Carried onto the log so a diary entry still knows which product it was. Without
+ // it every Recent row compares as brand '', so a branded favourite shows an empty
+ // star there and starring it creates a second, brandless row.
+ brand: r.brand ?? '',
calories: +(r.calories * servings).toFixed(1),
protein: +(r.protein * servings).toFixed(1),
carbs: +(r.carbs * servings).toFixed(1),
@@ -51,3 +56,19 @@ export function savedToResult(s: SavedFood): FoodSearchResult {
fat: s.fat, fiber: s.fiber, serving_size: s.serving_size, source: 'saved',
}
}
+
+// Which saved food, if any, is the same favourite as `item`.
+//
+// Starring stores the unscaled food and the servings stepper scales at log time, so
+// "same food" is name + brand, and nothing else. Matched exactly, mirroring the
+// UNIQUE(user_id, name, brand) index the server enforces: if the two disagreed, the
+// client would offer a star the server then refuses to create as new.
+//
+// Brand is normalised to '' because that is what the API stores for a food with no
+// brand, while a search result can carry undefined.
+export function findSavedFood(
+ saved: SavedFood[],
+ item: Pick<FoodSearchResult, 'name' | 'brand'>,
+): SavedFood | undefined {
+ return saved.find(s => s.name === item.name && (s.brand ?? '') === (item.brand ?? ''))
+}
diff --git a/web/e2e/food.spec.ts b/web/e2e/food.spec.ts
index 6a1dca7..94f6e32 100644
--- a/web/e2e/food.spec.ts
+++ b/web/e2e/food.spec.ts
@@ -10,6 +10,10 @@ const today = `${_now.getFullYear()}-${_pad(_now.getMonth() + 1)}-${_pad(_now.ge
// Local noon → UTC ISO, same anchor as dayToIsoNoon() in the app.
const todayNoon = new Date(_now.getFullYear(), _now.getMonth(), _now.getDate(), 12, 0, 0, 0).toISOString()
+// The two fields the cleanup below needs off a food log or saved food. Narrower than
+// the real types on purpose: this is a delete-by-name sweep, not a model.
+type SeedRow = { id: number; name: string }
+
let authToken: string
let seedFoodIds: number[] = []
let seedSavedIds: number[] = []
@@ -64,7 +68,7 @@ test.describe('Food', () => {
// Clean up any UI-created entries
const list = await request.get(`${API}/food?date=${today}`, { headers: h })
const lb = await list.json()
- const toDelete = (lb.data ?? []).filter((e: any) =>
+ const toDelete = (lb.data ?? []).filter((e: SeedRow) =>
e.name.startsWith('E2ELog-') || e.name.startsWith('E2ESave-') || e.name.startsWith('E2EEdit-')
)
for (const e of toDelete) {
@@ -74,7 +78,7 @@ test.describe('Food', () => {
// Clean up saved foods created via UI
const sfList = await request.get(`${API}/food/saved`, { headers: h })
const sfb = await sfList.json()
- const sfToDelete = (sfb.data ?? []).filter((s: any) => s.name.startsWith('E2ESave-'))
+ const sfToDelete = (sfb.data ?? []).filter((s: SeedRow) => s.name.startsWith('E2ESave-'))
for (const s of sfToDelete) {
await request.delete(`${API}/food/saved/${s.id}`, { headers: h })
}
@@ -333,15 +337,17 @@ test.describe('Food', () => {
await expect(page.getByText(deleteName)).not.toBeVisible({ timeout: 3000 })
})
- // ─── My Foods ─────────────────────────────────────────────────────────────
+ // ─── Favorites ────────────────────────────────────────────────────────────
- test('My Foods tab shows seeded saved food', async ({ page }) => {
+ test('Favorites tab shows seeded saved food', async ({ page }) => {
await page.goto('/food/log')
- await page.getByRole('button', { name: 'My Foods' }).click()
+ await page.getByRole('button', { name: 'Favorites', exact: true }).click()
await expect(page.getByText(`${SEED_PREFIX}-saved`).first()).toBeVisible({ timeout: 3000 })
})
- test('Save to My Foods toggle saves food during logging', async ({ page }) => {
+ // Favouriting is no longer a side effect of logging: the star acts on its own, from
+ // the detail view, without the food ever being logged.
+ test('starring from the detail view favourites without logging', async ({ page }) => {
const savedName = `E2ESave-${Date.now()}`
await page.route('**/api/v1/food/search**', route =>
@@ -352,21 +358,49 @@ test.describe('Food', () => {
await expect(page.getByText(`No results for "${savedName}"`)).toBeVisible({ timeout: 2000 })
await page.getByRole('button').filter({ hasText: /manually/ }).click()
- // Toggle "Save to My Foods"
- await page.getByText('Save to My Foods').click()
-
- await page.getByRole('button', { name: 'Log Food' }).click()
- await page.waitForURL('/food', { timeout: 5000 })
+ // Star it, then leave without logging.
+ await page.getByRole('button', { name: `Add ${savedName} to Favorites` }).click()
+ await expect(page.getByRole('button', { name: `Remove ${savedName} from Favorites` })).toBeVisible({ timeout: 5000 })
- // Verify in My Foods tab
await page.goto('/food/log')
- await page.getByRole('button', { name: 'My Foods' }).click()
+ await page.getByRole('button', { name: 'Favorites', exact: true }).click()
await expect(page.getByText(savedName)).toBeVisible({ timeout: 8000 })
+
+ // And it was never logged — the diary has no entry for it.
+ await page.goto('/food')
+ await expect(page.getByText(savedName)).not.toBeVisible({ timeout: 3000 })
+ })
+
+ // #115: the delete endpoint and the client method both existed, but nothing called
+ // them — a saved food could not be removed from either app. Creates its own row rather
+ // than using the shared seed so the other Favorites tests keep theirs.
+ test('unstarring removes it from Favorites', async ({ page, request }) => {
+ const name = `E2EDelete-${Date.now()}`
+ const created = await request.post(`${API}/food/saved`, {
+ headers: { Authorization: `Bearer ${authToken}` },
+ data: { name, calories: 120, protein: 10, carbs: 12, fat: 4, serving_size: '1 cup' },
+ })
+ expect(created.ok()).toBeTruthy()
+
+ await page.goto('/food/log')
+ await page.getByRole('button', { name: 'Favorites', exact: true }).click()
+ await expect(page.getByText(name)).toBeVisible({ timeout: 5000 })
+
+ // One click, no confirmation sheet in between.
+ await page.getByRole('button', { name: `Remove ${name} from Favorites` }).click()
+
+ await expect(page.getByText(name)).not.toBeVisible({ timeout: 5000 })
+
+ // The row vanishing only proves local state was filtered. Reload to prove the
+ // DELETE actually reached the server.
+ await page.reload()
+ await page.getByRole('button', { name: 'Favorites', exact: true }).click()
+ await expect(page.getByText(name)).not.toBeVisible({ timeout: 5000 })
})
- test('selecting from My Foods goes to detail phase', async ({ page }) => {
+ test('selecting from Favorites goes to detail phase', async ({ page }) => {
await page.goto('/food/log')
- await page.getByRole('button', { name: 'My Foods' }).click()
+ await page.getByRole('button', { name: 'Favorites', exact: true }).click()
await expect(page.getByText(`${SEED_PREFIX}-saved`).first()).toBeVisible({ timeout: 3000 })
await page.getByText(`${SEED_PREFIX}-saved`).first().click()
diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsx
index 73c456e..26c3e3b 100644
--- a/web/src/pages/LogFood.tsx
+++ b/web/src/pages/LogFood.tsx
@@ -2,11 +2,11 @@ import { useState, useEffect, useRef } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import {
ArrowLeft, Search, Scan, Minus, Plus, X,
- Bookmark, BookmarkCheck, AlertCircle, Utensils, Zap,
+ Star, AlertCircle, Utensils, Zap,
Coffee, Sun, Moon, Cookie, ChevronRight,
} from 'lucide-react'
import { foodAPI, savedFoodsAPI } from '../services/api'
-import { todayStr, dayToInstant, entryDay, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing } from '@lyftr/shared'
+import { todayStr, dayToInstant, entryDay, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, apiErrorMessage, findSavedFood } from '@lyftr/shared'
import BarcodeScanner from '../components/BarcodeScanner'
import IconButton from '../components/ui/IconButton'
import SegmentedControl from '../components/ui/SegmentedControl'
@@ -27,12 +27,28 @@ const MEAL_COLORS: Record<string, string> = {
dinner: 'text-indigo-400', snacks: 'text-pink-400',
}
-function FoodResultRow({ item, onClick }: { item: types.FoodSearchResult; onClick: () => void }) {
- return (
- <button
- onClick={onClick}
- className="flex items-center gap-3 w-full px-4 py-3.5 hover:bg-surface-muted active:bg-surface-muted/80 transition-colors border-b border-surface-border last:border-0 text-left"
- >
+// The star is the whole favourites mechanic: one tap on, one tap off, from every tab.
+// It replaces the trash + inline confirm this row briefly had, which only appeared on the
+// Favorites tab — so a food found by search could not be favourited without logging it.
+//
+// No confirmation, deliberately: a favourite is a bookmark, not a record, and a second
+// click restores it. Matches Cronometer.
+//
+// The star has to be a sibling of the row button, not a child: a <button> inside a
+// <button> is invalid HTML and React warns about it, which is why the two-branch shape
+// below exists instead of one container.
+function FoodResultRow(
+ { item, onClick, favorited, onToggleFavorite, togglingFavorite = false }:
+ {
+ item: types.FoodSearchResult
+ onClick: () => void
+ favorited: boolean
+ onToggleFavorite: () => void
+ togglingFavorite?: boolean
+ },
+) {
+ const content = (
+ <>
{item.image_url ? (
<img src={item.image_url} alt="" className="w-11 h-11 rounded-xl object-cover flex-shrink-0 border border-surface-border" />
) : (
@@ -60,6 +76,42 @@ function FoodResultRow({ item, onClick }: { item: types.FoodSearchResult; onClic
</div>
</div>
<ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
+ </>
+ )
+
+ return (
+ <div className="flex items-center gap-2 w-full px-4 hover:bg-surface-muted transition-colors border-b border-surface-border last:border-0">
+ <button onClick={onClick} className="flex items-center gap-3 flex-1 min-w-0 py-3.5 text-left">
+ {content}
+ </button>
+ <FavoriteStar
+ favorited={favorited}
+ busy={togglingFavorite}
+ name={item.name}
+ onClick={onToggleFavorite}
+ />
+ </div>
+ )
+}
+
+// Shared by the rows and the detail header so the two cannot drift. aria-pressed carries
+// the toggle state that the fill conveys visually.
+function FavoriteStar(
+ { favorited, busy = false, name, onClick, size = 'sm' }:
+ { favorited: boolean; busy?: boolean; name: string; onClick: () => void; size?: 'sm' | 'md' },
+) {
+ const box = size === 'sm' ? 'w-8 h-8' : 'w-10 h-10'
+ const icon = size === 'sm' ? 'w-[18px] h-[18px]' : 'w-[22px] h-[22px]'
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={busy}
+ aria-pressed={favorited}
+ aria-label={favorited ? `Remove ${name} from Favorites` : `Add ${name} to Favorites`}
+ className={`${box} flex items-center justify-center rounded-lg flex-shrink-0 transition-colors hover:bg-surface-muted active:scale-95 disabled:opacity-40 ${favorited ? 'text-brand-500' : 'text-tx-muted'}`}
+ >
+ <Star className={icon} fill={favorited ? 'currentColor' : 'none'} strokeWidth={2.2} />
</button>
)
}
@@ -86,10 +138,70 @@ export default function LogFood() {
const [servings, setServings] = useState(1)
const [meal, setMeal] = useState<types.FoodLog['meal']>(initMeal)
const [date, setDate] = useState(initDate)
- const [saveToMyFoods, setSaveToMyFoods] = useState(false)
const [saving, setSaving] = useState(false)
const [saveError, setSaveError] = useState<string | null>(null)
+ // Derived from the list rather than tracked, so a star clicked on any tab is reflected
+ // everywhere the same food appears — including the detail view.
+ const favoriteOf = (item: types.FoodSearchResult) => findSavedFood(savedFoods, item)
+ const favoriteKey = (item: types.FoodSearchResult) => `${item.name}|${item.brand ?? ''}`
+ const isToggling = (item: types.FoodSearchResult) => togglingFavorite.has(favoriteKey(item))
+
+ // Favouriting is its own action, not a side effect of logging: one click on, one click
+ // off, from any row or from the detail view. No confirmation — a second click undoes it.
+ // The guard is a ref, not the state below. setState does not apply within the tick it
+ // is called in, so a burst of taps in one frame all read the same empty set and all
+ // fire — five rapid clicks sent one DELETE that worked and four that 404'd, then showed
+ // "Couldn't remove …" for an unstar that had actually succeeded. The state exists only
+ // to dim the star; the ref is what decides.
+ const inFlightFavorites = useRef<Set<string>>(new Set())
+
+ const toggleFavorite = async (item: types.FoodSearchResult) => {
+ const key = favoriteKey(item)
+ // Guard this food only. A single global flag dropped clicks on *other* rows while a
+ // request was in flight, so on a slow connection every other star went dead with no
+ // feedback — indistinguishable from a broken button.
+ if (inFlightFavorites.current.has(key)) return
+ inFlightFavorites.current.add(key)
+ setTogglingFavorite(new Set(inFlightFavorites.current))
+ setFavoriteError(null)
+ const existing = favoriteOf(item)
+ try {
+ if (existing) {
+ await savedFoodsAPI.delete(existing.id)
+ setSavedFoods(prev => prev.filter(f => f.id !== existing.id))
+ } else {
+ const created = await savedFoodsAPI.create({
+ name: item.name, brand: item.brand ?? '',
+ calories: item.calories, protein: item.protein,
+ carbs: item.carbs, fat: item.fat, fiber: item.fiber ?? 0,
+ serving_size: item.serving_size ?? '',
+ })
+ // The server answers 200 with the existing row when the food is already
+ // favourited, so `created` can be something the list already holds — after a
+ // refetch that raced this request, for instance. Appending blind puts two rows
+ // with the same id (and the same React key) in the list.
+ // Inserted in name order rather than appended: ListSaved returns ORDER BY name,
+ // so appending parks a new favourite at the bottom until the next load and then
+ // jumps it. Plain < to match SQLite's BINARY collation rather than localeCompare,
+ // which would order differently from the server it is imitating.
+ setSavedFoods(prev => prev.some(f => f.id === created.id)
+ ? prev
+ : [...prev, created].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)))
+ }
+ } catch (err) {
+ setFavoriteError(apiErrorMessage(err, existing
+ ? `Couldn't remove ${item.name} from Favorites.`
+ : `Couldn't add ${item.name} to Favorites.`))
+ } finally {
+ inFlightFavorites.current.delete(key)
+ setTogglingFavorite(new Set(inFlightFavorites.current))
+ }
+ }
+
+ const [togglingFavorite, setTogglingFavorite] = useState<Set<string>>(new Set())
+ const [favoriteError, setFavoriteError] = useState<string | null>(null)
+
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const searchInputRef = useRef<HTMLInputElement>(null)
@@ -175,14 +287,6 @@ export default function LogFood() {
await foodAPI.update(editId, payload)
} else {
await foodAPI.log(payload)
- if (saveToMyFoods) {
- await savedFoodsAPI.create({
- name: selected.name, brand: selected.brand ?? '',
- calories: selected.calories, protein: selected.protein,
- carbs: selected.carbs, fat: selected.fat, fiber: selected.fiber ?? 0,
- serving_size: selected.serving_size ?? '',
- }).catch(() => {})
- }
}
navigate('/food', { replace: true })
} catch (err: any) {
@@ -234,8 +338,32 @@ export default function LogFood() {
<h1 className="font-display font-bold text-2xl text-tx-primary">Log Food</h1>
)}
</div>
+ {/* Favouriting is decoupled from logging, so the star sits beside the food rather
+ than inside the form — you can star something without logging it, and unstar
+ it the same way. Hidden in edit mode, where `selected` is a logged entry being
+ amended rather than a food being picked. */}
+ {phase === 'detail' && selected && !editId && selected.name && (
+ <FavoriteStar
+ size="md"
+ favorited={favoriteOf(selected) !== undefined}
+ busy={isToggling(selected)}
+ name={selected.name}
+ onClick={() => toggleFavorite(selected)}
+ />
+ )}
</div>
+ {/* Outside both phases on purpose: the star is on the rows *and* in the header
+ above, so a failure has to be visible whichever one the user pressed. Sitting
+ inside the search phase meant a failed star on the detail view said nothing at
+ all and simply snapped back to unfilled. */}
+ {favoriteError && (
+ <div className="flex items-center gap-2 px-3 py-2.5 mb-4 rounded-xl border border-error-500/20 bg-error-500/10">
+ <AlertCircle className="w-4 h-4 text-error-400 flex-shrink-0" />
+ <p className="text-xs text-error-400">{favoriteError}</p>
+ </div>
+ )}
+
{/* Search phase */}
{phase === 'search' && (
<div className="space-y-4">
@@ -275,7 +403,7 @@ export default function LogFood() {
<SegmentedControl
options={[
{ value: 'recent', label: 'Recent' },
- { value: 'myfoods', label: 'My Foods' },
+ { value: 'myfoods', label: 'Favorites' },
{ value: 'all', label: 'Search' },
] as const}
value={tab}
@@ -322,19 +450,40 @@ export default function LogFood() {
<p className="text-xs text-tx-muted mt-1 opacity-60">Search or scan to log food</p>
</div>
)
- : recentItems.map((item) => <FoodResultRow key={`${item.name}-${item.calories}`} item={item} onClick={() => selectResult(item)} />)
+ : recentItems.map((item) => (
+ <FoodResultRow
+ key={`${item.name}-${item.calories}`}
+ item={item}
+ onClick={() => selectResult(item)}
+ favorited={favoriteOf(item) !== undefined}
+ onToggleFavorite={() => toggleFavorite(item)}
+ togglingFavorite={isToggling(item)}
+ />
+ ))
)}
{tab === 'myfoods' && (
savedFoods.length === 0
? (
<div className="px-4 py-14 text-center">
- <Bookmark className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />
- <p className="text-sm text-tx-muted">No saved foods yet</p>
- <p className="text-xs text-tx-muted mt-1 opacity-60">Save foods while logging to find them here</p>
+ <Star className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />
+ <p className="text-sm text-tx-muted">No favorites yet</p>
+ <p className="text-xs text-tx-muted mt-1 opacity-60">Star foods while logging to find them here</p>
</div>
)
- : savedFoods.map(sf => <FoodResultRow key={sf.id} item={savedToResult(sf)} onClick={() => selectResult(savedToResult(sf))} />)
+ : savedFoods.map(sf => {
+ const item = savedToResult(sf)
+ return (
+ <FoodResultRow
+ key={sf.id}
+ item={item}
+ onClick={() => selectResult(item)}
+ favorited
+ onToggleFavorite={() => toggleFavorite(item)}
+ togglingFavorite={isToggling(item)}
+ />
+ )
+ })
)}
{tab === 'all' && !query.trim() && (
@@ -359,7 +508,14 @@ export default function LogFood() {
</div>
)}
{tab === 'all' && !searching && searchResults.map((item) => (
- <FoodResultRow key={`${item.name}-${item.calories}`} item={item} onClick={() => selectResult(item)} />
+ <FoodResultRow
+ key={`${item.name}-${item.calories}`}
+ item={item}
+ onClick={() => selectResult(item)}
+ favorited={favoriteOf(item) !== undefined}
+ onToggleFavorite={() => toggleFavorite(item)}
+ togglingFavorite={isToggling(item)}
+ />
))}
</div>
</div>
@@ -500,23 +656,6 @@ export default function LogFood() {
<DateInput label="When" value={date} onChange={setDate} max={todayStr()} />
</div>
- {/* Save to My Foods toggle — hidden in edit mode */}
- {!editId && <button
- type="button"
- onClick={() => setSaveToMyFoods(v => !v)}
- className="flex items-center gap-3 w-full card p-4 hover:bg-surface-muted/50 transition-colors"
- >
- <div className={`relative w-11 h-6 rounded-full border transition-colors flex-shrink-0 ${saveToMyFoods ? 'bg-brand-500 border-brand-500' : 'bg-surface-muted border-surface-border'}`}>
- <div className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${saveToMyFoods ? 'translate-x-5' : 'translate-x-0.5'}`} />
- </div>
- <div className="flex items-center gap-2 flex-1">
- {saveToMyFoods
- ? <BookmarkCheck className="w-4 h-4 text-brand-500" />
- : <Bookmark className="w-4 h-4 text-tx-muted" />
- }
- <span className="text-sm font-medium text-tx-secondary">Save to My Foods</span>
- </div>
- </button>}
</div>
)}