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.

feat(web): centralized client-side weight validation (mirrors backend bound) (#54)

Carter8c9d2925dce9
diff --git a/web/src/components/EditWeightModal.tsx b/web/src/components/EditWeightModal.tsx
index 16e61d3..f1f159c 100644
--- a/web/src/components/EditWeightModal.tsx
+++ b/web/src/components/EditWeightModal.tsx
@@ -2,11 +2,10 @@ import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { X, Scale, AlertCircle, Save } from 'lucide-react'
import { weightAPI } from '../services/api'
-import { useSettingsStore, weightShort, displayToLbs, displayWeight } from '../stores/settings'
+import { useSettingsStore, weightShort, displayToLbs, displayWeight , weightError, maxWeight } from '../stores/settings'
import WeightInput from './WeightInput'
import { useBodyScrollLock } from '../hooks/useBodyScrollLock'
import { useEscapeKey } from '../hooks/useEscapeKey'
-import { isPositiveNumber } from '../utils/numberUtils'
import { dayToIsoNoon, isoToDayInput, todayStr } from '../utils/dateUtils'
import * as types from '../types'
@@ -44,8 +43,9 @@ export default function EditWeightModal({ isOpen, onClose, onSuccess, log }: Pro
e.preventDefault()
if (!log || saving) return
const w = parseFloat(weight)
- if (!Number.isFinite(w) || w <= 0) {
- setError('Enter a valid weight')
+ const wErr = weightError(w, settings.weight_unit)
+ if (wErr) {
+ setError(wErr)
return
}
setSaving(true)
@@ -100,7 +100,7 @@ export default function EditWeightModal({ isOpen, onClose, onSuccess, log }: Pro
<div>
<label className="label">Weight</label>
<div className="mt-1">
- <WeightInput value={weight} onChange={setWeight} unit={wUnit} autoFocus />
+ <WeightInput value={weight} onChange={setWeight} unit={wUnit} max={maxWeight(settings.weight_unit)} autoFocus />
</div>
</div>
@@ -137,7 +137,7 @@ export default function EditWeightModal({ isOpen, onClose, onSuccess, log }: Pro
</button>
<button
type="submit"
- disabled={!isPositiveNumber(weight) || saving}
+ disabled={!(parseFloat(weight) > 0) || saving}
className="btn-primary btn-md"
>
<Save className="w-4 h-4" />
diff --git a/web/src/components/QuickWeighInSheet.tsx b/web/src/components/QuickWeighInSheet.tsx
index 9af6294..a0cfcea 100644
--- a/web/src/components/QuickWeighInSheet.tsx
+++ b/web/src/components/QuickWeighInSheet.tsx
@@ -2,10 +2,9 @@ import { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { X, Scale, Save, AlertCircle, Calendar, FileText } from 'lucide-react'
import { weightAPI } from '../services/api'
-import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'
+import { useSettingsStore, weightShort, displayToLbs , weightError, maxWeight } from '../stores/settings'
import { useBodyScrollLock } from '../hooks/useBodyScrollLock'
import { useEscapeKey } from '../hooks/useEscapeKey'
-import { isPositiveNumber } from '../utils/numberUtils'
import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'
import WeightInput from './WeightInput'
import * as types from '../types'
@@ -55,8 +54,9 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
e.preventDefault()
if (saving) return
const w = parseFloat(value)
- if (!Number.isFinite(w) || w <= 0) {
- setError('Enter a valid weight')
+ const wErr = weightError(w, settings.weight_unit)
+ if (wErr) {
+ setError(wErr)
return
}
@@ -151,6 +151,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
value={value}
onChange={setValue}
unit={wUnit}
+ max={maxWeight(settings.weight_unit)}
autoFocus
size="lg"
/>
@@ -195,7 +196,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
<button
type="submit"
- disabled={!isPositiveNumber(value) || saving}
+ disabled={!(parseFloat(value) > 0) || saving}
className="btn-primary btn-lg w-full"
>
<Save className="w-4 h-4" />
diff --git a/web/src/components/WeightInput.tsx b/web/src/components/WeightInput.tsx
index 7831c5d..071e3fc 100644
--- a/web/src/components/WeightInput.tsx
+++ b/web/src/components/WeightInput.tsx
@@ -12,6 +12,10 @@ interface Props {
stepper?: boolean
placeholder?: string
disabled?: boolean
+ /** Optional upper bound (display units) — clamps the +/- stepper. Submit-time
+ * validation/messaging is the caller's job (an html max would preempt it with
+ * a native browser tooltip). */
+ max?: number
}
// The field always accepts 0.1 precision (the #39 feature); the +/- buttons step
@@ -34,11 +38,12 @@ export default function WeightInput({
stepper = true,
placeholder = '0.0',
disabled = false,
+ max,
}: Props) {
const adjust = (delta: number) => {
const current = parseFloat(value)
const base = Number.isFinite(current) ? current : 0
- const next = Math.max(0, +(base + delta).toFixed(1))
+ const next = Math.min(max ?? Infinity, Math.max(0, +(base + delta).toFixed(1)))
onChange(String(next))
}
diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsx
index 1735219..6982ced 100644
--- a/web/src/pages/Weight.tsx
+++ b/web/src/pages/Weight.tsx
@@ -9,10 +9,9 @@ import DateInput from '../components/ui/DateInput'
import PeriodSelector from '../components/PeriodSelector'
import WeightInput from '../components/WeightInput'
import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
-import { isPositiveNumber } from '../utils/numberUtils'
import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'
import { weightAPI } from '../services/api'
-import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs, displayWeight, round1 } from '../stores/settings'
+import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs, displayWeight, round1 , weightError, maxWeight } from '../stores/settings'
import * as types from '../types'
const PERIODS = ['7d', '30d', '90d', 'All'] as const
@@ -269,8 +268,9 @@ export default function Weight() {
e.preventDefault()
if (logging) return
const w = parseFloat(newWeight)
- if (!Number.isFinite(w) || w <= 0) {
- setError('Enter a valid weight')
+ const wErr = weightError(w, settings.weight_unit)
+ if (wErr) {
+ setError(wErr)
return
}
@@ -381,6 +381,7 @@ export default function Weight() {
value={newWeight}
onChange={setNewWeight}
unit={wUnit}
+ max={maxWeight(settings.weight_unit)}
size="lg"
/>
@@ -449,7 +450,7 @@ export default function Weight() {
<button
type="submit"
- disabled={!isPositiveNumber(newWeight) || logging}
+ disabled={!(parseFloat(newWeight) > 0) || logging}
className="btn-primary btn-lg w-full"
>
<Plus className="w-4 h-4" /> {logging ? 'Logging…' : 'Log Weight'}
diff --git a/web/src/pages/WeightDetail.tsx b/web/src/pages/WeightDetail.tsx
index 0ad88b3..2296bbc 100644
--- a/web/src/pages/WeightDetail.tsx
+++ b/web/src/pages/WeightDetail.tsx
@@ -4,10 +4,9 @@ import { useParams, useNavigate, Link } from 'react-router-dom'
import { format } from 'date-fns'
import { ArrowLeft, Scale, Trash2, Edit2, Save, X, AlertCircle, Loader } from 'lucide-react'
import { weightAPI } from '../services/api'
-import { useSettingsStore, weightShort, displayToLbs, displayWeight } from '../stores/settings'
+import { useSettingsStore, weightShort, displayToLbs, displayWeight , weightError, maxWeight } from '../stores/settings'
import { useBodyScrollLock } from '../hooks/useBodyScrollLock'
import { useEscapeKey } from '../hooks/useEscapeKey'
-import { isPositiveNumber } from '../utils/numberUtils'
import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'
import WeightInput from '../components/WeightInput'
import * as types from '../types'
@@ -63,8 +62,9 @@ export default function WeightDetail() {
e.preventDefault()
if (!log || saving) return
const w = parseFloat(editWeight)
- if (!Number.isFinite(w) || w <= 0) {
- setEditError('Enter a valid weight')
+ const wErr = weightError(w, settings.weight_unit)
+ if (wErr) {
+ setEditError(wErr)
return
}
setSaving(true)
@@ -192,6 +192,7 @@ export default function WeightDetail() {
value={editWeight}
onChange={setEditWeight}
unit={wUnit}
+ max={maxWeight(settings.weight_unit)}
size="lg"
/>
</div>
@@ -230,7 +231,7 @@ export default function WeightDetail() {
</button>
<button
type="submit"
- disabled={!isPositiveNumber(editWeight) || saving}
+ disabled={!(parseFloat(editWeight) > 0) || saving}
className="flex-1 btn-primary py-2.5 rounded-xl flex items-center justify-center gap-1.5"
>
<Save className="w-4 h-4" />
diff --git a/web/src/stores/settings.test.ts b/web/src/stores/settings.test.ts
index 03b3e94..30f44be 100644
--- a/web/src/stores/settings.test.ts
+++ b/web/src/stores/settings.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { round1, displayWeight, displayVolume } from './settings'
+import { round1, displayWeight, displayVolume, weightError, isValidWeight, maxWeight } from './settings'
describe('round1', () => {
it('rounds to one decimal place', () => {
@@ -46,3 +46,30 @@ describe('displayVolume', () => {
expect(displayVolume(5000, 'kg')).toBe(2268)
})
})
+
+describe('weight validation (mirrors backend gt=0, lte=2000 lbs)', () => {
+ it('rejects non-positive / non-finite', () => {
+ expect(weightError(0, 'lbs')).toMatch(/valid/)
+ expect(weightError(-5, 'lbs')).toMatch(/valid/)
+ expect(weightError(NaN, 'lbs')).toMatch(/valid/)
+ expect(isValidWeight(0, 'lbs')).toBe(false)
+ })
+
+ it('accepts a normal weight', () => {
+ expect(weightError(175.3, 'lbs')).toBeNull()
+ expect(isValidWeight(175.3, 'lbs')).toBe(true)
+ })
+
+ it('enforces the 2000 lb upper bound', () => {
+ expect(weightError(2000, 'lbs')).toBeNull() // at the bound
+ expect(weightError(2001, 'lbs')).toMatch(/under 2000 lb/)
+ expect(isValidWeight(2001, 'lbs')).toBe(false)
+ })
+
+ it('applies the bound unit-correctly in kg (2000 lb ≈ 907 kg)', () => {
+ expect(maxWeight('kg')).toBe(907.2)
+ expect(isValidWeight(907, 'kg')).toBe(true) // 907 kg = 1999.6 lb
+ expect(isValidWeight(910, 'kg')).toBe(false) // 910 kg = 2006 lb
+ expect(weightError(910, 'kg')).toMatch(/under 907 kg/)
+ })
+})
diff --git a/web/src/stores/settings.ts b/web/src/stores/settings.ts
index 5a6fde1..8077704 100644
--- a/web/src/stores/settings.ts
+++ b/web/src/stores/settings.ts
@@ -75,3 +75,22 @@ export const displayWeight = (lbs: number, unit: string): number => round1(lbsTo
// Volumes are large and never want 0.1 precision — keep this distinct from
// displayWeight so the two can't be confused.
export const displayVolume = (lbs: number, unit: string): number => Math.round(lbsToDisplay(lbs, unit))
+
+// Bodyweight bounds — mirror the backend (LogWeightRequest: gt=0, lte=2000 lbs)
+// so the user gets instant feedback instead of a round-trip 400. Defined once
+// here; the weight-logging forms validate through weightError/isValidWeight.
+export const MAX_WEIGHT_LBS = 2000
+
+// The max in the user's display unit (2000 lb ≈ 907 kg).
+export const maxWeight = (unit: string): number => round1(lbsToDisplay(MAX_WEIGHT_LBS, unit))
+
+// `value` is in the user's display unit. Returns an error message, or null if valid.
+export const weightError = (value: number, unit: string): string | null => {
+ if (!Number.isFinite(value) || value <= 0) return 'Enter a valid weight'
+ if (displayToLbs(value, unit) > MAX_WEIGHT_LBS) {
+ return `Weight must be under ${Math.round(maxWeight(unit))} ${weightShort(unit)}`
+ }
+ return null
+}
+
+export const isValidWeight = (value: number, unit: string): boolean => weightError(value, unit) === null