Skip to content

armgit / lyftr

Public Imported from GitHub
0

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

A failed star flips back and toasts why, instead of a banner above the list (#190)

Carter8cca7b6dbc3d
diff --git a/mobile/app/(tabs)/nutrition/[id].tsx b/mobile/app/(tabs)/nutrition/[id].tsx
index a336e3a..00934fa 100644
--- a/mobile/app/(tabs)/nutrition/[id].tsx
+++ b/mobile/app/(tabs)/nutrition/[id].tsx
@@ -2,10 +2,10 @@ 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 { AlertCircle, ArrowLeft, Edit2, Flame, Trash2 } from 'lucide-react-native'
import { apiErrorMessage, entryToResult, formatLoggedAmount, isNotFound, useAsyncAction, useFavorites, entryDay, type FoodLog, formatDay } from '@lyftr/shared'
import {
- Alert, AppText, Button, Card, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps,
+ AppText, Button, Card, ConfirmSheet, ErrorState, Loading, Screen, Toast, deleteConfirmProps,
} from '../../../src/components/ui'
import {
MACRO_COLORS, MACRO_TEXT, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal,
@@ -155,9 +155,6 @@ 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 ? (
@@ -230,6 +227,8 @@ export default function NutritionDetail() {
onConfirm={() => { void remove.run() }}
onCancel={() => { setConfirming(false); remove.reset() }}
/>
+
+ {favorites.error ? <Toast variant="error" icon={AlertCircle} title={favorites.error} onDismiss={() => favorites.setError(null)} /> : null}
</Screen>
)
}
diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsx
index ee8940c..7dcffd6 100644
--- a/mobile/app/(tabs)/nutrition/log.tsx
+++ b/mobile/app/(tabs)/nutrition/log.tsx
@@ -10,7 +10,7 @@ import {
type FoodSearchResult,
} from '@lyftr/shared'
import {
- Alert, AppText, Button, Card, DateInput, ErrorState, IconButton, Label, NumberField,
+ Alert, AppText, Button, Card, DateInput, ErrorState, IconButton, Label, NumberField, Toast,
NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, SearchField, SegmentedControl,
} from '../../../src/components/ui'
import { BarcodeScanner } from '../../../src/components/nutrition/BarcodeScanner'
@@ -49,7 +49,7 @@ export default function LogFood() {
const [searchResults, setSearchResults] = useState<FoodSearchResult[]>([])
const [recentItems, setRecentItems] = useState<FoodSearchResult[]>([])
const favorites = useFavorites(client.savedFoodsAPI)
- const { savedFoods, setSavedFoods, favoriteOf, isToggling, error: favoriteError } = favorites
+ const { savedFoods, setSavedFoods, favoriteOf, isToggling } = favorites
// Bumped by every star/unstar; a list load drops its result if a toggle landed meanwhile.
const listEpoch = favorites.epoch
const [searching, setSearching] = useState(false)
@@ -123,7 +123,7 @@ export default function LogFood() {
}).catch(() => {}),
client.savedFoodsAPI.list().then(apply(setSavedFoods)).catch(() => {}),
])
- }, [])
+ }, [listEpoch, setSavedFoods])
useEffect(() => { loadLists() }, [loadLists])
@@ -297,12 +297,6 @@ export default function LogFood() {
</View>
) : null}
- {favoriteError ? (
- <View className="pb-3">
- <Alert variant="error">{favoriteError}</Alert>
- </View>
- ) : null}
-
{/* ── Search phase ── */}
{phase === 'search' ? (
<ScrollView
@@ -615,6 +609,14 @@ export default function LogFood() {
<NumericKeyboardAccessory />
</>
) : null}
+
+ {favorites.error ? (
+ // Detail has a sticky Log Food button in the toast's default band; ride above it.
+ <Toast
+ variant="error" icon={AlertCircle} title={favorites.error} onDismiss={() => favorites.setError(null)}
+ className={phase === 'detail' ? 'bottom-28' : ''}
+ />
+ ) : null}
</Screen>
)
}
diff --git a/packages/shared/src/hooks/useFavorites.ts b/packages/shared/src/hooks/useFavorites.ts
index 83c7669..0589f09 100644
--- a/packages/shared/src/hooks/useFavorites.ts
+++ b/packages/shared/src/hooks/useFavorites.ts
@@ -33,6 +33,14 @@ export interface Favorites {
epoch: React.MutableRefObject<number>
}
+// 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. A row already present (same id) is kept.
+const insertByName = (list: SavedFood[], row: SavedFood) => list.some(f => f.id === row.id)
+ ? list
+ : [...list, row].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
+
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,
@@ -44,6 +52,7 @@ export function useFavorites(api: SavedFoodsApi): Favorites {
const [toggling, setToggling] = useState<Set<string>>(new Set())
const [error, setError] = useState<string | null>(null)
const epoch = useRef(0)
+ const tempId = 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
@@ -68,31 +77,35 @@ export function useFavorites(api: SavedFoodsApi): Favorites {
setError(null)
epoch.current += 1
const existing = favoriteOf(item)
+ const food = {
+ 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 ?? '',
+ }
+ // Answer the tap at once and put it back if the server refuses: on gym wifi the round
+ // trip is seconds of a dead-looking star. `pending` stands in until the real id arrives.
+ const pending: SavedFood = { id: --tempId.current, ...food }
+ if (existing) setSavedFoods(prev => prev.filter(f => f.id !== existing.id))
+ else setSavedFoods(prev => insertByName(prev, pending))
try {
if (existing) {
await api.delete(existing.id)
+ // Again after the await: a list load that came back mid-request can have put the
+ // row back, and the epoch only drops loads that land after this settles.
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 ?? '',
- })
+ const created = await api.create(food)
// 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)))
+ // this request, for instance. insertByName skips an id it already has.
+ setSavedFoods(prev => insertByName(prev.filter(f => f.id !== pending.id), created))
return 'added'
} catch (err) {
+ setSavedFoods(prev => existing
+ ? insertByName(prev, existing)
+ : prev.filter(f => f.id !== pending.id))
setError(apiErrorMessage(err, existing
? `Couldn't remove ${item.name} from Favorites.`
: `Couldn't add ${item.name} to Favorites.`))
diff --git a/web/src/hooks/useFavorites.test.ts b/web/src/hooks/useFavorites.test.ts
index a0bc70a..15e06fa 100644
--- a/web/src/hooks/useFavorites.test.ts
+++ b/web/src/hooks/useFavorites.test.ts
@@ -34,3 +34,61 @@ describe('useFavorites epoch', () => {
expect(result.current.savedFoods).toEqual([])
})
})
+
+// The star answers the tap at once; a refusal puts it back and says why.
+describe('useFavorites optimistic toggle', () => {
+ const granola = { ...oats, name: 'Granola', brand: '' }
+ const GRANOLA: SavedFood = { ...OATS, id: 7, name: 'Granola', brand: '' }
+ const refuse = () => Promise.reject(new Error('down'))
+
+ it('shows a new favourite before the server answers, then swaps in the real row', async () => {
+ let finish!: (f: SavedFood) => void
+ const api = { create: () => new Promise<SavedFood>(r => { finish = r }), delete: () => Promise.resolve() }
+ const { result } = renderHook(() => useFavorites(api))
+
+ let pending!: Promise<unknown>
+ act(() => { pending = result.current.toggle(oats) })
+ expect(result.current.favoriteOf(oats)).toBeDefined()
+
+ await act(async () => { finish(OATS); await pending })
+ expect(result.current.savedFoods).toEqual([OATS])
+ })
+
+ it('takes a failed add back out and reports it', async () => {
+ const { result } = renderHook(() => useFavorites({ create: refuse, delete: () => Promise.resolve() }))
+
+ await act(async () => { await result.current.toggle(oats) })
+
+ expect(result.current.favoriteOf(oats)).toBeUndefined()
+ expect(result.current.savedFoods).toEqual([])
+ expect(result.current.error).toEqual(expect.any(String))
+ })
+
+ it('drops the row again when a reload mid-delete brought it back', 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) })
+ act(() => { result.current.setSavedFoods([OATS]) })
+
+ await act(async () => { finishDelete(); await pending })
+ expect(result.current.savedFoods).toEqual([])
+ })
+
+ it('puts a failed unstar back in its place, in name order', async () => {
+ const { result } = renderHook(() => useFavorites({ create: () => Promise.resolve(OATS), delete: refuse }))
+ act(() => { result.current.setSavedFoods([GRANOLA, OATS]) })
+
+ let pending!: Promise<unknown>
+ act(() => { pending = result.current.toggle(oats) })
+ expect(result.current.favoriteOf(oats)).toBeUndefined()
+
+ await act(async () => { await pending })
+ expect(result.current.savedFoods).toEqual([GRANOLA, OATS])
+ expect(result.current.error).toEqual(expect.any(String))
+ expect(result.current.favoriteOf(granola)).toBeDefined()
+ })
+})
diff --git a/web/src/pages/Food.tsx b/web/src/pages/Food.tsx
index 81dc94d..4813f6e 100644
--- a/web/src/pages/Food.tsx
+++ b/web/src/pages/Food.tsx
@@ -16,7 +16,7 @@ import PeriodSelector from '../components/PeriodSelector'
import { foodAPI, savedFoodsAPI } from '../services/api'
import { useSettingsStore } from '../stores/settings'
import { apiErrorMessage, entryToResult, formatLoggedAmount, isDailyStats, todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay, useFavorites, type Favorites } from '@lyftr/shared'
-import { ErrorState } from '../components/ui'
+import { ErrorState, Toast } from '../components/ui'
import FavoriteStar from '../components/FavoriteStar'
const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as const
@@ -260,13 +260,15 @@ export default function Food() {
}
/>
- {(error || favorites.error) && (
+ {error && (
<div className="alert-error">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error ?? favorites.error}</span>
+ <span>{error}</span>
</div>
)}
+ {favorites.error && <Toast variant="error" icon={AlertCircle} title={favorites.error} onDismiss={() => favorites.setError(null)} />}
+
{/* Date navigator */}
<div className="flex items-center gap-2">
<button
diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsx
index 0eed7b2..56cb986 100644
--- a/web/src/pages/LogFood.tsx
+++ b/web/src/pages/LogFood.tsx
@@ -7,7 +7,7 @@ import {
} 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 { ErrorState, ListError } from '../components/ui'
+import { ErrorState, ListError, Toast } from '../components/ui'
import BarcodeScanner from '../components/BarcodeScanner'
import BarcodeLookup from '../components/BarcodeLookup'
import FavoriteStar from '../components/FavoriteStar'
@@ -110,8 +110,8 @@ export default function LogFood() {
const [searchResults, setSearchResults] = useState<types.FoodSearchResult[]>([])
const [recentItems, setRecentItems] = useState<types.FoodSearchResult[]>([])
// 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)
+ const favorites = useFavorites(savedFoodsAPI)
+ const { savedFoods, setSavedFoods, favoriteOf, isToggling, toggle: toggleFavorite } = favorites
// 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.
@@ -338,16 +338,9 @@ export default function LogFood() {
)}
</div>
- {/* Outside both phases on purpose: the star is on the rows *and* in the header
- above, so a failure has to be visible whichever one the user pressed. Sitting
- inside the search phase meant a failed star on the detail view said nothing at
- all and simply snapped back to unfilled. */}
- {favoriteError && (
- <div className="flex items-center gap-2 px-3 py-2.5 mb-4 rounded-xl border border-error-500/20 bg-error-500/10">
- <AlertCircle className="w-4 h-4 text-error-400 flex-shrink-0" />
- <p className="text-xs text-error-400">{favoriteError}</p>
- </div>
- )}
+ {/* A toast, not a banner: the star is on the rows *and* in the header, and the
+ failed star has already snapped back, so this only has to say why. */}
+ {favorites.error && <Toast variant="error" icon={AlertCircle} title={favorites.error} onDismiss={() => favorites.setError(null)} />}
{/* Search phase */}
{phase === 'search' && (