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.

Log food by weight, and read the pack's own serving (#186)

Carter67ae31a22174
diff --git a/backend/controllers/food.go b/backend/controllers/food.go
index 992d82d..78693c5 100644
--- a/backend/controllers/food.go
+++ b/backend/controllers/food.go
@@ -275,12 +275,70 @@ func (b *offBrands) UnmarshalJSON(data []byte) error {
return nil
}
+// offFloat accepts a JSON number or a numeric string. OpenFoodFacts writes
+// serving_quantity both ways depending on how the product was edited, and anything it
+// could not parse it leaves as free text — which is not an error, it is the same "no
+// quantity known" the field being absent means, so it decodes to 0.
+type offFloat float64
+
+func (f *offFloat) UnmarshalJSON(data []byte) error {
+ if len(data) == 0 || string(data) == "null" {
+ return nil
+ }
+ if data[0] == '"' {
+ var s string
+ if err := json.Unmarshal(data, &s); err != nil {
+ return err
+ }
+ v, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
+ if err != nil {
+ return nil
+ }
+ *f = offFloat(v)
+ return nil
+ }
+ var v float64
+ if err := json.Unmarshal(data, &v); err != nil {
+ return err
+ }
+ *f = offFloat(v)
+ return nil
+}
+
type offProduct struct {
+ Code string `json:"code"`
ProductName string `json:"product_name"`
Brands offBrands `json:"brands"`
Nutriments offNutrients `json:"nutriments"`
ServingSize string `json:"serving_size"`
- ImageURL string `json:"image_url"`
+ // ServingQuantity is the serving as a number, in grams or millilitres, already
+ // parsed by OpenFoodFacts out of the free-text label. We do not parse the label
+ // ourselves: real values include "1/4 cup 7 g", "227 g (227 g)" and "200 m (100
+ // ml)". It can be absent even when a serving label is set — openfoodfacts-server#7768
+ // counted 7,700+ such products — which is why 0 has to stay meaningful.
+ ServingQuantity offFloat `json:"serving_quantity"`
+ ProductQuantityUnit string `json:"product_quantity_unit"`
+ ImageURL string `json:"image_url"`
+}
+
+// A serving spelled in any volume unit means the product's figures are per 100 ml, not
+// per 100 g — OpenFoodFacts files both under the same *_100g keys.
+//
+// Read off the label rather than OpenFoodFacts' own serving_quantity_unit, which
+// reports "ml" for every cup-based serving: "1/4 cup (7 g)" comes back as ml. The label
+// is the thing the user is shown, so agreeing with it is also what looks right.
+var servingVolumeRe = regexp.MustCompile(`(?i)(^|[^a-z])(ml|cl|dl|l|litres?|liters?)([^a-z]|$)`)
+
+func servingUnit(label, productQuantityUnit string) string {
+ if servingVolumeRe.MatchString(label) {
+ return "ml"
+ }
+ // No label to read: the pack size is the only other signal, and it is only
+ // sometimes filled in. "1l" of sunflower oil gives ml; a crisp packet gives g.
+ if strings.TrimSpace(label) == "" && strings.EqualFold(strings.TrimSpace(productQuantityUnit), "ml") {
+ return "ml"
+ }
+ return "g"
}
type offNutrients struct {
@@ -309,6 +367,8 @@ func offProductToResult(p offProduct) models.FoodSearchResult {
useServing := p.Nutriments.EnergyKcalServing > 0 && strings.TrimSpace(p.ServingSize) != ""
var cal, pro, carb, fat, fiber float64
var servingLabel string
+ unit := servingUnit(p.ServingSize, p.ProductQuantityUnit)
+ servingQuantity := float64(p.ServingQuantity)
if useServing {
cal = p.Nutriments.EnergyKcalServing
pro = p.Nutriments.ProteinsServing
@@ -325,7 +385,12 @@ func offProductToResult(p offProduct) models.FoodSearchResult {
// "100 g", not "per 100g": the serving branch above passes through
// OpenFoodFacts' own label ("30 g", "250 ml"), which carries no preposition, and
// the clients supply the "per". Including it here produced "per per 100g".
- servingLabel = "100 g"
+ //
+ // "100 ml" for a liquid, because that is what the figures are: OpenFoodFacts
+ // files per-100ml values under the same *_100g keys, which is how a bottle of
+ // olive oil came to read 800 kcal per "100 g" (#171).
+ servingLabel = "100 " + unit
+ servingQuantity = 100
}
return models.FoodSearchResult{
@@ -337,8 +402,14 @@ func offProductToResult(p offProduct) models.FoodSearchResult {
Fat: fat,
Fiber: fiber,
ServingSize: servingLabel,
- ImageURL: imageURL,
- Source: "off",
+ // 0 when OpenFoodFacts knows a serving but not its size. The clients read that
+ // as "weight entry is not available for this one" and stay on servings, which
+ // is the truth — better than scaling against a made-up number.
+ ServingQuantity: servingQuantity,
+ ServingUnit: unit,
+ Barcode: p.Code,
+ ImageURL: imageURL,
+ Source: "off",
}
}
@@ -373,7 +444,7 @@ func (h *Handler) SearchFood(c *gin.Context) {
start := time.Now()
searchURL := fmt.Sprintf(
- "https://search.openfoodfacts.org/search?q=%s&lang=en&cc=world&page_size=%d&page=1&fields=product_name,brands,nutriments,serving_size,image_url",
+ "https://search.openfoodfacts.org/search?q=%s&lang=en&cc=world&page_size=%d&page=1&fields=code,product_name,brands,nutriments,serving_size,image_url",
url.QueryEscape(q), limit,
)
log.Printf("[food/search] OFF request: q=%q limit=%d", q, limit)
diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.go
index f397e66..763314b 100644
--- a/backend/controllers/food_test.go
+++ b/backend/controllers/food_test.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/models"
)
// ─── helpers ──────────────────────────────────────────────────────────────────
@@ -249,6 +250,90 @@ func TestLogFood_defaultsServingsToOne(t *testing.T) {
}
}
+// The numeric serving is what lets the clients offer "15 ml" instead of "0.15
+// servings", so it has to survive the write — and an entry written without one has to
+// read back as 0 rather than a guess, which is what every row logged before #171 is.
+func TestLogFood_roundTripsServingQuantity(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ body := map[string]any{
+ "name": "Olive Oil", "meal": "dinner",
+ "calories": 120.0, "fat": 14.0, "servings": 1.0,
+ "serving_size": "1 Tbsp (15 ml)", "serving_quantity": 15.0, "serving_unit": "ml",
+ }
+ 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())
+ }
+ data := decodeResponse(t, w)["data"].(map[string]any)
+ if data["serving_quantity"].(float64) != 15.0 || data["serving_unit"].(string) != "ml" {
+ t.Errorf("expected 15 ml back, got %v %v", data["serving_quantity"], data["serving_unit"])
+ }
+
+ c2, w2 := newContext(uid, http.MethodPost, "/api/v1/food", map[string]any{
+ "name": "Toast", "meal": "breakfast", "calories": 80.0,
+ })
+ th.LogFood(c2)
+ if w2.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w2.Code, w2.Body.String())
+ }
+ data2 := decodeResponse(t, w2)["data"].(map[string]any)
+ if data2["serving_quantity"].(float64) != 0 || data2["serving_unit"].(string) != "" {
+ t.Errorf("expected an unknown serving to stay unknown, got %v %v",
+ data2["serving_quantity"], data2["serving_unit"])
+ }
+}
+
+// A unit that is neither g nor ml would reach the clients' arithmetic as one of them.
+func TestLogFood_rejectsUnknownServingUnit(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", map[string]any{
+ "name": "Olive Oil", "meal": "dinner", "calories": 120.0,
+ "serving_quantity": 1.0, "serving_unit": "tbsp",
+ })
+ th.LogFood(c)
+ if w.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("expected 422, got %d: %s", w.Code, w.Body.String())
+ }
+ if msg := decodeResponse(t, w)["error"].(string); msg != "Serving unit must be one of: g, ml." {
+ t.Errorf("unexpected message: %q", msg)
+ }
+}
+
+// A ceiling on one entry, and the sentence it answers with. The tag carries a literal
+// because struct tags cannot interpolate, so this also pins the literal to the constant:
+// change one without the other and the boundary cases below disagree.
+func TestLogFood_rejectsMoreThanMaxServings(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ entry := func(servings float64) map[string]any {
+ return map[string]any{
+ "name": "Olive Oil", "meal": "dinner", "calories": 120.0, "servings": servings,
+ }
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", entry(float64(models.MaxServings)+1))
+ th.LogFood(c)
+ if w.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("expected 422 over the cap, got %d: %s", w.Code, w.Body.String())
+ }
+ if msg := decodeResponse(t, w)["error"].(string); !strings.Contains(msg, "100") {
+ t.Errorf("message should name the limit, got %q", msg)
+ }
+
+ // The cap itself is allowed — an off-by-one here would reject a legal entry.
+ c, w = newContext(uid, http.MethodPost, "/api/v1/food", entry(float64(models.MaxServings)))
+ th.LogFood(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected the cap itself to log, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
func TestLogFood_missingName(t *testing.T) {
setupTestDB(t)
uid := createTestUser(t)
@@ -691,6 +776,133 @@ func TestOffProductToResult_fallsBackTo100g(t *testing.T) {
}
}
+// #171: a bottle of olive oil read 800 kcal and 93.3 g fat "per 100 g". The numbers are
+// right and OpenFoodFacts has no other figures for it — but they are per 100 *ml*, and
+// a user cannot pour 100 ml onto a salad, so the label has to say what they are and the
+// quantity has to be a number the clients can divide.
+func TestOffProductToResult_liquidFallbackIsPer100ml(t *testing.T) {
+ p := offProduct{
+ ProductName: "Organic Extra Virgin Olive Oil",
+ ServingSize: "15 ml",
+ ProductQuantityUnit: "ml",
+ // A serving label with no per-serving nutriments behind it: the case
+ // openfoodfacts-server#7768 tracks, and the one the reporter hit.
+ Nutriments: offNutrients{EnergyKcal100g: 800, Fat100g: 93.33},
+ }
+ r := offProductToResult(p)
+
+ if r.Calories != 800 {
+ t.Errorf("expected per-100 calories 800, got %v", r.Calories)
+ }
+ if r.ServingSize != "100 ml" {
+ t.Errorf("expected '100 ml' label, got %q", r.ServingSize)
+ }
+ if r.ServingQuantity != 100 || r.ServingUnit != "ml" {
+ t.Errorf("expected 100 ml as a number, got %v %q", r.ServingQuantity, r.ServingUnit)
+ }
+}
+
+func TestOffProductToResult_carriesServingQuantityAndBarcode(t *testing.T) {
+ p := offProduct{
+ Code: "0085239033265",
+ ProductName: "Olive Oil",
+ ServingSize: "1 Tbsp (15 ml)",
+ ServingQuantity: 15,
+ Nutriments: offNutrients{
+ EnergyKcal100g: 800, Fat100g: 93.33,
+ EnergyKcalServing: 120, FatServing: 14,
+ },
+ }
+ r := offProductToResult(p)
+
+ if r.Calories != 120 || r.Fat != 14 {
+ t.Errorf("expected the per-serving figures, got %v kcal %v fat", r.Calories, r.Fat)
+ }
+ if r.ServingQuantity != 15 || r.ServingUnit != "ml" {
+ t.Errorf("expected 15 ml, got %v %q", r.ServingQuantity, r.ServingUnit)
+ }
+ // Search hits carry it so selecting one can re-read the product in full.
+ if r.Barcode != "0085239033265" {
+ t.Errorf("expected the barcode to survive, got %q", r.Barcode)
+ }
+}
+
+// OpenFoodFacts knows the serving but not its size for thousands of products
+// (openfoodfacts-server#7768). Inventing a number there would scale every weight the
+// user typed against a fiction, so 0 has to survive as "unknown".
+func TestOffProductToResult_servingWithoutAQuantityStaysUnknown(t *testing.T) {
+ p := offProduct{
+ ProductName: "Soda",
+ ServingSize: "12 fl oz",
+ Nutriments: offNutrients{EnergyKcal100g: 41, EnergyKcalServing: 145},
+ }
+ r := offProductToResult(p)
+
+ if r.ServingQuantity != 0 {
+ t.Errorf("expected an unknown quantity to stay 0, got %v", r.ServingQuantity)
+ }
+ if r.Calories != 145 {
+ t.Errorf("expected the per-serving calories to still be used, got %v", r.Calories)
+ }
+}
+
+func TestServingUnit(t *testing.T) {
+ // Every label here is a real OpenFoodFacts value, sampled from the API.
+ cases := []struct {
+ label, productUnit, want string
+ }{
+ {"1 Tbsp (15 ml)", "", "ml"},
+ {"150ml", "", "ml"},
+ {"8 fl. oz (240 ml)", "", "ml"},
+ {"1l", "", "ml"},
+ {"1 serving (170 g)", "", "g"},
+ {"90.0g", "", "g"},
+ {"1 barra/bar (23 g)", "", "g"},
+ // OpenFoodFacts' own serving_quantity_unit says "ml" for these — it converts
+ // cups to volume. The label says grams, and the label is what the user reads.
+ {"1/4 cup (7 g)", "", "g"},
+ {"0.67 cup (55 g)", "", "g"},
+ // No label at all: the pack size is the only signal, when it is filled in.
+ {"", "ml", "ml"},
+ {"", "g", "g"},
+ {"", "", "g"},
+ // Volume units are whole words, not letters found inside one.
+ {"1 slice (30 g)", "", "g"},
+ {"1 bowl (250 g)", "", "g"},
+ }
+ for _, c := range cases {
+ if got := servingUnit(c.label, c.productUnit); got != c.want {
+ t.Errorf("servingUnit(%q, %q) = %q, want %q", c.label, c.productUnit, got, c.want)
+ }
+ }
+}
+
+// OpenFoodFacts writes serving_quantity as a number or as a string, and leaves whatever
+// it could not parse in the field as free text.
+func TestOffFloatUnmarshal(t *testing.T) {
+ cases := []struct {
+ json string
+ want float64
+ }{
+ {`{"serving_quantity": 15}`, 15},
+ {`{"serving_quantity": "15"}`, 15},
+ {`{"serving_quantity": "15.5"}`, 15.5},
+ {`{"serving_quantity": null}`, 0},
+ {`{"serving_quantity": ""}`, 0},
+ {`{"serving_quantity": "about 2 cookies"}`, 0},
+ {`{}`, 0},
+ }
+ for _, c := range cases {
+ var p offProduct
+ if err := json.Unmarshal([]byte(c.json), &p); err != nil {
+ t.Fatalf("%s: %v", c.json, err)
+ }
+ if float64(p.ServingQuantity) != c.want {
+ t.Errorf("%s: got %v, want %v", c.json, float64(p.ServingQuantity), c.want)
+ }
+ }
+}
+
func TestOffProductToResult_rejectsNonHTTPSImageURL(t *testing.T) {
p := offProduct{
ProductName: "Test",
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index 6bf8a92..7f73198 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -144,6 +144,18 @@ func alterMigrations() {
// 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 ''`)
+ // The serving as a number, so an entry can be re-opened and edited by weight rather
+ // than by a servings multiplier. serving_size stays: it is the label the user reads
+ // ("1 Tbsp (15 ml)"), free text from OpenFoodFacts and not parseable.
+ //
+ // 0 is "we don't know", which is the honest value for every row written before this
+ // and for products OpenFoodFacts has no quantity for. Those keep working — the
+ // clients fall back to servings — so there is nothing to backfill and no guessing.
+ ensureColumn("food_logs", "serving_quantity", `ALTER TABLE food_logs ADD COLUMN serving_quantity REAL NOT NULL DEFAULT 0`)
+ ensureColumn("food_logs", "serving_unit", `ALTER TABLE food_logs ADD COLUMN serving_unit TEXT NOT NULL DEFAULT ''`)
+ ensureColumn("saved_foods", "serving_quantity", `ALTER TABLE saved_foods ADD COLUMN serving_quantity REAL NOT NULL DEFAULT 0`)
+ ensureColumn("saved_foods", "serving_unit", `ALTER TABLE saved_foods ADD COLUMN serving_unit 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.
diff --git a/backend/models/models.go b/backend/models/models.go
index ddadd0a..4cc3146 100644
--- a/backend/models/models.go
+++ b/backend/models/models.go
@@ -55,12 +55,12 @@ type Exercise struct {
}
type Workout struct {
- ID int64 `json:"id" db:"id"`
- UserID int64 `json:"user_id" db:"user_id"`
- Name string `json:"name" db:"name"`
- Notes string `json:"notes,omitempty" db:"notes"`
- Duration int `json:"duration" db:"duration"` // seconds
- StartedAt time.Time `json:"started_at" db:"started_at"`
+ ID int64 `json:"id" db:"id"`
+ UserID int64 `json:"user_id" db:"user_id"`
+ Name string `json:"name" db:"name"`
+ Notes string `json:"notes,omitempty" db:"notes"`
+ Duration int `json:"duration" db:"duration"` // seconds
+ StartedAt time.Time `json:"started_at" db:"started_at"`
// TZOffsetMinutes is the user's UTC offset when the workout started, e.g. -240
// for New York in summer. StartedAt plus this offset gives the local day and the
// local clock time, permanently — a workout is a real moment, so unlike the
@@ -118,11 +118,11 @@ 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"` // 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"`
+ ID int64 `json:"id" db:"id"`
+ UserID int64 `json:"user_id" db:"user_id"`
+ 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"`
// LoggedOn is the calendar day this weigh-in belongs to (see FoodLog.LoggedOn).
// It is also what "one entry per day" is enforced against.
LoggedOn string `json:"logged_on" db:"logged_on"`
@@ -130,21 +130,25 @@ type WeightLog struct {
}
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"`
- Carbs float64 `json:"carbs" db:"carbs"`
- Fat float64 `json:"fat" db:"fat"`
- Fiber float64 `json:"fiber" db:"fiber"`
- Servings float64 `json:"servings" db:"servings"`
- ServingSize string `json:"serving_size" db:"serving_size"`
- Barcode string `json:"barcode,omitempty" db:"barcode"`
- ImageURL string `json:"image_url,omitempty" db:"image_url"`
- LoggedAt time.Time `json:"logged_at" db:"logged_at"`
+ 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"`
+ Carbs float64 `json:"carbs" db:"carbs"`
+ Fat float64 `json:"fat" db:"fat"`
+ Fiber float64 `json:"fiber" db:"fiber"`
+ Servings float64 `json:"servings" db:"servings"`
+ ServingSize string `json:"serving_size" db:"serving_size"`
+ // The serving as a number, so editing an entry can still offer entry by weight.
+ // 0 for entries written before this column, which read back as servings-only.
+ ServingQuantity float64 `json:"serving_quantity" db:"serving_quantity"`
+ ServingUnit string `json:"serving_unit" db:"serving_unit"`
+ Barcode string `json:"barcode,omitempty" db:"barcode"`
+ ImageURL string `json:"image_url,omitempty" db:"image_url"`
+ LoggedAt time.Time `json:"logged_at" db:"logged_at"`
// LoggedOn is the calendar day this entry belongs to, YYYY-MM-DD, in the user's
// zone at the moment they logged it. It is the day the diary groups by — stored,
// never re-derived, so it survives the user changing zones. LoggedAt remains the
@@ -154,18 +158,24 @@ type FoodLog struct {
}
type SavedFood struct {
- ID int64 `json:"id" db:"id"`
- UserID int64 `json:"user_id,omitempty" db:"user_id"`
- Name string `json:"name" db:"name"`
- Brand string `json:"brand" db:"brand"`
- Calories float64 `json:"calories" db:"calories"`
- Protein float64 `json:"protein" db:"protein"`
- Carbs float64 `json:"carbs" db:"carbs"`
- Fat float64 `json:"fat" db:"fat"`
- Fiber float64 `json:"fiber" db:"fiber"`
- ServingSize string `json:"serving_size" db:"serving_size"`
- Barcode string `json:"barcode,omitempty" db:"barcode"`
- CreatedAt time.Time `json:"created_at" db:"created_at"`
+ ID int64 `json:"id" db:"id"`
+ UserID int64 `json:"user_id,omitempty" db:"user_id"`
+ Name string `json:"name" db:"name"`
+ Brand string `json:"brand" db:"brand"`
+ Calories float64 `json:"calories" db:"calories"`
+ Protein float64 `json:"protein" db:"protein"`
+ Carbs float64 `json:"carbs" db:"carbs"`
+ Fat float64 `json:"fat" db:"fat"`
+ Fiber float64 `json:"fiber" db:"fiber"`
+ ServingSize string `json:"serving_size" db:"serving_size"`
+ // ServingQuantity/ServingUnit express the same serving as a number the client can
+ // do arithmetic with — see FoodSearchResult. Stored so a food starred before this
+ // existed, or one OpenFoodFacts has no quantity for, reads back as 0 and falls
+ // back to servings rather than pretending to a weight.
+ ServingQuantity float64 `json:"serving_quantity" db:"serving_quantity"`
+ ServingUnit string `json:"serving_unit" db:"serving_unit"`
+ Barcode string `json:"barcode,omitempty" db:"barcode"`
+ CreatedAt time.Time `json:"created_at" db:"created_at"`
}
type FoodSearchResult struct {
@@ -177,8 +187,20 @@ type FoodSearchResult struct {
Fat float64 `json:"fat"`
Fiber float64 `json:"fiber"`
ServingSize string `json:"serving_size"`
- ImageURL string `json:"image_url,omitempty"`
- Source string `json:"source"` // "off" | "saved"
+ // ServingSize is OpenFoodFacts free text and unparseable in practice — real values
+ // include "1/4 cup 7 g", "227 g (227 g)" and "200 m (100 ml)". ServingQuantity is
+ // the same serving as a number, so a client can offer "15 g" instead of "0.15
+ // servings"; ServingUnit is "g" or "ml". Zero means OpenFoodFacts has no quantity
+ // for this product (it happens: openfoodfacts-server#7768) and the client should
+ // stay on servings rather than invent a weight.
+ ServingQuantity float64 `json:"serving_quantity,omitempty"`
+ ServingUnit string `json:"serving_unit,omitempty"`
+ // The product this came from, when it is an OpenFoodFacts row. Search results carry
+ // it so selecting one can re-read the product in full — the search index answers
+ // with per-100g figures only, and no serving at all.
+ Barcode string `json:"barcode,omitempty"`
+ ImageURL string `json:"image_url,omitempty"`
+ Source string `json:"source"` // "off" | "saved"
}
type FoodHistoryPoint struct {
@@ -288,20 +310,41 @@ type LogWeightRequest struct {
LoggedOn string `json:"logged_on"`
}
+// MaxServings bounds a single diary entry. Without a ceiling a fat-fingered amount logs
+// an arbitrary number of calories against the day: typing 999999 into the amount field
+// read 7,999,992 kcal, and the server stored whatever arrived.
+//
+// Servings is the right thing to bound rather than the amount the client collects,
+// because it is what is stored and what every macro is multiplied by — an absurd weight
+// is only absurd once divided by the serving it is measured in. It is also the only
+// number both sides can check and mean the same by, which is why there is one ceiling
+// here and not a second one on the amount.
+//
+// A hundred of them is ten kilos of a food held per 100 g — OpenNutriTracker's
+// "unrealistically high" threshold, reached without a second rule.
+//
+// The literal in LogFoodRequest's tag below has to match: struct tags cannot interpolate
+// a constant. TestLogFood_rejectsMoreThanMaxServings pins the two together.
+const MaxServings = 100
+
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"`
- Carbs float64 `json:"carbs" validate:"gte=0"`
- Fat float64 `json:"fat" validate:"gte=0"`
- Fiber float64 `json:"fiber" validate:"gte=0"`
- Servings float64 `json:"servings" validate:"gte=0"`
- ServingSize string `json:"serving_size"`
- Barcode string `json:"barcode"`
- ImageURL string `json:"image_url"`
- LoggedAt time.Time `json:"logged_at"`
+ 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"`
+ Carbs float64 `json:"carbs" validate:"gte=0"`
+ Fat float64 `json:"fat" validate:"gte=0"`
+ Fiber float64 `json:"fiber" validate:"gte=0"`
+ Servings float64 `json:"servings" validate:"gte=0,lte=100"`
+ ServingSize string `json:"serving_size"`
+ // The serving as a number plus its unit, carried so an edit can go on offering
+ // entry by weight. Optional: clients older than this send neither.
+ ServingQuantity float64 `json:"serving_quantity" validate:"gte=0"`
+ ServingUnit string `json:"serving_unit" validate:"omitempty,oneof=g ml"`
+ Barcode string `json:"barcode"`
+ ImageURL string `json:"image_url"`
+ LoggedAt time.Time `json:"logged_at"`
// LoggedOn is the calendar day the client files this under, YYYY-MM-DD. Optional:
// omitted by clients older than the stored-day change, in which case the server
// derives it from the account zone (see Handler.resolveDay).
@@ -317,7 +360,11 @@ type SaveFoodRequest struct {
Fat float64 `json:"fat" validate:"gte=0"`
Fiber float64 `json:"fiber" validate:"gte=0"`
ServingSize string `json:"serving_size"`
- Barcode string `json:"barcode"`
+ // See LogFoodRequest: the numeric serving, kept on the favourite so logging it
+ // later can still offer weight.
+ ServingQuantity float64 `json:"serving_quantity" validate:"gte=0"`
+ ServingUnit string `json:"serving_unit" validate:"omitempty,oneof=g ml"`
+ Barcode string `json:"barcode"`
}
// UpdateSettingsRequest is a PATCH: every field is a pointer so a nil (absent
diff --git a/backend/stores/food.go b/backend/stores/food.go
index 1a36d21..c1e6096 100644
--- a/backend/stores/food.go
+++ b/backend/stores/food.go
@@ -22,13 +22,13 @@ 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, brand, 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, serving_quantity, serving_unit, 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.Brand, &f.Meal,
&f.Calories, &f.Protein, &f.Carbs, &f.Fat, &f.Fiber,
- &f.Servings, &f.ServingSize, &f.Barcode, &f.ImageURL,
+ &f.Servings, &f.ServingSize, &f.ServingQuantity, &f.ServingUnit, &f.Barcode, &f.ImageURL,
&f.LoggedAt, &f.LoggedOn, &f.CreatedAt,
)
}
@@ -69,10 +69,10 @@ 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, brand, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `INSERT INTO food_logs (user_id, name, brand, meal, calories, protein, carbs, fat, fiber, servings, serving_size, serving_quantity, serving_unit, 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,
+ req.Servings, req.ServingSize, req.ServingQuantity, req.ServingUnit, req.Barcode, req.ImageURL, req.LoggedAt, day,
)
if err != nil {
return models.FoodLog{}, err
@@ -84,10 +84,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=?, brand=?, meal=?, calories=?, protein=?, carbs=?, fat=?, fiber=?,
- servings=?, serving_size=?, barcode=?, image_url=?, logged_at=?, logged_on=?
+ servings=?, serving_size=?, serving_quantity=?, serving_unit=?, barcode=?, image_url=?, logged_at=?, logged_on=?
WHERE id=? AND user_id=?`,
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,
+ req.Servings, req.ServingSize, req.ServingQuantity, req.ServingUnit, req.Barcode, req.ImageURL, req.LoggedAt, day,
id, uid,
)
if err != nil {
@@ -156,11 +156,11 @@ func (s *FoodStore) History(uid int64, sinceDay string) ([]models.FoodHistoryPoi
return points, rows.Err()
}
-const savedFoodSelect = `SELECT id, user_id, name, brand, calories, protein, carbs, fat, fiber, serving_size, barcode, created_at FROM saved_foods`
+const savedFoodSelect = `SELECT id, user_id, name, brand, calories, protein, carbs, fat, fiber, serving_size, serving_quantity, serving_unit, barcode, created_at FROM saved_foods`
func scanSavedFood(row interface{ Scan(...any) error }, f *models.SavedFood) error {
return row.Scan(&f.ID, &f.UserID, &f.Name, &f.Brand, &f.Calories, &f.Protein, &f.Carbs, &f.Fat,
- &f.Fiber, &f.ServingSize, &f.Barcode, &f.CreatedAt)
+ &f.Fiber, &f.ServingSize, &f.ServingQuantity, &f.ServingUnit, &f.Barcode, &f.CreatedAt)
}
func (s *FoodStore) ListSaved(uid int64) ([]models.SavedFood, error) {
@@ -203,10 +203,10 @@ func (s *FoodStore) CreateSaved(uid int64, req models.SaveFoodRequest) (models.S
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `INSERT INTO saved_foods (user_id, name, brand, calories, protein, carbs, fat, fiber, serving_size, serving_quantity, serving_unit, barcode)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
uid, req.Name, req.Brand, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,
- req.ServingSize, req.Barcode,
+ req.ServingSize, req.ServingQuantity, req.ServingUnit, req.Barcode,
)
if err != nil {
if !utils.IsUniqueViolation(err) {
diff --git a/mobile/app/(tabs)/nutrition/[id].tsx b/mobile/app/(tabs)/nutrition/[id].tsx
index c3c8401..a336e3a 100644
--- a/mobile/app/(tabs)/nutrition/[id].tsx
+++ b/mobile/app/(tabs)/nutrition/[id].tsx
@@ -3,7 +3,7 @@ import { Image, Pressable, ScrollView, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import * as Haptics from 'expo-haptics'
import { ArrowLeft, Edit2, Flame, Trash2 } from 'lucide-react-native'
-import { apiErrorMessage, entryToResult, isNotFound, useAsyncAction, useFavorites, entryDay, type FoodLog, formatDay } from '@lyftr/shared'
+import { apiErrorMessage, entryToResult, formatLoggedAmount, isNotFound, useAsyncAction, useFavorites, entryDay, type FoodLog, formatDay } from '@lyftr/shared'
import {
Alert, AppText, Button, Card, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps,
} from '../../../src/components/ui'
@@ -103,10 +103,11 @@ export default function NutritionDetail() {
const macroCal = cals.protein + cals.carbs + cals.fat
const pctCal = (v: number) => (macroCal > 0 ? Math.round((v / macroCal) * 100) : 0)
- // Spec-list rows (MFP / Lose It convention): serving size, servings, meal, logged.
+ // Spec-list rows (MFP / Lose It convention): serving size, amount, meal, logged.
const specRows: { label: string; value: string; tabular?: boolean }[] = [
...(entry.serving_size ? [{ label: 'Serving size', value: entry.serving_size }] : []),
- { label: 'Servings', value: String(entry.servings), tabular: true },
+ // In the unit it was logged in — "15 ml", not "0.15 servings" (#171).
+ { label: 'Amount', value: formatLoggedAmount(entry), tabular: true },
{ label: 'Meal', value: MEAL_LABELS[meal] },
{ label: 'Logged', value: formatDay(entryDay(entry), 'EEE, MMM d, yyyy') },
]
diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsx
index a74f2f8..ee8940c 100644
--- a/mobile/app/(tabs)/nutrition/log.tsx
+++ b/mobile/app/(tabs)/nutrition/log.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react'
-import { Image, Pressable, RefreshControl, ScrollView, View } from 'react-native'
+import { Pressable, RefreshControl, ScrollView, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import * as Haptics from 'expo-haptics'
import {
@@ -15,13 +15,14 @@ import {
} from '../../../src/components/ui'
import { BarcodeScanner } from '../../../src/components/nutrition/BarcodeScanner'
import { BarcodeLookup } from '../../../src/components/nutrition/BarcodeLookup'
+import { FoodHero } from '../../../src/components/nutrition/FoodImage'
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 { apiErrorMessage, entryToResult, isNotFound, savedToResult, scaleServing, useFavorites } from '@lyftr/shared'
+import { apiErrorMessage, entryToResult, foodResultKey, isNotFound, savedToResult, scaleServing, useFavorites, useFoodAmount } from '@lyftr/shared'
type Phase = 'search' | 'detail' | 'scan'
type SearchTab = 'recent' | 'myfoods' | 'all'
@@ -62,7 +63,15 @@ export default function LogFood() {
const lookingUp = lookup !== null && lookup.error === null
const [selected, setSelected] = useState<FoodSearchResult | null>(null)
- const [servingsStr, setServingsStr] = useState('1')
+ // The amount field — grams, millilitres or servings, depending on the food. Shared
+ // with web, because what it computes is how much food the person recorded (#171).
+ const amount = useFoodAmount(selected)
+ const { basis, servings, servingsLabel, overLimit, maxAmount, openOnEntry } = amount
+ // Which search row is being re-read in full, and what to say if that failed. The
+ // search index answers with per-100g figures and no serving at all, so a hit has to
+ // be read again through the product endpoint before it can be trusted (#171).
+ const [upgrading, setUpgrading] = useState<string | null>(null)
+ const [staleServing, setStaleServing] = useState<string | null>(null)
const [meal, setMeal] = useState<Meal>(initMeal)
const [date, setDate] = useState(initDate)
const [pulling, setPulling] = useState(false)
@@ -79,21 +88,18 @@ export default function LogFood() {
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- // Web keeps servings as a clamped number; here the field is a string buffer, so derive
- // the numeric value (same Math.max(0.5, …||1) clamp web applies on change).
- const servings = Math.max(0.5, Number(servingsStr) || 1)
-
// Edit mode: load the entry, reduce to per-serving, jump to detail.
useEffect(() => {
if (!editId) return
client.foodAPI.get(editId).then((entry) => {
- setSelected(entryToResult(entry))
- setServingsStr(String(entry.servings || 1))
+ const result = entryToResult(entry)
+ setSelected(result)
+ openOnEntry(result, entry.servings)
setMeal(entry.meal)
setDate(entryDay(entry))
setPhase('detail')
}).catch((err) => setEditError(apiErrorMessage(err, "Couldn't load that entry.")))
- }, [editId])
+ }, [editId, openOnEntry])
// Recent (today, deduped ≤10) + favourites.
const loadLists = useCallback(async () => {
@@ -152,13 +158,32 @@ export default function LogFood() {
return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }
}, [query, tab])
- const selectResult = (result: FoodSearchResult) => {
+ const selectResult = (result: FoodSearchResult, note: string | null = null) => {
hSelect()
setSelected(result)
- setServingsStr('1')
+ amount.openOn(result)
+ setStaleServing(note)
setPhase('detail')
}
+ // A search hit is not enough to log against. OpenFoodFacts' search index carries
+ // per-100g figures and no serving at all, so the same olive oil reads 800 kcal per
+ // 100 g from a search and 120 kcal per tablespoon from a scan (#171). Read the
+ // product in full before opening the detail, the way every other OFF client does.
+ const selectSearchResult = async (result: FoodSearchResult) => {
+ if (result.source !== 'off' || !result.barcode) { selectResult(result); return }
+ setUpgrading(result.barcode)
+ try {
+ selectResult(await client.foodAPI.barcode(result.barcode))
+ } catch (err) {
+ // The search row is still real data, so log against it rather than dead-ending —
+ // but say which figures these are, because they are the ones that read wrong.
+ selectResult(result, apiErrorMessage(err, "Couldn't re-read this product."))
+ } finally {
+ setUpgrading(null)
+ }
+ }
+
const enterManually = () => {
setLookup(null)
selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })
@@ -179,10 +204,9 @@ export default function LogFood() {
}
}
- const stepServings = (delta: number) => {
+ const stepAmount = (dir: 1 | -1) => {
hSelect()
- const next = delta < 0 ? Math.max(0.5, +(servings - 0.5).toFixed(1)) : +(servings + 0.5).toFixed(1)
- setServingsStr(String(next))
+ amount.step(dir)
}
const save = useAsyncAction(async (item: FoodSearchResult) => {
@@ -367,7 +391,7 @@ export default function LogFood() {
) : (
recentItems.map((item, i) => (
<FoodResultRow
- key={`${item.name}-${item.calories}-${i}`}
+ key={foodResultKey(item, i)}
item={item}
onPress={() => selectResult(item)}
favorited={favoriteOf(item) !== undefined}
@@ -416,9 +440,10 @@ export default function LogFood() {
) : null}
{tab === 'all' && !searching ? searchResults.map((item, i) => (
<FoodResultRow
- key={`${item.name}-${item.calories}-${i}`}
+ key={foodResultKey(item, i)}
item={item}
- onPress={() => selectResult(item)}
+ loading={upgrading !== null && upgrading === item.barcode}
+ onPress={() => void selectSearchResult(item)}
favorited={favoriteOf(item) !== undefined}
onToggleFavorite={() => toggleFavorite(item)}
togglingFavorite={isToggling(item)}
@@ -442,15 +467,18 @@ export default function LogFood() {
</View>
) : null}
+ {/* The product couldn't be re-read, so these are the search index's
+ figures: per 100 g, whatever the pack's own serving is. Say so rather
+ than let them read as a serving — that is the whole of #171. */}
+ {staleServing ? (
+ <Alert variant="warning">
+ {staleServing} Showing search results, which are always per {selected.serving_size}.
+ </Alert>
+ ) : null}
+
{/* Food hero + macros */}
<Card className="overflow-hidden p-0">
- {selected.image_url ? (
- <Image source={{ uri: selected.image_url }} className="h-52 w-full" resizeMode="cover" />
- ) : (
- <View className="h-32 w-full items-center justify-center border-b border-surface-border bg-surface-muted">
- <Utensils size={40} color={colors.txMuted} style={{ opacity: 0.2 }} />
- </View>
- )}
+ <FoodHero src={selected.image_url} />
<View className="p-5">
{/* Calorie hero */}
<View className="mb-5 flex-row items-end justify-between">
@@ -460,7 +488,7 @@ export default function LogFood() {
<AppText variant="body" color="muted">kcal</AppText>
</View>
{selected.serving_size ? (
- <AppText variant="caption" color="muted" className="mt-1">per {servings === 1 ? '' : `${servings} × `}{selected.serving_size}</AppText>
+ <AppText variant="caption" color="muted" className="mt-1">per {servingsLabel === 1 || servings <= 0 ? '' : `${servingsLabel} × `}{selected.serving_size}</AppText>
) : null}
</View>
{pro + carb + fat_ > 0 ? (
@@ -504,25 +532,43 @@ export default function LogFood() {
</View>
</Card>
- {/* Servings */}
+ {/* Amount */}
<Card className="gap-3">
<View className="flex-row items-baseline gap-2">
- <Label>Servings</Label>
- {selected.serving_size ? <AppText variant="caption" color="muted">({selected.serving_size} each)</AppText> : null}
+ <Label>{basis ? 'Amount' : 'Servings'}</Label>
+ {selected.serving_size && !basis
+ ? <AppText variant="caption" color="muted">({selected.serving_size} each)</AppText>
+ : null}
</View>
<View className="flex-row items-center gap-3">
- <IconButton icon={Minus} variant="secondary" size="lg" label="Decrease servings" onPress={() => stepServings(-0.5)} />
- <View className="flex-1">
- <NumberField
- inputMode="decimal"
- value={servingsStr}
- onChange={setServingsStr}
- accessibilityLabel="Servings"
- inputAccessoryViewID={NUMERIC_ACCESSORY_ID}
- />
+ <IconButton icon={Minus} variant="secondary" size="lg" label={basis ? 'Decrease amount' : 'Decrease servings'} onPress={() => stepAmount(-1)} />
+ <View className="flex-1 flex-row items-center justify-center">
+ <View className="flex-1">
+ <NumberField
+ inputMode="decimal"
+ value={amount.text}
+ onChange={amount.setText}
+ accessibilityLabel={basis ? `Amount in ${basis.unit}` : 'Servings'}
+ inputAccessoryViewID={NUMERIC_ACCESSORY_ID}
+ />
+ </View>
+ {basis ? <AppText variant="caption" color="muted" className="ml-1">{basis.unit}</AppText> : null}
</View>
- <IconButton icon={Plus} variant="secondary" size="lg" label="Increase servings" onPress={() => stepServings(0.5)} />
+ <IconButton icon={Plus} variant="secondary" size="lg" label={basis ? 'Increase amount' : 'Increase servings'} onPress={() => stepAmount(1)} />
</View>
+ {/* The readout doubles as the reason the Log button is disabled. Deleting
+ the 0.5-serving floor made an empty or nonsense amount reachable for the
+ first time, and a dead button with no words beside it says what, not why.
+ Shown without a basis too, where the field counts servings. */}
+ {basis || servings <= 0 || overLimit ? (
+ <AppText variant="caption" color={overLimit ? 'warning' : 'muted'} className="text-center">
+ {servings <= 0
+ ? `Enter an amount${basis ? ` in ${basis.unit}` : ''} to log this`
+ : overLimit
+ ? `One entry holds at most ${maxAmount}`
+ : `${servingsLabel} ${servingsLabel === 1 ? 'serving' : 'servings'} of ${selected.serving_size}`}
+ </AppText>
+ ) : null}
</Card>
{/* Meal + when */}
@@ -562,7 +608,8 @@ export default function LogFood() {
title={save.busy ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}
onPress={handleLog}
loading={save.busy}
- disabled={save.busy}
+ // An empty or zero amount would log a row of zeroes.
+ disabled={save.busy || servings <= 0 || overLimit}
/>
</View>
<NumericKeyboardAccessory />
diff --git a/mobile/src/components/nutrition/FoodEntryRow.test.tsx b/mobile/src/components/nutrition/FoodEntryRow.test.tsx
new file mode 100644
index 0000000..f9c66b5
--- /dev/null
+++ b/mobile/src/components/nutrition/FoodEntryRow.test.tsx
@@ -0,0 +1,54 @@
+import { render, screen } from '@testing-library/react-native'
+import type { FoodLog } from '@lyftr/shared'
+import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'
+import { FoodEntryRow } from './FoodEntryRow'
+
+// Same preamble as FoodResultRow's test: expo-router can't load under bare jest, and the
+// ui barrel reaches it via useTheme → lib/lyftr.
+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 entry = (overrides: Partial<FoodLog> = {}): FoodLog => ({
+ id: 1,
+ name: 'Extra Virgin Olive Oil',
+ meal: 'breakfast',
+ calories: 40,
+ protein: 0,
+ carbs: 0,
+ fat: 4.7,
+ fiber: 0,
+ servings: 1,
+ serving_size: '15mL',
+ logged_at: '2026-09-21T08:00:00Z',
+ logged_on: '2026-09-21',
+ ...overrides,
+}) as FoodLog
+
+const row = (e: FoodLog) =>
+ render(<FoodEntryRow entry={e} first onPress={() => {}} onEdit={() => {}} onDeleted={() => {}} />)
+
+describe('FoodEntryRow amount', () => {
+ // The bug this pins: the row rendered `entry.servings` raw, so a third of a 15 ml
+ // serving read "× 0.3333333333333333" here while the entry's own screen — which goes
+ // through formatLoggedAmount — read "5 ml" (#171).
+ it('reads in the unit the food was logged in', () => {
+ row(entry({ servings: 1 / 3, serving_quantity: 15, serving_unit: 'ml' }))
+ expect(screen.getByText('5 ml')).toBeTruthy()
+ })
+
+ it('falls back to servings when nothing knows what one measures', () => {
+ row(entry({ servings: 1 / 3, serving_quantity: 0, serving_unit: '' }))
+ expect(screen.getByText('0.33 servings')).toBeTruthy()
+ })
+
+ // One serving is the default and says nothing, so the row stays quiet.
+ it('says nothing for a single serving', () => {
+ row(entry({ servings: 1, serving_quantity: 15, serving_unit: 'ml' }))
+ expect(screen.queryByText('15 ml')).toBeNull()
+ })
+})
diff --git a/mobile/src/components/nutrition/FoodEntryRow.tsx b/mobile/src/components/nutrition/FoodEntryRow.tsx
index 518a9ab..22f97a5 100644
--- a/mobile/src/components/nutrition/FoodEntryRow.tsx
+++ b/mobile/src/components/nutrition/FoodEntryRow.tsx
@@ -1,12 +1,13 @@
-import { useAsyncAction } from '@lyftr/shared'
+import { formatLoggedAmount, useAsyncAction } from '@lyftr/shared'
import { useState } from 'react'
-import { Image, Pressable, View } from 'react-native'
+import { Pressable, View } from 'react-native'
import * as Haptics from 'expo-haptics'
-import { ChevronRight, Flame, MoreVertical, Utensils } from 'lucide-react-native'
+import { ChevronRight, Flame, MoreVertical } from 'lucide-react-native'
import type { FoodLog } from '@lyftr/shared'
import { ActionSheet, AppText, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'
import { useTheme } from '../../theme/useTheme'
import { client } from '../../lib/lyftr'
+import { FoodThumb } from './FoodImage'
import { MACRO_TEXT, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal } from './nutritionMeta'
// Compact meal tag shown on each row now that meals share one list (icon + label in the
@@ -52,14 +53,7 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props
onDeleted(entry.id)
}, 'Failed to delete entry')
- const Thumb = ({ size = 44 }: { size?: number }) =>
- entry.image_url ? (
- <Image source={{ uri: entry.image_url }} style={{ width: size, height: size, borderRadius: 12 }} className="border border-surface-border" />
- ) : (
- <View style={{ width: size, height: size }} className="items-center justify-center rounded-xl border border-surface-border bg-surface-muted">
- <Utensils size={size * 0.45} color={colors.txMuted} style={{ opacity: 0.4 }} />
- </View>
- )
+ const Thumb = ({ size = 44 }: { size?: number }) => <FoodThumb src={entry.image_url} size={size} />
const macroLine = (
// Calories (flame) + each macro as a colored-dot chip (P/C/F), mirroring the dot
@@ -83,7 +77,7 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props
<AppText variant="caption" color="muted">{label}</AppText>
</View>
))}
- {entry.servings !== 1 ? <AppText variant="caption" color="muted">× {entry.servings}</AppText> : null}
+ {entry.servings !== 1 ? <AppText variant="caption" color="muted">{formatLoggedAmount(entry)}</AppText> : null}
</View>
)
diff --git a/mobile/src/components/nutrition/FoodImage.tsx b/mobile/src/components/nutrition/FoodImage.tsx
new file mode 100644
index 0000000..2b34ab5
--- /dev/null
+++ b/mobile/src/components/nutrition/FoodImage.tsx
@@ -0,0 +1,54 @@
+import { useState } from 'react'
+import { Image, View } from 'react-native'
+import { Utensils } from 'lucide-react-native'
+import { useTheme } from '../../theme/useTheme'
+
+// Product photos, on the two terms OpenFoodFacts actually offers them. Web's copy of
+// this carries the full reasoning (web/src/components/FoodImage.tsx); in short:
+//
+// Half the catalogue has no photo — per query, milk 12%, bread 54% — and a real share of
+// the rest never answer, so a picture that fails and a picture that was never there have
+// to look the same. There is deliberately no onError: a photo appears once it has
+// loaded, which handles both.
+//
+// Nothing stands in for it but a glyph. Peer apps are unanimous, and OpenNutriTracker's
+// source says why it will not guess an icon from a branded product's category: it would
+// often be wrong.
+
+// A row's picture. Fixed square whether or not a photo arrives, so the list cannot jitter.
+export function FoodThumb({ src, size = 44 }: { src?: string, size?: number }) {
+ const { colors } = useTheme()
+ const [loaded, setLoaded] = useState(false)
+ return (
+ <View
+ style={{ width: size, height: size }}
+ className="items-center justify-center overflow-hidden rounded-xl border border-surface-border bg-surface-muted"
+ >
+ <Utensils size={size * 0.45} color={colors.txMuted} />
+ {src ? (
+ <Image
+ source={{ uri: src }}
+ onLoad={() => setLoaded(true)}
+ resizeMode="cover"
+ style={{ position: 'absolute', top: 0, left: 0, width: size, height: size, opacity: loaded ? 1 : 0 }}
+ />
+ ) : null}
+ </View>
+ )
+}
+
+// The detail screen's picture, which takes no room until it has one to fill. The band it
+// used to reserve pushed the amount field — the only control the screen is for — most of
+// a phone down when there was no photo, which is half the time.
+export function FoodHero({ src }: { src?: string }) {
+ const [loaded, setLoaded] = useState(false)
+ if (!src) return null
+ return (
+ <Image
+ source={{ uri: src }}
+ onLoad={() => setLoaded(true)}
+ resizeMode="cover"
+ className={loaded ? 'h-52 w-full border-b border-surface-border' : 'h-0 w-full'}
+ />
+ )
+}
diff --git a/mobile/src/components/nutrition/FoodResultRow.tsx b/mobile/src/components/nutrition/FoodResultRow.tsx
index 0a15a73..b60fe95 100644
--- a/mobile/src/components/nutrition/FoodResultRow.tsx
+++ b/mobile/src/components/nutrition/FoodResultRow.tsx
@@ -1,8 +1,9 @@
-import { Image, Pressable, View } from 'react-native'
-import { ChevronRight, Star, Utensils } from 'lucide-react-native'
+import { ActivityIndicator, Pressable, View } from 'react-native'
+import { ChevronRight, Star } from 'lucide-react-native'
import type { FoodSearchResult } from '@lyftr/shared'
import { AppText } from '../ui'
import { useTheme } from '../../theme/useTheme'
+import { FoodThumb } from './FoodImage'
import { MACRO_TEXT } from './nutritionMeta'
interface Props {
@@ -15,6 +16,8 @@ interface Props {
onToggleFavorite: () => void
/** Star is mid-request — dimmed and inert so a double tap can't race itself. */
togglingFavorite?: boolean
+ /** The product behind this row is being read in full before the detail opens. */
+ loading?: boolean
}
// The search / Recent / Favorites result row.
@@ -28,22 +31,17 @@ interface Props {
// 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,
+ item, onPress, favorited, onToggleFavorite, togglingFavorite = false, loading = false,
}: Props) {
const { colors } = useTheme()
return (
<Pressable
onPress={onPress}
+ disabled={loading}
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>
- )}
+ <FoodThumb src={item.image_url} />
<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}
@@ -65,7 +63,9 @@ export function FoodResultRow({
name={item.name}
onPress={onToggleFavorite}
/>
- <ChevronRight size={16} color={colors.txMuted} />
+ {loading
+ ? <ActivityIndicator size="small" color={colors.txMuted} />
+ : <ChevronRight size={16} color={colors.txMuted} />}
</Pressable>
)
}
diff --git a/packages/shared/src/hooks/useFoodAmount.ts b/packages/shared/src/hooks/useFoodAmount.ts
new file mode 100644
index 0000000..ebd63bc
--- /dev/null
+++ b/packages/shared/src/hooks/useFoodAmount.ts
@@ -0,0 +1,95 @@
+import { useCallback, useState } from 'react'
+import type { FoodSearchResult } from '../types'
+import {
+ amountForServings, formatServings, MAX_SERVINGS, maxAmountFor, servingBasis,
+ servingsForAmount, type ServingBasis,
+} from '../utils/food'
+
+export interface FoodAmount {
+ /** The field's text, as typed. A buffer, so a half-typed "0." survives. */
+ text: string
+ setText: (next: string) => void
+ /** What a serving measures, or null when nothing knows and the field counts servings. */
+ basis: ServingBasis | null
+ /** What the diary stores. 0 for an empty or nonsense field — the caller blocks the log. */
+ servings: number
+ /** The same number, to read rather than compute with. */
+ servingsLabel: number
+ /** Set when the amount is more than one entry may hold — the caller blocks the log. */
+ overLimit: boolean
+ /** What the field will accept, in the unit it is showing, for the message. */
+ maxAmount: string
+ /** Step by one serving's worth, in whatever unit the field is showing. */
+ step: (direction: 1 | -1) => void
+ /** Open the field on one serving of this food. */
+ openOn: (result: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'>) => void
+ /** Open it on the amount an existing entry recorded, in the unit it was logged in. */
+ openOnEntry: (
+ result: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'>,
+ servings: number,
+ ) => void
+}
+
+// The amount field on the Log Food screen, for both apps.
+//
+// It is a weight or a volume when OpenFoodFacts knows what a serving measures, and a
+// servings multiplier when nothing does — which is half of OpenFoodFacts and every
+// hand-entered food. Either way what comes out is servings, because that is what the
+// diary has always stored; the unit is a way to type one (#171, #41).
+//
+// Shared rather than written twice for the reason entryToResult is: this is arithmetic
+// that decides how much food a person recorded, and a version of it that drifted on one
+// platform would mis-log food there with nothing failing.
+//
+// There is deliberately no minimum. The old one was 0.5 servings, which for a bottle of
+// olive oil — whose figures OpenFoodFacts holds per 100 ml — meant 50 ml was the
+// smallest pour anyone could record. The server has never had a floor.
+export function useFoodAmount(
+ selected: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'> | null,
+): FoodAmount {
+ const [text, setText] = useState('1')
+
+ const openOn = useCallback((result: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'>) => {
+ const b = servingBasis(result)
+ setText(String(b ? b.quantity : 1))
+ }, [])
+
+ const openOnEntry = useCallback((
+ result: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'>,
+ entryServings: number,
+ ) => {
+ const b = servingBasis(result)
+ const s = entryServings || 1
+ setText(String(b ? amountForServings(s, b) : s))
+ }, [])
+
+ const basis = selected ? servingBasis(selected) : null
+ const amount = Number(text)
+ const servings = Number.isFinite(amount) && amount > 0
+ ? (basis ? servingsForAmount(amount, basis) : amount)
+ : 0
+
+ return {
+ text,
+ setText,
+ basis,
+ servings,
+ servingsLabel: formatServings(servings),
+ // Checked here rather than on each screen so web and mobile cannot disagree about
+ // what is loggable — and on servings, which is the number the server bounds too, so
+ // the two cannot refuse different things.
+ overLimit: servings > MAX_SERVINGS,
+ maxAmount: maxAmountFor(basis),
+ step: (direction) => {
+ const size = basis ? basis.quantity : 0.5
+ const from = Number.isFinite(amount) ? amount : 0
+ setText(String(+Math.max(0, from + direction * size).toFixed(1)))
+ },
+ // Both openers take the food as an argument rather than reading `selected`: the
+ // caller sets that in the same render, so the hook cannot see it yet. Both are
+ // stable, so an effect that opens an entry for editing can depend on one without
+ // re-running on every keystroke.
+ openOn,
+ openOnEntry,
+ }
+}
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index d235cda..8faec45 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -31,6 +31,7 @@ export * from './hooks/useRestTimer'
export * from './hooks/useServerList'
export * from './hooks/useServerInfo'
export * from './hooks/useFavorites'
+export * from './hooks/useFoodAmount'
export * from './utils/dateUtils'
export * from './brand/barbell'
export * from './utils/programUtils'
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 8df0732..779a249 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -104,6 +104,9 @@ export interface FoodLog {
fiber?: number
servings: number
serving_size?: string
+ /** The serving as a number, in {@link serving_unit}. 0 when unknown — see FoodSearchResult. */
+ serving_quantity?: number
+ serving_unit?: 'g' | 'ml' | ''
barcode?: string
image_url?: string
logged_at: string
@@ -131,6 +134,18 @@ export interface FoodSearchResult {
fat: number
fiber: number
serving_size: string
+ /**
+ * The serving as a number the UI can do arithmetic with, so a food can be logged as
+ * "15 ml" rather than "0.15 servings". `serving_size` stays the label people read
+ * ("1 Tbsp (15 ml)"); it is OpenFoodFacts free text and is not parseable.
+ *
+ * 0 or absent means no quantity is known — OpenFoodFacts often has a serving but not
+ * its size — and the screens then stay on servings rather than invent a weight.
+ */
+ serving_quantity?: number
+ serving_unit?: 'g' | 'ml' | ''
+ /** Set on OpenFoodFacts rows; search hits carry it so selecting one can re-read the product. */
+ barcode?: string
image_url?: string
source: 'off' | 'saved' | 'manual'
}
@@ -145,6 +160,9 @@ export interface SavedFood {
fat: number
fiber: number
serving_size: string
+ /** See FoodSearchResult — kept so logging a favourite can still offer weight. */
+ serving_quantity?: number
+ serving_unit?: 'g' | 'ml' | ''
barcode?: string
}
diff --git a/packages/shared/src/utils/food.test.ts b/packages/shared/src/utils/food.test.ts
index 50ae522..6126c7d 100644
--- a/packages/shared/src/utils/food.test.ts
+++ b/packages/shared/src/utils/food.test.ts
@@ -1,4 +1,4 @@
-import { eanModules, entryToResult, findSavedFood, formatBarcode, isDailyStats, normaliseFoodKey, savedToResult, scaleServing } from './food'
+import { amountForServings, MAX_SERVINGS, maxAmountFor, eanModules, entryToResult, findSavedFood, foodResultKey, formatBarcode, formatLoggedAmount, formatServings, isDailyStats, normaliseFoodKey, savedToResult, scaleServing, servingBasis, servingsForAmount } from './food'
import type { FoodLog, SavedFood } from '../types'
const log = (over: Partial<FoodLog> = {}): FoodLog => ({
@@ -238,3 +238,123 @@ describe('eanModules', () => {
expect(eanModules('ABC1234567890')).toBeNull()
})
})
+
+
+describe('servingBasis', () => {
+ // #171: a bottle of olive oil OpenFoodFacts only has per-100ml figures for. 100 ml is
+ // a real basis, so 15 ml of it is 0.15 servings — the arithmetic the user should not
+ // have to do, and could not do at all while the field floored at 0.5.
+ it('reads the serving as a number to scale against', () => {
+ expect(servingBasis({ serving_quantity: 100, serving_unit: 'ml' })).toEqual({ quantity: 100, unit: 'ml' })
+ expect(servingBasis({ serving_quantity: 15, serving_unit: 'ml' })).toEqual({ quantity: 15, unit: 'ml' })
+ })
+
+ it('defaults the unit to grams, because most servings are a weight', () => {
+ expect(servingBasis({ serving_quantity: 32 })).toEqual({ quantity: 32, unit: 'g' })
+ expect(servingBasis({ serving_quantity: 32, serving_unit: '' })).toEqual({ quantity: 32, unit: 'g' })
+ })
+
+ // Every entry logged before #171 reads back as 0, as does any product OpenFoodFacts
+ // has a serving but no size for. Weight entry is simply not offered for those.
+ it('is null when nothing knows what a serving weighs', () => {
+ expect(servingBasis({ serving_quantity: 0, serving_unit: 'g' })).toBeNull()
+ expect(servingBasis({})).toBeNull()
+ expect(servingBasis({ serving_quantity: -5 })).toBeNull()
+ expect(servingBasis({ serving_quantity: NaN })).toBeNull()
+ })
+})
+
+describe('servingsForAmount / amountForServings', () => {
+ const per100ml = { quantity: 100, unit: 'ml' } as const
+ const tablespoon = { quantity: 15, unit: 'ml' } as const
+
+ it('turns a tablespoon of oil into the servings the diary stores', () => {
+ expect(servingsForAmount(15, per100ml)).toBeCloseTo(0.15)
+ expect(servingsForAmount(15, tablespoon)).toBe(1)
+ })
+
+ it('round-trips, so opening an entry shows the amount that was logged', () => {
+ expect(amountForServings(servingsForAmount(15, per100ml), per100ml)).toBe(15)
+ expect(amountForServings(2, tablespoon)).toBe(30)
+ })
+
+ // A third of a serving would otherwise open the field as 33.33333333333333.
+ it('rounds the amount to the 0.1 every other number here is entered at', () => {
+ expect(amountForServings(1 / 3, per100ml)).toBe(33.3)
+ })
+})
+
+
+describe('the ceiling on one entry', () => {
+ // The client's copy of models.MaxServings. If the two drift, the field either refuses
+ // something the server would take or sends something it will refuse.
+ it('matches the number the server enforces', () => {
+ expect(MAX_SERVINGS).toBe(100)
+ })
+
+ // Said in the unit the person is typing in, not in servings: "1000 servings" would
+ // mean nothing next to a field showing ml.
+ it('states the limit in whatever the field is showing', () => {
+ expect(maxAmountFor(null)).toBe('100 servings')
+ })
+
+ // The same ceiling, read in the unit on screen: ten kilos of a food held per 100 g.
+ it('converts the ceiling into the unit on screen', () => {
+ expect(maxAmountFor({ quantity: 100, unit: 'g' })).toBe('10000 g')
+ expect(maxAmountFor({ quantity: 15, unit: 'ml' })).toBe('1500 ml')
+ })
+})
+
+
+describe('foodResultKey', () => {
+ // The bug: OpenFoodFacts answers "olive oil" with several products of the same name,
+ // two of them reading 0 kcal, so a name+calories key collided and React warned.
+ it('separates two products that share a name', () => {
+ const a = foodResultKey({ name: 'Extra Virgin Olive Oil', barcode: '6194620845616' }, 3)
+ const b = foodResultKey({ name: 'Extra Virgin Olive Oil', barcode: '20108144' }, 4)
+ expect(a).not.toBe(b)
+ })
+
+ it('falls back to the position when a food has no barcode', () => {
+ expect(foodResultKey({ name: 'Porridge' }, 0)).not.toBe(foodResultKey({ name: 'Porridge' }, 1))
+ })
+
+ // A barcode is stable across re-renders, so the row keeps its identity even if the
+ // list is refetched in a different order.
+ it('ignores position when a barcode is there', () => {
+ expect(foodResultKey({ name: 'Oats', barcode: '123' }, 0)).toBe(foodResultKey({ name: 'Oats', barcode: '123' }, 7))
+ })
+})
+
+
+describe('formatLoggedAmount', () => {
+ // The diary row and the entry detail both read this, so a tablespoon of oil cannot
+ // show as "15 ml" on one screen and "0.15 servings" on the other.
+ it('reads back in the unit it was logged in', () => {
+ expect(formatLoggedAmount({ servings: 0.15, serving_quantity: 100, serving_unit: 'ml' })).toBe('15 ml')
+ expect(formatLoggedAmount({ servings: 2, serving_quantity: 32, serving_unit: 'g' })).toBe('64 g')
+ })
+
+ it('says servings when nothing knows what one weighs', () => {
+ expect(formatLoggedAmount({ servings: 0.5 })).toBe('0.5 servings')
+ expect(formatLoggedAmount({ servings: 1 })).toBe('1 serving')
+ expect(formatLoggedAmount({ servings: 1 / 3 })).toBe('0.33 servings')
+ })
+})
+
+
+describe('formatServings', () => {
+ it('rounds to something a person can read', () => {
+ expect(formatServings(1)).toBe(1)
+ expect(formatServings(0.15)).toBe(0.15)
+ expect(formatServings(1 / 3)).toBe(0.33)
+ })
+
+ // 0.4 ml of an oil held per 100 ml is 0.004 servings. Two decimals alone printed
+ // "0 servings" next to a figure of 3 kcal.
+ it('does not round a real amount away to zero', () => {
+ expect(formatServings(0.004)).toBe(0.004)
+ expect(formatServings(0.0001)).toBe(0.0001)
+ expect(formatServings(0)).toBe(0)
+ })
+})
diff --git a/packages/shared/src/utils/food.ts b/packages/shared/src/utils/food.ts
index 059cf5e..99602e8 100644
--- a/packages/shared/src/utils/food.ts
+++ b/packages/shared/src/utils/food.ts
@@ -19,6 +19,11 @@ export function entryToResult(e: FoodLog): FoodSearchResult {
fat: e.fat / s,
fiber: (e.fiber ?? 0) / s,
serving_size: e.serving_size ?? '',
+ // Carried so re-opening an entry can still offer entry by weight. Unlike the
+ // macros these are per *one* serving already, so they do not divide.
+ serving_quantity: e.serving_quantity,
+ serving_unit: e.serving_unit,
+ barcode: e.barcode,
image_url: e.image_url,
source: 'saved',
}
@@ -44,16 +49,80 @@ export function scaleServing(r: FoodSearchResult, servings: number) {
fiber: +((r.fiber ?? 0) * servings).toFixed(1),
servings,
serving_size: r.serving_size ?? '',
+ serving_quantity: r.serving_quantity ?? 0,
+ serving_unit: r.serving_unit ?? '',
+ barcode: r.barcode ?? '',
image_url: r.image_url ?? '',
}
}
+/** A serving expressed as a number, so an amount can be scaled against it. */
+export interface ServingBasis {
+ quantity: number
+ unit: 'g' | 'ml'
+}
+
+// What one serving of this food weighs (or measures), or null when nothing knows.
+//
+// OpenFoodFacts has a serving but no size for thousands of products, and everything
+// logged before #171 stored none either. Both read back as 0, and 0 is not a basis you
+// can divide by — the screens fall back to servings, which is what they have always
+// done. Never substitute 100 here: that is a real number for a product whose figures
+// are per 100 g and a fiction for one whose serving is a tablespoon.
+export function servingBasis(r: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'>): ServingBasis | null {
+ const quantity = r.serving_quantity ?? 0
+ if (!(quantity > 0)) return null
+ return { quantity, unit: r.serving_unit === 'ml' ? 'ml' : 'g' }
+}
+
+// Amount (in the basis' unit) → servings, which is what the log stores and what
+// scaleServing multiplies by. The diary has always been in servings; weight is a way
+// to type one, not a second thing to store.
+export function servingsForAmount(amount: number, basis: ServingBasis): number {
+ return amount / basis.quantity
+}
+
+// Servings as a number to read, not to compute with: a third of a serving is
+// 0.3333333333333333 and nobody needs that.
+//
+// Two decimals is enough for everything except a very small amount of a food measured
+// per 100 — 0.4 ml of oil is 0.004 servings, which rounds to "0 servings" beside a
+// figure of 3 kcal. Falling back to one significant digit keeps that honest.
+export function formatServings(servings: number): number {
+ const rounded = +servings.toFixed(2)
+ if (rounded === 0 && servings > 0) return +servings.toPrecision(1)
+ return rounded
+}
+
+// The inverse, for showing the amount when a screen opens on an existing entry.
+// Rounded to 0.1 to match the precision every other number in the app is entered at;
+// without it a third of a serving opens the field as 33.33333333333333 g.
+export function amountForServings(servings: number, basis: ServingBasis): number {
+ return +(servings * basis.quantity).toFixed(1)
+}
+
+// How much of the food an entry records, in the unit it was logged in: "15 ml" when
+// the serving's size is known, "0.5 servings" when it is not. One copy, because the
+// diary row and the entry detail have to read the same or the same tablespoon of oil
+// appears as two different amounts on two screens.
+export function formatLoggedAmount(
+ e: Pick<FoodLog, 'servings'> & Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'>,
+): string {
+ const servings = e.servings || 1
+ const basis = servingBasis(e)
+ if (basis) return `${amountForServings(servings, basis)} ${basis.unit}`
+ const n = formatServings(servings)
+ return `${n} ${n === 1 ? 'serving' : 'servings'}`
+}
+
// A saved food is already stored per serving, so it maps across untouched.
export function savedToResult(s: SavedFood): FoodSearchResult {
return {
name: s.name, brand: s.brand,
calories: s.calories, protein: s.protein, carbs: s.carbs,
- fat: s.fat, fiber: s.fiber, serving_size: s.serving_size, source: 'saved',
+ fat: s.fat, fiber: s.fiber, serving_size: s.serving_size,
+ serving_quantity: s.serving_quantity, serving_unit: s.serving_unit,
+ barcode: s.barcode, source: 'saved',
}
}
@@ -75,6 +144,51 @@ export function findSavedFood(
return saved.find(s => normaliseFoodKey(s.name) === name && normaliseFoodKey(s.brand) === brand)
}
+// The ceiling on one diary entry, matching the server's models.MaxServings. Typing
+// 999999 into the amount field read 7,999,992 kcal against the day, and the server
+// stored whatever arrived. This copy exists so the field can refuse before asking.
+//
+// Servings is the bounded thing, and it is the only bounded thing: it is what gets
+// stored, what every macro is multiplied by, and so the one number the client and the
+// server can both check and mean the same by. A hundred of them is ten kilos of a food
+// held per 100 g, which is OpenNutriTracker's "unrealistically high" threshold reached
+// without a second rule to keep in step with this one.
+//
+// Checked after the amount is converted, not before. OpenNutriTracker checks the typed
+// number instead, so "500 servings" of a 30 g portion passes their guard and stores
+// 15000 g.
+//
+// (wger caps its amount at 1000, but that column doubles as a portion multiplier, which
+// is why it also carries a MinValueValidator of 1 — so it can log neither half a slice
+// nor a gram of anything, the very complaint #41 raised here. Waistline and FitBook have
+// no maximum at all.)
+export const MAX_SERVINGS = 100
+
+// The ceiling expressed in whatever the field is showing, for the message.
+export function maxAmountFor(basis: ServingBasis | null): string {
+ return basis
+ ? `${+(MAX_SERVINGS * basis.quantity).toFixed(1)} ${basis.unit}`
+ : `${MAX_SERVINGS} servings`
+}
+
+// React's key for one row of search or recent results, in both apps.
+//
+// The barcode is the only stable identity a result has. Keying on name + calories put
+// two real products under one key — OpenFoodFacts returns several "Extra Virgin Olive
+// Oil" rows from different brands, two of which read 0 kcal — and React answered with
+// "Encountered two children with the same key", having quietly dropped one row's state
+// onto the other.
+//
+// Without a barcode (a hand-entered food, a recent entry logged before barcodes were
+// stored) there is nothing unique to key on, so the position stands in. That is only
+// sound because these lists are replaced wholesale by a fetch rather than reordered.
+export function foodResultKey(
+ item: Pick<FoodSearchResult, 'barcode' | 'name'>,
+ index: number,
+): string {
+ return item.barcode || `${index}:${normaliseFoodKey(item.name)}`
+}
+
// The single definition of "the same food", client-side. It has to agree with the
// server, which trims before storing — otherwise a search result carrying "Oats " reads
// as different from the stored "Oats", the star shows unfilled next to a food that is
diff --git a/web/e2e/food.spec.ts b/web/e2e/food.spec.ts
index 94f6e32..b225cdf 100644
--- a/web/e2e/food.spec.ts
+++ b/web/e2e/food.spec.ts
@@ -216,6 +216,37 @@ test.describe('Food', () => {
await expect(page.getByText('400').first()).toBeVisible()
})
+ // #171: OpenFoodFacts only has per-100ml figures for a lot of oils, and the amount
+ // field used to floor at 0.5 — so the least anyone could log was 50 ml. This drives
+ // the whole path: a search hit re-read through the product endpoint, then an amount
+ // typed in the pack's own unit.
+ test('logs a tablespoon of oil, not half of 100 ml', { tag: '@mobile' }, async ({ page }) => {
+ const hit = {
+ name: 'Olive Oil', brand: 'Thrive Market', calories: 800, protein: 0, carbs: 0,
+ fat: 93.3, fiber: 0, serving_size: '100 ml', serving_quantity: 100,
+ serving_unit: 'ml', barcode: '0085239033265', source: 'off',
+ }
+ await page.route('**/api/v1/food/search**', route => route.fulfill({ json: { data: [hit] } }))
+ await page.route('**/api/v1/food/barcode/**', route => route.fulfill({
+ json: { data: { ...hit, calories: 120, fat: 14, serving_size: '1 Tbsp (15 ml)', serving_quantity: 15 } },
+ }))
+
+ await page.goto('/food/log')
+ await page.fill('input[placeholder="Search food…"]', 'olive oil')
+ // Exact: the empty state that shows while the search is in flight contains the
+ // query too, and a substring match resolves to it as well as the row.
+ await page.getByText('Olive Oil', { exact: true }).click()
+
+ // The pack's serving, read from the product endpoint — not the index's 100 ml.
+ const amount = page.getByLabel('Amount in ml')
+ await expect(amount).toHaveValue('15')
+ await expect(page.getByText('120').first()).toBeVisible()
+
+ await amount.fill('5')
+ await expect(page.getByText('40').first()).toBeVisible()
+ await expect(page.getByText(/0\.33 servings/)).toBeVisible()
+ })
+
// @mobile: touch chip selector that sets the entry's meal.
test('meal selector in detail phase updates active meal', { tag: '@mobile' }, async ({ page }) => {
await page.route('**/api/v1/food/search**', route =>
diff --git a/web/src/components/FoodImage.test.tsx b/web/src/components/FoodImage.test.tsx
new file mode 100644
index 0000000..6a37a04
--- /dev/null
+++ b/web/src/components/FoodImage.test.tsx
@@ -0,0 +1,46 @@
+import { describe, it, expect } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import { FoodHero, FoodThumb } from './FoodImage'
+
+// What these pin is the failure that is invisible in a test that only checks the happy
+// path: a photo OpenFoodFacts advertises but never delivers. Half its products have no
+// photo at all, and its image host answers a fair share of the rest with a reset or a
+// handshake that hangs — so "the src is set" must not be what decides the layout.
+describe('FoodHero', () => {
+ it('takes no room at all when the food has no photo', () => {
+ const { container } = render(<FoodHero alt="Olive Oil" />)
+ expect(container.firstChild).toBeNull()
+ })
+
+ // The band used to be reserved the moment a src existed, which on a phone pushed the
+ // amount field off the screen for as long as the request hung — forever, in the case
+ // that prompted this.
+ it('stays collapsed while the photo has not arrived', () => {
+ render(<FoodHero src="https://images.openfoodfacts.org/x.jpg" alt="Olive Oil" />)
+ expect(screen.getByAltText('Olive Oil').className).toContain('h-0')
+ })
+
+ it('takes its full height once the photo loads', () => {
+ render(<FoodHero src="https://images.openfoodfacts.org/x.jpg" alt="Olive Oil" />)
+ fireEvent.load(screen.getByAltText('Olive Oil'))
+ expect(screen.getByAltText('Olive Oil').className).toContain('h-52')
+ })
+})
+
+describe('FoodThumb', () => {
+ // The row's slot is a fixed square either way, so a list does not jitter as photos
+ // stream in — the glyph sits underneath and the photo covers it once it is there.
+ it('shows the glyph when there is no photo', () => {
+ const { container } = render(<FoodThumb />)
+ expect(container.querySelector('svg')).toBeTruthy()
+ expect(container.querySelector('img')).toBeNull()
+ })
+
+ it('keeps the glyph visible until the photo has loaded', () => {
+ const { container } = render(<FoodThumb src="https://images.openfoodfacts.org/x.jpg" />)
+ const img = container.querySelector('img')!
+ expect(img.className).toContain('opacity-0')
+ fireEvent.load(img)
+ expect(img.className).toContain('opacity-100')
+ })
+})
diff --git a/web/src/components/FoodImage.tsx b/web/src/components/FoodImage.tsx
new file mode 100644
index 0000000..9a6c9cb
--- /dev/null
+++ b/web/src/components/FoodImage.tsx
@@ -0,0 +1,63 @@
+import { useState } from 'react'
+import { Utensils } from 'lucide-react'
+
+// Product photos, on the two terms OpenFoodFacts actually offers them.
+//
+// Half of the catalogue has no photo at all — sampled per query against the search
+// index: milk 12%, olive oil 19%, yogurt 39%, bread 54% — and a real share of the rest
+// answer with a connection reset or a TLS handshake that never completes (measured from
+// this machine while verifying #171: 3 of 5 olive-oil images). So a missing picture is
+// the ordinary case, and a picture that never arrives has to look the same as one that
+// was never there. An <img> alone does neither: it leaves an empty bordered box, and on
+// the detail screen it held a blank 208px band above the calories forever.
+//
+// Which is why there is no onError here. A photo is shown once it has loaded and not
+// before; failing and hanging then need no separate handling, because neither ever
+// loads. This is the same rule the API client follows — nothing is left mid-request
+// with the UI pretending otherwise.
+//
+// Nothing stands in for the photo but a glyph. Peer apps are unanimous: OpenFoodFacts'
+// own app, wger, OpenNutriTracker, Waistline and FitBook all show a flat tinted box with
+// an outline icon, and OpenNutriTracker's source says outright why it will not guess an
+// icon from the product's category — branded products make that "often misleading". A
+// plausible-looking stand-in for data we do not have is the thing to avoid.
+
+// A row's picture. The slot is a fixed square whether or not a photo ever arrives, so a
+// list does not jitter as images stream in.
+export function FoodThumb({ src, className = '' }: { src?: string, className?: string }) {
+ const [loaded, setLoaded] = useState(false)
+ return (
+ <div className={`relative w-11 h-11 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center flex-shrink-0 overflow-hidden ${className}`}>
+ <Utensils className="w-5 h-5 text-tx-muted" />
+ {src && (
+ <img
+ src={src}
+ alt=""
+ onLoad={() => setLoaded(true)}
+ className={`absolute inset-0 w-full h-full object-cover transition-opacity ${loaded ? 'opacity-100' : 'opacity-0'}`}
+ />
+ )}
+ </div>
+ )
+}
+
+// The detail screen's picture, which takes no room until it has one to fill.
+//
+// It used to reserve a band — 208px for a photo on its way, 128px of placeholder when
+// there was none — which on a 390px phone pushed the amount field, the only control
+// anyone opened this screen to use, most of a screen down. No peer reserves that space:
+// wger and FitBook build the image widget only `if (image != null)`, Waistline hides the
+// row outright, and MyFitnessPal, Cronometer and MacroFactor have no product photo on
+// their log screens at all. The numbers are what the screen is for.
+export function FoodHero({ src, alt }: { src?: string, alt: string }) {
+ const [loaded, setLoaded] = useState(false)
+ if (!src) return null
+ return (
+ <img
+ src={src}
+ alt={alt}
+ onLoad={() => setLoaded(true)}
+ className={`w-full object-cover ${loaded ? 'h-52 border-b border-surface-border' : 'h-0'}`}
+ />
+ )
+}
diff --git a/web/src/hooks/useFoodAmount.test.ts b/web/src/hooks/useFoodAmount.test.ts
new file mode 100644
index 0000000..4858d21
--- /dev/null
+++ b/web/src/hooks/useFoodAmount.test.ts
@@ -0,0 +1,95 @@
+import { describe, it, expect } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+import { useFoodAmount } from '@lyftr/shared'
+
+// The hook lives in @lyftr/shared; the suite is here because it needs jsdom and
+// @testing-library, which shared's plain-node jest does not carry (see useFavorites).
+
+const OIL = { serving_quantity: 100, serving_unit: 'ml' as const } // figures per 100 ml
+const TBSP = { serving_quantity: 15, serving_unit: 'ml' as const } // a real pack serving
+const UNKNOWN = { serving_quantity: 0, serving_unit: '' as const } // hand-entered food
+
+describe('useFoodAmount', () => {
+ it('counts the unit a serving is measured in, when one is known', () => {
+ const { result } = renderHook(() => useFoodAmount(OIL))
+ act(() => result.current.openOn(OIL))
+
+ expect(result.current.basis).toEqual({ quantity: 100, unit: 'ml' })
+ expect(result.current.text).toBe('100')
+
+ act(() => result.current.setText('15'))
+ expect(result.current.servings).toBeCloseTo(0.15)
+ expect(result.current.servingsLabel).toBe(0.15)
+ })
+
+ // The bug: the field floored at 0.5 servings, so the least anyone could log of an oil
+ // held per 100 ml was 50 ml. A tablespoon was unreachable (#171).
+ it('has no minimum', () => {
+ const { result } = renderHook(() => useFoodAmount(OIL))
+ act(() => result.current.setText('0.4'))
+ expect(result.current.servings).toBeCloseTo(0.004)
+ expect(result.current.servingsLabel).toBe(0.004)
+ })
+
+ // No minimum, but a maximum: 999999 in the field read 7,999,992 kcal against the day.
+ it('refuses more than one entry can hold, and says the limit in the unit shown', () => {
+ const { result } = renderHook(() => useFoodAmount(OIL))
+
+ act(() => result.current.setText('999999'))
+ expect(result.current.overLimit).toBe(true)
+ // OIL is held per 100 ml, so the ceiling reads as ten litres.
+ expect(result.current.maxAmount).toBe('10000 ml')
+
+ // The ceiling itself is allowed, so the two sides cannot be out of step by one.
+ act(() => result.current.setText('10000'))
+ expect(result.current.servings).toBe(100)
+ expect(result.current.overLimit).toBe(false)
+ })
+
+ it('counts servings when nothing knows what one measures', () => {
+ const { result } = renderHook(() => useFoodAmount(UNKNOWN))
+ act(() => result.current.openOn(UNKNOWN))
+
+ expect(result.current.basis).toBeNull()
+ expect(result.current.text).toBe('1')
+ act(() => result.current.setText('0.25'))
+ expect(result.current.servings).toBe(0.25)
+ })
+
+ // An empty field is not zero food, it is no answer — the caller blocks the log on it.
+ it.each(['', '.', 'abc', '-2', '0'])('is 0 servings for %o', (typed) => {
+ const { result } = renderHook(() => useFoodAmount(OIL))
+ act(() => result.current.setText(typed))
+ expect(result.current.servings).toBe(0)
+ })
+
+ it('steps by one serving, in the field’s own unit, and stops at zero', () => {
+ const { result } = renderHook(() => useFoodAmount(TBSP))
+ act(() => result.current.openOn(TBSP))
+ act(() => result.current.step(1))
+ expect(result.current.text).toBe('30')
+ act(() => result.current.step(-1))
+ act(() => result.current.step(-1))
+ expect(result.current.text).toBe('0')
+ // Not negative: there is no such amount of food.
+ act(() => result.current.step(-1))
+ expect(result.current.text).toBe('0')
+ })
+
+ it('steps by half a serving when that is all the field counts', () => {
+ const { result } = renderHook(() => useFoodAmount(UNKNOWN))
+ act(() => result.current.step(1))
+ expect(result.current.text).toBe('1.5')
+ })
+
+ // Re-opening an entry has to show what was logged, not one serving of it.
+ it('opens an existing entry on the amount it recorded', () => {
+ const { result } = renderHook(() => useFoodAmount(OIL))
+ act(() => result.current.openOnEntry(OIL, 0.15))
+ expect(result.current.text).toBe('15')
+
+ const plain = renderHook(() => useFoodAmount(UNKNOWN))
+ act(() => plain.result.current.openOnEntry(UNKNOWN, 2.5))
+ expect(plain.result.current.text).toBe('2.5')
+ })
+})
diff --git a/web/src/index.css b/web/src/index.css
index cb56800..c239135 100644
--- a/web/src/index.css
+++ b/web/src/index.css
@@ -63,6 +63,13 @@
focus:outline-none focus:ring-1 focus:ring-brand-500 focus:border-brand-500
transition-colors duration-150;
}
+ /* The −/+ buttons beside a field already step it, so the browser's own spinners are
+ a second, tinier copy of the same control — and they land on top of a unit suffix
+ like "ml". Opt in per field; a field with no buttons of its own keeps them. */
+ .input-no-spin { appearance: textfield; }
+ .input-no-spin::-webkit-outer-spin-button,
+ .input-no-spin::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
+
.input-group { @apply space-y-1.5; }
.input-help { @apply text-xs text-tx-muted mt-1; }
diff --git a/web/src/pages/Food.tsx b/web/src/pages/Food.tsx
index 5e3d821..81dc94d 100644
--- a/web/src/pages/Food.tsx
+++ b/web/src/pages/Food.tsx
@@ -15,7 +15,7 @@ import Loading from '../components/Loading'
import PeriodSelector from '../components/PeriodSelector'
import { foodAPI, savedFoodsAPI } from '../services/api'
import { useSettingsStore } from '../stores/settings'
-import { apiErrorMessage, entryToResult, isDailyStats, todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay, useFavorites, type Favorites } from '@lyftr/shared'
+import { apiErrorMessage, entryToResult, formatLoggedAmount, isDailyStats, todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay, useFavorites, type Favorites } from '@lyftr/shared'
import { ErrorState } from '../components/ui'
import FavoriteStar from '../components/FavoriteStar'
@@ -465,7 +465,7 @@ export default function Food() {
<span className="text-[10px] text-tx-muted">·</span>
<span className="text-xs text-violet-400 tabular-nums">{entry.fat.toFixed(0)}g F</span>
{entry.servings !== 1 && (
- <span className="text-xs text-tx-muted">× {entry.servings}</span>
+ <span className="text-xs text-tx-muted">{formatLoggedAmount(entry)}</span>
)}
</div>
</div>
diff --git a/web/src/pages/LogFood.test.tsx b/web/src/pages/LogFood.test.tsx
index b88df73..9cf242f 100644
--- a/web/src/pages/LogFood.test.tsx
+++ b/web/src/pages/LogFood.test.tsx
@@ -2,6 +2,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import LogFood from './LogFood'
+import type { FoodSearchResult } from '@lyftr/shared'
+
+// What the page sends to the API: scaleServing's fields plus where and when.
+type LoggedPayload = ReturnType<typeof import('@lyftr/shared').scaleServing> & {
+ meal: string
+ logged_at: string
+}
// A barcode lookup goes through Open Food Facts and takes seconds. The bug these pin
// (#164): the scanner closed and the screen sat unchanged while it ran, so people
@@ -9,14 +16,16 @@ import LogFood from './LogFood'
// reason other than "no such product", it said "Product not found" anyway.
const barcode = vi.fn()
+const search = vi.fn(async (_q: string): Promise<FoodSearchResult[]> => [])
+const logFood = vi.fn(async (_payload: LoggedPayload) => ({}))
vi.mock('../services/api', () => ({
foodAPI: {
list: () => Promise.resolve([]),
- search: () => Promise.resolve([]),
+ search: (q: string) => search(q),
barcode: (code: string) => barcode(code),
get: vi.fn(),
- log: vi.fn(),
+ log: (payload: LoggedPayload) => logFood(payload),
update: vi.fn(),
},
savedFoodsAPI: {
@@ -119,3 +128,157 @@ describe('Barcode lookup', () => {
expect(await screen.findByText('New Entry')).toBeTruthy()
})
})
+
+
+// #171: a bottle of olive oil read 800 kcal and 93.3 g fat for "1 serving", because
+// OpenFoodFacts only has per-100ml figures for it — and the servings field floored at
+// 0.5, so the smallest thing anyone could log was half of that. 15 ml was unreachable.
+describe('Logging an amount', () => {
+ const OIL_SEARCH_HIT: FoodSearchResult = {
+ name: 'Olive Oil', brand: 'Thrive Market',
+ calories: 800, protein: 0, carbs: 0, fat: 93.3, fiber: 0,
+ serving_size: '100 ml', serving_quantity: 100, serving_unit: 'ml',
+ barcode: '0085239033265', source: 'off',
+ }
+ const OIL_PRODUCT: FoodSearchResult = {
+ ...OIL_SEARCH_HIT,
+ calories: 120, fat: 14,
+ serving_size: '1 Tbsp (15 ml)', serving_quantity: 15,
+ }
+
+ const searchFor = async (term: string) => {
+ fireEvent.click(await screen.findByRole('button', { name: 'Search' }))
+ fireEvent.change(screen.getByPlaceholderText('Search food…'), { target: { value: term } })
+ }
+
+ const logButton = () => screen.getByRole('button', { name: 'Log Food' }) as HTMLButtonElement
+
+ it('logs the amount typed, not a multiple of half a serving', async () => {
+ search.mockResolvedValue([OIL_SEARCH_HIT])
+ barcode.mockResolvedValue(OIL_PRODUCT)
+ renderPage()
+
+ await searchFor('olive oil')
+ fireEvent.click(await screen.findByText('Olive Oil'))
+
+ const amount = await screen.findByLabelText('Amount in ml') as HTMLInputElement
+ // One serving of the product, which is what the field opens on.
+ expect(amount.value).toBe('15')
+
+ fireEvent.change(amount, { target: { value: '5' } })
+ expect(screen.getByText(/0\.33 servings/)).toBeTruthy()
+
+ fireEvent.click(logButton())
+ await waitFor(() => expect(logFood).toHaveBeenCalled())
+ const payload = logFood.mock.calls[0][0]
+ expect(payload.servings).toBeCloseTo(1 / 3)
+ expect(payload.calories).toBe(40)
+ expect(payload.serving_quantity).toBe(15)
+ expect(payload.serving_unit).toBe('ml')
+ })
+
+ // Deleting the 0.5-serving floor made an empty or nonsense amount reachable for the
+ // first time. The button has to refuse it — and say so, rather than sit there dead
+ // next to "0 servings", which states what happened and not why.
+ it.each([
+ ['empty', ''],
+ ['zero', '0'],
+ ['negative', '-3'],
+ ])('refuses to log an %s amount, and says what it wants instead', async (_label, typed) => {
+ search.mockResolvedValue([OIL_SEARCH_HIT])
+ barcode.mockResolvedValue(OIL_PRODUCT)
+ renderPage()
+
+ await searchFor('olive oil')
+ fireEvent.click(await screen.findByText('Olive Oil'))
+
+ const amount = await screen.findByLabelText('Amount in ml') as HTMLInputElement
+ fireEvent.change(amount, { target: { value: typed } })
+
+ expect(logButton().disabled).toBe(true)
+ expect(screen.getByText('Enter an amount in ml to log this')).toBeTruthy()
+ // And the header stops claiming a zero-sized serving.
+ expect(screen.queryByText(/0 × /)).toBeNull()
+ })
+
+ // The other end of the same field. A fat-fingered 999999 read 7,999,992 kcal against
+ // the day and the server stored it, because neither side had a ceiling.
+ it('refuses an amount larger than one entry can hold', async () => {
+ search.mockResolvedValue([OIL_SEARCH_HIT])
+ barcode.mockResolvedValue(OIL_PRODUCT)
+ renderPage()
+
+ await searchFor('olive oil')
+ fireEvent.click(await screen.findByText('Olive Oil'))
+
+ const amount = await screen.findByLabelText('Amount in ml') as HTMLInputElement
+ fireEvent.change(amount, { target: { value: '999999' } })
+
+ expect(logButton().disabled).toBe(true)
+ // Said in millilitres, which is what the field is showing — a hundred servings of
+ // a 15 ml tablespoon.
+ expect(screen.getByText('One entry holds at most 1500 ml')).toBeTruthy()
+
+ // And the limit itself still logs.
+ fireEvent.change(amount, { target: { value: '1500' } })
+ expect(logButton().disabled).toBe(false)
+ })
+
+ // The search index answers with per-100g figures and no serving at all, so a hit is
+ // not what the pack says. Selecting one has to read the product in full first.
+ it('re-reads a search hit through the product endpoint before opening it', async () => {
+ search.mockResolvedValue([OIL_SEARCH_HIT])
+ barcode.mockResolvedValue(OIL_PRODUCT)
+ renderPage()
+
+ await searchFor('olive oil')
+ fireEvent.click(await screen.findByText('Olive Oil'))
+
+ await waitFor(() => expect(barcode).toHaveBeenCalledWith('0085239033265'))
+ // The pack's own serving, not the index's 100 ml. The label is assembled from
+ // several nodes, so it is read off the whole paragraph.
+ const amount = await screen.findByLabelText('Amount in ml') as HTMLInputElement
+ expect(amount.value).toBe('15')
+ expect(screen.getByText('120')).toBeTruthy()
+ expect(screen.getByText(
+ (_, el) => el?.textContent === '1 serving of 1 Tbsp (15 ml)',
+ )).toBeTruthy()
+ })
+
+ it('still opens the search figures when that re-read fails, and says which they are', async () => {
+ search.mockResolvedValue([OIL_SEARCH_HIT])
+ barcode.mockRejectedValue(httpError(503, TIMEOUT))
+ renderPage()
+
+ await searchFor('olive oil')
+ fireEvent.click(await screen.findByText('Olive Oil'))
+
+ expect(await screen.findByText(new RegExp(TIMEOUT))).toBeTruthy()
+ expect(screen.getByText(/always per 100 ml/)).toBeTruthy()
+ // Still loggable: the per-100 figures are real, they are just not a pack serving.
+ const amount = screen.getByLabelText('Amount in ml') as HTMLInputElement
+ expect(amount.value).toBe('100')
+ fireEvent.change(amount, { target: { value: '15' } })
+ fireEvent.click(logButton())
+ await waitFor(() => expect(logFood).toHaveBeenCalled())
+ expect(logFood.mock.calls[0][0].servings).toBeCloseTo(0.15)
+ })
+
+ // Nothing knows what a serving of a hand-entered food weighs, so it stays in
+ // servings — but unfloored, which is the other half of the bug.
+ it('falls back to servings when no serving size is known, with no minimum', async () => {
+ search.mockResolvedValue([])
+ renderPage()
+
+ await searchFor('sourdough')
+ fireEvent.click(await screen.findByRole('button', { name: /Enter "sourdough" manually/ }))
+
+ const servings = await screen.findByLabelText('Servings') as HTMLInputElement
+ expect(servings.value).toBe('1')
+ fireEvent.change(servings, { target: { value: '0.25' } })
+ fireEvent.click(logButton())
+ await waitFor(() => expect(logFood).toHaveBeenCalled())
+ expect(logFood.mock.calls[0][0].servings).toBe(0.25)
+ })
+
+})
diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsx
index ceec613..0eed7b2 100644
--- a/web/src/pages/LogFood.tsx
+++ b/web/src/pages/LogFood.tsx
@@ -3,10 +3,10 @@ import { useNavigate, useSearchParams } from 'react-router-dom'
import {
ArrowLeft, Search, Scan, Minus, Plus, X,
Star, AlertCircle, Utensils, Zap,
- Coffee, Sun, Moon, Cookie, ChevronRight,
+ Coffee, Sun, Moon, Cookie, ChevronRight, Loader2,
} from 'lucide-react'
import { foodAPI, savedFoodsAPI } from '../services/api'
-import { apiErrorMessage, isNotFound, useAsyncAction, todayStr, dayToInstant, entryDay, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, useFavorites } from '@lyftr/shared'
+import { apiErrorMessage, isNotFound, useAsyncAction, todayStr, dayToInstant, entryDay, foodResultKey, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, useFavorites, useFoodAmount } from '@lyftr/shared'
import { ErrorState, ListError } from '../components/ui'
import BarcodeScanner from '../components/BarcodeScanner'
import BarcodeLookup from '../components/BarcodeLookup'
@@ -14,6 +14,7 @@ import FavoriteStar from '../components/FavoriteStar'
import IconButton from '../components/ui/IconButton'
import SegmentedControl from '../components/ui/SegmentedControl'
import DateInput from '../components/ui/DateInput'
+import { FoodHero, FoodThumb } from '../components/FoodImage'
type Phase = 'search' | 'detail' | 'scan'
type SearchTab = 'recent' | 'myfoods' | 'all'
@@ -41,24 +42,20 @@ const MEAL_COLORS: Record<string, string> = {
// <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, onClick, favorited, onToggleFavorite, togglingFavorite = false, loading = false }:
{
item: types.FoodSearchResult
onClick: () => void
favorited: boolean
onToggleFavorite: () => void
togglingFavorite?: boolean
+ /** The product behind this row is being read in full before the detail opens. */
+ loading?: 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" />
- ) : (
- <div className="w-11 h-11 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center flex-shrink-0">
- <Utensils className="w-5 h-5 text-tx-muted" />
- </div>
- )}
+ <FoodThumb src={item.image_url} />
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-tx-primary truncate">{item.name}</p>
{item.brand && <p className="text-xs text-tx-muted truncate mt-0.5">{item.brand}</p>}
@@ -78,13 +75,15 @@ function FoodResultRow(
)}
</div>
</div>
- <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
+ {loading
+ ? <Loader2 className="w-4 h-4 text-tx-muted flex-shrink-0 animate-spin" />
+ : <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">
+ <button onClick={onClick} disabled={loading} className="flex items-center gap-3 flex-1 min-w-0 py-3.5 text-left">
{content}
</button>
<FavoriteStar
@@ -130,10 +129,19 @@ export default function LogFood() {
const lookingUp = lookup !== null && lookup.error === null
const [selected, setSelected] = useState<types.FoodSearchResult | null>(null)
- const [servings, setServings] = useState(1)
+ // The amount field — grams, millilitres or servings, depending on the food. Shared
+ // with mobile, because what it computes is how much food the person recorded (#171).
+ const amount = useFoodAmount(selected)
+ const { basis, servings, servingsLabel, overLimit, maxAmount, openOnEntry } = amount
+ // Which search row is being re-read in full, and what to say if that failed. The
+ // search index answers with per-100g figures and no serving at all, so a hit has to
+ // be read again through the product endpoint before it can be trusted (#171).
+ const [upgrading, setUpgrading] = useState<string | null>(null)
+ const [staleServing, setStaleServing] = useState<string | null>(null)
const [meal, setMeal] = useState<types.FoodLog['meal']>(initMeal)
const [date, setDate] = useState(initDate)
+
const [editError, setEditError] = useState<string | null>(null)
const [editRetry, setEditRetry] = useState(0)
@@ -143,13 +151,14 @@ export default function LogFood() {
useEffect(() => {
if (!editId) return
foodAPI.get(editId).then(entry => {
- setSelected(entryToResult(entry))
- setServings(entry.servings || 1)
+ const result = entryToResult(entry)
+ setSelected(result)
+ openOnEntry(result, entry.servings)
setMeal(entry.meal)
setDate(entryDay(entry))
setPhase('detail')
}).catch(err => setEditError(apiErrorMessage(err, "The server didn't say what went wrong.")))
- }, [editId, navigate, editRetry])
+ }, [editId, navigate, editRetry, openOnEntry])
useEffect(() => {
foodAPI.list(todayStr()).then(logs => {
@@ -192,12 +201,31 @@ export default function LogFood() {
return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }
}, [query, tab])
- const selectResult = (result: types.FoodSearchResult) => {
+ const selectResult = (result: types.FoodSearchResult, note: string | null = null) => {
setSelected(result)
- setServings(1)
+ amount.openOn(result)
+ setStaleServing(note)
setPhase('detail')
}
+ // A search hit is not enough to log against. OpenFoodFacts' search index carries
+ // per-100g figures and no serving at all, so the same olive oil reads 800 kcal per
+ // 100 g from a search and 120 kcal per tablespoon from a scan (#171). Read the
+ // product in full before opening the detail, the way every other OFF client does.
+ const selectSearchResult = async (result: types.FoodSearchResult) => {
+ if (result.source !== 'off' || !result.barcode) { selectResult(result); return }
+ setUpgrading(result.barcode)
+ try {
+ selectResult(await foodAPI.barcode(result.barcode))
+ } catch (err) {
+ // The search row is still real data, so log against it rather than dead-ending —
+ // but say which figures these are, because they are the ones that read wrong.
+ selectResult(result, apiErrorMessage(err, "Couldn't re-read this product."))
+ } finally {
+ setUpgrading(null)
+ }
+ }
+
const enterManually = () => {
setLookup(null)
selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })
@@ -424,9 +452,9 @@ 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) => (
+ : recentItems.map((item, i) => (
<FoodResultRow
- key={`${item.name}-${item.calories}`}
+ key={foodResultKey(item, i)}
item={item}
onClick={() => selectResult(item)}
favorited={favoriteOf(item) !== undefined}
@@ -483,11 +511,12 @@ export default function LogFood() {
</button>
</div>
)}
- {tab === 'all' && !searching && searchResults.map((item) => (
+ {tab === 'all' && !searching && searchResults.map((item, i) => (
<FoodResultRow
- key={`${item.name}-${item.calories}`}
+ key={foodResultKey(item, i)}
item={item}
- onClick={() => selectResult(item)}
+ loading={upgrading !== null && upgrading === item.barcode}
+ onClick={() => void selectSearchResult(item)}
favorited={favoriteOf(item) !== undefined}
onToggleFavorite={() => toggleFavorite(item)}
togglingFavorite={isToggling(item)}
@@ -508,21 +537,19 @@ export default function LogFood() {
</div>
)}
+ {/* The product couldn't be re-read, so these are the search index's figures:
+ per 100 g, whatever the pack's own serving is. Say so rather than let them
+ read as a serving — that is the whole of #171. */}
+ {staleServing && (
+ <div className="alert-warning">
+ <AlertCircle className="w-4 h-4 flex-shrink-0" />
+ <span>{staleServing} Showing search results, which are always per {selected.serving_size}.</span>
+ </div>
+ )}
+
{/* Food hero + macros */}
<div className="card overflow-hidden">
- {/* Image or placeholder */}
- {selected.image_url ? (
- <img
- src={selected.image_url}
- alt={selected.name}
- className="w-full h-52 object-cover"
- onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
- />
- ) : (
- <div className="w-full h-32 bg-surface-muted border-b border-surface-border flex items-center justify-center">
- <Utensils className="w-10 h-10 text-tx-muted opacity-20" />
- </div>
- )}
+ <FoodHero src={selected.image_url} alt={selected.name} />
<div className="p-5">
{/* Calorie hero */}
@@ -537,7 +564,7 @@ export default function LogFood() {
{/* The label comes from OpenFoodFacts, which is free text — and rows
logged before the backend stopped prefixing it still read "per
100g". Supplying a second "per" gave "per per 100g". */}
- per {servings === 1 ? '' : `${servings} × `}
+ per {servingsLabel === 1 || servings <= 0 ? '' : `${servingsLabel} × `}
{selected.serving_size.replace(/^per\s+/i, '')}
</p>
)}
@@ -583,25 +610,55 @@ export default function LogFood() {
</div>
</div>
- {/* Servings */}
+ {/* Amount */}
<div className="card p-4 space-y-3">
<div className="flex items-baseline gap-2">
- <label className="label">Servings</label>
- {selected.serving_size && (
+ <label className="label" htmlFor="food-amount">{basis ? 'Amount' : 'Servings'}</label>
+ {selected.serving_size && !basis && (
<span className="text-xs text-tx-muted">({selected.serving_size} each)</span>
)}
</div>
<div className="flex items-center gap-3">
- <IconButton icon={Minus} variant="secondary" size="lg" label="Decrease servings" onClick={() => setServings(s => Math.max(0.5, +(s - 0.5).toFixed(1)))} />
- <input
- type="number"
- value={servings}
- onChange={e => setServings(Math.max(0.5, Number(e.target.value) || 1))}
- step="0.5" min="0.5"
- className="input text-center flex-1 h-12 text-lg font-semibold tabular-nums"
- />
- <IconButton icon={Plus} variant="secondary" size="lg" label="Increase servings" onClick={() => setServings(s => +(s + 0.5).toFixed(1))} />
+ <IconButton icon={Minus} variant="secondary" size="lg" label={basis ? 'Decrease amount' : 'Decrease servings'} onClick={() => amount.step(-1)} />
+ <div className="relative flex-1">
+ <input
+ id="food-amount"
+ type="number"
+ inputMode="decimal"
+ value={amount.text}
+ onChange={e => amount.setText(e.target.value)}
+ // No minimum: a tablespoon of oil is 0.15 of the 100 ml OpenFoodFacts
+ // holds the figures for, and flooring this at 0.5 is what made that
+ // bottle unloggable (#171). The server has never had a floor.
+ min="0"
+ step="any"
+ aria-label={basis ? `Amount in ${basis.unit}` : 'Servings'}
+ className={`input input-no-spin text-center h-12 text-lg font-semibold tabular-nums ${basis ? 'pr-9' : ''}`}
+ />
+ {basis && (
+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-tx-muted pointer-events-none">
+ {basis.unit}
+ </span>
+ )}
+ </div>
+ <IconButton icon={Plus} variant="secondary" size="lg" label={basis ? 'Increase amount' : 'Increase servings'} onClick={() => amount.step(1)} />
</div>
+ {/* The readout doubles as the reason the Log button is disabled. Deleting the
+ 0.5-serving floor made an empty or nonsense amount reachable for the first
+ time, and "0 servings" beside a dead button says what, not why. */}
+ {servings <= 0 ? (
+ <p className="text-xs text-tx-muted text-center">
+ Enter an amount{basis ? ` in ${basis.unit}` : ''} to log this
+ </p>
+ ) : overLimit ? (
+ <p className="text-xs text-warning-400 text-center">
+ One entry holds at most {maxAmount}
+ </p>
+ ) : basis && (
+ <p className="text-xs text-tx-muted text-center">
+ {servingsLabel} {servingsLabel === 1 ? 'serving' : 'servings'} of {selected.serving_size}
+ </p>
+ )}
</div>
{/* Log to: meal + when */}
@@ -645,7 +702,8 @@ export default function LogFood() {
<div className="fixed bottom-0 inset-x-0 p-4 bg-surface-base/95 backdrop-blur-sm border-t border-surface-border safe-area-bottom">
<button
onClick={handleLog}
- disabled={save.busy}
+ // An empty or zero amount would log a row of zeroes.
+ disabled={save.busy || servings <= 0 || overLimit}
className="btn-primary btn-lg w-full"
>
{save.busy ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}