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.

Show a barcode lookup is running, and say why it failed (#183)

Carter98a88c51798b
diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsx
index 93dfcc3..6c0137d 100644
--- a/mobile/app/(tabs)/nutrition/log.tsx
+++ b/mobile/app/(tabs)/nutrition/log.tsx
@@ -10,17 +10,18 @@ import {
type FoodSearchResult, type SavedFood,
} from '@lyftr/shared'
import {
- Alert, AppText, Button, Card, DateInput, IconButton, Label, NumberField,
+ Alert, AppText, Button, Card, DateInput, ErrorState, IconButton, Label, NumberField,
NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, SearchField, SegmentedControl,
} from '../../../src/components/ui'
import { BarcodeScanner } from '../../../src/components/nutrition/BarcodeScanner'
+import { BarcodeLookup } from '../../../src/components/nutrition/BarcodeLookup'
import { FavoriteStar, FoodResultRow } from '../../../src/components/nutrition/FoodResultRow'
import {
MACRO_COLORS, MACRO_TEXT, MEALS, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal,
} from '../../../src/components/nutrition/nutritionMeta'
import { client } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
-import { apiErrorMessage, entryToResult, findSavedFood, savedToResult, scaleServing } from '@lyftr/shared'
+import { apiErrorMessage, entryToResult, findSavedFood, isNotFound, savedToResult, scaleServing } from '@lyftr/shared'
type Phase = 'search' | 'detail' | 'scan'
type SearchTab = 'recent' | 'myfoods' | 'all'
@@ -50,6 +51,12 @@ export default function LogFood() {
const [searching, setSearching] = useState(false)
const [searchError, setSearchError] = useState<string | null>(null)
const [rateLimited, setRateLimited] = useState(false)
+ // A barcode lookup goes through Open Food Facts and routinely takes seconds (the
+ // server allows it 5). The scanner closes the moment it reads a code, so without
+ // this the screen sat unchanged and people rescanned, thinking it had failed (#164).
+ // null: no lookup. error null: in flight. error set: failed, in the server's words.
+ const [lookup, setLookup] = useState<{ code: string; error: string | null } | null>(null)
+ const lookingUp = lookup !== null && lookup.error === null
const [selected, setSelected] = useState<FoodSearchResult | null>(null)
const [servingsStr, setServingsStr] = useState('1')
@@ -210,16 +217,23 @@ export default function LogFood() {
setPhase('detail')
}
- const handleBarcodeResult = async (code: string) => {
+ const enterManually = () => {
+ setLookup(null)
+ selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })
+ }
+
+ const lookUpBarcode = async (code: string) => {
setPhase('search')
+ setLookup({ code, error: null })
try {
selectResult(await client.foodAPI.barcode(code))
- } catch (err: any) {
- if (err?.response?.status === 404) {
- selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })
- } else {
- setSearchError('Product not found — enter details manually')
- }
+ setLookup(null)
+ } catch (err) {
+ // Only a 404 means the product isn't in the database. A timeout or an
+ // unreachable upstream is not an answer, and saying "not found" for it sent
+ // people to type in a product that does exist.
+ if (isNotFound(err)) enterManually()
+ else setLookup({ code, error: apiErrorMessage(err, "Couldn't look up that barcode.") })
}
}
@@ -257,7 +271,7 @@ export default function LogFood() {
}
if (phase === 'scan') {
- return <BarcodeScanner onResult={handleBarcodeResult} onClose={() => setPhase('search')} />
+ return <BarcodeScanner onResult={lookUpBarcode} onClose={() => setPhase('search')} />
}
const cal = selected ? Math.round(selected.calories * servings) : 0
@@ -340,13 +354,15 @@ export default function LogFood() {
loading={tab === 'all' && searching}
placeholder="Search food…"
value={query}
- onChangeText={(t) => { setQuery(t); if (t.trim()) setTab('all') }}
+ onChangeText={(t) => { setQuery(t); if (t.trim()) setTab('all'); if (lookup?.error) setLookup(null) }}
/>
</View>
<Pressable
onPress={() => { hSelect(); setPhase('scan') }}
+ disabled={lookingUp}
accessibilityLabel="Scan barcode"
- className="h-12 flex-row items-center gap-1.5 rounded-xl border border-surface-border bg-surface-muted px-3.5 active:opacity-70"
+ accessibilityState={{ disabled: lookingUp }}
+ className={`h-12 flex-row items-center gap-1.5 rounded-xl border border-surface-border bg-surface-muted px-3.5 active:opacity-70 ${lookingUp ? 'opacity-40' : ''}`}
>
<Scan size={20} color={colors.txSecondary} />
<AppText variant="caption" color="secondary" style={{ fontWeight: '600' }}>Scan</AppText>
@@ -354,7 +370,7 @@ export default function LogFood() {
</View>
{/* Tabs */}
- <SegmentedControl options={TAB_OPTIONS} value={tab} onChange={setTab} />
+ <SegmentedControl options={TAB_OPTIONS} value={tab} onChange={(t) => { setTab(t); if (lookup?.error) setLookup(null) }} />
{/* Above the tab content, not inside one branch: the star is on every tab, so
a failure starring a search result has to be visible on the search tab. */}
@@ -372,6 +388,20 @@ export default function LogFood() {
) : null}
{/* Results */}
+ {lookup && lookup.error === null ? (
+ <BarcodeLookup code={lookup.code} />
+ ) : lookup?.error ? (
+ // In place of the results rather than a banner above them: the lookup is
+ // what failed, and both ways forward keep the code already scanned.
+ <Card>
+ <ErrorState
+ title="Couldn't look up this barcode"
+ message={lookup.error}
+ onRetry={() => lookUpBarcode(lookup.code)}
+ secondary={<Button title="Enter it manually" variant="secondary" onPress={enterManually} />}
+ />
+ </Card>
+ ) : (
<Card className="overflow-hidden p-0">
{tab === 'all' && quickAddCals !== null ? (
<Pressable
@@ -453,6 +483,7 @@ export default function LogFood() {
/>
)) : null}
</Card>
+ )}
</View>
</ScrollView>
) : null}
diff --git a/mobile/src/components/nutrition/BarcodeLookup.tsx b/mobile/src/components/nutrition/BarcodeLookup.tsx
new file mode 100644
index 0000000..b29dd9a
--- /dev/null
+++ b/mobile/src/components/nutrition/BarcodeLookup.tsx
@@ -0,0 +1,89 @@
+import { useEffect, useState } from 'react'
+import { View } from 'react-native'
+import Animated, {
+ Easing,
+ cancelAnimation,
+ useAnimatedStyle,
+ useReducedMotion,
+ useSharedValue,
+ withRepeat,
+ withTiming,
+} from 'react-native-reanimated'
+import { Barcode } from 'lucide-react-native'
+import { eanModules, formatBarcode } from '@lyftr/shared'
+import { AppText, Card } from '../ui'
+import { useTheme } from '../../theme/useTheme'
+
+// When a lookup has run this long, say so: the silence past this point is what made
+// people rescan (#164). Open Food Facts routinely takes a few seconds.
+const SLOW_AFTER_MS = 4000
+
+const WIDTH = 144
+const HEIGHT = 56
+// Start, centre and end guards drop below the other bars, as they do on a pack.
+const GUARD_BARS = new Set([0, 2, 46, 48, 92, 94])
+const SHORT_BAR = HEIGHT * (40 / 46)
+
+// The barcode that was scanned, drawn from its digits, with a glyph for any symbology
+// we don't draw. One View per run of bar modules.
+function Bars({ code, color }: { code: string; color: string }) {
+ const modules = eanModules(code)
+ if (!modules) return <Barcode size={HEIGHT} color={color} strokeWidth={1.5} style={{ alignSelf: 'center' }} />
+ const unit = WIDTH / modules.length
+ const bars = []
+ for (let i = 0; i < modules.length; i++) {
+ if (modules[i] !== '1') continue
+ const start = i
+ while (modules[i + 1] === '1') i++
+ bars.push(
+ <View
+ key={start}
+ style={{
+ position: 'absolute', top: 0, left: start * unit, width: (i - start + 1) * unit,
+ height: GUARD_BARS.has(start) ? HEIGHT : SHORT_BAR, backgroundColor: color,
+ }}
+ />,
+ )
+ }
+ return <>{bars}</>
+}
+
+// Shown in place of the results while a scanned code is looked up: the barcode and its
+// digits, as printed on the pack, so the scan visibly landed. Mirrors web BarcodeLookup.
+export function BarcodeLookup({ code }: { code: string }) {
+ const { colors, accent } = useTheme()
+ const [slow, setSlow] = useState(false)
+ useEffect(() => {
+ const t = setTimeout(() => setSlow(true), SLOW_AFTER_MS)
+ return () => clearTimeout(t)
+ }, [])
+
+ // The scanner's read line passing over the bars; still, mid-way, for reduced motion.
+ const reduceMotion = useReducedMotion()
+ const sweep = useSharedValue(0.5)
+ useEffect(() => {
+ if (reduceMotion) return
+ sweep.value = 0.08
+ sweep.value = withRepeat(withTiming(0.88, { duration: 1100, easing: Easing.inOut(Easing.ease) }), -1, true)
+ return () => cancelAnimation(sweep)
+ }, [reduceMotion, sweep])
+ const line = useAnimatedStyle(() => ({ transform: [{ translateY: sweep.value * HEIGHT }] }))
+
+ return (
+ <Card className="items-center px-6 py-9" accessibilityRole="progressbar" accessibilityLiveRegion="polite">
+ <View style={{ width: WIDTH, height: HEIGHT }} importantForAccessibility="no-hide-descendants">
+ <Bars code={code} color={colors.txPrimary} />
+ <Animated.View style={[{ position: 'absolute', left: -8, right: -8, top: -3 }, line]}>
+ <View style={{ height: 6, borderRadius: 3, backgroundColor: accent, opacity: 0.25 }} />
+ <View style={{ position: 'absolute', top: 2, left: 0, right: 0, height: 2, borderRadius: 1, backgroundColor: accent }} />
+ </Animated.View>
+ </View>
+ <AppText variant="heading" className="mt-2" style={{ fontVariant: ['tabular-nums'], letterSpacing: 2.4 }}>
+ {formatBarcode(code)}
+ </AppText>
+ <AppText variant="body" color="muted" className="mt-3 text-center">
+ {slow ? 'Still looking. This can take a few seconds.' : 'Looking up this product…'}
+ </AppText>
+ </Card>
+ )
+}
diff --git a/packages/shared/src/utils/food.test.ts b/packages/shared/src/utils/food.test.ts
index 68452b0..50ae522 100644
--- a/packages/shared/src/utils/food.test.ts
+++ b/packages/shared/src/utils/food.test.ts
@@ -1,4 +1,4 @@
-import { entryToResult, findSavedFood, isDailyStats, normaliseFoodKey, savedToResult, scaleServing } from './food'
+import { eanModules, entryToResult, findSavedFood, formatBarcode, isDailyStats, normaliseFoodKey, savedToResult, scaleServing } from './food'
import type { FoodLog, SavedFood } from '../types'
const log = (over: Partial<FoodLog> = {}): FoodLog => ({
@@ -205,3 +205,36 @@ describe('isDailyStats', () => {
expect(isDailyStats(value)).toBe(false)
})
})
+
+describe('formatBarcode', () => {
+ it('groups each symbology the way it is printed on the pack', () => {
+ expect(formatBarcode('3017620422003')).toBe('3 017620 422003') // EAN-13
+ expect(formatBarcode('012345678905')).toBe('0 12345 67890 5') // UPC-A
+ expect(formatBarcode('12345670')).toBe('1234 5670') // EAN-8
+ })
+
+ it('leaves anything it does not recognise as scanned', () => {
+ expect(formatBarcode('0123456789')).toBe('0123456789')
+ expect(formatBarcode('0123456')).toBe('0123456')
+ expect(formatBarcode('ABC-123')).toBe('ABC-123')
+ })
+})
+
+describe('eanModules', () => {
+ // Pinned to a pattern a real decoder read: this exact string, drawn as bars, was
+ // scanned back to 3017620422003 by ZXing in the browser.
+ it('draws the bars of an EAN-13', () => {
+ expect(eanModules('3017620422003')).toBe(
+ '10100011010011001001000100001010011011000110101010101110011011001101100111001011100101000010101')
+ })
+
+ it('draws a UPC-A as the EAN-13 it is, with a leading 0', () => {
+ expect(eanModules('012345678905')).toBe(eanModules('0012345678905'))
+ expect(eanModules('012345678905')).toHaveLength(95)
+ })
+
+ it('declines what it cannot draw', () => {
+ expect(eanModules('12345670')).toBeNull() // EAN-8
+ expect(eanModules('ABC1234567890')).toBeNull()
+ })
+})
diff --git a/packages/shared/src/utils/food.ts b/packages/shared/src/utils/food.ts
index 652aa11..059cf5e 100644
--- a/packages/shared/src/utils/food.ts
+++ b/packages/shared/src/utils/food.ts
@@ -100,6 +100,38 @@ export function normaliseFoodKey(value: string | undefined): string {
// dashboard's macro rows read carbs and fat too, so checking only calories and protein
// let a payload missing those through to render NaN. Extra fields are still fine: a server
// that grows one must not make an older client call the payload broken.
+// A scanned code, grouped the way it is printed under the bars on the pack, so the
+// person can check it against the jar in their hand: EAN-13 `3 017620 422003`, UPC-A
+// `0 12345 67890 5`, EAN-8 `1234 5670`. Anything else is shown as scanned.
+export function formatBarcode(code: string): string {
+ if (!/^\d+$/.test(code)) return code
+ switch (code.length) {
+ case 13: return `${code[0]} ${code.slice(1, 7)} ${code.slice(7)}`
+ case 12: return `${code[0]} ${code.slice(1, 6)} ${code.slice(6, 11)} ${code[11]}`
+ case 8: return `${code.slice(0, 4)} ${code.slice(4)}`
+ default: return code
+ }
+}
+
+// The bars of an EAN-13 (or UPC-A, which is EAN-13 with a leading 0), as 95 modules,
+// '1' for a bar — so a screen can draw the barcode that was scanned rather than a
+// generic glyph. Null for anything else; callers fall back to an icon.
+const EAN_L = ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011']
+const EAN_G = ['0100111', '0110011', '0011011', '0100001', '0011101', '0111001', '0000101', '0010001', '0001001', '0010111']
+const EAN_R = ['1110010', '1100110', '1101100', '1000010', '1011100', '1001110', '1010000', '1000100', '1001000', '1110100']
+const EAN_PARITY = ['LLLLLL', 'LLGLGG', 'LLGGLG', 'LLGGGL', 'LGLLGG', 'LGGLLG', 'LGGGLL', 'LGLGLG', 'LGLGGL', 'LGGLGL']
+
+export function eanModules(code: string): string | null {
+ const c = code.length === 12 ? `0${code}` : code
+ if (!/^\d{13}$/.test(c)) return null
+ const parity = EAN_PARITY[Number(c[0])]
+ let bits = '101'
+ for (let i = 1; i <= 6; i++) bits += (parity[i - 1] === 'L' ? EAN_L : EAN_G)[Number(c[i])]
+ bits += '01010'
+ for (let i = 7; i <= 12; i++) bits += EAN_R[Number(c[i])]
+ return `${bits}101`
+}
+
const RENDERED_MACROS = ['total_calories', 'total_protein', 'total_carbs', 'total_fat'] as const
export function isDailyStats(value: unknown): value is import('../types').DailyStats {
diff --git a/web/src/components/BarcodeLookup.test.tsx b/web/src/components/BarcodeLookup.test.tsx
new file mode 100644
index 0000000..cb8f1d6
--- /dev/null
+++ b/web/src/components/BarcodeLookup.test.tsx
@@ -0,0 +1,18 @@
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { render, screen, act } from '@testing-library/react'
+import BarcodeLookup from './BarcodeLookup'
+
+afterEach(() => vi.useRealTimers())
+
+describe('BarcodeLookup', () => {
+ // The silence past a few seconds is what made people rescan (#164), so a slow lookup
+ // says it is still going rather than sitting on the first line indefinitely.
+ it('says it is still looking once the lookup runs long', () => {
+ vi.useFakeTimers()
+ render(<BarcodeLookup code="3017620422003" />)
+
+ expect(screen.getByText('Looking up this product…')).toBeTruthy()
+ act(() => { vi.advanceTimersByTime(4000) })
+ expect(screen.getByText('Still looking. This can take a few seconds.')).toBeTruthy()
+ })
+})
diff --git a/web/src/components/BarcodeLookup.tsx b/web/src/components/BarcodeLookup.tsx
new file mode 100644
index 0000000..996abf0
--- /dev/null
+++ b/web/src/components/BarcodeLookup.tsx
@@ -0,0 +1,54 @@
+import { useEffect, useState } from 'react'
+import { Barcode } from 'lucide-react'
+import { eanModules, formatBarcode } from '@lyftr/shared'
+
+// When a lookup has run this long, say so: the silence past this point is what made
+// people rescan (#164). Open Food Facts routinely takes a few seconds.
+const SLOW_AFTER_MS = 4000
+
+// Start, centre and end guards drop below the other bars, as they do on a pack.
+const GUARD_BARS = new Set([0, 2, 46, 48, 92, 94])
+
+// The barcode that was scanned, drawn from its digits, with a glyph for any symbology
+// we don't draw. One rect per run of bar modules.
+function Bars({ code }: { code: string }) {
+ const modules = eanModules(code)
+ if (!modules) return <Barcode className="w-full h-full text-tx-muted" strokeWidth={1.5} />
+ const runs: { x: number; w: number; guard: boolean }[] = []
+ for (let i = 0; i < modules.length; i++) {
+ if (modules[i] !== '1') continue
+ const start = i
+ while (modules[i + 1] === '1') i++
+ runs.push({ x: start, w: i - start + 1, guard: GUARD_BARS.has(start) })
+ }
+ return (
+ <svg viewBox="0 0 95 46" preserveAspectRatio="none" shapeRendering="crispEdges" className="w-full h-full text-tx-primary" fill="currentColor">
+ {runs.map(r => <rect key={r.x} x={r.x} width={r.w} y={0} height={r.guard ? 46 : 40} />)}
+ </svg>
+ )
+}
+
+// Shown in place of the results while a scanned code is looked up: the barcode and its
+// digits, as printed on the pack, so the scan visibly landed.
+export default function BarcodeLookup({ code }: { code: string }) {
+ const [slow, setSlow] = useState(false)
+ useEffect(() => {
+ const t = setTimeout(() => setSlow(true), SLOW_AFTER_MS)
+ return () => clearTimeout(t)
+ }, [])
+
+ return (
+ <div className="card px-6 py-9 flex flex-col items-center text-center" role="status">
+ <div className="relative w-36 h-14" aria-hidden="true">
+ <Bars code={code} />
+ <span className="absolute -inset-x-2 h-0.5 rounded-full bg-brand-500 shadow-[0_0_10px_2px] shadow-brand-500/60 animate-scan-sweep" />
+ </div>
+ <p className="mt-2 font-display font-bold text-lg tabular-nums tracking-[0.14em] text-tx-primary">
+ {formatBarcode(code)}
+ </p>
+ <p className="mt-3 text-sm text-tx-muted">
+ {slow ? 'Still looking. This can take a few seconds.' : 'Looking up this product…'}
+ </p>
+ </div>
+ )
+}
diff --git a/web/src/components/ui/ErrorState.tsx b/web/src/components/ui/ErrorState.tsx
index 4458569..412f70c 100644
--- a/web/src/components/ui/ErrorState.tsx
+++ b/web/src/components/ui/ErrorState.tsx
@@ -60,7 +60,7 @@ export default function ErrorState({
<p className={`font-display font-bold text-tx-primary ${page ? 'text-xl' : 'text-base'}`}>
{title}
</p>
- <p className="text-sm text-tx-muted leading-relaxed">{message}</p>
+ <p className="text-sm text-tx-muted leading-relaxed text-pretty">{message}</p>
</div>
{(onRetry || secondary) && (
<div className="flex flex-wrap items-center justify-center gap-2 mt-1">
diff --git a/web/src/index.css b/web/src/index.css
index 12ad198..cb56800 100644
--- a/web/src/index.css
+++ b/web/src/index.css
@@ -156,6 +156,16 @@
to { opacity: 1; }
}
+ /* The scanner's read line, passing over the barcode while it is looked up. */
+ @keyframes scan-sweep {
+ from { top: 8%; }
+ to { top: 88%; }
+ }
+ .animate-scan-sweep { animation: scan-sweep 1.1s ease-in-out infinite alternate; }
+ @media (prefers-reduced-motion: reduce) {
+ .animate-scan-sweep { animation: none; top: 48%; }
+ }
+
.animate-slide-up { animation: slide-up 0.2s ease-out both; }
.animate-fade-in { animation: fade-in 0.15s ease-out both; }
diff --git a/web/src/pages/LogFood.test.tsx b/web/src/pages/LogFood.test.tsx
new file mode 100644
index 0000000..b88df73
--- /dev/null
+++ b/web/src/pages/LogFood.test.tsx
@@ -0,0 +1,121 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { MemoryRouter } from 'react-router-dom'
+import LogFood from './LogFood'
+
+// A barcode lookup goes through Open Food Facts and takes seconds. The bug these pin
+// (#164): the scanner closed and the screen sat unchanged while it ran, so people
+// rescanned three or four times thinking it had failed — and when it did fail for a
+// reason other than "no such product", it said "Product not found" anyway.
+
+const barcode = vi.fn()
+
+vi.mock('../services/api', () => ({
+ foodAPI: {
+ list: () => Promise.resolve([]),
+ search: () => Promise.resolve([]),
+ barcode: (code: string) => barcode(code),
+ get: vi.fn(),
+ log: vi.fn(),
+ update: vi.fn(),
+ },
+ savedFoodsAPI: {
+ list: () => Promise.resolve([]),
+ create: vi.fn(),
+ delete: vi.fn(),
+ },
+}))
+
+// The real scanner needs a camera. This one hands back a code the way it would.
+vi.mock('../components/BarcodeScanner', () => ({
+ default: ({ onResult }: { onResult: (code: string) => void }) => (
+ <button onClick={() => onResult('3017620422003')}>Simulate scan</button>
+ ),
+}))
+
+const renderPage = () => render(<MemoryRouter><LogFood /></MemoryRouter>)
+
+const scan = async () => {
+ fireEvent.click(await screen.findByRole('button', { name: 'Scan barcode' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Simulate scan' }))
+}
+
+const scanButton = () => screen.getByRole('button', { name: 'Scan barcode' }) as HTMLButtonElement
+
+const httpError = (status: number, error?: string) =>
+ Object.assign(new Error(`HTTP ${status}`), { response: { status, data: error ? { error } : {} } })
+
+const TIMEOUT = "The food database didn't respond in time. Try again."
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('Barcode lookup', () => {
+ it('shows the scanned code while it is looked up, and blocks a second scan', async () => {
+ barcode.mockReturnValue(new Promise(() => {}))
+ renderPage()
+
+ await scan()
+
+ // The code, grouped as printed on the pack, is the proof the scan landed.
+ expect(await screen.findByText('3 017620 422003')).toBeTruthy()
+ expect(screen.getByText('Looking up this product…')).toBeTruthy()
+ expect(scanButton().disabled).toBe(true)
+ })
+
+ it("says what actually went wrong when the lookup fails, not that the product doesn't exist", async () => {
+ barcode.mockRejectedValue(httpError(503, TIMEOUT))
+ renderPage()
+
+ await scan()
+
+ expect(await screen.findByText("Couldn't look up this barcode")).toBeTruthy()
+ expect(screen.getByText(TIMEOUT)).toBeTruthy()
+ expect(screen.queryByText(/not found/i)).toBeNull()
+ expect(scanButton().disabled).toBe(false)
+ })
+
+ it('retries the same code without asking for another scan', async () => {
+ barcode.mockRejectedValueOnce(httpError(503, TIMEOUT))
+ barcode.mockResolvedValueOnce({ name: 'Nutella', calories: 539, protein: 6.3, carbs: 57.5, fat: 30.9, fiber: 0, serving_size: '100 g', source: 'off' })
+ renderPage()
+
+ await scan()
+ fireEvent.click(await screen.findByRole('button', { name: /try again/i }))
+
+ expect(await screen.findByText('Nutella')).toBeTruthy()
+ expect(barcode).toHaveBeenCalledTimes(2)
+ expect(barcode).toHaveBeenLastCalledWith('3017620422003')
+ })
+
+ it('lets a failed lookup be entered by hand instead', async () => {
+ barcode.mockRejectedValue(httpError(503, TIMEOUT))
+ renderPage()
+
+ await scan()
+ fireEvent.click(await screen.findByRole('button', { name: 'Enter it manually' }))
+
+ expect(await screen.findByText('New Entry')).toBeTruthy()
+ })
+
+ it('clears a failed lookup once the person starts searching instead', async () => {
+ barcode.mockRejectedValue(httpError(503, TIMEOUT))
+ renderPage()
+
+ await scan()
+ await screen.findByText("Couldn't look up this barcode")
+ fireEvent.change(screen.getByPlaceholderText('Search food…'), { target: { value: 'oats' } })
+
+ await waitFor(() => expect(screen.queryByText("Couldn't look up this barcode")).toBeNull())
+ })
+
+ it('opens a blank entry to fill in when the product really is not in the database', async () => {
+ barcode.mockRejectedValue(httpError(404, 'No product matched that barcode.'))
+ renderPage()
+
+ await scan()
+
+ expect(await screen.findByText('New Entry')).toBeTruthy()
+ })
+})
diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsx
index e112cba..341ea06 100644
--- a/web/src/pages/LogFood.tsx
+++ b/web/src/pages/LogFood.tsx
@@ -6,9 +6,10 @@ import {
Coffee, Sun, Moon, Cookie, ChevronRight,
} from 'lucide-react'
import { foodAPI, savedFoodsAPI } from '../services/api'
-import { apiErrorMessage, 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, findSavedFood } from '@lyftr/shared'
import { ErrorState, ListError } from '../components/ui'
import BarcodeScanner from '../components/BarcodeScanner'
+import BarcodeLookup from '../components/BarcodeLookup'
import IconButton from '../components/ui/IconButton'
import SegmentedControl from '../components/ui/SegmentedControl'
import DateInput from '../components/ui/DateInput'
@@ -140,6 +141,12 @@ export default function LogFood() {
const [searching, setSearching] = useState(false)
const [searchError, setSearchError] = useState<string | null>(null)
const [rateLimited, setRateLimited] = useState(false)
+ // A barcode lookup goes through Open Food Facts and routinely takes seconds (the
+ // server allows it 5). The scanner closes the moment it reads a code, so without
+ // this the screen sat unchanged and people rescanned, thinking it had failed (#164).
+ // null: no lookup. error null: in flight. error set: failed, in the server's words.
+ const [lookup, setLookup] = useState<{ code: string; error: string | null } | null>(null)
+ const lookingUp = lookup !== null && lookup.error === null
const [selected, setSelected] = useState<types.FoodSearchResult | null>(null)
const [servings, setServings] = useState(1)
@@ -270,16 +277,23 @@ export default function LogFood() {
setPhase('detail')
}
- const handleBarcodeResult = async (code: string) => {
+ const enterManually = () => {
+ setLookup(null)
+ selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })
+ }
+
+ const lookUpBarcode = async (code: string) => {
setPhase('search')
+ setLookup({ code, error: null })
try {
selectResult(await foodAPI.barcode(code))
- } catch (err: any) {
- if (err?.response?.status === 404) {
- selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })
- } else {
- setSearchError('Product not found — enter details manually')
- }
+ setLookup(null)
+ } catch (err) {
+ // Only a 404 means the product isn't in the database. A timeout or an
+ // unreachable upstream is not an answer, and saying "not found" for it sent
+ // people to type in a product that does exist.
+ if (isNotFound(err)) enterManually()
+ else setLookup({ code, error: apiErrorMessage(err, "Couldn't look up that barcode.") })
}
}
@@ -305,7 +319,7 @@ export default function LogFood() {
if (phase === 'scan') {
return (
<BarcodeScanner
- onResult={handleBarcodeResult}
+ onResult={lookUpBarcode}
onClose={() => setPhase('search')}
/>
)
@@ -398,7 +412,7 @@ export default function LogFood() {
autoFocus
type="text"
value={query}
- onChange={e => { setQuery(e.target.value); if (e.target.value.trim()) setTab('all') }}
+ onChange={e => { setQuery(e.target.value); if (e.target.value.trim()) setTab('all'); if (lookup?.error) setLookup(null) }}
placeholder="Search food…"
className="input pl-10 pr-10 w-full h-12 text-base"
/>
@@ -413,7 +427,8 @@ export default function LogFood() {
</div>
<button
onClick={() => setPhase('scan')}
- className="flex items-center gap-1.5 px-3.5 h-12 rounded-xl bg-surface-muted hover:bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors flex-shrink-0"
+ disabled={lookingUp}
+ className="flex items-center gap-1.5 px-3.5 h-12 rounded-xl bg-surface-muted hover:bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors flex-shrink-0 disabled:opacity-40 disabled:pointer-events-none"
aria-label="Scan barcode"
>
<Scan className="w-5 h-5" />
@@ -429,7 +444,7 @@ export default function LogFood() {
{ value: 'all', label: 'Search' },
] as const}
value={tab}
- onChange={setTab}
+ onChange={t => { setTab(t); if (lookup?.error) setLookup(null) }}
/>
{rateLimited && (
@@ -446,6 +461,20 @@ export default function LogFood() {
)}
{/* Results */}
+ {lookup && lookup.error === null ? (
+ <BarcodeLookup code={lookup.code} />
+ ) : lookup?.error ? (
+ // In place of the results rather than a banner above them: the lookup is
+ // what failed, and both ways forward keep the code already scanned.
+ <div className="card">
+ <ErrorState
+ title="Couldn't look up this barcode"
+ message={lookup.error}
+ onRetry={() => lookUpBarcode(lookup.code)}
+ secondary={<button onClick={enterManually} className="btn-secondary btn-sm">Enter it manually</button>}
+ />
+ </div>
+ ) : (
<div className="card overflow-hidden">
{tab === 'all' && quickAddCals !== null && (
<button
@@ -544,6 +573,7 @@ export default function LogFood() {
/>
))}
</div>
+ )}
</div>
)}