Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Stop the Log Food amount field taking a value no entry can hold (#191)
Carter86f2116d4359
diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsxindex 7dcffd6..8f76106 100644--- a/mobile/app/(tabs)/nutrition/log.tsx+++ b/mobile/app/(tabs)/nutrition/log.tsx@@ -22,7 +22,7 @@ import {} from '../../../src/components/nutrition/nutritionMeta'import { client } from '../../../src/lib/lyftr'import { useTheme } from '../../../src/theme/useTheme'-import { apiErrorMessage, entryToResult, foodResultKey, isNotFound, savedToResult, scaleServing, useFavorites, useFoodAmount } from '@lyftr/shared'+import { apiErrorMessage, entryToResult, foodResultKey, isNotFound, savedToResult, scaleServing, scaledFigures, useFavorites, useFoodAmount } from '@lyftr/shared'type Phase = 'search' | 'detail' | 'scan'type SearchTab = 'recent' | 'myfoods' | 'all'@@ -66,7 +66,7 @@ export default function LogFood() {// 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+ const { basis, servings, servingsLabel, overLimit, limitHint, 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).@@ -240,11 +240,10 @@ export default function LogFood() {return <BarcodeScanner onResult={lookUpBarcode} onClose={() => setPhase('search')} />}- const cal = selected ? Math.round(selected.calories * servings) : 0- const pro = selected ? +(selected.protein * servings).toFixed(1) : 0- const carb = selected ? +(selected.carbs * servings).toFixed(1) : 0- const fat_ = selected ? +(selected.fat * servings).toFixed(1) : 0- const fib = selected ? +((selected.fiber ?? 0) * servings).toFixed(1) : 0+ const figures = selected ? scaledFigures(selected, servings) : null+ const pro = figures?.protein ?? 0+ const carb = figures?.carbs ?? 0+ const fat_ = figures?.fat ?? 0const quickAddCals = /^\d+(\.\d+)?$/.test(query.trim()) ? Number(query.trim()) : nullreturn (@@ -478,11 +477,11 @@ export default function LogFood() {<View className="mb-5 flex-row items-end justify-between"><View><View className="flex-row items-baseline gap-1.5">- <AppText variant="display" style={{ fontSize: 44, lineHeight: 46, fontVariant: ['tabular-nums'] }}>{cal}</AppText>+ <AppText variant="display" style={{ fontSize: 44, lineHeight: 46, fontVariant: ['tabular-nums'] }}>{figures?.calories ?? '—'}</AppText><AppText variant="body" color="muted">kcal</AppText></View>{selected.serving_size ? (- <AppText variant="caption" color="muted" className="mt-1">per {servingsLabel === 1 || servings <= 0 ? '' : `${servingsLabel} × `}{selected.serving_size}</AppText>+ <AppText variant="caption" color="muted" className="mt-1">per {servingsLabel === 1 || !figures ? '' : `${servingsLabel} × `}{selected.serving_size}</AppText>) : null}</View>{pro + carb + fat_ > 0 ? (@@ -512,13 +511,13 @@ export default function LogFood() {{/* Macro grid */}<View className="flex-row gap-2">{[- { label: 'Protein', value: pro, color: MACRO_TEXT.protein, bg: 'rgba(16,185,129,0.10)', border: 'rgba(16,185,129,0.20)' },- { label: 'Carbs', value: carb, color: MACRO_TEXT.carbs, bg: 'rgba(245,158,11,0.10)', border: 'rgba(245,158,11,0.20)' },- { label: 'Fat', value: fat_, color: MACRO_TEXT.fat, bg: 'rgba(139,92,246,0.10)', border: 'rgba(139,92,246,0.20)' },- { label: 'Fiber', value: fib, color: colors.txSecondary, bg: colors.muted, border: colors.border },+ { label: 'Protein', value: figures ? `${pro}g` : '—', color: MACRO_TEXT.protein, bg: 'rgba(16,185,129,0.10)', border: 'rgba(16,185,129,0.20)' },+ { label: 'Carbs', value: figures ? `${carb}g` : '—', color: MACRO_TEXT.carbs, bg: 'rgba(245,158,11,0.10)', border: 'rgba(245,158,11,0.20)' },+ { label: 'Fat', value: figures ? `${fat_}g` : '—', color: MACRO_TEXT.fat, bg: 'rgba(139,92,246,0.10)', border: 'rgba(139,92,246,0.20)' },+ { label: 'Fiber', value: figures ? `${figures.fiber}g` : '—', color: colors.txSecondary, bg: colors.muted, border: colors.border },].map((m) => (<View key={m.label} className="flex-1 items-center rounded-xl border p-2.5" style={{ backgroundColor: m.bg, borderColor: m.border }}>- <AppText variant="bodySemibold" style={{ color: m.color, fontVariant: ['tabular-nums'] }}>{m.value}g</AppText>+ <AppText variant="bodySemibold" style={{ color: m.color, fontVariant: ['tabular-nums'] }}>{m.value}</AppText><AppText variant="caption" color="muted" style={{ fontSize: 10 }} className="mt-0.5">{m.label}</AppText></View>))}@@ -554,12 +553,12 @@ export default function LogFood() {the 0.5-serving floor made an empty or nonsense amount reachable for thefirst 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">+ {basis || servings <= 0 || limitHint ? (+ <AppText variant="caption" color={limitHint ? 'warning' : 'muted'} className="text-center">{servings <= 0? `Enter an amount${basis ? ` in ${basis.unit}` : ''} to log this`- : overLimit- ? `One entry holds at most ${maxAmount}`+ : limitHint+ ? limitHint: `${servingsLabel} ${servingsLabel === 1 ? 'serving' : 'servings'} of ${selected.serving_size}`}</AppText>) : null}diff --git a/mobile/src/components/ui/NumberField.tsx b/mobile/src/components/ui/NumberField.tsxindex c7560f4..1885cd2 100644--- a/mobile/src/components/ui/NumberField.tsx+++ b/mobile/src/components/ui/NumberField.tsx@@ -1,10 +1,12 @@+import { useReducer } from 'react'import { TextInput } from 'react-native'import { useTheme } from '../../theme/useTheme'import { sanitizeNumericInput, useNumericText } from '@lyftr/shared'interface Props {value: string- onChange: (next: string) => void+ /** Return false to refuse the keystroke: the field keeps what it showed, as a maxLength would. */+ onChange: (next: string) => unknown/** 'numeric' = integers only (reps); 'decimal' allows one decimal point (weight). */inputMode?: 'numeric' | 'decimal'placeholder?: string@@ -28,6 +30,7 @@ export function NumberField({}: Props) {const { colors } = useTheme()const [text, setText] = useNumericText(value)+ const [, resync] = useReducer((n: number) => n + 1, 0)return (<TextInputvalue={text}@@ -41,8 +44,13 @@ export function NumberField({inputAccessoryViewID={inputAccessoryViewID}onChangeText={(raw) => {const v = sanitizeNumericInput(raw, inputMode)+ if (onChange(v) === false) {+ // Nothing in state moved, so nothing would re-render and the native field could+ // keep the refused digit; a render makes it show `text` again.+ resync()+ return+ }setText(v)- onChange(v)}}// tabular-nums keeps the value from jittering as digits change (web parity).className={`w-full py-1 text-center font-display-heavy text-3xl text-tx-primary ${disabled ? 'opacity-40' : ''}`}diff --git a/packages/shared/src/hooks/useFoodAmount.ts b/packages/shared/src/hooks/useFoodAmount.tsindex ebd63bc..210b3ed 100644--- a/packages/shared/src/hooks/useFoodAmount.ts+++ b/packages/shared/src/hooks/useFoodAmount.ts@@ -8,7 +8,8 @@ import {export interface FoodAmount {/** The field's text, as typed. A buffer, so a half-typed "0." survives. */text: string- setText: (next: string) => void+ /** Type `next`. Returns false when it passed the ceiling and was not taken. */+ setText: (next: string) => boolean/** 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. */@@ -17,8 +18,8 @@ export interface FoodAmount {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+ /** Why the field is at its limit — over it, or the last keystroke was refused for passing it. */+ limitHint: string | null/** 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. */@@ -48,10 +49,12 @@ export function useFoodAmount(selected: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'> | null,): FoodAmount {const [text, setText] = useState('1')+ const [refused, setRefused] = useState(false)const openOn = useCallback((result: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'>) => {const b = servingBasis(result)setText(String(b ? b.quantity : 1))+ setRefused(false)}, [])const openOnEntry = useCallback((@@ -61,17 +64,35 @@ export function useFoodAmount(const b = servingBasis(result)const s = entryServings || 1setText(String(b ? amountForServings(s, b) : s))+ setRefused(false)}, [])const basis = selected ? servingBasis(selected) : nullconst amount = Number(text)- const servings = Number.isFinite(amount) && amount > 0- ? (basis ? servingsForAmount(amount, basis) : amount)+ const current = Number.isFinite(amount) ? amount : 0+ const ceiling = basis ? amountForServings(MAX_SERVINGS, basis) : MAX_SERVINGS+ const servingsFor = (a: number) => Number.isFinite(a) && a > 0+ ? (basis ? servingsForAmount(a, basis) : a): 0+ const servings = servingsFor(amount)++ // A keystroke that would take the field past the ceiling is not accepted, so the+ // person types up to the limit and no further, as a maxLength would. Lowering is+ // always allowed, so an entry stored above the limit before the server enforced it can+ // still be edited down rather than trapping the field. A refusal is remembered so the+ // screen can say why the digit did not land. Judged in servings, as overLimit is, so+ // the field can never take a value it then calls over the limit.+ const setAmountText = (next: string) => {+ const nextServings = servingsFor(Number(next))+ const ok = !(nextServings > MAX_SERVINGS && nextServings > servings)+ setRefused(!ok)+ if (ok) setText(next)+ return ok+ }return {text,- setText,+ setText: setAmountText,basis,servings,servingsLabel: formatServings(servings),@@ -79,11 +100,15 @@ export function useFoodAmount(// 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),+ limitHint: servings > MAX_SERVINGS || refused ? `One entry holds at most ${maxAmountFor(basis)}` : null,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)))+ // Stops at the ceiling as it stops at zero: a stepper that walks past what one+ // entry holds lands on a figure the Log button refuses. Only upward — lowering an+ // entry stored over the limit steps down from where it is, not down to the ceiling.+ const raw = current + direction * size+ setText(String(+Math.max(0, direction > 0 ? Math.min(ceiling, raw) : raw).toFixed(1)))+ setRefused(false)},// 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 arediff --git a/packages/shared/src/utils/food.test.ts b/packages/shared/src/utils/food.test.tsindex 6126c7d..42fd343 100644--- a/packages/shared/src/utils/food.test.ts+++ b/packages/shared/src/utils/food.test.ts@@ -1,4 +1,4 @@-import { amountForServings, MAX_SERVINGS, maxAmountFor, eanModules, entryToResult, findSavedFood, foodResultKey, formatBarcode, formatLoggedAmount, formatServings, isDailyStats, normaliseFoodKey, savedToResult, scaleServing, servingBasis, servingsForAmount } from './food'+import { amountForServings, MAX_SERVINGS, maxAmountFor, eanModules, entryToResult, findSavedFood, foodResultKey, formatBarcode, formatLoggedAmount, formatServings, isDailyStats, normaliseFoodKey, savedToResult, scaledFigures, scaleServing, servingBasis, servingsForAmount } from './food'import type { FoodLog, SavedFood } from '../types'const log = (over: Partial<FoodLog> = {}): FoodLog => ({@@ -271,6 +271,8 @@ describe('servingsForAmount / amountForServings', () => {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)+ // 3330 / 33.3 is 100.00000000000001 unrounded, which reads as past MAX_SERVINGS.+ expect(servingsForAmount(3330, { quantity: 33.3, unit: 'g' })).toBe(100)})it('round-trips, so opening an entry shows the amount that was logged', () => {@@ -305,6 +307,24 @@ describe('the ceiling on one entry', () => {})})+describe('scaledFigures', () => {+ const oats = { name: 'Oats', calories: 300, protein: 10, carbs: 50.55, fat: 5, fiber: 2 }++ it('scales every figure and rounds as the diary stores them', () => {+ expect(scaledFigures(oats, 1.5)).toEqual({ calories: 450, protein: 15, carbs: 75.8, fat: 7.5, fiber: 3 })+ })++ // A hero beside a disabled Log button must not show a figure nobody can log.+ it.each([0, -1, NaN])('has no figures for %o servings', (servings) => {+ expect(scaledFigures(oats, servings)).toBeNull()+ })++ it('shows the ceiling itself but nothing above it', () => {+ expect(scaledFigures(oats, MAX_SERVINGS)?.calories).toBe(30000)+ expect(scaledFigures(oats, MAX_SERVINGS + 0.1)).toBeNull()+ })+})+describe('foodResultKey', () => {// The bug: OpenFoodFacts answers "olive oil" with several products of the same name,diff --git a/packages/shared/src/utils/food.ts b/packages/shared/src/utils/food.tsindex 99602e8..53ca035 100644--- a/packages/shared/src/utils/food.ts+++ b/packages/shared/src/utils/food.ts@@ -79,7 +79,9 @@ export function servingBasis(r: Pick<FoodSearchResult, 'serving_quantity' | 'ser// 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+ // Twelve significant figures: 3330 / 33.3 is 100.00000000000001, which would read as+ // past the ceiling the field just let it reach.+ return +(amount / basis.quantity).toPrecision(12)}// Servings as a number to read, not to compute with: a third of a serving is@@ -171,6 +173,33 @@ export function maxAmountFor(basis: ServingBasis | null): string {: `${MAX_SERVINGS} servings`}+export interface ScaledFigures {+ calories: number+ protein: number+ carbs: number+ fat: number+ fiber: number+}++// What the Log Food hero shows for the amount typed, or null when no entry could be+// logged at it. An empty or nonsense field is no answer and an over-limit one is a figure+// the server will refuse, so neither gets numbers: 999999 g read 7,999,992 kcal in the+// hero beside a disabled button. The screens render null as a dash. One copy so web and+// mobile cannot scale, round or blank differently.+export function scaledFigures(+ item: Pick<FoodSearchResult, 'calories' | 'protein' | 'carbs' | 'fat' | 'fiber'>,+ servings: number,+): ScaledFigures | null {+ if (!(servings > 0) || servings > MAX_SERVINGS) return null+ return {+ calories: Math.round(item.calories * servings),+ protein: +(item.protein * servings).toFixed(1),+ carbs: +(item.carbs * servings).toFixed(1),+ fat: +(item.fat * servings).toFixed(1),+ fiber: +((item.fiber ?? 0) * servings).toFixed(1),+ }+}+// 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 putdiff --git a/web/src/hooks/useFoodAmount.test.ts b/web/src/hooks/useFoodAmount.test.tsindex 4858d21..c1005ca 100644--- a/web/src/hooks/useFoodAmount.test.ts+++ b/web/src/hooks/useFoodAmount.test.ts@@ -32,20 +32,82 @@ describe('useFoodAmount', () => {})// 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', () => {+ // The field does not take it: the keystroke that would pass the ceiling is dropped.+ it('does not accept a keystroke past what one entry holds', () => {const { result } = renderHook(() => useFoodAmount(OIL))+ act(() => result.current.setText('1000'))+ act(() => result.current.setText('10000'))+ // The ceiling itself is allowed, so the two sides cannot be out of step by one.+ expect(result.current.text).toBe('10000')+ expect(result.current.servings).toBe(100)+ expect(result.current.overLimit).toBe(false)++ // For a field that holds its own copy of the text and has to refuse the key itself.+ let landed = true+ act(() => { landed = result.current.setText('100000') })+ expect(landed).toBe(false)+ expect(result.current.text).toBe('10000')+ act(() => { landed = result.current.setText('9999') })+ expect(landed).toBe(true)++ const plain = renderHook(() => useFoodAmount(UNKNOWN))+ act(() => plain.result.current.setText('100'))+ act(() => plain.result.current.setText('1000'))+ expect(plain.result.current.text).toBe('100')+ })++ // Entries stored before the server enforced the ceiling can be over it. They open as+ // they were, say so, and can be lowered; they cannot be raised further.+ it('remembers a refusal until the next edit or step lands', () => {+ const { result } = renderHook(() => useFoodAmount(null))+ expect(result.current.limitHint).toBeNull()+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')+ expect(result.current.limitHint).toBe('One entry holds at most 100 servings')- // The ceiling itself is allowed, so the two sides cannot be out of step by one.- act(() => result.current.setText('10000'))+ act(() => result.current.setText('50'))+ expect(result.current.limitHint).toBeNull()++ act(() => result.current.setText('999999'))+ act(() => result.current.step(-1))+ expect(result.current.limitHint).toBeNull()+ })++ // 3330 / 33.3 is 100.00000000000001 in floating point; the field must not take the+ // ceiling and then call it over the limit.+ it('takes the ceiling on a serving that does not divide evenly', () => {+ const ODD = { serving_quantity: 33.3, serving_unit: 'g' as const }+ const { result } = renderHook(() => useFoodAmount(ODD))+ act(() => result.current.setText('3330'))+ expect(result.current.text).toBe('3330')expect(result.current.servings).toBe(100)expect(result.current.overLimit).toBe(false)})+ it('still holds the ceiling when the field is not a number', () => {+ const { result } = renderHook(() => useFoodAmount(OIL))+ act(() => result.current.setText('.'))+ let landed = true+ act(() => { landed = result.current.setText('999999') })+ expect(landed).toBe(false)+ expect(result.current.text).toBe('.')+ })++ it('lets an entry stored over the limit be edited down but not up', () => {+ const { result } = renderHook(() => useFoodAmount(OIL))+ act(() => result.current.openOnEntry(OIL, 5000))+ expect(result.current.text).toBe('500000')+ expect(result.current.overLimit).toBe(true)+ // OIL is held per 100 ml, so the ceiling reads as ten litres.+ expect(result.current.limitHint).toBe('One entry holds at most 10000 ml')++ act(() => result.current.setText('5000000'))+ expect(result.current.text).toBe('500000')+ act(() => result.current.setText('50000'))+ expect(result.current.text).toBe('50000')+ })+it('counts servings when nothing knows what one measures', () => {const { result } = renderHook(() => useFoodAmount(UNKNOWN))act(() => result.current.openOn(UNKNOWN))@@ -76,6 +138,32 @@ describe('useFoodAmount', () => {expect(result.current.text).toBe('0')})+ // Past the ceiling the Log button refuses, so the stepper stops there as it does at zero.+ it('stops stepping at the most one entry holds', () => {+ const { result } = renderHook(() => useFoodAmount(TBSP))+ act(() => result.current.setText('1485'))+ act(() => result.current.step(1))+ expect(result.current.text).toBe('1500')+ expect(result.current.overLimit).toBe(false)+ act(() => result.current.step(1))+ expect(result.current.text).toBe('1500')++ // From beyond it, a step up brings the field back to the ceiling rather than past it.+ act(() => result.current.openOnEntry(TBSP, 5000))+ act(() => result.current.step(1))+ expect(result.current.text).toBe('1500')++ // A step down lowers it by one serving from where it was, not down to the ceiling.+ act(() => result.current.openOnEntry(TBSP, 5000))+ act(() => result.current.step(-1))+ expect(result.current.text).toBe('74985')++ const plain = renderHook(() => useFoodAmount(UNKNOWN))+ act(() => plain.result.current.setText('100'))+ act(() => plain.result.current.step(1))+ expect(plain.result.current.text).toBe('100')+ })+it('steps by half a serving when that is all the field counts', () => {const { result } = renderHook(() => useFoodAmount(UNKNOWN))act(() => result.current.step(1))diff --git a/web/src/pages/LogFood.test.tsx b/web/src/pages/LogFood.test.tsxindex 9cf242f..0d9a28c 100644--- a/web/src/pages/LogFood.test.tsx+++ b/web/src/pages/LogFood.test.tsx@@ -202,8 +202,9 @@ describe('Logging an amount', () => {})// 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 () => {+ // the day and the server stored it, because neither side had a ceiling. The field now+ // refuses the keystroke rather than showing a figure nobody can log.+ it('does not take an amount larger than one entry can hold', async () => {search.mockResolvedValue([OIL_SEARCH_HIT])barcode.mockResolvedValue(OIL_PRODUCT)renderPage()@@ -212,16 +213,19 @@ describe('Logging an amount', () => {fireEvent.click(await screen.findByText('Olive Oil'))const amount = await screen.findByLabelText('Amount in ml') as HTMLInputElement+ expect(amount.value).toBe('15')+ // A hundred servings of a 15 ml tablespoon is the most one entry holds.fireEvent.change(amount, { target: { value: '999999' } })+ expect(amount.value).toBe('15')+ expect(logButton().disabled).toBe(false)+ // The digit not landing says why, where the person is looking.+ expect(screen.getByRole('status').textContent).toMatch(/One entry holds at most/)- 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.+ // And the limit itself still logs, with the reason gone once an edit lands.fireEvent.change(amount, { target: { value: '1500' } })+ expect(amount.value).toBe('1500')expect(logButton().disabled).toBe(false)+ expect(screen.queryByText(/One entry holds at most/)).toBeNull()})// The search index answers with per-100g figures and no serving at all, so a hit isdiff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsxindex 56cb986..667762c 100644--- a/web/src/pages/LogFood.tsx+++ b/web/src/pages/LogFood.tsx@@ -6,7 +6,7 @@ import {Coffee, Sun, Moon, Cookie, ChevronRight, Loader2,} from 'lucide-react'import { foodAPI, savedFoodsAPI } from '../services/api'-import { apiErrorMessage, isNotFound, useAsyncAction, todayStr, dayToInstant, entryDay, foodResultKey, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, useFavorites, useFoodAmount } from '@lyftr/shared'+import { apiErrorMessage, isNotFound, useAsyncAction, todayStr, dayToInstant, entryDay, foodResultKey, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, scaledFigures, useFavorites, useFoodAmount } from '@lyftr/shared'import { ErrorState, ListError, Toast } from '../components/ui'import BarcodeScanner from '../components/BarcodeScanner'import BarcodeLookup from '../components/BarcodeLookup'@@ -132,7 +132,7 @@ export default function LogFood() {// 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+ const { basis, servings, servingsLabel, overLimit, limitHint, 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).@@ -288,11 +288,10 @@ export default function LogFood() {)}- const cal = selected ? Math.round(selected.calories * servings) : 0- const pro = selected ? +(selected.protein * servings).toFixed(1) : 0- const carb = selected ? +(selected.carbs * servings).toFixed(1) : 0- const fat_ = selected ? +(selected.fat * servings).toFixed(1) : 0- const fib = selected ? +((selected.fiber ?? 0) * servings).toFixed(1) : 0+ const figures = selected ? scaledFigures(selected, servings) : null+ const pro = figures?.protein ?? 0+ const carb = figures?.carbs ?? 0+ const fat_ = figures?.fat ?? 0const quickAddCals = /^\d+(\.\d+)?$/.test(query.trim()) ? Number(query.trim()) : nullreturn (@@ -549,7 +548,7 @@ export default function LogFood() {<div className="flex items-end justify-between mb-5"><div><div className="flex items-baseline gap-1.5">- <span className="text-5xl font-bold tabular-nums text-tx-primary leading-none">{cal}</span>+ <span className="text-5xl font-bold tabular-nums text-tx-primary leading-none">{figures?.calories ?? '—'}</span><span className="text-sm text-tx-muted">kcal</span></div>{selected.serving_size && (@@ -557,7 +556,7 @@ export default function LogFood() {{/* The label comes from OpenFoodFacts, which is free text — and rowslogged before the backend stopped prefixing it still read "per100g". Supplying a second "per" gave "per per 100g". */}- per {servingsLabel === 1 || servings <= 0 ? '' : `${servingsLabel} × `}+ per {servingsLabel === 1 || !figures ? '' : `${servingsLabel} × `}{selected.serving_size.replace(/^per\s+/i, '')}</p>)}@@ -589,13 +588,13 @@ export default function LogFood() {{/* Macro grid */}<div className="grid grid-cols-4 gap-2">{[- { label: 'Protein', value: pro, color: 'text-emerald-400', bg: 'bg-emerald-500/10 border-emerald-500/20' },- { label: 'Carbs', value: carb, color: 'text-amber-400', bg: 'bg-amber-500/10 border-amber-500/20' },- { label: 'Fat', value: fat_, color: 'text-violet-400', bg: 'bg-violet-500/10 border-violet-500/20' },- { label: 'Fiber', value: fib, color: 'text-tx-secondary', bg: 'bg-surface-muted border-surface-border' },+ { label: 'Protein', value: figures ? `${pro}g` : '—', color: 'text-emerald-400', bg: 'bg-emerald-500/10 border-emerald-500/20' },+ { label: 'Carbs', value: figures ? `${carb}g` : '—', color: 'text-amber-400', bg: 'bg-amber-500/10 border-amber-500/20' },+ { label: 'Fat', value: figures ? `${fat_}g` : '—', color: 'text-violet-400', bg: 'bg-violet-500/10 border-violet-500/20' },+ { label: 'Fiber', value: figures ? `${figures.fiber}g` : '—', color: 'text-tx-secondary', bg: 'bg-surface-muted border-surface-border' },].map(m => (<div key={m.label} className={`rounded-xl border p-2.5 text-center ${m.bg}`}>- <p className={`text-sm font-bold tabular-nums ${m.color}`}>{m.value}g</p>+ <p className={`text-sm font-bold tabular-nums ${m.color}`}>{m.value}</p><p className="text-[10px] text-tx-muted mt-0.5">{m.label}</p></div>))}@@ -643,10 +642,8 @@ export default function LogFood() {<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>+ ) : limitHint ? (+ <p className="text-xs text-warning-400 text-center" role="status">{limitHint}</p>) : basis && (<p className="text-xs text-tx-muted text-center">{servingsLabel} {servingsLabel === 1 ? 'serving' : 'servings'} of {selected.serving_size}