From 877f7332994be02efd25424c35a3c34800ac95f6 Mon Sep 17 00:00:00 2001 From: Timothy Oluwatobi Ojebiyi Date: Fri, 6 Nov 2026 19:10:36 +0000 Subject: [PATCH 1/9] Phase 7 in progress: food database schema, local search and nutrients - Migration for GRIT's food tables (foods, barcodes, servings, nutrients, names, sources) with a trigram search index, nutrient snapshots on food logs, and food links on remembered and favourite foods - Food search from GRIT's own data first, barcodes looked up locally (UPC-E aware) and saved when found live, Smart log matched to measured foods, and a fix for alcohol's calories in estimates - Nutrients by day and week against US Dietary Reference Intakes, a coach line and a 'running low' check-in - App: serving picker, Verified labels, Nutrients screen, often-low card and a food data sources screen - Start of the importer package (writer and shared record code) --- .../__tests__/notificationRoute.test.ts | 2 + apps/mobile/__tests__/nutrients.test.ts | 119 +++ apps/mobile/__tests__/quickFoods.test.ts | 31 +- apps/mobile/__tests__/servings.test.ts | 110 +++ apps/mobile/app/(tabs)/activity.tsx | 6 +- apps/mobile/app/(tabs)/food.tsx | 15 +- apps/mobile/app/(tabs)/profile.tsx | 1 + apps/mobile/app/barcode-scanner.tsx | 15 +- apps/mobile/app/nutrients.tsx | 151 ++++ apps/mobile/app/settings/food-sources.tsx | 41 + apps/mobile/components/food/FoodSearchBar.tsx | 148 ++-- apps/mobile/components/food/LogFoodSheet.tsx | 134 ++- apps/mobile/components/food/SmartLogSheet.tsx | 9 +- apps/mobile/components/food/VerifiedPill.tsx | 12 + .../components/stats/LowNutrientsCard.tsx | 47 + apps/mobile/hooks/useFoodLog.ts | 77 +- apps/mobile/hooks/useMe.ts | 3 + apps/mobile/hooks/useNutrients.ts | 21 + apps/mobile/hooks/useQuickFoods.ts | 10 +- apps/mobile/hooks/useSmartLog.ts | 16 +- apps/mobile/lib/foodSources.ts | 69 ++ apps/mobile/lib/notificationRoute.ts | 2 + apps/mobile/lib/nutrients.ts | 181 ++++ apps/mobile/lib/quickFoods.ts | 36 + apps/mobile/lib/searchEvents.ts | 13 +- apps/mobile/lib/servings.ts | 131 +++ .../migration.sql | 150 ++++ packages/backend/prisma/schema.prisma | 161 +++- packages/backend/src/ai/ai.service.ts | 54 +- .../backend/src/ai/coach-memory.db-spec.ts | 93 ++ packages/backend/src/alerts/alerts.db-spec.ts | 110 +++ packages/backend/src/alerts/alerts.service.ts | 52 +- .../backend/src/alerts/coach-checkins.spec.ts | 210 ++++- packages/backend/src/alerts/coach-checkins.ts | 151 +++- packages/backend/src/app.module.ts | 2 + packages/backend/src/common/dri.spec.ts | 63 ++ packages/backend/src/common/dri.ts | 123 +++ .../src/food/__fixtures__/off-products.json | 817 ++++++++++++++++++ packages/backend/src/food/food-data.spec.ts | 291 +++++++ packages/backend/src/food/food-db.db-spec.ts | 420 +++++++++ packages/backend/src/food/food-db.service.ts | 460 ++++++++++ packages/backend/src/food/food-record.ts | 208 +++++ packages/backend/src/food/food-text.ts | 109 +++ packages/backend/src/food/food.controller.ts | 31 +- packages/backend/src/food/food.dto.ts | 63 +- packages/backend/src/food/food.module.ts | 5 +- .../backend/src/food/food.service.spec.ts | 139 ++- packages/backend/src/food/food.service.ts | 256 +++++- packages/backend/src/food/food.types.ts | 22 +- packages/backend/src/food/nutrients.ts | 292 +++++++ packages/backend/src/food/off-product.ts | 493 +++++++++++ .../backend/src/food/quick-foods.service.ts | 11 + packages/backend/src/food/quick-foods.spec.ts | 5 + packages/backend/src/food/quick-foods.ts | 5 + .../src/meal-parse/meal-parse.db-spec.ts | 124 ++- .../backend/src/meal-parse/meal-parse.dto.ts | 12 + .../src/meal-parse/meal-parse.service.ts | 137 ++- .../backend/src/meal-parse/meal-parse.spec.ts | 70 +- packages/backend/src/meal-parse/meal-parse.ts | 65 +- .../src/nutrients/nutrient-days.spec.ts | 369 ++++++++ .../backend/src/nutrients/nutrient-days.ts | 315 +++++++ .../src/nutrients/nutrients.controller.ts | 39 + .../src/nutrients/nutrients.db-spec.ts | 414 +++++++++ .../backend/src/nutrients/nutrients.module.ts | 9 + .../src/nutrients/nutrients.service.ts | 135 +++ packages/food-data/.gitignore | 2 + packages/food-data/.prettierrc | 4 + packages/food-data/eslint.config.mjs | 35 + packages/food-data/jest-db.json | 8 + packages/food-data/jest.config.json | 7 + packages/food-data/package.json | 30 + packages/food-data/src/archive.ts | 117 +++ packages/food-data/src/csv.ts | 66 ++ packages/food-data/src/db.ts | 39 + packages/food-data/src/download.ts | 100 +++ packages/food-data/src/record.ts | 3 + packages/food-data/src/sources/fdc.ts | 750 ++++++++++++++++ packages/food-data/src/writer.db-spec.ts | 227 +++++ packages/food-data/src/writer.ts | 392 +++++++++ packages/food-data/tsconfig.json | 15 + 80 files changed, 9488 insertions(+), 192 deletions(-) create mode 100644 apps/mobile/__tests__/nutrients.test.ts create mode 100644 apps/mobile/__tests__/servings.test.ts create mode 100644 apps/mobile/app/nutrients.tsx create mode 100644 apps/mobile/app/settings/food-sources.tsx create mode 100644 apps/mobile/components/food/VerifiedPill.tsx create mode 100644 apps/mobile/components/stats/LowNutrientsCard.tsx create mode 100644 apps/mobile/hooks/useNutrients.ts create mode 100644 apps/mobile/lib/foodSources.ts create mode 100644 apps/mobile/lib/nutrients.ts create mode 100644 apps/mobile/lib/servings.ts create mode 100644 packages/backend/prisma/migrations/20261109120000_phase7_food_database/migration.sql create mode 100644 packages/backend/src/common/dri.spec.ts create mode 100644 packages/backend/src/common/dri.ts create mode 100644 packages/backend/src/food/__fixtures__/off-products.json create mode 100644 packages/backend/src/food/food-data.spec.ts create mode 100644 packages/backend/src/food/food-db.db-spec.ts create mode 100644 packages/backend/src/food/food-db.service.ts create mode 100644 packages/backend/src/food/food-record.ts create mode 100644 packages/backend/src/food/food-text.ts create mode 100644 packages/backend/src/food/nutrients.ts create mode 100644 packages/backend/src/food/off-product.ts create mode 100644 packages/backend/src/nutrients/nutrient-days.spec.ts create mode 100644 packages/backend/src/nutrients/nutrient-days.ts create mode 100644 packages/backend/src/nutrients/nutrients.controller.ts create mode 100644 packages/backend/src/nutrients/nutrients.db-spec.ts create mode 100644 packages/backend/src/nutrients/nutrients.module.ts create mode 100644 packages/backend/src/nutrients/nutrients.service.ts create mode 100644 packages/food-data/.gitignore create mode 100644 packages/food-data/.prettierrc create mode 100644 packages/food-data/eslint.config.mjs create mode 100644 packages/food-data/jest-db.json create mode 100644 packages/food-data/jest.config.json create mode 100644 packages/food-data/package.json create mode 100644 packages/food-data/src/archive.ts create mode 100644 packages/food-data/src/csv.ts create mode 100644 packages/food-data/src/db.ts create mode 100644 packages/food-data/src/download.ts create mode 100644 packages/food-data/src/record.ts create mode 100644 packages/food-data/src/sources/fdc.ts create mode 100644 packages/food-data/src/writer.db-spec.ts create mode 100644 packages/food-data/src/writer.ts create mode 100644 packages/food-data/tsconfig.json diff --git a/apps/mobile/__tests__/notificationRoute.test.ts b/apps/mobile/__tests__/notificationRoute.test.ts index 142edec..9e9c333 100644 --- a/apps/mobile/__tests__/notificationRoute.test.ts +++ b/apps/mobile/__tests__/notificationRoute.test.ts @@ -10,6 +10,8 @@ describe('where an alert opens', () => { expect(notificationRoute('coach_checkin', { screen: 'food' })).toBe('/(tabs)/food'); expect(notificationRoute('coach_checkin', { screen: 'stats' })).toBe('/(tabs)/activity'); expect(notificationRoute('coach_checkin', {})).toBe('/coach'); + expect(notificationRoute('coach_checkin', { screen: 'food', rule: 'nutrient_low', nutrient: 'iron_mg' })).toBe('/nutrients'); + expect(notificationRoute('coach_checkin', { screen: 'food', rule: 'nutrient_low', nutrient: '' })).toBe('/(tabs)/food'); }); it('falls back to the inbox when ids are missing or the type is unknown', () => { expect(notificationRoute('follow')).toBe('/notifications'); diff --git a/apps/mobile/__tests__/nutrients.test.ts b/apps/mobile/__tests__/nutrients.test.ts new file mode 100644 index 0000000..4647028 --- /dev/null +++ b/apps/mobile/__tests__/nutrients.test.ts @@ -0,0 +1,119 @@ +import { + amountText, barFraction, barTone, coverageNote, formatAmount, lowDaysText, nutrientA11yLabel, nutrientSections, + percentText, sourcesLine, statusTag, type DayNutrient, +} from '@/lib/nutrients'; + +const nutrient = (over: Partial): DayNutrient => ({ + code: 'iron_mg', name: 'Iron', unit: 'mg', group: 'mineral', kind: 'target', + amount: 9.4, target: 18, percent: 52, coverage: 0.8, status: 'low', sources: [], + ...over, +}); + +describe('nutrient amounts', () => { + it('rounds to a sensible precision', () => { + expect(formatAmount(1840.4)).toBe('1,840'); + expect(formatAmount(18)).toBe('18'); + expect(formatAmount(12.6)).toBe('13'); + expect(formatAmount(9.44)).toBe('9.4'); + expect(formatAmount(0.354)).toBe('0.35'); + expect(formatAmount(0)).toBe('0'); + expect(formatAmount(-1)).toBe('0'); + }); + it('shows amount against target or limit', () => { + expect(amountText(nutrient({}))).toBe('9.4 / 18 mg'); + expect(amountText(nutrient({ code: 'sodium_mg', kind: 'limit', amount: 1840, target: 2300 }))).toBe('1,840 / 2,300 mg max'); + expect(amountText(nutrient({ unit: 'µg', amount: 2.4, target: null }))).toBe('2.4 µg'); + }); + it('shows percent and fills the bar up to full', () => { + expect(percentText(52)).toBe('52%'); + expect(percentText(null)).toBe(''); + expect(barFraction(52)).toBeCloseTo(0.52); + expect(barFraction(140)).toBe(1); + expect(barFraction(null)).toBe(0); + }); +}); + +describe('nutrient status', () => { + it('only calls a nutrient low or over when the server judged it', () => { + expect(statusTag('low')).toEqual({ text: 'Low', tone: 'orange' }); + expect(statusTag('over')).toEqual({ text: 'Over the limit', tone: 'error' }); + expect(statusTag('ok')).toBeNull(); + expect(statusTag(null)).toEqual({ text: 'not enough data', tone: 'muted' }); + }); + it('colours the bar by status, grey without data', () => { + expect(barTone('low')).toBe('orange'); + expect(barTone('ok')).toBe('teal'); + expect(barTone('over')).toBe('error'); + expect(barTone(null)).toBe('muted'); + }); + it('tags nothing but a passed limit while today is in progress', () => { + expect(statusTag(null, true)).toBeNull(); + expect(statusTag('over', true)).toEqual({ text: 'Over the limit', tone: 'error' }); + expect(barTone(null, true)).toBe('blue'); + expect(barTone('over', true)).toBe('error'); + expect(nutrientA11yLabel(nutrient({ status: null }), true)).toBe('Iron: 9.4 of 18 mg, 52%'); + expect(nutrientA11yLabel(nutrient({ status: null }))).toBe('Iron: 9.4 of 18 mg, 52%, not enough data'); + }); + it('reads out for screen readers', () => { + expect(nutrientA11yLabel(nutrient({}))).toBe('Iron: 9.4 of 18 mg, 52%, low'); + expect(nutrientA11yLabel(nutrient({ status: 'ok', percent: 110, amount: 19.8 }))).toBe('Iron: 20 of 18 mg, 110%'); + }); + it('never uses diagnostic words', () => { + const words = [statusTag('low'), statusTag('over'), statusTag(null)].map((t) => t?.text ?? '').join(' '); + expect(words).not.toMatch(/deficien/i); + }); +}); + +describe('good sources', () => { + const sources = [{ name: 'Spinach, raw', amount: 2.7 }, { name: 'Tea', amount: 0.1 }]; + it('lists foods giving a good share of a target', () => { + expect(sourcesLine(nutrient({ sources }), true)).toBe('Good sources today: Spinach, raw (2.7 mg)'); + expect(sourcesLine(nutrient({ sources }), false)).toBe('Good sources: Spinach, raw (2.7 mg)'); + expect(sourcesLine(nutrient({ sources: [{ name: 'Tea', amount: 0.1 }] }), true)).toBeNull(); + expect(sourcesLine(nutrient({ sources: [] }), true)).toBeNull(); + }); + it('says where a limit came from only when over it', () => { + const sodium = nutrient({ code: 'sodium_mg', name: 'Sodium', group: 'energy', kind: 'limit', sources: [{ name: 'Bacon', amount: 800 }] }); + expect(sourcesLine({ ...sodium, status: 'over' }, true)).toBe('Mostly from: Bacon (800 mg)'); + expect(sourcesLine({ ...sodium, status: 'ok' }, true)).toBeNull(); + }); +}); + +describe('sections', () => { + it('groups vitamins, minerals, then fibre, sodium and saturated fat', () => { + const all = [ + nutrient({ code: 'kcal', name: 'Energy', group: 'energy', kind: 'none' }), + nutrient({ code: 'sat_fat_g', name: 'Saturated fat', group: 'energy', kind: 'limit' }), + nutrient({ code: 'fibre_g', name: 'Fibre', group: 'energy', kind: 'target' }), + nutrient({ code: 'sodium_mg', name: 'Sodium', group: 'energy', kind: 'limit' }), + nutrient({ code: 'vit_c_mg', name: 'Vitamin C', group: 'vitamin' }), + nutrient({ code: 'iron_mg', name: 'Iron', group: 'mineral' }), + nutrient({ code: 'caffeine_mg', name: 'Caffeine', group: 'other', kind: 'none' }), + ]; + expect(nutrientSections(all).map((s) => [s.title, s.items.map((n) => n.name)])).toEqual([ + ['Vitamins', ['Vitamin C']], + ['Minerals', ['Iron']], + ['Fibre, sodium and saturated fat', ['Fibre', 'Sodium', 'Saturated fat']], + ]); + expect(nutrientSections([nutrient({})]).map((s) => s.title)).toEqual(['Minerals']); + }); +}); + +describe('coverage note', () => { + const today = '2026-11-06'; + const yesterday = '2026-11-05'; + it("says how much of the day's calories it's based on", () => { + expect(coverageNote(0.64, today, today, yesterday)).toBe("Based on 64% of today's calories"); + expect(coverageNote(0.5, yesterday, today, yesterday)).toBe("Based on 50% of yesterday's calories"); + expect(coverageNote(0.5, '2026-11-01', today, yesterday)).toBe("Based on 50% of the day's calories"); + expect(coverageNote(0.002, today, today, yesterday)).toBe("Based on 1% of today's calories"); + expect(coverageNote(1, today, today, yesterday)).toBe("Based on all of today's calories"); + }); +}); + +describe('often low', () => { + it('counts the low days', () => { + expect(lowDaysText({ lowDays: 4, days: 4 })).toBe('low on 4 of 4 days'); + expect(lowDaysText({ lowDays: 1, days: 1 })).toBe('low on 1 of 1 day'); + }); +}); diff --git a/apps/mobile/__tests__/quickFoods.test.ts b/apps/mobile/__tests__/quickFoods.test.ts index 7f63a07..3e73862 100644 --- a/apps/mobile/__tests__/quickFoods.test.ts +++ b/apps/mobile/__tests__/quickFoods.test.ts @@ -1,4 +1,4 @@ -import { foodKey, portionAsFood, portionLabel } from '@/lib/quickFoods'; +import { favoriteBody, foodKey, portionAsFood, portionGrams, portionLabel } from '@/lib/quickFoods'; describe('quick foods', () => { it('matches the server key', () => { @@ -13,5 +13,34 @@ describe('quick foods', () => { it('turns a saved portion into a loggable food', () => { const food = portionAsFood({ name: 'Oats', brand: null, barcode: null, calories: 300, proteinG: 10, carbsG: 50, fatG: 6, servingQty: 80, servingUnit: 'g' }); expect(food).toMatchObject({ portion: true, offId: '', calories: 300, servingQty: 80 }); + expect(food.foodId).toBeUndefined(); + expect(food.portionGrams).toBeUndefined(); + }); + it("keeps a database food's id and grams", () => { + const food = portionAsFood({ name: 'Bread', brand: null, barcode: null, calories: 148, proteinG: 5.6, carbsG: 24, fatG: 1.9, servingQty: 56, servingUnit: 'g', foodId: 'f1', grams: 56 }); + expect(food).toMatchObject({ portion: true, foodId: 'f1', portionGrams: 56 }); + }); + it('scales grams by the number of portions', () => { + expect(portionGrams(56, 2)).toBe(112); + expect(portionGrams(28, 1.5)).toBe(42); + expect(portionGrams(33.3, 3)).toBe(99.9); + expect(portionGrams(null, 2)).toBeUndefined(); + expect(portionGrams(undefined, 2)).toBeUndefined(); + expect(portionGrams(0, 2)).toBeUndefined(); + }); + it('sends only the fields a favourite takes', () => { + const recent = { + name: 'Bread', brand: null, barcode: '5000000000001', calories: 148, proteinG: 5.6, carbsG: 24, fatG: 1.9, + servingQty: 56, servingUnit: 'g', foodId: 'f1', grams: 56, + key: 'bread|', timesLogged: 3, lastMealType: 'lunch', lastLoggedAt: '2026-11-05T12:00:00Z', favoriteId: null, + }; + expect(favoriteBody(recent)).toEqual({ + name: 'Bread', brand: undefined, barcode: '5000000000001', calories: 148, proteinG: 5.6, carbsG: 24, fatG: 1.9, + servingQty: 56, servingUnit: 'g', foodId: 'f1', grams: 56, + }); + const manual = favoriteBody({ ...recent, foodId: null, grams: null }); + expect(manual.foodId).toBeUndefined(); + expect(manual.grams).toBeUndefined(); + expect(favoriteBody({ ...recent, grams: 6000 }).grams).toBeUndefined(); }); }); diff --git a/apps/mobile/__tests__/servings.test.ts b/apps/mobile/__tests__/servings.test.ts new file mode 100644 index 0000000..42b6810 --- /dev/null +++ b/apps/mobile/__tests__/servings.test.ts @@ -0,0 +1,110 @@ +import { + amountEaten, defaultOption, defaultServing, foodUnit, kcalIn, parseQty, qtyAfterSwitch, scalePer100, searchServing, + servingLabel, servingLog, servingOptions, +} from '@/lib/servings'; + +// Wholemeal bread, per 100 g +const bread = { + calories: 265, proteinG: 10, carbsG: 43, fatG: 3.4, + servingQty: 28, servingUnit: 'g', + servings: [ + { label: '1 slice', grams: 28, typical: true }, + { label: '1 thick slice', grams: 44, typical: false }, + ], +}; + +describe('serving labels', () => { + it('shows the grams in brackets', () => { + expect(servingLabel({ label: '1 slice', grams: 28 })).toBe('1 slice (28 g)'); + expect(servingLabel({ label: '1 cup, chopped', grams: 160.4 })).toBe('1 cup, chopped (160 g)'); + expect(servingLabel({ label: '1 tsp', grams: 4.2 })).toBe('1 tsp (4.2 g)'); + expect(servingLabel({ label: '1 can', grams: 330 }, 'ml')).toBe('1 can (330 ml)'); + }); + it('treats only ml as millilitres', () => { + expect(foodUnit({ servingUnit: 'ml' })).toBe('ml'); + expect(foodUnit({ servingUnit: 'g' })).toBe('g'); + expect(foodUnit({ servingUnit: 'serving' })).toBe('g'); + }); +}); + +describe('serving options', () => { + it("lists the food's servings, then 100 g, then grams", () => { + expect(servingOptions(bread).map((o) => o.label)).toEqual(['1 slice (28 g)', '1 thick slice (44 g)', '100 g', 'Grams']); + const direct = servingOptions(bread).at(-1)!; + expect(direct).toMatchObject({ direct: true, grams: 1 }); + }); + it('drops servings with no grams or label', () => { + const food = { ...bread, servings: [{ label: '', grams: 30, typical: false }, { label: '1 pot', grams: 0, typical: true }] }; + expect(servingOptions(food).map((o) => o.key)).toEqual(['serving', '100', 'direct']); + }); + it('offers a plain serving size when there are no named servings', () => { + expect(servingOptions({ servingQty: 30, servingUnit: 'g' }).map((o) => o.label)).toEqual(['1 serving (30 g)', '100 g', 'Grams']); + expect(servingOptions({ servingQty: 100, servingUnit: 'ml' }).map((o) => o.label)).toEqual(['100 ml', 'Millilitres']); + }); +}); + +describe('default serving', () => { + it('starts on the typical serving', () => { + const food = { ...bread, servings: [bread.servings[1], bread.servings[0]] }; + expect(defaultOption(food).label).toBe('1 slice (28 g)'); + }); + it('else on the first serving', () => { + const food = { ...bread, servings: bread.servings.map((s) => ({ ...s, typical: false })) }; + expect(defaultOption(food).label).toBe('1 slice (28 g)'); + }); + it("else on the food's serving size, or 100 g", () => { + expect(defaultOption({ servingQty: 30, servingUnit: 'g' }).label).toBe('1 serving (30 g)'); + expect(defaultOption({ servingQty: 100, servingUnit: 'g' }).label).toBe('100 g'); + expect(defaultOption({ servingQty: 0, servingUnit: 'g' }).label).toBe('100 g'); + expect(defaultServing({ servingQty: 100, servingUnit: 'g' })).toBeNull(); + }); +}); + +describe('search rows', () => { + it('show the typical serving and its kcal', () => { + expect(searchServing(bread)).toEqual({ serving: '1 slice (28 g)', kcal: 74 }); + }); + it('show kcal per 100 g without a serving', () => { + expect(searchServing({ calories: 89.4, servingQty: 100, servingUnit: 'g' })).toEqual({ serving: null, kcal: 89 }); + }); +}); + +describe('serving maths', () => { + it('multiplies servings by the serving grams', () => { + const slice = defaultOption(bread); + expect(amountEaten(2, slice)).toBe(56); + expect(amountEaten(-1, slice)).toBe(0); + expect(amountEaten(45, { grams: 1 })).toBe(45); + }); + it('scales per-100 g values to the grams eaten', () => { + const per = scalePer100({ ...bread, caffeineMg: 10, alcoholG: 1.25 }, 56); + expect(per.calories).toBeCloseTo(148.4); + expect(per.proteinG).toBeCloseTo(5.6); + expect(per.carbsG).toBeCloseTo(24.08); + expect(per.fatG).toBeCloseTo(1.904); + expect(per.caffeineMg).toBe(6); + expect(per.alcoholG).toBe(0.7); + expect(scalePer100(bread, 50).caffeineMg).toBeUndefined(); + expect(kcalIn(bread, 28)).toBe(74); + }); + it('logs a number of servings as grams', () => { + const [slice, , hundred, direct] = servingOptions(bread); + expect(servingLog(bread, slice, '2')).toMatchObject({ grams: 56 }); + expect(servingLog(bread, slice, '2').calories).toBeCloseTo(148.4); + expect(servingLog(bread, hundred, '1.5').grams).toBe(150); + expect(servingLog(bread, direct, '45').grams).toBe(45); + expect(servingLog(bread, direct, '45').calories).toBeCloseTo(119.25); + }); + it('reads the amount field', () => { + expect(parseQty('1.5', false)).toBe(1.5); + expect(parseQty('1,5', false)).toBe(1.5); + expect(parseQty('', false)).toBe(1); + expect(parseQty('', true)).toBe(0); + expect(parseQty('-3', true)).toBe(0); + }); + it('keeps the grams when switching to typing grams, and starts a serving at 1', () => { + expect(qtyAfterSwitch({ direct: true }, 56)).toBe('56'); + expect(qtyAfterSwitch({ direct: true }, 42.04)).toBe('42'); + expect(qtyAfterSwitch({}, 56)).toBe('1'); + }); +}); diff --git a/apps/mobile/app/(tabs)/activity.tsx b/apps/mobile/app/(tabs)/activity.tsx index 67533cf..82e840a 100644 --- a/apps/mobile/app/(tabs)/activity.tsx +++ b/apps/mobile/app/(tabs)/activity.tsx @@ -19,6 +19,7 @@ import { ACTIVITY_LABELS, LogActivitySheet } from '@/components/activity/LogActi import { DateNavigator } from '@/components/ui/DateNavigator'; import { TrendsCard } from '@/components/stats/TrendsCard'; import { AdaptiveCard } from '@/components/stats/AdaptiveCard'; +import { LowNutrientsCard } from '@/components/stats/LowNutrientsCard'; import { LogWeightSheet } from '@/components/stats/LogWeightSheet'; import { usePullToRefresh } from '@/hooks/usePullToRefresh'; import { Colors } from '@/constants/colors'; @@ -129,7 +130,7 @@ export default function ActivityScreen() { const { data: habitSummary } = useHabitSummary(); const [showSheet, setShowSheet] = useState(false); const [showWeight, setShowWeight] = useState(false); - const { refreshing, onRefresh } = usePullToRefresh([['activity-week'], ['food-week'], ['me'], ['habits'], ['habit-streaks'], ['trends'], ['weight'], ['adaptive']]); + const { refreshing, onRefresh } = usePullToRefresh([['activity-week'], ['food-week'], ['me'], ['habits'], ['habit-streaks'], ['trends'], ['weight'], ['adaptive'], ['nutrients-week']]); useFocusEffect( React.useCallback(() => { @@ -255,6 +256,9 @@ export default function ActivityScreen() { + {/* Vitamins and minerals low on most days of this week (hidden if none) */} + + {/* Activity bar chart */} diff --git a/apps/mobile/app/(tabs)/food.tsx b/apps/mobile/app/(tabs)/food.tsx index a03f094..38a1bba 100644 --- a/apps/mobile/app/(tabs)/food.tsx +++ b/apps/mobile/app/(tabs)/food.tsx @@ -105,7 +105,7 @@ export default function FoodScreen() { const status = useQueriesStatus(foodQuery); const { mutate: deleteLog } = useDeleteFoodLog(); const { data: me } = useMe(); - const { refreshing, onRefresh } = usePullToRefresh([['food-logs', date], ['me'], ['food-recent'], ['food-favorites']]); + const { refreshing, onRefresh } = usePullToRefresh([['food-logs', date], ['me'], ['food-recent'], ['food-favorites'], ['nutrients-day', date]]); const [editingLog, setEditingLog] = useState(null); const [smartOpen, setSmartOpen] = useState(false); const ensureAiConsent = useEnsureAiConsent(); @@ -198,7 +198,7 @@ export default function FoodScreen() { Smart log router.push('/barcode-scanner' as never)} + onPress={() => router.push({ pathname: '/barcode-scanner', params: { date } })} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1, width: 40, height: 40, borderRadius: 12, @@ -268,6 +268,17 @@ export default function FoodScreen() { {alcoholG > 0 ? `🍷 ${alcoholG} g alcohol` : ''} )} + {/* Vitamins, minerals, fibre, sodium and saturated fat for this day */} + router.push({ pathname: '/nutrients', params: { date } })} + accessibilityRole="button" + accessibilityLabel="Nutrients" + accessibilityHint="Vitamins, minerals and fibre for this day" + hitSlop={8} + style={({ pressed }) => ({ alignSelf: 'flex-start', marginTop: 2, opacity: pressed ? 0.6 : 1 })} + > + Nutrients › + diff --git a/apps/mobile/app/(tabs)/profile.tsx b/apps/mobile/app/(tabs)/profile.tsx index f98a030..dc2954d 100644 --- a/apps/mobile/app/(tabs)/profile.tsx +++ b/apps/mobile/app/(tabs)/profile.tsx @@ -147,6 +147,7 @@ const SETTINGS_ROWS = [ { icon: '❤️', color: 'error' as const, label: Platform.OS === 'android' ? 'Health Connect' : Platform.OS === 'ios' ? 'Apple Health' : 'Health data', sub: 'Sync workouts, steps, sleep and weight', href: '/settings/health' as const }, { icon: '🧠', color: 'teal' as const, label: 'What your coach knows', sub: 'Notes from your chats', href: '/settings/coach-memory' as const }, { icon: '✨', color: 'orange' as const, label: 'Foods GRIT knows', sub: 'Portions learned from Smart log', href: '/settings/foods' as const }, + { icon: '📖', color: 'blue' as const, label: 'Food data sources', sub: 'Where nutrition data comes from', href: '/settings/food-sources' as const }, { icon: '🔔', color: 'blue' as const, label: 'Notifications', sub: 'Reminders and alerts', href: '/settings/notifications' as const }, { icon: '👤', color: 'muted' as const, label: 'Account', sub: 'Appearance, units, password, delete account', href: '/settings/account' as const }, { icon: '📊', color: 'teal' as const, label: 'My Progress', sub: 'Weekly stats', href: '/(tabs)/activity' as const }, diff --git a/apps/mobile/app/barcode-scanner.tsx b/apps/mobile/app/barcode-scanner.tsx index 8d41b4f..61f43b9 100644 --- a/apps/mobile/app/barcode-scanner.tsx +++ b/apps/mobile/app/barcode-scanner.tsx @@ -1,7 +1,7 @@ import React, { useState, useCallback } from 'react'; import { View, Text, Pressable, StyleSheet, Alert } from 'react-native'; import { CameraView, useCameraPermissions } from 'expo-camera'; -import { router } from 'expo-router'; +import { router, useLocalSearchParams } from 'expo-router'; import * as Haptics from 'expo-haptics'; import { SafeAreaView } from 'react-native-safe-area-context'; import { useFoodBarcode } from '@/hooks/useFoodLog'; @@ -10,6 +10,9 @@ import { Colors } from '@/constants/colors'; export default function BarcodeScannerScreen() { const styles = makeStyles(); + // The day the Food tab is showing, so a scan logs to it + const params = useLocalSearchParams<{ date?: string }>(); + const date = typeof params.date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(params.date) ? params.date : undefined; const [permission, requestPermission] = useCameraPermissions(); const [scannedCode, setScannedCode] = useState(null); const [showSheet, setShowSheet] = useState(false); @@ -140,6 +143,7 @@ export default function BarcodeScannerScreen() { servingUnit: 'serving', imageUrl: null, }} + date={date} onClose={() => { setShowSheet(false); setScannedCode(null); @@ -153,7 +157,6 @@ export default function BarcodeScannerScreen() { const CORNER_SIZE = 24; const CORNER_THICKNESS = 3; -const CORNER_COLOR = Colors.orange; // Built during render, so it follows the current theme const makeStyles = () => StyleSheet.create({ @@ -187,25 +190,25 @@ const makeStyles = () => StyleSheet.create({ position: 'absolute', top: 0, left: 0, width: CORNER_SIZE, height: CORNER_SIZE, borderTopWidth: CORNER_THICKNESS, borderLeftWidth: CORNER_THICKNESS, - borderColor: CORNER_COLOR, + borderColor: Colors.orange, }, cornerTR: { position: 'absolute', top: 0, right: 0, width: CORNER_SIZE, height: CORNER_SIZE, borderTopWidth: CORNER_THICKNESS, borderRightWidth: CORNER_THICKNESS, - borderColor: CORNER_COLOR, + borderColor: Colors.orange, }, cornerBL: { position: 'absolute', bottom: 0, left: 0, width: CORNER_SIZE, height: CORNER_SIZE, borderBottomWidth: CORNER_THICKNESS, borderLeftWidth: CORNER_THICKNESS, - borderColor: CORNER_COLOR, + borderColor: Colors.orange, }, cornerBR: { position: 'absolute', bottom: 0, right: 0, width: CORNER_SIZE, height: CORNER_SIZE, borderBottomWidth: CORNER_THICKNESS, borderRightWidth: CORNER_THICKNESS, - borderColor: CORNER_COLOR, + borderColor: Colors.orange, }, permissionView: { flex: 1, diff --git a/apps/mobile/app/nutrients.tsx b/apps/mobile/app/nutrients.tsx new file mode 100644 index 0000000..c74a1a8 --- /dev/null +++ b/apps/mobile/app/nutrients.tsx @@ -0,0 +1,151 @@ +import React, { useState } from 'react'; +import { ActivityIndicator, Pressable, RefreshControl, ScrollView, Text, View } from 'react-native'; +import { SafeAreaView } from 'react-native-safe-area-context'; +import { router, useLocalSearchParams } from 'expo-router'; +import { Colors } from '@/constants/colors'; +import { ScreenHeader, Section } from '@/components/settings/SettingsUI'; +import { DateNavigator } from '@/components/ui/DateNavigator'; +import { ErrorNotice } from '@/components/ui/QueryStatus'; +import { useNutrientsDay } from '@/hooks/useNutrients'; +import { usePullToRefresh } from '@/hooks/usePullToRefresh'; +import { addDaysStr, dayLabel, localDateStr } from '@/lib/date'; +import { + amountText, barFraction, barTone, coverageNote, nutrientA11yLabel, nutrientSections, percentText, sourcesLine, statusTag, + type DayNutrient, +} from '@/lib/nutrients'; + +const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; + +/** One nutrient: amount against its target or limit, as a bar. */ +function NutrientRow({ n, isToday, inProgress }: { n: DayNutrient; isToday: boolean; inProgress: boolean }) { + const tag = statusTag(n.status, inProgress); + const tone = barTone(n.status, inProgress); + // Without enough data the bar stays grey, so nothing reads as low + const fill = tone === 'muted' ? `${Colors.muted}60` : Colors[tone]; + const sources = sourcesLine(n, isToday); + const percent = percentText(n.percent); + return ( + + + {n.name} + {tag && tag.tone === 'muted' && ( + {tag.text} + )} + {tag && tag.tone !== 'muted' && ( + + {tag.text} + + )} + + {!!percent && ( + {percent} + )} + + + + + {amountText(n)} + {!!sources && ( + {sources} + )} + + ); +} + +/** + * Vitamins, minerals, fibre, sodium and saturated fat for a day, against + * targets for the user's age and sex. Only foods from GRIT's database carry + * this data, so the screen says how much of the day it's based on. + */ +export default function NutrientsScreen() { + const params = useLocalSearchParams<{ date?: string }>(); + const today = localDateStr(); + const yesterday = addDaysStr(today, -1); + const [date, setDate] = useState(() => + typeof params.date === 'string' && DATE_RE.test(params.date) && params.date <= today ? params.date : today, + ); + const { data, isLoading, isError, refetch } = useNutrientsDay(date); + const { refreshing, onRefresh } = usePullToRefresh([['nutrients-day', date]]); + const isToday = date === today; + // Today is still being logged: no Low tags yet (a passed limit still shows) + const inProgress = data?.inProgress === true; + + const card = { backgroundColor: Colors.surface, borderRadius: 18, borderWidth: 1, borderColor: Colors.border, padding: 16, gap: 6 } as const; + + return ( + + + } + > + setDate((d) => addDaysStr(d, -1))} + onNext={() => setDate((d) => addDaysStr(d, 1))} + canGoNext={date < today} + onReset={isToday ? undefined : () => setDate(today)} + /> + + {isError && !data ? ( + refetch()} /> + ) : isLoading || !data ? ( + + ) : !(data.coverage > 0) ? ( + + 🥦 + + {data.entries === 0 ? 'Nothing logged yet' : 'No vitamin and mineral data yet'} + + + Log foods from the food database to see vitamins and minerals. + + + ) : ( + <> + + + {coverageNote(data.coverage, date, today, yesterday)} + + {data.coverage < 0.995 && ( + + Vitamins and minerals come from foods in the food database. Foods typed in by hand and Smart log estimates aren't counted. + + )} + {inProgress ? ( + + Today isn't over yet, so nothing is marked low until it is. + + ) : !data.judged && ( + + Nothing is marked low until more of the day is logged. + + )} + + + {nutrientSections(data.nutrients).map((s) => ( +
+ {s.items.map((n) => )} +
+ ))} + + )} + + + + Targets are US Dietary Reference Intakes for your age and sex. They don't cover pregnancy or breastfeeding. + + router.push('/settings/food-sources')} + accessibilityRole="button" + accessibilityLabel="Food data sources" + hitSlop={8} + style={({ pressed }) => ({ alignSelf: 'flex-start', opacity: pressed ? 0.6 : 1 })} + > + Food data sources › + + +
+
+ ); +} diff --git a/apps/mobile/app/settings/food-sources.tsx b/apps/mobile/app/settings/food-sources.tsx new file mode 100644 index 0000000..75a9340 --- /dev/null +++ b/apps/mobile/app/settings/food-sources.tsx @@ -0,0 +1,41 @@ +import React from 'react'; +import { Linking, Pressable, ScrollView, Text, View } from 'react-native'; +import { SafeAreaView } from 'react-native-safe-area-context'; +import { Colors } from '@/constants/colors'; +import { ScreenHeader, Section } from '@/components/settings/SettingsUI'; +import { FOOD_SOURCES, siteName } from '@/lib/foodSources'; + +/** The public food tables and product data GRIT's food database is built from, with their credits. */ +export default function FoodSourcesScreen() { + return ( + + + + + GRIT's food database is built from these public food tables and product data. Foods marked ✓ Verified come from a government table or the manufacturer's own data. + +
+ {FOOD_SOURCES.map((s, i) => ( + + {s.name} + {s.credit} + {!!s.notice && ( + {s.notice} + )} + Licence: {s.licence} + Linking.openURL(s.url).catch(() => {})} + accessibilityRole="link" + accessibilityLabel={`Open the ${s.name} website`} + hitSlop={6} + style={({ pressed }) => ({ alignSelf: 'flex-start', marginTop: 2, opacity: pressed ? 0.6 : 1 })} + > + {siteName(s.url)} › + + + ))} +
+
+
+ ); +} diff --git a/apps/mobile/components/food/FoodSearchBar.tsx b/apps/mobile/components/food/FoodSearchBar.tsx index b82d68e..d0252c9 100644 --- a/apps/mobile/components/food/FoodSearchBar.tsx +++ b/apps/mobile/components/food/FoodSearchBar.tsx @@ -7,82 +7,116 @@ import { Pressable, ActivityIndicator, } from 'react-native'; -import { useFoodSearch, type NormalizedFood } from '@/hooks/useFoodLog'; +import { MIN_SEARCH_LENGTH, useFoodSearch, type NormalizedFood } from '@/hooks/useFoodLog'; import { recordSearch } from '@/lib/searchEvents'; +import { searchServing } from '@/lib/servings'; +import { VerifiedPill } from '@/components/food/VerifiedPill'; import { Colors } from '@/constants/colors'; +/** Wait this long after the last keystroke before searching */ +const DEBOUNCE_MS = 250; + interface FoodSearchBarProps { onSelect: (food: NormalizedFood) => void; } export function FoodSearchBar({ onSelect }: FoodSearchBarProps) { const [query, setQuery] = useState(''); - const { data: results, isLoading } = useFoodSearch(query); + const term = query.trim(); + const [searched, setSearched] = useState(term); + useEffect(() => { + const t = setTimeout(() => setSearched(term), DEBOUNCE_MS); + return () => clearTimeout(t); + }, [term]); + const { data: results, isLoading } = useFoodSearch(searched); + const active = term.length >= MIN_SEARCH_LENGTH && searched.length >= MIN_SEARCH_LENGTH; // A search the user leaves without picking anything counts as a miss const pending = useRef(''); pending.current = query; - useEffect(() => () => recordSearch(pending.current), []); + // What the list shows, for the search events + const shown = useRef<{ term: string; count?: number }>({ term: '' }); + shown.current = { term: searched, count: searched === term ? results?.length : undefined }; + useEffect(() => () => recordSearch(pending.current, undefined, shown.current.count), []); const clear = () => { - recordSearch(query); + recordSearch(query, undefined, shown.current.count); setQuery(''); }; const renderItem = useCallback( - ({ item, index }: { item: NormalizedFood; index: number }) => ( - { - recordSearch(pending.current, { position: index, name: item.name }); - pending.current = ''; - onSelect(item); - setQuery(''); - }} - style={({ pressed }) => ({ - paddingVertical: 12, - paddingHorizontal: 16, - backgroundColor: pressed ? Colors.surface2 : 'transparent', - borderBottomWidth: 1, - borderBottomColor: Colors.border, - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', - })} - > - - - {item.name} - - {item.brand && ( + ({ item, index }: { item: NormalizedFood; index: number }) => { + const { serving, kcal } = searchServing(item); + const sub = [item.brand, serving].filter(Boolean).join(' · '); + return ( + { + recordSearch(shown.current.term, { position: index, name: item.name, foodId: item.foodId }, shown.current.count); + pending.current = ''; + onSelect(item); + setQuery(''); + }} + style={({ pressed }) => ({ + paddingVertical: 12, + paddingHorizontal: 16, + backgroundColor: pressed ? Colors.surface2 : 'transparent', + borderBottomWidth: 1, + borderBottomColor: Colors.border, + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + })} + > + + + + {item.name} + + {item.verified === true && } + + {!!sub && ( + + {sub} + + )} + + - {item.brand} + {kcal} kcal - )} - - - {Math.round(item.calories)} kcal - - - ), + {!serving && ( + per 100 g + )} + + + ); + }, [onSelect], ); @@ -124,7 +158,7 @@ export function FoodSearchBar({ onSelect }: FoodSearchBarProps) { )}
- {query.length >= 2 && results && results.length > 0 && ( + {active && results && results.length > 0 && ( `${item.offId}-${i}`} + keyExtractor={(item, i) => `${item.foodId ?? item.offId}-${i}`} renderItem={renderItem} keyboardShouldPersistTaps="handled" /> )} - {query.length >= 2 && !isLoading && results?.length === 0 && ( + {active && !isLoading && results?.length === 0 && ( No results for "{query}" - { recordSearch(query); pending.current = ''; onSelect({ offId: '', name: query, brand: null, barcode: null, calories: 0, proteinG: 0, carbsG: 0, fatG: 0, servingQty: 1, servingUnit: 'serving', imageUrl: null }); }}> + { recordSearch(query, undefined, 0); pending.current = ''; onSelect({ offId: '', name: query, brand: null, barcode: null, calories: 0, proteinG: 0, carbsG: 0, fatG: 0, servingQty: 1, servingUnit: 'serving', imageUrl: null }); }}> Log "{query}" manually → diff --git a/apps/mobile/components/food/LogFoodSheet.tsx b/apps/mobile/components/food/LogFoodSheet.tsx index 770fd06..e978772 100644 --- a/apps/mobile/components/food/LogFoodSheet.tsx +++ b/apps/mobile/components/food/LogFoodSheet.tsx @@ -1,19 +1,26 @@ -import React, { useRef, useState, useCallback } from 'react'; +import React, { useRef, useState, useCallback, useMemo } from 'react'; import { View, Text, Pressable, Alert, } from 'react-native'; -import BottomSheet, { BottomSheetView } from '@gorhom/bottom-sheet'; +import BottomSheet, { BottomSheetScrollView } from '@gorhom/bottom-sheet'; import { SheetTextInput, sheetKeyboardProps } from '@/components/ui/SheetTextInput'; import * as Haptics from 'expo-haptics'; import { useLogFood, type NormalizedFood } from '@/hooks/useFoodLog'; import { foodKey, useFavoriteFoods, useRemoveFavorite, useSaveFavorite } from '@/hooks/useQuickFoods'; import { Button } from '@/components/ui/Button'; +import { VerifiedPill } from '@/components/food/VerifiedPill'; import { useHideTabBar } from '@/stores/uiStore'; import { Colors } from '@/constants/colors'; import { loggedAtFor } from '@/lib/date'; +import { notify } from '@/lib/confirm'; +import { portionGrams } from '@/lib/quickFoods'; +import { + MAX_LOG_GRAMS, defaultOption, foodUnit, formatGrams, qtyAfterSwitch, round1, servingLog, servingOptions, + type ServingOption, +} from '@/lib/servings'; const MEAL_TYPES = ['breakfast', 'lunch', 'dinner', 'snack'] as const; @@ -46,28 +53,45 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP const [mealType, setMealType] = useState(initialMeal ?? 'breakfast'); const [qty, setQty] = useState('1'); - // Foods from the database carry nutrition per 100 g (or ml) plus a serving - // size; manual entries have neither, so the user types values per serving. - // Saved portions (recent or favourite foods) carry amounts for the whole - // portion, so servings multiply them directly. + // Foods from the database carry nutrition per 100 g (or ml) plus servings + // to pick from; manual entries have neither, so the user types values per + // serving. Saved portions (recent or favourite foods) carry amounts for + // the whole portion, so servings multiply them directly. A database food + // can have no Open Food Facts id, so `foodId` also marks it as not manual. const isPortion = !!food?.portion; - const isManual = !food?.offId && !isPortion; + const isManual = !food?.offId && !food?.foodId && !isPortion; + const usesPicker = !!food && !isManual && !isPortion; + const unit = food ? foodUnit(food) : 'g'; const [name, setName] = useState(food?.name ?? ''); const [manual, setManual] = useState({ calories: '', proteinG: '', carbsG: '', fatG: '' }); const num = (v: string) => Math.max(0, parseFloat(v) || 0); + // The serving picker: the food's servings, then 100 g, then grams typed directly + const options = useMemo(() => (food && usesPicker ? servingOptions(food) : []), [food, usesPicker]); + const [optionKey, setOptionKey] = useState(() => (food && options.length ? defaultOption(food, options).key : '')); + const option = options.find((o) => o.key === optionKey) ?? options[0]; + const picked = food && usesPicker && option ? servingLog(food, option, qty) : null; + const servings = parseFloat(qty) > 0 ? parseFloat(qty) : 1; - const amount = servings * (food?.servingQty ?? 100); // grams or ml eaten + const amount = picked ? picked.grams : servings * (food?.servingQty ?? 100); // grams or ml eaten // How much of the food's listed amounts this is const factor = isManual ? servings : isPortion ? servings : amount / 100; - const adjustedCalories = isManual ? num(manual.calories) * servings : (food?.calories ?? 0) * factor; - const adjustedProtein = isManual ? num(manual.proteinG) * servings : (food?.proteinG ?? 0) * factor; - const adjustedCarbs = isManual ? num(manual.carbsG) * servings : (food?.carbsG ?? 0) * factor; - const adjustedFat = isManual ? num(manual.fatG) * servings : (food?.fatG ?? 0) * factor; + const adjustedCalories = isManual ? num(manual.calories) * servings : picked ? picked.calories : (food?.calories ?? 0) * factor; + const adjustedProtein = isManual ? num(manual.proteinG) * servings : picked ? picked.proteinG : (food?.proteinG ?? 0) * factor; + const adjustedCarbs = isManual ? num(manual.carbsG) * servings : picked ? picked.carbsG : (food?.carbsG ?? 0) * factor; + const adjustedFat = isManual ? num(manual.fatG) * servings : picked ? picked.fatG : (food?.fatG ?? 0) * factor; const caffeineMg = food?.caffeineMg != null && !isManual ? Math.round(food.caffeineMg * factor) : undefined; const alcoholG = food?.alcoholG != null && !isManual ? Math.round(food.alcoholG * factor * 10) / 10 : undefined; + // What's logged: database foods as grams, so the server can save their nutrients + const loggedQty = isManual ? servings : picked ? round1(amount) : amount; + const loggedUnit = isManual ? 'serving' : picked ? unit : food?.servingUnit ?? 'g'; + const loggedFoodId = !isManual ? food?.foodId : undefined; + const loggedGrams = picked + ? (unit === 'g' ? round1(amount) : undefined) + : isPortion ? portionGrams(food?.portionGrams, servings) : undefined; + // The star saves exactly what would be logged now const { data: favorites } = useFavoriteFoods(); const { mutate: saveFavorite, isPending: savingFavorite } = useSaveFavorite(); @@ -89,17 +113,35 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP proteinG: Math.round(adjustedProtein * 10) / 10, carbsG: Math.round(adjustedCarbs * 10) / 10, fatG: Math.round(adjustedFat * 10) / 10, - servingQty: isManual ? servings : amount, - servingUnit: isManual ? 'serving' : food.servingUnit, + servingQty: loggedQty, + servingUnit: loggedUnit, + foodId: loggedFoodId ?? null, + grams: loggedGrams ?? null, }); } + function pickOption(o: ServingOption) { + if (o.key === option?.key) return; + Haptics.selectionAsync(); + // Keep the amount when switching to grams; start at 1 of a serving + setQty(qtyAfterSwitch(o, amount)); + setOptionKey(o.key); + } + const handleLog = useCallback(async () => { if (!food) return; if (isManual && (!name.trim() || !manual.calories.trim())) { Alert.alert('Missing details', 'Enter a name and the calories per serving.'); return; } + if (usesPicker && !(amount > 0)) { + notify('How much?', `Enter the ${unit === 'ml' ? 'millilitres' : 'grams'} you had.`); + return; + } + if (loggedGrams != null && loggedGrams > MAX_LOG_GRAMS) { + notify("That's a lot", `Log up to ${MAX_LOG_GRAMS.toLocaleString()} g at a time.`); + return; + } try { await logFood({ name: isManual ? name.trim() : food.name, @@ -110,8 +152,10 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP proteinG: adjustedProtein, carbsG: adjustedCarbs, fatG: adjustedFat, - servingQty: isManual ? servings : amount, - servingUnit: isManual ? 'serving' : food.servingUnit, + servingQty: loggedQty, + servingUnit: loggedUnit, + foodId: loggedFoodId, + grams: loggedGrams, caffeineMg, alcoholG, loggedAt: date ? loggedAtFor(date) : undefined, @@ -121,21 +165,30 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP } catch { Alert.alert('Error', 'Could not log food. Please try again.'); } - }, [food, isManual, name, manual.calories, mealType, servings, amount, adjustedCalories, adjustedProtein, adjustedCarbs, adjustedFat, caffeineMg, alcoholG, logFood, onClose, date]); + }, [food, isManual, name, manual.calories, usesPicker, amount, unit, mealType, loggedQty, loggedUnit, loggedFoodId, loggedGrams, adjustedCalories, adjustedProtein, adjustedCarbs, adjustedFat, caffeineMg, alcoholG, logFood, onClose, date]); if (!food) return null; + const directLabel = unit === 'ml' ? 'Millilitres' : 'Grams'; + const qtyLabel = isPortion + ? `Portions (1 = ${Math.round(food.servingQty * 10) / 10} ${food.servingUnit})` + : isManual + ? 'Servings' + : option?.direct + ? directLabel + : `Servings · ${formatGrams(amount)} ${unit}`; + return ( - + {/* Food name */} @@ -172,6 +225,11 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP {food.brand} )} + {food.verified === true && ( + + + + )} + {/* Serving picker (database foods) */} + {usesPicker && options.length > 0 && ( + + Serving + + {options.map((o) => { + const selected = o.key === option?.key; + return ( + pickOption(o)} + accessibilityRole="radio" + accessibilityLabel={o.direct ? `Type the amount in ${directLabel.toLowerCase()}` : o.label} + aria-checked={selected} + style={{ + paddingHorizontal: 12, + paddingVertical: 8, + borderRadius: 999, + backgroundColor: selected ? Colors.orange : Colors.surface2, + borderWidth: 1.5, + borderColor: selected ? Colors.orange : Colors.border, + }} + > + + {o.label} + + + ); + })} + + + )} + {/* Qty + meal type row */} - {isPortion ? `Portions (1 = ${Math.round(food.servingQty * 10) / 10} ${food.servingUnit})` : `Servings${!isManual ? ` (${food.servingQty} ${food.servingUnit})` : ''}`} + {qtyLabel} @@ -296,7 +388,7 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP