Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Gym workout flow: fix weight input + polish the logging UI (#59)
Carter5b1dc1e79d4f
diff --git a/web/e2e/workouts.spec.ts b/web/e2e/workouts.spec.tsindex 5ac4961..a2a4078 100644--- a/web/e2e/workouts.spec.ts+++ b/web/e2e/workouts.spec.ts@@ -268,11 +268,11 @@ test.describe('Gym Mode', { tag: '@mobile' }, () => {await page.goto('/workout/active')await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })- // X button (aria-label="Cancel workout") in overview header opens cancel confirm- await page.getByRole('button', { name: 'Cancel workout', exact: true }).click()- await expect(page.getByText('Cancel Workout?')).toBeVisible({ timeout: 3000 })+ // X button (aria-label="Discard workout") in overview header opens the discard confirm+ await page.getByRole('button', { name: 'Discard workout', exact: true }).click()+ await expect(page.getByText('Discard workout?')).toBeVisible({ timeout: 3000 })await page.getByRole('button', { name: /keep going/i }).click()- await expect(page.getByText('Cancel Workout?')).not.toBeVisible()+ await expect(page.getByText('Discard workout?')).not.toBeVisible()})test('gym mode navigates overview → exercise info → sets', async ({ page }) => {diff --git a/web/src/components/DiscardConfirm.tsx b/web/src/components/DiscardConfirm.tsxnew file mode 100644index 0000000..6f98454--- /dev/null+++ b/web/src/components/DiscardConfirm.tsx@@ -0,0 +1,35 @@+import { createPortal } from 'react-dom'+import { Trash2 } from 'lucide-react'+import { useEscapeKey } from '../hooks/useEscapeKey'+import { useBodyScrollLock } from '../hooks/useBodyScrollLock'++interface Props {+ open: boolean+ onKeep: () => void+ onDiscard: () => void+}++// Discard-workout confirmation bottom sheet, shared by every gym-mode phase (was+// triplicated inline). Renders to document.body so it overlays the full-screen gym;+// uses the shared escape/scroll-lock hooks like every other sheet.+export default function DiscardConfirm({ open, onKeep, onDiscard }: Props) {+ useBodyScrollLock(open)+ useEscapeKey(open, onKeep) // Escape dismisses (the non-destructive choice)+ if (!open) return null+ return createPortal(+ <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">+ <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">+ <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />+ <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Discard workout?</h3>+ <p className="text-sm text-tx-muted mb-5">This ends the workout without saving — all progress is lost.</p>+ <div className="flex gap-3">+ <button onClick={onKeep} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">Keep Going</button>+ <button onClick={onDiscard} className="flex-1 py-3 bg-error-500 hover:bg-error-600 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">+ <Trash2 className="w-3.5 h-3.5" />Discard+ </button>+ </div>+ </div>+ </div>,+ document.body,+ )+}diff --git a/web/src/components/WeightInput.tsx b/web/src/components/WeightInput.tsxindex 071e3fc..76d921e 100644--- a/web/src/components/WeightInput.tsx+++ b/web/src/components/WeightInput.tsx@@ -1,4 +1,6 @@import { Minus, Plus } from 'lucide-react'+import { useNumericText } from '../hooks/useNumericText'+import { clampStep } from '../utils/number'interface Props {value: string@@ -27,7 +29,7 @@ const STEP_DEFAULT = 0.5// Single component for every weight input in the app. Conversion-agnostic: the// caller owns lbs↔display unit (pass display-unit strings in/out). `stepper`// toggles the prominent +/- layout (bodyweight, gym mode) vs a bare field for-// compact sets-table rows. All weight inputs share step=0.1 + the unit suffix.+// compact sets-table rows. (Gym set tiles use the borderless NumberField instead.)export default function WeightInput({value,onChange,@@ -40,19 +42,22 @@ export default function WeightInput({disabled = false,max,}: Props) {- const adjust = (delta: number) => {- const current = parseFloat(value)- const base = Number.isFinite(current) ? current : 0- const next = Math.min(max ?? Infinity, Math.max(0, +(base + delta).toFixed(1)))- onChange(String(next))+ // Raw typed text (see useNumericText) so in-progress entry isn't clobbered by the+ // parent re-deriving `value` from a rounded/0→'' number on every keystroke.+ const [text, setText] = useNumericText(value)++ const emit = (next: string) => {+ setText(next)+ onChange(next)}+ const adjust = (delta: number) => emit(String(clampStep(parseFloat(text), delta, { max })))+const inputSize = size === 'lg'? 'text-3xl py-4 font-display font-bold': size === 'sm'? 'text-sm py-2.5': 'text-base py-2.5'- // Compact contexts (bare field or sm) use tighter unit padding.const compact = !stepper || size === 'sm'const pad = compact ? 'pr-7' : 'pr-12'const unitPos = compact ? 'right-2' : 'right-3.5'@@ -63,8 +68,9 @@ export default function WeightInput({type="number"inputMode="decimal"enterKeyHint="done"- value={value}- onChange={e => onChange(e.target.value)}+ value={text}+ onChange={e => emit(e.target.value.replace(/-/g, ''))}+ onKeyDown={e => { if (['e', 'E', '+', '-'].includes(e.key)) e.preventDefault() }}step={INPUT_STEP}min="0"autoFocus={autoFocus}diff --git a/web/src/components/ui/NumberField.tsx b/web/src/components/ui/NumberField.tsxnew file mode 100644index 0000000..8699918--- /dev/null+++ b/web/src/components/ui/NumberField.tsx@@ -0,0 +1,40 @@+import { useNumericText } from '../../hooks/useNumericText'++// Borderless big-number field style for the inside of a metric tile (the card is+// the visual container).+const PLAIN_FIELD_CLASS =+ 'w-full bg-transparent border-0 outline-none focus:ring-0 px-0 py-1 text-3xl font-black text-center tabular-nums text-tx-primary placeholder-tx-muted/50'++interface Props {+ value: string+ onChange: (next: string) => void+ inputMode?: 'numeric' | 'decimal'+ placeholder?: string+ disabled?: boolean+ min?: number+ 'aria-label'?: string+}++// Borderless numeric field for use inside a StepperTile. Robust typing via+// useNumericText; the parent owns conversion/validation in onChange.+export default function NumberField({ value, onChange, inputMode = 'decimal', placeholder = '0', disabled = false, min = 0, ...aria }: Props) {+ const [text, setText] = useNumericText(value)+ // Non-negative always; integer fields (inputMode "numeric") also reject a decimal+ // point so reps can't be typed fractional.+ const blocked = inputMode === 'numeric' ? ['e', 'E', '+', '-', '.'] : ['e', 'E', '+', '-']+ return (+ <input+ type="number"+ inputMode={inputMode}+ enterKeyHint="done"+ min={min}+ value={text}+ disabled={disabled}+ placeholder={placeholder}+ onKeyDown={e => { if (blocked.includes(e.key)) e.preventDefault() }}+ onChange={e => { const v = e.target.value.replace(/-/g, ''); setText(v); onChange(v) }}+ className={`${PLAIN_FIELD_CLASS} ${disabled ? 'opacity-40' : ''}`}+ aria-label={aria['aria-label']}+ />+ )+}diff --git a/web/src/components/ui/StepperTile.tsx b/web/src/components/ui/StepperTile.tsxnew file mode 100644index 0000000..ba58761--- /dev/null+++ b/web/src/components/ui/StepperTile.tsx@@ -0,0 +1,39 @@+import { Minus, Plus } from 'lucide-react'+import type { LucideIcon } from 'lucide-react'++interface Props {+ icon: LucideIcon+ label: string+ /** Concise metric name for the step buttons' aria-labels (e.g. "reps", "weight"). */+ name: string+ step: number+ onStep: (delta: number) => void+ disabled?: boolean+ /** The value field (a NumberField / WeightInput) shown between header and footer. */+ children: React.ReactNode+}++// A metric tile: icon header, a full-width value field, and a split decrement /+// increment footer. Shared by the gym reps + weight inputs so the layout and the+// stepper buttons live in one place.+export default function StepperTile({ icon: Icon, label, name, step, onStep, disabled = false, children }: Props) {+ const btn = 'flex-1 py-2.5 flex items-center justify-center text-tx-secondary hover:bg-surface-muted active:scale-95 transition-all disabled:opacity-30'+ return (+ <div className="card overflow-hidden">+ <div className="px-3 pt-3 pb-1.5 flex flex-col items-center gap-1">+ <div className="flex items-center gap-1.5 text-xs font-semibold text-tx-muted uppercase tracking-wider">+ <Icon className="w-3.5 h-3.5 text-brand-400" />{label}+ </div>+ {children}+ </div>+ <div className="flex border-t border-surface-border divide-x divide-surface-border">+ <button type="button" aria-label={`Decrease ${name}`} disabled={disabled} onClick={() => onStep(-step)} className={btn}>+ <Minus className="w-5 h-5" />+ </button>+ <button type="button" aria-label={`Increase ${name}`} disabled={disabled} onClick={() => onStep(step)} className={btn}>+ <Plus className="w-5 h-5" />+ </button>+ </div>+ </div>+ )+}diff --git a/web/src/components/ui/index.ts b/web/src/components/ui/index.tsindex f8a895d..5da1b59 100644--- a/web/src/components/ui/index.ts+++ b/web/src/components/ui/index.ts@@ -4,3 +4,5 @@ export { default as SegmentedControl } from './SegmentedControl'export { default as EmptyState } from './EmptyState'export { default as SectionHeader } from './SectionHeader'export { default as PageHeader } from './PageHeader'+export { default as NumberField } from './NumberField'+export { default as StepperTile } from './StepperTile'diff --git a/web/src/hooks/useNumericText.test.ts b/web/src/hooks/useNumericText.test.tsnew file mode 100644index 0000000..3a04a79--- /dev/null+++ b/web/src/hooks/useNumericText.test.ts@@ -0,0 +1,40 @@+import { describe, it, expect } from 'vitest'+import { renderHook, act } from '@testing-library/react'+import { useNumericText } from './useNumericText'++// Regression guard for the gym weight/reps in-progress-typing bug fixed in PR #59:+// the parent re-derives `value` from a rounded / 0→'' number on every keystroke, and+// must NOT clobber what the user is mid-typing (a trailing ".", a leading "0"), while+// still re-syncing for genuinely different numbers (stepper / programmatic changes).+describe('useNumericText', () => {+ it('initializes to the given value', () => {+ const { result } = renderHook(() => useNumericText('90'))+ expect(result.current[0]).toBe('90')+ })++ it('preserves an in-progress "2." when the parent re-derives an equal number', () => {+ const { result, rerender } = renderHook(({ v }) => useNumericText(v), { initialProps: { v: '2' } })+ act(() => result.current[1]('2.')) // user typed a trailing dot+ rerender({ v: '2.0' }) // parent re-derived; 2.0 is numerically equal to 2.+ expect(result.current[0]).toBe('2.')+ })++ it('preserves a leading "0" even when the parent maps 0 → ""', () => {+ const { result, rerender } = renderHook(({ v }) => useNumericText(v), { initialProps: { v: '5' } })+ act(() => result.current[1]('0')) // user cleared and typed "0"+ rerender({ v: '' }) // parent stored 0 and maps it to ''+ expect(result.current[0]).toBe('0')+ })++ it('re-syncs when the parent value is a genuinely different number (stepper/prefill)', () => {+ const { result, rerender } = renderHook(({ v }) => useNumericText(v), { initialProps: { v: '90' } })+ rerender({ v: '95' }) // stepper / programmatic change / deferred prefill+ expect(result.current[0]).toBe('95')+ })++ it('populates a deferred prefill (empty → value), e.g. autofocus edit modals', () => {+ const { result, rerender } = renderHook(({ v }) => useNumericText(v), { initialProps: { v: '' } })+ rerender({ v: '180' }) // parent effect prefills after mount+ expect(result.current[0]).toBe('180')+ })+})diff --git a/web/src/hooks/useNumericText.ts b/web/src/hooks/useNumericText.tsnew file mode 100644index 0000000..87e4d85--- /dev/null+++ b/web/src/hooks/useNumericText.ts@@ -0,0 +1,26 @@+import { useEffect, useState } from 'react'++// Holds the raw typed text for a numeric field whose committed value is owned by a+// parent (which may round it, convert units, or map 0 → ''). Without this, the+// parent re-deriving `value` on every keystroke clobbers in-progress entry — a+// trailing ".", a leading "0". We re-sync from the parent only when it represents a+// genuinely *different* number than what's shown (stepper taps, programmatic+// changes, prefills); '' and 0 are treated as equivalent so a 0→'' mapping doesn't+// wipe a "0." mid-type.+//+// NOTE: we intentionally do NOT skip re-sync while focused — autofocus + a deferred+// prefill (EditWeightModal, QuickWeighInSheet) must still populate the field. The+// residual sub-0.1 mid-type snap is a limit of the 0.1-precision design (#39) + the+// underlying type=number field, not something to work around here.+export function useNumericText(value: string): [string, (next: string) => void] {+ const [text, setText] = useState(value)+ useEffect(() => {+ const a = parseFloat(text)+ const b = parseFloat(value)+ const aEmpty = Number.isNaN(a) || a === 0+ const bEmpty = Number.isNaN(b) || b === 0+ if (a !== b && !(aEmpty && bEmpty)) setText(value)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [value])+ return [text, setText]+}diff --git a/web/src/pages/GymModeWorkout.tsx b/web/src/pages/GymModeWorkout.tsxindex 64cf99d..5f439a5 100644--- a/web/src/pages/GymModeWorkout.tsx+++ b/web/src/pages/GymModeWorkout.tsx@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'import { useNavigate } from 'react-router-dom'import {CheckCircle2, Plus, X, Dumbbell, Flag, ChevronRight, ChevronLeft, Play,- Minimize2, Trash2,+ Minimize2, Trash2, Repeat, Check, Layers,} from 'lucide-react'import Model, { IExerciseData } from 'react-body-highlighter'import * as types from '../types'@@ -11,7 +11,10 @@ import { muscleColor, muscleColorBordered, EQUIPMENT_LABEL, muscleToBodySlugs }import { useTheme } from '../hooks/useTheme'import { useWorkoutSession } from '../stores/workoutSession'import { workoutAPI } from '../services/api'-import WeightInput from '../components/WeightInput'+import StepperTile from '../components/ui/StepperTile'+import NumberField from '../components/ui/NumberField'+import DiscardConfirm from '../components/DiscardConfirm'+import { clampStep, clampValue } from '../utils/number'import { displayWeight, displayToLbs } from '../stores/settings'function buildBodyData(exercise: types.Exercise): IExerciseData[] {@@ -127,46 +130,52 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {><ChevronLeft className="w-5 h-5" /></button>- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 mb-1.5">+ <div className="flex-1 min-w-0 flex items-center gap-2">+ <div className="flex items-center gap-1.5 overflow-x-auto min-w-0">{s.exercises.map((_, i) => (<buttonkey={i}onClick={() => setGymState('exercise-info', i, 0)}- className={`h-1.5 rounded-full transition-all duration-200 ${+ aria-label={`Go to exercise ${i + 1}`}+ className={`h-1.5 rounded-full flex-shrink-0 transition-all duration-200 ${i === activeIdx ? 'w-6 bg-brand-500' :s.exercises[i].sets.every(st => st.completed) && s.exercises[i].sets.length > 0? 'w-2 bg-brand-500/40' : 'w-2 bg-surface-border'}`}/>))}- <span className="text-xs text-tx-muted tabular-nums">{activeIdx + 1}/{s.exercises.length}</span>- </div>- <div className="h-0.5 bg-surface-muted rounded-full overflow-hidden">- <div- className="h-full bg-brand-500 transition-all duration-500"- style={{ width: `${totalSets > 0 ? (completedSets / totalSets) * 100 : 0}%` }}- /></div>+ <span className="text-xs text-tx-muted tabular-nums flex-shrink-0">{activeIdx + 1}/{s.exercises.length}</span>+ </div>+ <div className="flex items-center gap-1 flex-shrink-0">+ <button+ onClick={() => setConfirmFinish(true)}+ className={`flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold transition-all ${+ allDone+ ? 'bg-brand-500 hover:bg-brand-600 text-white shadow-sm shadow-brand-500/30'+ : 'bg-surface-muted text-tx-muted border border-surface-border'+ }`}+ >+ <Flag className="w-3.5 h-3.5" />+ Finish+ </button>+ <button+ onClick={handleMinimize}+ className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted"+ aria-label="Minimize workout"+ title="Minimize"+ >+ <Minimize2 className="w-4 h-4" />+ </button>+ <button+ onClick={() => setConfirmCancel(true)}+ className="p-2 hover:bg-error-500/10 rounded-xl transition-colors text-tx-muted hover:text-error-400"+ aria-label="Discard workout"+ title="Discard workout"+ >+ <X className="w-5 h-5" />+ </button></div>- <button- onClick={() => setConfirmFinish(true)}- className={`flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold transition-all flex-shrink-0 ${- allDone- ? 'bg-brand-500 hover:bg-brand-600 text-white shadow-sm shadow-brand-500/30'- : 'bg-surface-muted text-tx-muted border border-surface-border'- }`}- >- <Flag className="w-3.5 h-3.5" />- Finish- </button>- <button- onClick={handleMinimize}- className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted"- aria-label="Minimize"- >- <Minimize2 className="w-4 h-4" />- </button></div>)}@@ -184,7 +193,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<button onClick={handleMinimize} className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted" aria-label="Minimize"><Minimize2 className="w-4 h-4" /></button>- <button onClick={() => setConfirmCancel(true)} aria-label="Cancel workout" className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted hover:text-error-400">+ <button onClick={() => setConfirmCancel(true)} aria-label="Discard workout" title="Discard workout" className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted hover:text-error-400"><X className="w-5 h-5" /></button></div>@@ -288,22 +297,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {</div>,document.body)}- {confirmCancel && createPortal(- <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Cancel Workout?</h3>- <p className="text-sm text-tx-muted mb-5">All progress will be lost.</p>- <div className="flex gap-3">- <button onClick={() => setConfirmCancel(false)} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">Keep Going</button>- <button onClick={() => { cancelSession(); handleMinimize() }} className="flex-1 py-3 bg-error-500 hover:bg-error-600 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">- <Trash2 className="w-3.5 h-3.5" />Cancel- </button>- </div>- </div>- </div>,- document.body- )}+ <DiscardConfirm open={confirmCancel} onKeep={() => setConfirmCancel(false)} onDiscard={() => { cancelSession(); handleMinimize() }} /></div>)}@@ -322,6 +316,15 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {? exercise.description.split('\n').filter(l => l.trim()): []const bodyData = buildBodyData(exercise)+ // Plan summary: one value if every set matches, else a min–max range.+ const repsVals = ex.sets.map(s => s.target_reps).filter(r => r > 0)+ const wtVals = ex.sets.map(s => displayWeight(s.target_weight, wUnit)).filter(w => w > 0)+ const range = (a: number[]) => (a.length === 0 ? '—' : Math.min(...a) === Math.max(...a) ? String(Math.min(...a)) : `${Math.min(...a)}–${Math.max(...a)}`)+ const planStats = [+ { icon: Layers, label: 'Sets', value: <>{ex.sets.length}</> },+ { icon: Repeat, label: 'Reps', value: <>{range(repsVals)}</> },+ { icon: Dumbbell, label: 'Weight', value: <>{range(wtVals)}<span className="text-xs font-semibold text-tx-muted ml-0.5">{wUnit}</span></> },+ ]return (<div className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col">@@ -352,13 +355,24 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {</span>)}{exercise.category && (- <span className="inline-flex items-center px-3 py-1 rounded-full bg-brand-500/10 border border-brand-500/20 text-xs font-medium text-brand-400 capitalize">+ <span className="inline-flex items-center px-3 py-1 rounded-full bg-surface-muted border border-surface-border text-xs font-medium text-tx-secondary capitalize">{exercise.category}</span>)}</div></div>+ {/* Plan — what you're about to do, as an icon stat strip */}+ <div className="card p-4 grid grid-cols-3 divide-x divide-surface-border">+ {planStats.map(({ icon: Ico, label, value }) => (+ <div key={label} className="flex flex-col items-center gap-1.5 px-2">+ <Ico className="w-4 h-4 text-brand-400" />+ <span className="font-display font-bold text-xl text-tx-primary tabular-nums leading-none whitespace-nowrap">{value}</span>+ <span className="text-[10px] font-medium text-tx-muted uppercase tracking-wider">{label}</span>+ </div>+ ))}+ </div>+{/* Secondary muscles */}{exercise.secondary_muscles?.length > 0 && (<div>@@ -448,22 +462,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {</div>,document.body)}- {confirmCancel && createPortal(- <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Cancel Workout?</h3>- <p className="text-sm text-tx-muted mb-5">All progress will be lost.</p>- <div className="flex gap-3">- <button onClick={() => setConfirmCancel(false)} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">Keep Going</button>- <button onClick={() => { cancelSession(); handleMinimize() }} className="flex-1 py-3 bg-error-500 hover:bg-error-600 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">- <Trash2 className="w-3.5 h-3.5" />Cancel- </button>- </div>- </div>- </div>,- document.body- )}+ <DiscardConfirm open={confirmCancel} onKeep={() => setConfirmCancel(false)} onDiscard={() => { cancelSession(); handleMinimize() }} /></div>)}@@ -512,8 +511,8 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {</div></div>{!allSetsComplete && (- <button onClick={handleRemoveExercise} className="p-1.5 hover:bg-error-500/10 rounded-lg transition-colors flex-shrink-0">- <X className="w-4 h-4 text-tx-muted hover:text-error-400 transition-colors" />+ <button onClick={handleRemoveExercise} aria-label="Remove this exercise" title="Remove exercise" className="p-1.5 hover:bg-error-500/10 rounded-lg transition-colors flex-shrink-0">+ <Trash2 className="w-4 h-4 text-tx-muted hover:text-error-400 transition-colors" /></button>)}</div>@@ -522,73 +521,76 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {</div></div>- {/* Set dots nav */}- <div className="flex items-center justify-center gap-2 py-3 px-5 flex-shrink-0">- {ex.sets.map((s, i) => (- <button- key={i}- onClick={() => setActiveSetIdx(i)}- className={`rounded-full transition-all duration-200 ${- i === clampedSetIdx ? 'w-6 h-2.5 bg-brand-500' :- s.completed ? 'w-2.5 h-2.5 bg-brand-500/50' :- 'w-2.5 h-2.5 bg-surface-border'- }`}- />- ))}- </div>-- {/* Single set card — centred, fills remaining space */}+ {/* The whole logging group (set chips, target, inputs, action) centred+ together as one composed unit. */}<div className="flex-1 flex flex-col items-center justify-center px-5 gap-6">- {/* Set label */}- <div className="text-center">- <p className={`text-6xl font-black tabular-nums transition-colors ${set.completed ? 'text-brand-400' : 'text-tx-primary'}`}>- {set.set_number}- </p>- <p className="text-sm text-tx-muted mt-1">of {ex.sets.length} sets</p>+ {/* Set selector — one chip per set: active filled, done shows a check.+ Progress + navigation in one place (replaced the old dots + big number). */}+ <div className="flex items-center justify-center flex-wrap gap-2">+ {ex.sets.map((s, i) => (+ <button+ key={i}+ onClick={() => setActiveSetIdx(i)}+ aria-label={`Set ${i + 1}${s.completed ? ', done' : ''}`}+ aria-current={i === clampedSetIdx}+ className={`flex items-center justify-center gap-1 min-w-[2.75rem] h-10 px-3 rounded-full text-sm font-bold tabular-nums transition-all active:scale-95 ${+ i === clampedSetIdx ? 'bg-brand-500 text-white shadow-sm shadow-brand-500/30' :+ s.completed ? 'bg-brand-500/15 text-brand-400' :+ 'bg-surface-muted text-tx-muted hover:text-tx-secondary'+ }`}+ >+ {s.completed && <Check className="w-3.5 h-3.5" />}+ {i + 1}+ </button>+ ))}</div>- {/* Reps + Weight inputs */}- <div className="w-full grid grid-cols-2 gap-4">- {/* Reps */}- <div className="flex flex-col items-center gap-2">- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">Reps</p>- <div className="flex items-center gap-2 w-full">- <button- onClick={() => updateSet(activeIdx, clampedSetIdx, 'actual_reps', Math.max(0, (set.actual_reps || 0) - 1))}- disabled={set.completed}- className="w-11 h-11 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border flex items-center justify-center text-xl font-bold text-tx-secondary transition-colors disabled:opacity-30"- >−</button>- <input- type="number" inputMode="numeric"- value={set.actual_reps || ''}- onChange={e => updateSet(activeIdx, clampedSetIdx, 'actual_reps', Number(e.target.value) || 0)}- placeholder={set.target_reps > 0 ? String(set.target_reps) : '0'}- className={`input text-2xl font-bold text-center flex-1 py-3 transition-opacity ${set.completed ? 'opacity-40' : ''}`}- disabled={set.completed}- />- <button- onClick={() => updateSet(activeIdx, clampedSetIdx, 'actual_reps', (set.actual_reps || 0) + 1)}- disabled={set.completed}- className="w-11 h-11 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border flex items-center justify-center text-xl font-bold text-tx-secondary transition-colors disabled:opacity-30"- >+</button>- </div>- </div>+ {/* Target reference for this set (the goal to hit) */}+ {(set.target_reps > 0 || set.target_weight > 0) && (+ <p className="text-sm text-tx-muted text-center">+ Target{' '}+ <span className="font-semibold text-tx-secondary tabular-nums">{set.target_reps > 0 ? set.target_reps : '—'} reps</span>+ {set.target_weight > 0 && (+ <> · <span className="font-semibold text-tx-secondary tabular-nums">{displayWeight(set.target_weight, wUnit)} {wUnit}</span></>+ )}+ </p>+ )}++ {/* Reps + Weight — a tile per metric: icon header, big value, split ⊖/⊕ footer.+ Value spans the full tile (buttons are below, not flanking) so long+ weights never clip. */}+ <div className="w-full grid grid-cols-2 gap-3">+ {/* Reps — key by set so a half-typed value can't bleed to the next set */}+ <StepperTile+ icon={Repeat} label="Reps" name="reps" step={1} disabled={set.completed}+ onStep={d => updateSet(activeIdx, clampedSetIdx, 'actual_reps', clampStep(set.actual_reps || 0, d, { min: 0 }))}+ >+ <NumberField+ key={`reps-${activeIdx}-${clampedSetIdx}`}+ inputMode="numeric"+ value={set.actual_reps ? String(set.actual_reps) : ''}+ onChange={v => updateSet(activeIdx, clampedSetIdx, 'actual_reps', Math.round(clampValue(v)))}+ placeholder={set.target_reps > 0 ? String(set.target_reps) : '0'}+ disabled={set.completed}+ aria-label="Reps"+ />+ </StepperTile>{/* Weight */}- <div className="flex flex-col items-center gap-2">- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">Weight ({wUnit})</p>- <div className="w-full">- <WeightInput- size="lg"- step={2.5}- value={set.actual_weight ? String(displayWeight(set.actual_weight, wUnit)) : ''}- onChange={v => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(Number(v) || 0, wUnit))}- unit={wUnit}- placeholder={set.target_weight > 0 ? String(displayWeight(set.target_weight, wUnit)) : '0'}- disabled={set.completed}- />- </div>- </div>+ <StepperTile+ icon={Dumbbell} label={`Weight (${wUnit})`} name="weight" step={2.5} disabled={set.completed}+ onStep={d => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampStep(displayWeight(set.actual_weight, wUnit), d, { min: 0 }), wUnit))}+ >+ <NumberField+ key={`wt-${activeIdx}-${clampedSetIdx}`}+ inputMode="decimal"+ value={set.actual_weight ? String(displayWeight(set.actual_weight, wUnit)) : ''}+ onChange={v => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampValue(v), wUnit))}+ placeholder={set.target_weight > 0 ? String(displayWeight(set.target_weight, wUnit)) : '0'}+ disabled={set.completed}+ aria-label="Weight"+ />+ </StepperTile></div>{/* Complete button */}@@ -604,13 +606,16 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {{set.completed ? 'Completed' : 'Complete Set'}</button>- {/* Remove set */}- <button- onClick={() => handleRemoveSet(clampedSetIdx)}- className="text-xs text-tx-muted/50 hover:text-error-400 transition-colors"- >- Remove this set- </button>+ {/* Remove set — hidden on the last set (removing it would empty the exercise+ and drop to a blank screen; use the header trash to remove the exercise) */}+ {ex.sets.length > 1 && (+ <button+ onClick={() => handleRemoveSet(clampedSetIdx)}+ className="text-xs text-tx-muted/50 hover:text-error-400 transition-colors"+ >+ Remove this set+ </button>+ )}</div>{/* Bottom nav */}@@ -700,25 +705,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {)}{/* ── Cancel confirm ── */}- {confirmCancel && createPortal(- <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Cancel Workout?</h3>- <p className="text-sm text-tx-muted mb-5">All progress will be lost.</p>- <div className="flex gap-3">- <button onClick={() => setConfirmCancel(false)} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">- Keep Going- </button>- <button onClick={() => { cancelSession(); handleMinimize() }} className="flex-1 py-3 bg-error-500 hover:bg-error-600 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">- <Trash2 className="w-3.5 h-3.5" />- Cancel- </button>- </div>- </div>- </div>,- document.body- )}+ <DiscardConfirm open={confirmCancel} onKeep={() => setConfirmCancel(false)} onDiscard={() => { cancelSession(); handleMinimize() }} /></div>)}diff --git a/web/src/utils/number.ts b/web/src/utils/number.tsnew file mode 100644index 0000000..5666bf5--- /dev/null+++ b/web/src/utils/number.ts@@ -0,0 +1,15 @@+// Step a numeric value by `delta`, round to the app's 0.1 precision, and clamp to+// [min, max]. Single source for the +/- stepper math shared by WeightInput and the+// gym StepperTile (default min 0 also serves as the "no negatives" guard).+export function clampStep(base: number, delta: number, opts: { min?: number; max?: number } = {}): number {+ const { min = 0, max = Infinity } = opts+ const b = Number.isFinite(base) ? base : 0+ return Math.min(max, Math.max(min, +(b + delta).toFixed(1)))+}++// Clamp a freely-typed numeric string to a lower bound (validation for inputs that+// commit on every keystroke). Returns a finite number ≥ min.+export function clampValue(raw: string | number, min = 0): number {+ const n = typeof raw === 'number' ? raw : Number(raw)+ return Number.isFinite(n) ? Math.max(min, n) : min+}