Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Star a food from the diary too (#185)
Carter621295e9551f
diff --git a/mobile/app/(tabs)/nutrition/[id].tsx b/mobile/app/(tabs)/nutrition/[id].tsxindex 706163e..c3c8401 100644--- a/mobile/app/(tabs)/nutrition/[id].tsx+++ b/mobile/app/(tabs)/nutrition/[id].tsx@@ -1,14 +1,16 @@import { useEffect, useState } from 'react'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, isNotFound, useAsyncAction, entryDay, type FoodLog, formatDay } from '@lyftr/shared'+import { apiErrorMessage, entryToResult, isNotFound, useAsyncAction, useFavorites, entryDay, type FoodLog, formatDay } from '@lyftr/shared'import {- AppText, Button, Card, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps,+ Alert, AppText, Button, Card, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps,} from '../../../src/components/ui'import {MACRO_COLORS, MACRO_TEXT, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal,} from '../../../src/components/nutrition/nutritionMeta'+import { FavoriteStar } from '../../../src/components/nutrition/FoodResultRow'import { client } from '../../../src/lib/lyftr'import { useTheme } from '../../../src/theme/useTheme'@@ -26,6 +28,11 @@ export default function NutritionDetail() {const [gone, setGone] = useState(false)const [retryKey, setRetryKey] = useState(0)const [confirming, setConfirming] = useState(false)+ // The star in the header (#138), drawn only once the favourites list has loaded: a+ // failed load leaves it off rather than showing a favourite as not one.+ const favorites = useFavorites(client.savedFoodsAPI)+ const { setSavedFoods } = favorites+ const [favoritesLoaded, setFavoritesLoaded] = useState(false)const goBack = () => (router.canGoBack() ? router.back() : router.replace('/nutrition'))@@ -39,6 +46,12 @@ export default function NutritionDetail() {.finally(() => setLoading(false))}, [id, retryKey])+ useEffect(() => {+ client.savedFoodsAPI.list()+ .then((list) => { setSavedFoods(list); setFavoritesLoaded(true) })+ .catch(() => {})+ }, [setSavedFoods])+// The catch here just closed up and left the screen unchanged, which is// indistinguishable from a tap that never registered. It says why now.const remove = useAsyncAction(async () => {@@ -65,6 +78,16 @@ export default function NutritionDetail() {)}+ // Starred as the food it is: entryToResult divides the logged amount back down to one+ // serving, which is what a favourite stores, so the star matches the same food on the+ // Recent, Favorites and Search tabs.+ const food = entryToResult(entry)+ const toggleFavorite = async () => {+ const done = await favorites.toggle(food)+ if (done === 'added') Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})+ else if (done === 'removed') Haptics.selectionAsync().catch(() => {})+ }+const meal = entry.meal as Mealconst MealIcon = MEAL_ICONS[meal]const mealColor = MEAL_COLORS[meal]@@ -99,6 +122,15 @@ export default function NutritionDetail() {<AppText variant="body" color="muted">Nutrition</AppText></Pressable><View className="flex-row items-center gap-2">+ {favoritesLoaded ? (+ <FavoriteStar+ size="header"+ favorited={favorites.favoriteOf(food) !== undefined}+ busy={favorites.isToggling(food)}+ name={entry.name}+ onPress={toggleFavorite}+ />+ ) : null}<PressableaccessibilityRole="button"accessibilityLabel="Edit entry"@@ -122,6 +154,9 @@ export default function NutritionDetail() {</View></View>+ {/* Said where the tap was: directly under the star that failed. */}+ {favorites.error ? <Alert variant="error">{favorites.error}</Alert> : null}+{/* Hero card */}<Card className="overflow-hidden p-0">{entry.image_url ? (diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsxindex 6c0137d..a74f2f8 100644--- a/mobile/app/(tabs)/nutrition/log.tsx+++ b/mobile/app/(tabs)/nutrition/log.tsx@@ -7,7 +7,7 @@ import {} from 'lucide-react-native'import {useAsyncAction, dayToInstant, entryDay, todayStr,- type FoodSearchResult, type SavedFood,+ type FoodSearchResult,} from '@lyftr/shared'import {Alert, AppText, Button, Card, DateInput, ErrorState, IconButton, Label, NumberField,@@ -21,7 +21,7 @@ import {} from '../../../src/components/nutrition/nutritionMeta'import { client } from '../../../src/lib/lyftr'import { useTheme } from '../../../src/theme/useTheme'-import { apiErrorMessage, entryToResult, findSavedFood, isNotFound, savedToResult, scaleServing } from '@lyftr/shared'+import { apiErrorMessage, entryToResult, isNotFound, savedToResult, scaleServing, useFavorites } from '@lyftr/shared'type Phase = 'search' | 'detail' | 'scan'type SearchTab = 'recent' | 'myfoods' | 'all'@@ -47,7 +47,10 @@ export default function LogFood() {const [query, setQuery] = useState('')const [searchResults, setSearchResults] = useState<FoodSearchResult[]>([])const [recentItems, setRecentItems] = useState<FoodSearchResult[]>([])- const [savedFoods, setSavedFoods] = useState<SavedFood[]>([])+ const favorites = useFavorites(client.savedFoodsAPI)+ const { savedFoods, setSavedFoods, favoriteOf, isToggling, error: favoriteError } = favorites+ // Bumped by every star/unstar; a list load drops its result if a toggle landed meanwhile.+ const listEpoch = favorites.epochconst [searching, setSearching] = useState(false)const [searchError, setSearchError] = useState<string | null>(null)const [rateLimited, setRateLimited] = useState(false)@@ -62,77 +65,16 @@ export default function LogFood() {const [servingsStr, setServingsStr] = useState('1')const [meal, setMeal] = useState<Meal>(initMeal)const [date, setDate] = useState(initDate)- const [togglingFavorite, setTogglingFavorite] = useState<Set<string>>(new Set())const [pulling, setPulling] = useState(false)- // Derived from the list rather than tracked, so a star tapped on any tab is reflected- // everywhere the same food appears — including the detail screen.- const favoriteOf = (item: FoodSearchResult) => findSavedFood(savedFoods, item)-- // Bumped by every star/unstar. A list load captures it and discards its own result if- // a toggle landed while it was in flight — otherwise a pull-to-refresh issued just- // before a DELETE resolves comes back holding the row and puts the unstarred food back- // on screen, and the next tap deletes an id the server no longer has.- const listEpoch = useRef(0)-- // Favouriting is its own action, not a side effect of logging. One tap on, one tap off,- // from any row or from the detail header. No confirmation: a second tap undoes it.- // The guard is a ref, not the state below. setState does not apply within the tick it- // is called in, so a burst of taps in one frame all read the same empty set and all- // fire — five rapid clicks sent one DELETE that worked and four that 404'd, then showed- // "Couldn't remove …" for an unstar that had actually succeeded. The state exists only- // to dim the star; the ref is what decides.- const inFlightFavorites = useRef<Set<string>>(new Set())-+ // Starring lives in useFavorites, shared with the diary entry screen so the rules can't+ // drift (#138). The haptic is the only part that belongs to this screen.const toggleFavorite = async (item: FoodSearchResult) => {- const key = `${item.name}|${item.brand ?? ''}`- // Guard this food only. A single global flag dropped taps on *other* rows while a- // request was in flight, so on a slow connection every other star went dead with no- // feedback — indistinguishable from a broken button.- if (inFlightFavorites.current.has(key)) return- inFlightFavorites.current.add(key)- setTogglingFavorite(new Set(inFlightFavorites.current))- setFavoriteError(null)- listEpoch.current += 1- const existing = favoriteOf(item)- try {- if (existing) {- await client.savedFoodsAPI.delete(existing.id)- setSavedFoods((prev) => prev.filter((f) => f.id !== existing.id))- Haptics.selectionAsync().catch(() => {})- } else {- const created = await client.savedFoodsAPI.create({- name: item.name, brand: item.brand ?? '',- calories: item.calories, protein: item.protein,- carbs: item.carbs, fat: item.fat, fiber: item.fiber ?? 0,- serving_size: item.serving_size ?? '',- })- // The server answers 200 with the existing row when the food is already- // favourited, so `created` can be something the list already holds — after a- // pull-to-refresh that raced this request, for instance. Appending blind puts two- // rows with the same id (and the same React key) in the list.- // Inserted in name order rather than appended: ListSaved returns ORDER BY name,- // so appending parks a new favourite at the bottom until the next load and then- // jumps it. Plain < to match SQLite's BINARY collation rather than localeCompare,- // which would order differently from the server it is imitating.- setSavedFoods((prev) => prev.some((f) => f.id === created.id)- ? prev- : [...prev, created].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)))- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})- }- } catch (err) {- setFavoriteError(apiErrorMessage(err, existing- ? `Couldn't remove ${item.name} from Favorites.`- : `Couldn't add ${item.name} to Favorites.`))- } finally {- inFlightFavorites.current.delete(key)- setTogglingFavorite(new Set(inFlightFavorites.current))- }+ const done = await favorites.toggle(item)+ if (done === 'added') Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})+ else if (done === 'removed') Haptics.selectionAsync().catch(() => {})}- const isToggling = (item: FoodSearchResult) =>- togglingFavorite.has(`${item.name}|${item.brand ?? ''}`)- const [favoriteError, setFavoriteError] = useState<string | null>(null)const [editError, setEditError] = useState<string | null>(null)const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)diff --git a/mobile/src/components/nutrition/FoodResultRow.tsx b/mobile/src/components/nutrition/FoodResultRow.tsxindex 8dd410e..0a15a73 100644--- a/mobile/src/components/nutrition/FoodResultRow.tsx+++ b/mobile/src/components/nutrition/FoodResultRow.tsx@@ -75,13 +75,15 @@ export function FoodResultRow({// carries the toggle state that the fill conveys visually.export function FavoriteStar({ favorited, busy = false, name, onPress, size = 'sm' }:- { favorited: boolean; busy?: boolean; name: string; onPress: () => void; size?: 'sm' | 'md' },+ { favorited: boolean; busy?: boolean; name: string; onPress: () => void; size?: 'sm' | 'md' | 'header' },) {const { colors, accent } = useTheme()// Same box, hit slop and press feedback as ui/IconButton — written out rather than// reusing it because a filled star needs an SVG `fill`, and adding a fill prop to the// shared primitive for one toggle is the wrong place to put it.- const box = size === 'sm' ? 'w-8 h-8 rounded-lg' : 'w-10 h-10 rounded-xl'+ // `header` matches the h-9 icon actions every detail screen's header uses (weight,+ // workouts and nutrition [id]), so the star reads as one of that set.+ const box = size === 'sm' ? 'w-8 h-8 rounded-lg' : size === 'header' ? 'h-9 w-9 rounded-lg active:bg-surface-muted' : 'w-10 h-10 rounded-xl'return (<PressableaccessibilityRole="button"@@ -89,11 +91,11 @@ export function FavoriteStar(accessibilityLabel={favorited ? `Remove ${name} from Favorites` : `Add ${name} to Favorites`}onPress={onPress}disabled={busy}- hitSlop={8}+ hitSlop={size === 'header' ? 6 : 8}className={`items-center justify-center active:scale-95 ${box} ${busy ? 'opacity-40' : ''}`}><Star- size={size === 'sm' ? 18 : 22}+ size={size === 'sm' ? 18 : size === 'header' ? 17 : 22}color={favorited ? accent : colors.txMuted}fill={favorited ? accent : 'transparent'}strokeWidth={2.2}diff --git a/packages/shared/src/hooks/useFavorites.ts b/packages/shared/src/hooks/useFavorites.tsnew file mode 100644index 0000000..83c7669--- /dev/null+++ b/packages/shared/src/hooks/useFavorites.ts@@ -0,0 +1,108 @@+import { useRef, useState } from 'react'+import { apiErrorMessage } from '../client'+import type { FoodSearchResult, SavedFood } from '../types'+import { findSavedFood, normaliseFoodKey } from '../utils/food'++/** The slice of the saved-foods API a toggle needs; both apps pass their client's. */+export interface SavedFoodsApi {+ create: (data: Record<string, unknown>) => Promise<SavedFood>+ delete: (id: number) => Promise<unknown>+}++export interface Favorites {+ /** The favourites list. The caller loads it; toggles keep it current. */+ savedFoods: SavedFood[]+ setSavedFoods: React.Dispatch<React.SetStateAction<SavedFood[]>>+ /** The saved row for this food, if it is a favourite. */+ favoriteOf: (item: FoodSearchResult) => SavedFood | undefined+ /** This food's star has a request in flight. Dim it; don't block the others. */+ isToggling: (item: FoodSearchResult) => boolean+ /** Star or unstar. Resolves to what happened, or null if it failed or was ignored. */+ toggle: (item: FoodSearchResult) => Promise<'added' | 'removed' | null>+ /** The sentence to show when a toggle failed, in the server's words. */+ error: string | null+ setError: (error: string | null) => void+ /**+ * Bumped when a toggle starts and again when it settles. A list load captures it and+ * drops its own result if it moved while the load was in flight — otherwise a refresh+ * issued just before a DELETE resolves comes back holding the row, puts the unstarred+ * food back on screen, and the next tap deletes an id the server no longer has. The+ * bump on settling is what catches that one: the refresh started *after* the toggle+ * began, so only the toggle's end can move the value it captured.+ */+ epoch: React.MutableRefObject<number>+}++const keyOf = (item: FoodSearchResult) => `${normaliseFoodKey(item.name)}|${normaliseFoodKey(item.brand)}`++// Favouriting is its own action, not a side effect of logging: one tap on, one tap off,+// from any row, the food detail, or a diary entry. No confirmation — a second tap undoes+// it. One implementation for every screen that shows a star (#138), so the rules below+// cannot hold on one screen and drift on another.+export function useFavorites(api: SavedFoodsApi): Favorites {+ const [savedFoods, setSavedFoods] = useState<SavedFood[]>([])+ const [toggling, setToggling] = useState<Set<string>>(new Set())+ const [error, setError] = useState<string | null>(null)+ const epoch = useRef(0)++ // The guard is a ref, not the state above. setState does not apply within the tick it+ // is called in, so a burst of taps in one frame all read the same empty set and all+ // fire — five rapid taps sent one DELETE that worked and four that 404'd, then showed+ // "Couldn't remove …" for an unstar that had actually succeeded. The state exists only+ // to dim the star; the ref is what decides.+ const inFlight = useRef<Set<string>>(new Set())++ // Derived from the list rather than tracked, so a star tapped anywhere is reflected+ // everywhere the same food appears.+ const favoriteOf = (item: FoodSearchResult) => findSavedFood(savedFoods, item)+ const isToggling = (item: FoodSearchResult) => toggling.has(keyOf(item))++ const toggle = async (item: FoodSearchResult): Promise<'added' | 'removed' | null> => {+ const key = keyOf(item)+ // Guard this food only. A single global flag dropped taps on *other* rows while a+ // request was in flight, so on a slow connection every other star went dead with no+ // feedback — indistinguishable from a broken button.+ if (inFlight.current.has(key)) return null+ inFlight.current.add(key)+ setToggling(new Set(inFlight.current))+ setError(null)+ epoch.current += 1+ const existing = favoriteOf(item)+ try {+ if (existing) {+ await api.delete(existing.id)+ setSavedFoods(prev => prev.filter(f => f.id !== existing.id))+ return 'removed'+ }+ const created = await api.create({+ name: item.name, brand: item.brand ?? '',+ calories: item.calories, protein: item.protein,+ carbs: item.carbs, fat: item.fat, fiber: item.fiber ?? 0,+ serving_size: item.serving_size ?? '',+ })+ // The server answers 200 with the existing row when the food is already favourited,+ // so `created` can be something the list already holds — after a refresh that raced+ // this request, for instance. Appending blind puts two rows with the same id (and the+ // same React key) in the list.+ // Inserted in name order rather than appended: ListSaved returns ORDER BY name, so+ // appending parks a new favourite at the bottom until the next load and then jumps+ // it. Plain < to match SQLite's BINARY collation rather than localeCompare, which+ // would order differently from the server it is imitating.+ setSavedFoods(prev => prev.some(f => f.id === created.id)+ ? prev+ : [...prev, created].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)))+ return 'added'+ } catch (err) {+ setError(apiErrorMessage(err, existing+ ? `Couldn't remove ${item.name} from Favorites.`+ : `Couldn't add ${item.name} to Favorites.`))+ return null+ } finally {+ epoch.current += 1+ inFlight.current.delete(key)+ setToggling(new Set(inFlight.current))+ }+ }++ return { savedFoods, setSavedFoods, favoriteOf, isToggling, toggle, error, setError, epoch }+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 4852b14..d235cda 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -30,6 +30,7 @@ export * from './hooks/useElapsedSeconds'export * from './hooks/useRestTimer'export * from './hooks/useServerList'export * from './hooks/useServerInfo'+export * from './hooks/useFavorites'export * from './utils/dateUtils'export * from './brand/barbell'export * from './utils/programUtils'diff --git a/web/src/components/FavoriteStar.tsx b/web/src/components/FavoriteStar.tsxnew file mode 100644index 0000000..459cdf6--- /dev/null+++ b/web/src/components/FavoriteStar.tsx@@ -0,0 +1,25 @@+import { Star } from 'lucide-react'++// Shared by the food rows, the food detail header and the diary so they cannot drift.+// aria-pressed carries the toggle state that the fill conveys visually.+export default function FavoriteStar(+ { favorited, busy = false, name, onClick, size = 'sm' }:+ { favorited: boolean; busy?: boolean; name: string; onClick: () => void; size?: 'compact' | 'sm' | 'md' },+) {+ // `compact` is IconButton's `sm`, box and icon, for rows whose other actions are+ // IconButtons (the diary). `sm` and `md` are the Log Food rows and detail header.+ const box = size === 'md' ? 'w-10 h-10' : 'w-8 h-8'+ const icon = size === 'compact' ? 'w-3.5 h-3.5' : size === 'sm' ? 'w-[18px] h-[18px]' : 'w-[22px] h-[22px]'+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={busy}+ aria-pressed={favorited}+ aria-label={favorited ? `Remove ${name} from Favorites` : `Add ${name} to Favorites`}+ className={`${box} flex items-center justify-center rounded-lg flex-shrink-0 transition-colors hover:bg-surface-muted active:scale-95 disabled:opacity-40 ${favorited ? 'text-brand-500' : 'text-tx-muted'}`}+ >+ <Star className={icon} fill={favorited ? 'currentColor' : 'none'} strokeWidth={2.2} />+ </button>+ )+}diff --git a/web/src/hooks/useFavorites.test.ts b/web/src/hooks/useFavorites.test.tsnew file mode 100644index 0000000..a0bc70a--- /dev/null+++ b/web/src/hooks/useFavorites.test.ts@@ -0,0 +1,36 @@+import { describe, it, expect } from 'vitest'+import { renderHook, act } from '@testing-library/react'+import { useFavorites, type SavedFood } 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 useNumericText).++const OATS: SavedFood = {+ id: 42, name: 'Oats', brand: 'Quaker',+ calories: 300, protein: 10, carbs: 50, fat: 5, fiber: 3, serving_size: '40 g', barcode: '',+}+const oats = { name: 'Oats', brand: 'Quaker', calories: 300, protein: 10, carbs: 50, fat: 5, fiber: 3, serving_size: '40 g', source: 'saved' as const }++describe('useFavorites epoch', () => {+ // A refresh issued while an unstar is in flight captures the epoch *after* the toggle+ // began. If only the start bumped it, that refresh would come back holding the row the+ // DELETE just removed, match its captured value, and put the phantom favourite back.+ it('moves when a toggle settles, so a load started mid-toggle is seen as stale', async () => {+ let finishDelete!: () => void+ const api = {+ create: () => Promise.resolve(OATS),+ delete: () => new Promise<void>(r => { finishDelete = r }),+ }+ const { result } = renderHook(() => useFavorites(api))+ act(() => { result.current.setSavedFoods([OATS]) })++ let pending!: Promise<unknown>+ act(() => { pending = result.current.toggle(oats) })+ const capturedByRefresh = result.current.epoch.current++ await act(async () => { finishDelete(); await pending })++ expect(result.current.epoch.current).not.toBe(capturedByRefresh)+ expect(result.current.savedFoods).toEqual([])+ })+})diff --git a/web/src/pages/Food.test.tsx b/web/src/pages/Food.test.tsxnew file mode 100644index 0000000..818f643--- /dev/null+++ b/web/src/pages/Food.test.tsx@@ -0,0 +1,100 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import { MemoryRouter } from 'react-router-dom'+import Food from './Food'++// Starring from the diary (#138): a logged entry is starred as the food it is — one+// serving, the same row the Recent, Favorites and Search tabs would star.++const list = vi.fn()+const savedList = vi.fn()+const savedCreate = vi.fn()+const savedDelete = vi.fn()++vi.mock('../services/api', () => ({+ foodAPI: {+ list: (...a: unknown[]) => list(...a),+ stats: () => Promise.resolve({ date: '2026-09-18', total_calories: 900, total_protein: 30, total_carbs: 150, total_fat: 15, total_fiber: 9, workout_count: 0 }),+ history: () => Promise.resolve([]),+ delete: vi.fn(),+ },+ savedFoodsAPI: {+ list: () => savedList(),+ create: (d: unknown) => savedCreate(d),+ delete: (id: number) => savedDelete(id),+ },+}))++vi.mock('../stores/settings', () => ({+ useSettingsStore: () => ({+ settings: { calorie_target: 2000, protein_target: 150, carb_target: 250, fat_target: 70, weight_unit: 'lbs' },+ fetch: () => Promise.resolve(),+ }),+}))++// Three servings of Oats logged: 900 kcal on the diary, 300 kcal as a favourite.+const OATS = {+ id: 7, user_id: 1, name: 'Oats', brand: 'Quaker', meal: 'breakfast',+ calories: 900, protein: 30, carbs: 150, fat: 15, fiber: 9,+ servings: 3, serving_size: '40 g', logged_at: '2026-09-18T08:00:00Z', logged_on: '2026-09-18',+}+const SAVED_OATS = {+ id: 42, user_id: 1, name: 'Oats', brand: 'Quaker',+ calories: 300, protein: 10, carbs: 50, fat: 5, fiber: 3, serving_size: '40 g', barcode: '', created_at: '',+}++const renderPage = () => render(<MemoryRouter><Food /></MemoryRouter>)++beforeEach(() => {+ vi.clearAllMocks()+ list.mockResolvedValue([OATS])+})++describe('Starring from the diary', () => {+ it('adds the entry to Favorites as one serving of the food', async () => {+ savedList.mockResolvedValue([])+ savedCreate.mockResolvedValue(SAVED_OATS)+ renderPage()++ fireEvent.click(await screen.findByRole('button', { name: 'Add Oats to Favorites' }))++ await waitFor(() => expect(savedCreate).toHaveBeenCalledTimes(1))+ expect(savedCreate).toHaveBeenCalledWith(expect.objectContaining({+ name: 'Oats', brand: 'Quaker', calories: 300, protein: 10, carbs: 50, fat: 5, fiber: 3,+ }))+ expect(await screen.findByRole('button', { name: 'Remove Oats from Favorites' })).toBeTruthy()+ })++ it('removes an entry that is already a favourite', async () => {+ savedList.mockResolvedValue([SAVED_OATS])+ savedDelete.mockResolvedValue(undefined)+ renderPage()++ fireEvent.click(await screen.findByRole('button', { name: 'Remove Oats from Favorites' }))++ await waitFor(() => expect(savedDelete).toHaveBeenCalledWith(42))+ expect(await screen.findByRole('button', { name: 'Add Oats to Favorites' })).toBeTruthy()+ })++ it('says why a star failed', async () => {+ savedList.mockResolvedValue([])+ savedCreate.mockRejectedValue(Object.assign(new Error('HTTP 503'), {+ response: { status: 503, data: { error: 'The server is busy. Try again.' } },+ }))+ renderPage()++ fireEvent.click(await screen.findByRole('button', { name: 'Add Oats to Favorites' }))++ expect(await screen.findByText('The server is busy. Try again.')).toBeTruthy()+ })++ // Unknown is not "not a favourite": if the list never arrived, an empty star would claim+ // something we don't know, so there is no star at all.+ it('draws no star when the favourites list failed to load', async () => {+ savedList.mockRejectedValue(new Error('down'))+ renderPage()++ await screen.findByText('Oats')+ expect(screen.queryByRole('button', { name: /Favorites/ })).toBeNull()+ })+})diff --git a/web/src/pages/Food.tsx b/web/src/pages/Food.tsxindex c72f102..5e3d821 100644--- a/web/src/pages/Food.tsx+++ b/web/src/pages/Food.tsx@@ -13,10 +13,11 @@ import {} from 'recharts'import Loading from '../components/Loading'import PeriodSelector from '../components/PeriodSelector'-import { foodAPI } from '../services/api'+import { foodAPI, savedFoodsAPI } from '../services/api'import { useSettingsStore } from '../stores/settings'-import { apiErrorMessage, isDailyStats, todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay } from '@lyftr/shared'+import { apiErrorMessage, entryToResult, isDailyStats, todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay, useFavorites, type Favorites } from '@lyftr/shared'import { ErrorState } from '../components/ui'+import FavoriteStar from '../components/FavoriteStar'const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as constconst MEAL_LABELS: Record<string, string> = {@@ -66,6 +67,22 @@ function MacroRing({// ─── Food page ────────────────────────────────────────────────────────────────+// A diary entry starred as the food it is. entryToResult divides the logged amount back+// down to one serving, which is what a favourite stores, so starring "3 x Oats" favourites+// Oats, and the star matches the same food on Recent, Favorites and Search.+function EntryStar({ entry, favorites }: { entry: types.FoodLog; favorites: Favorites }) {+ const food = entryToResult(entry)+ return (+ <FavoriteStar+ size="compact"+ favorited={favorites.favoriteOf(food) !== undefined}+ busy={favorites.isToggling(food)}+ name={entry.name}+ onClick={() => void favorites.toggle(food)}+ />+ )+}+export default function Food() {const navigate = useNavigate()const location = useLocation()@@ -96,6 +113,11 @@ export default function Food() {const [deletingId, setDeletingId] = useState<number | null>(null)const dateInputRef = useRef<HTMLInputElement>(null)const [deleteConfirmId, setDeleteConfirmId] = useState<number | null>(null)+ // Stars on the diary rows (#138), drawn only once the favourites list has loaded: a+ // failed load leaves them off rather than showing every entry as not a favourite.+ const favorites = useFavorites(savedFoodsAPI)+ const { setSavedFoods } = favorites+ const [favoritesLoaded, setFavoritesLoaded] = useState(false)const hasLoadedRef = useRef(false)const loadDay = useCallback(async (date: string) => {@@ -141,6 +163,11 @@ export default function Food() {useEffect(() => { void fetchSettings() }, [fetchSettings])useEffect(() => { loadDay(selectedDate) }, [selectedDate, location.key, loadDay])+ useEffect(() => {+ savedFoodsAPI.list()+ .then(list => { setSavedFoods(list); setFavoritesLoaded(true) })+ .catch(() => {})+ }, [setSavedFoods])useEffect(() => {// Same race as the weight trend: 90d is a slower query than 7d, so without this a@@ -233,10 +260,10 @@ export default function Food() {}/>- {error && (+ {(error || favorites.error) && (<div className="alert-error"><AlertCircle className="w-4 h-4 flex-shrink-0" />- <span>{error}</span>+ <span>{error ?? favorites.error}</span></div>)}@@ -444,6 +471,7 @@ export default function Food() {</div><ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" /></button>+ {favoritesLoaded && <EntryStar entry={entry} favorites={favorites} />}<IconButton icon={Trash2} variant="danger" label="Delete" onClick={() => setDeleteConfirmId(entry.id)} /></div>)}diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsxindex 341ea06..ceec613 100644--- a/web/src/pages/LogFood.tsx+++ b/web/src/pages/LogFood.tsx@@ -6,10 +6,11 @@ import {Coffee, Sun, Moon, Cookie, ChevronRight,} from 'lucide-react'import { foodAPI, savedFoodsAPI } from '../services/api'-import { apiErrorMessage, isNotFound, useAsyncAction, todayStr, dayToInstant, entryDay, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, findSavedFood } from '@lyftr/shared'+import { apiErrorMessage, isNotFound, useAsyncAction, todayStr, dayToInstant, entryDay, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, useFavorites } from '@lyftr/shared'import { ErrorState, ListError } from '../components/ui'import BarcodeScanner from '../components/BarcodeScanner'import BarcodeLookup from '../components/BarcodeLookup'+import FavoriteStar from '../components/FavoriteStar'import IconButton from '../components/ui/IconButton'import SegmentedControl from '../components/ui/SegmentedControl'import DateInput from '../components/ui/DateInput'@@ -96,28 +97,6 @@ function FoodResultRow()}-// Shared by the rows and the detail header so the two cannot drift. aria-pressed carries-// the toggle state that the fill conveys visually.-function FavoriteStar(- { favorited, busy = false, name, onClick, size = 'sm' }:- { favorited: boolean; busy?: boolean; name: string; onClick: () => void; size?: 'sm' | 'md' },-) {- const box = size === 'sm' ? 'w-8 h-8' : 'w-10 h-10'- const icon = size === 'sm' ? 'w-[18px] h-[18px]' : 'w-[22px] h-[22px]'- return (- <button- type="button"- onClick={onClick}- disabled={busy}- aria-pressed={favorited}- aria-label={favorited ? `Remove ${name} from Favorites` : `Add ${name} to Favorites`}- className={`${box} flex items-center justify-center rounded-lg flex-shrink-0 transition-colors hover:bg-surface-muted active:scale-95 disabled:opacity-40 ${favorited ? 'text-brand-500' : 'text-tx-muted'}`}- >- <Star className={icon} fill={favorited ? 'currentColor' : 'none'} strokeWidth={2.2} />- </button>- )-}-export default function LogFood() {const navigate = useNavigate()const [searchParams] = useSearchParams()@@ -131,7 +110,9 @@ export default function LogFood() {const [query, setQuery] = useState('')const [searchResults, setSearchResults] = useState<types.FoodSearchResult[]>([])const [recentItems, setRecentItems] = useState<types.FoodSearchResult[]>([])- const [savedFoods, setSavedFoods] = useState<types.SavedFood[]>([])+ // Starring lives in useFavorites, shared with the diary so the rules can't drift (#138).+ const { savedFoods, setSavedFoods, favoriteOf, isToggling, toggle: toggleFavorite, error: favoriteError } =+ useFavorites(savedFoodsAPI)// Each list's own failure. Kept separate from the page: one of these failing is not a// reason to withhold search, and an empty list that failed to load must not draw the// same "nothing here" as a list that really is empty.@@ -153,66 +134,6 @@ export default function LogFood() {const [meal, setMeal] = useState<types.FoodLog['meal']>(initMeal)const [date, setDate] = useState(initDate)- // Derived from the list rather than tracked, so a star clicked on any tab is reflected- // everywhere the same food appears — including the detail view.- const favoriteOf = (item: types.FoodSearchResult) => findSavedFood(savedFoods, item)- const favoriteKey = (item: types.FoodSearchResult) => `${item.name}|${item.brand ?? ''}`- const isToggling = (item: types.FoodSearchResult) => togglingFavorite.has(favoriteKey(item))-- // Favouriting is its own action, not a side effect of logging: one click on, one click- // off, from any row or from the detail view. No confirmation — a second click undoes it.- // The guard is a ref, not the state below. setState does not apply within the tick it- // is called in, so a burst of taps in one frame all read the same empty set and all- // fire — five rapid clicks sent one DELETE that worked and four that 404'd, then showed- // "Couldn't remove …" for an unstar that had actually succeeded. The state exists only- // to dim the star; the ref is what decides.- const inFlightFavorites = useRef<Set<string>>(new Set())-- const toggleFavorite = async (item: types.FoodSearchResult) => {- const key = favoriteKey(item)- // Guard this food only. A single global flag dropped clicks on *other* rows while a- // request was in flight, so on a slow connection every other star went dead with no- // feedback — indistinguishable from a broken button.- if (inFlightFavorites.current.has(key)) return- inFlightFavorites.current.add(key)- setTogglingFavorite(new Set(inFlightFavorites.current))- setFavoriteError(null)- const existing = favoriteOf(item)- try {- if (existing) {- await savedFoodsAPI.delete(existing.id)- setSavedFoods(prev => prev.filter(f => f.id !== existing.id))- } else {- const created = await savedFoodsAPI.create({- name: item.name, brand: item.brand ?? '',- calories: item.calories, protein: item.protein,- carbs: item.carbs, fat: item.fat, fiber: item.fiber ?? 0,- serving_size: item.serving_size ?? '',- })- // The server answers 200 with the existing row when the food is already- // favourited, so `created` can be something the list already holds — after a- // refetch that raced this request, for instance. Appending blind puts two rows- // with the same id (and the same React key) in the list.- // Inserted in name order rather than appended: ListSaved returns ORDER BY name,- // so appending parks a new favourite at the bottom until the next load and then- // jumps it. Plain < to match SQLite's BINARY collation rather than localeCompare,- // which would order differently from the server it is imitating.- setSavedFoods(prev => prev.some(f => f.id === created.id)- ? prev- : [...prev, created].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)))- }- } catch (err) {- setFavoriteError(apiErrorMessage(err, existing- ? `Couldn't remove ${item.name} from Favorites.`- : `Couldn't add ${item.name} to Favorites.`))- } finally {- inFlightFavorites.current.delete(key)- setTogglingFavorite(new Set(inFlightFavorites.current))- }- }-- const [togglingFavorite, setTogglingFavorite] = useState<Set<string>>(new Set())- const [favoriteError, setFavoriteError] = useState<string | null>(null)const [editError, setEditError] = useState<string | null>(null)const [editRetry, setEditRetry] = useState(0)@@ -248,7 +169,7 @@ export default function LogFood() {savedFoodsAPI.list().then(list => { setSavedFoods(list); setSavedError(null) }).catch(err => setSavedError(apiErrorMessage(err, "Couldn't load your favourites.")))- }, [listReload])+ }, [listReload, setSavedFoods])useEffect(() => {if (tab !== 'all') return