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.

Rest timer: per-exercise rest, pause, push-up panel, set linkage (#58)

Carter6b1c2f868a9b
diff --git a/backend/controllers/rest_timer_test.go b/backend/controllers/rest_timer_test.go
new file mode 100644
index 0000000..083f50e
--- /dev/null
+++ b/backend/controllers/rest_timer_test.go
@@ -0,0 +1,52 @@
+package controllers
+
+import (
+ "net/http"
+ "testing"
+)
+
+// Per-exercise rest_seconds (#33) must persist through create + the re-read load.
+func TestWorkoutRestSecondsRoundTrips(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ body := map[string]any{
+ "name": "Rest RT",
+ "exercises": []map[string]any{
+ {"exercise_id": exID, "rest_seconds": 120, "sets": []map[string]any{{"reps": 5, "weight": 100}}},
+ },
+ }
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ th.CreateWorkout(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("create workout: %d (%s)", w.Code, w.Body.String())
+ }
+ exs := decodeResponse(t, w)["data"].(map[string]any)["exercises"].([]any)
+ if rest := exs[0].(map[string]any)["rest_seconds"].(float64); rest != 120 {
+ t.Errorf("workout exercise rest_seconds = %v, want 120", rest)
+ }
+}
+
+func TestProgramRestSecondsRoundTrips(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ body := map[string]any{
+ "name": "Rest RT",
+ "exercises": []map[string]any{
+ {"exercise_id": exID, "rest_seconds": 0, "sets": []map[string]any{{"target_reps": 5, "target_weight": 100}}},
+ },
+ }
+ c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)
+ th.CreateProgram(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("create program: %d (%s)", w.Code, w.Body.String())
+ }
+ // 0 = "off" must round-trip as 0, not get defaulted away.
+ exs := decodeResponse(t, w)["data"].(map[string]any)["exercises"].([]any)
+ if rest := exs[0].(map[string]any)["rest_seconds"].(float64); rest != 0 {
+ t.Errorf("program exercise rest_seconds = %v, want 0", rest)
+ }
+}
diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.go
index d23ea34..90e60c1 100644
--- a/backend/controllers/testhelper_test.go
+++ b/backend/controllers/testhelper_test.go
@@ -83,7 +83,8 @@ CREATE TABLE IF NOT EXISTS workout_exercises (
workout_id INTEGER NOT NULL REFERENCES workouts(id) ON DELETE CASCADE,
exercise_id INTEGER NOT NULL REFERENCES exercises(id),
order_index INTEGER NOT NULL DEFAULT 0,
- notes TEXT NOT NULL DEFAULT ''
+ notes TEXT NOT NULL DEFAULT '',
+ rest_seconds INTEGER NOT NULL DEFAULT 90
);
CREATE TABLE IF NOT EXISTS sets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -108,7 +109,8 @@ CREATE TABLE IF NOT EXISTS program_exercises (
program_id INTEGER NOT NULL REFERENCES programs(id) ON DELETE CASCADE,
exercise_id INTEGER NOT NULL REFERENCES exercises(id),
order_index INTEGER NOT NULL DEFAULT 0,
- notes TEXT NOT NULL DEFAULT ''
+ notes TEXT NOT NULL DEFAULT '',
+ rest_seconds INTEGER NOT NULL DEFAULT 90
);
CREATE TABLE IF NOT EXISTS program_sets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index 7cf0843..07e514a 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -44,6 +44,39 @@ func alterMigrations() {
log.Println("migration: added food_logs.image_url")
}
}
+
+ // Per-exercise rest timer (#33). Existing rows seed to 90s (on); 0 = off.
+ ensureColumn("program_exercises", "rest_seconds", `ALTER TABLE program_exercises ADD COLUMN rest_seconds INTEGER NOT NULL DEFAULT 90`)
+ ensureColumn("workout_exercises", "rest_seconds", `ALTER TABLE workout_exercises ADD COLUMN rest_seconds INTEGER NOT NULL DEFAULT 90`)
+}
+
+// ensureColumn adds a column to a table if it's missing — idempotent on every boot.
+func ensureColumn(table, column, alterSQL string) {
+ rows, err := DB.Query("PRAGMA table_info(" + table + ")")
+ if err != nil {
+ return
+ }
+ has := false
+ for rows.Next() {
+ var cid int
+ var name, typ string
+ var notnull int
+ var dflt interface{}
+ var pk int
+ if err := rows.Scan(&cid, &name, &typ, &notnull, &dflt, &pk); err != nil {
+ continue
+ }
+ if name == column {
+ has = true
+ }
+ }
+ rows.Close()
+ if !has {
+ if _, err := DB.Exec(alterSQL); err != nil {
+ log.Fatalf("alter %s add %s: %v", table, column, err)
+ }
+ log.Printf("migration: added %s.%s", table, column)
+ }
}
const schema = `
diff --git a/backend/models/models.go b/backend/models/models.go
index b001036..5a4e754 100644
--- a/backend/models/models.go
+++ b/backend/models/models.go
@@ -43,13 +43,14 @@ type Workout struct {
}
type WorkoutExercise struct {
- ID int64 `json:"id" db:"id"`
- WorkoutID int64 `json:"workout_id" db:"workout_id"`
- ExerciseID int64 `json:"exercise_id" db:"exercise_id"`
- OrderIndex int `json:"order_index" db:"order_index"`
- Notes string `json:"notes,omitempty" db:"notes"`
- Exercise Exercise `json:"exercise,omitempty"`
- Sets []Set `json:"sets,omitempty"`
+ ID int64 `json:"id" db:"id"`
+ WorkoutID int64 `json:"workout_id" db:"workout_id"`
+ ExerciseID int64 `json:"exercise_id" db:"exercise_id"`
+ OrderIndex int `json:"order_index" db:"order_index"`
+ Notes string `json:"notes,omitempty" db:"notes"`
+ RestSeconds int `json:"rest_seconds" db:"rest_seconds"`
+ Exercise Exercise `json:"exercise,omitempty"`
+ Sets []Set `json:"sets,omitempty"`
}
type Set struct {
@@ -158,10 +159,11 @@ type CreateWorkoutRequest struct {
}
type CreateWorkoutExerciseReq struct {
- ExerciseID int64 `json:"exercise_id" validate:"required"`
- OrderIndex int `json:"order_index"`
- Notes string `json:"notes"`
- Sets []CreateSetReq `json:"sets"`
+ ExerciseID int64 `json:"exercise_id" validate:"required"`
+ OrderIndex int `json:"order_index"`
+ Notes string `json:"notes"`
+ RestSeconds int `json:"rest_seconds"`
+ Sets []CreateSetReq `json:"sets"`
}
type CreateSetReq struct {
@@ -225,13 +227,14 @@ type Program struct {
}
type ProgramExercise struct {
- ID int64 `json:"id,omitempty"`
- ProgramID int64 `json:"program_id,omitempty"`
- ExerciseID int64 `json:"exercise_id"`
- OrderIndex int `json:"order_index,omitempty"`
- Notes string `json:"notes"`
- Exercise Exercise `json:"exercise"`
- Sets []ProgramSet `json:"sets"`
+ ID int64 `json:"id,omitempty"`
+ ProgramID int64 `json:"program_id,omitempty"`
+ ExerciseID int64 `json:"exercise_id"`
+ OrderIndex int `json:"order_index,omitempty"`
+ Notes string `json:"notes"`
+ RestSeconds int `json:"rest_seconds"`
+ Exercise Exercise `json:"exercise"`
+ Sets []ProgramSet `json:"sets"`
}
type ProgramSet struct {
@@ -249,9 +252,10 @@ type CreateProgramRequest struct {
}
type CreateProgramExerciseReq struct {
- ExerciseID int64 `json:"exercise_id" validate:"required"`
- Notes string `json:"notes"`
- Sets []CreateProgramSetReq `json:"sets"`
+ ExerciseID int64 `json:"exercise_id" validate:"required"`
+ Notes string `json:"notes"`
+ RestSeconds int `json:"rest_seconds"`
+ Sets []CreateProgramSetReq `json:"sets"`
}
type CreateProgramSetReq struct {
diff --git a/backend/stores/program.go b/backend/stores/program.go
index 4f5af79..86b9f0b 100644
--- a/backend/stores/program.go
+++ b/backend/stores/program.go
@@ -149,8 +149,8 @@ func (s *ProgramStore) Delete(uid, id int64) (int64, error) {
func insertProgramExercises(tx *sql.Tx, pid int64, exercises []models.CreateProgramExerciseReq) error {
for i, ex := range exercises {
exRes, err := tx.Exec(
- `INSERT INTO program_exercises (program_id, exercise_id, order_index, notes) VALUES (?, ?, ?, ?)`,
- pid, ex.ExerciseID, i, ex.Notes,
+ `INSERT INTO program_exercises (program_id, exercise_id, order_index, notes, rest_seconds) VALUES (?, ?, ?, ?, ?)`,
+ pid, ex.ExerciseID, i, ex.Notes, ex.RestSeconds,
)
if err != nil {
return err
@@ -179,7 +179,7 @@ func insertProgramExercises(tx *sql.Tx, pid int64, exercises []models.CreateProg
// sets (#36), and surfaces scan errors.
func (s *ProgramStore) loadExercises(programID int64) ([]models.ProgramExercise, error) {
rows, err := s.db.Query(
- `SELECT pe.id, pe.program_id, pe.exercise_id, pe.order_index, pe.notes,
+ `SELECT pe.id, pe.program_id, pe.exercise_id, pe.order_index, pe.notes, pe.rest_seconds,
e.name, e.muscle_group, e.category, e.equipment, e.image_url
FROM program_exercises pe
JOIN exercises e ON e.id = pe.exercise_id
@@ -193,7 +193,7 @@ func (s *ProgramStore) loadExercises(programID int64) ([]models.ProgramExercise,
for rows.Next() {
var pe models.ProgramExercise
if err := rows.Scan(
- &pe.ID, &pe.ProgramID, &pe.ExerciseID, &pe.OrderIndex, &pe.Notes,
+ &pe.ID, &pe.ProgramID, &pe.ExerciseID, &pe.OrderIndex, &pe.Notes, &pe.RestSeconds,
&pe.Exercise.Name, &pe.Exercise.MuscleGroup, &pe.Exercise.Category,
&pe.Exercise.Equipment, &pe.Exercise.ImageURL,
); err != nil {
diff --git a/backend/stores/workout.go b/backend/stores/workout.go
index 9769936..9aa4c80 100644
--- a/backend/stores/workout.go
+++ b/backend/stores/workout.go
@@ -160,8 +160,8 @@ func (s *WorkoutStore) Delete(uid, id int64) (int64, error) {
func insertWorkoutExercises(tx *sql.Tx, wid int64, exercises []models.CreateWorkoutExerciseReq) error {
for i, ex := range exercises {
exRes, err := tx.Exec(
- `INSERT INTO workout_exercises (workout_id, exercise_id, order_index, notes) VALUES (?, ?, ?, ?)`,
- wid, ex.ExerciseID, i, ex.Notes,
+ `INSERT INTO workout_exercises (workout_id, exercise_id, order_index, notes, rest_seconds) VALUES (?, ?, ?, ?, ?)`,
+ wid, ex.ExerciseID, i, ex.Notes, ex.RestSeconds,
)
if err != nil {
return err
@@ -188,7 +188,7 @@ func insertWorkoutExercises(tx *sql.Tx, wid int64, exercises []models.CreateWork
// queries (#36) so a request never holds two pool connections at once.
func (s *WorkoutStore) loadExercises(workoutID int64) ([]models.WorkoutExercise, error) {
rows, err := s.db.Query(
- `SELECT we.id, we.workout_id, we.exercise_id, we.order_index, we.notes,
+ `SELECT we.id, we.workout_id, we.exercise_id, we.order_index, we.notes, we.rest_seconds,
e.name, e.muscle_group, e.category, e.equipment, e.image_url
FROM workout_exercises we
JOIN exercises e ON e.id = we.exercise_id
@@ -202,7 +202,7 @@ func (s *WorkoutStore) loadExercises(workoutID int64) ([]models.WorkoutExercise,
for rows.Next() {
var we models.WorkoutExercise
if err := rows.Scan(
- &we.ID, &we.WorkoutID, &we.ExerciseID, &we.OrderIndex, &we.Notes,
+ &we.ID, &we.WorkoutID, &we.ExerciseID, &we.OrderIndex, &we.Notes, &we.RestSeconds,
&we.Exercise.Name, &we.Exercise.MuscleGroup, &we.Exercise.Category,
&we.Exercise.Equipment, &we.Exercise.ImageURL,
); err != nil {
diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsx
index 8f4d6e8..c6f5c19 100644
--- a/web/src/components/Layout.tsx
+++ b/web/src/components/Layout.tsx
@@ -8,8 +8,11 @@ import {
import { useAuthStore } from '../stores/auth'
import { useTheme } from '../hooks/useTheme'
import { useWorkoutSession } from '../stores/workoutSession'
+import { useRestTimer } from '../hooks/useRestTimer'
+import { fmtClock } from '../utils/workoutSets'
import { useSettingsStore, weightShort } from '../stores/settings'
import GymModeWorkout from '../pages/GymModeWorkout'
+import RestTimerBanner from './RestTimerBanner'
import Logo from './Logo'
const NAV = [
@@ -34,6 +37,10 @@ function ActiveSessionBar() {
const navigate = useNavigate()
const { pathname } = useLocation()
const [elapsed, setElapsed] = useState(0)
+ // Rest countdown for the minimized workout — the full panel doesn't follow you out
+ // of the workout; this compact chip does. (useRestTimer also owns the auto-dismiss,
+ // and this bar is always mounted, so "rest over" clears even while minimized.)
+ const { active: resting, paused, done, left } = useRestTimer()
useEffect(() => {
if (!session) return
@@ -73,6 +80,14 @@ function ActiveSessionBar() {
<p className="text-xs font-bold text-white leading-tight truncate max-w-[140px]">{session.name}</p>
<p className="text-[11px] text-white/70 leading-tight">{completedSets}/{totalSets} sets · {formatElapsed(elapsed)}</p>
</div>
+ {resting && (
+ <div className="flex items-center gap-1.5 pl-2.5 py-1 pr-1 rounded-full bg-white/15 flex-shrink-0">
+ <span className="text-[10px] font-semibold uppercase tracking-wide text-white/70 leading-none">
+ {done ? 'Rest over' : paused ? 'Paused' : 'Rest'}
+ </span>
+ {!done && <span className="text-xs font-bold text-white tabular-nums leading-none">{fmtClock(left)}</span>}
+ </div>
+ )}
<ChevronRight className="w-4 h-4 text-white/80 flex-shrink-0" />
</button>
</div>
@@ -159,7 +174,7 @@ function UserMenu() {
export default function Layout() {
const { pathname } = useLocation()
- const { session, gymOpen } = useWorkoutSession()
+ const { session, gymOpen, gymPhase } = useWorkoutSession()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
@@ -181,6 +196,12 @@ export default function Layout() {
<GymModeWorkout wUnit={wUnit} />
)}
+ {/* Rest timer floating panel — only INSIDE the workout, on the gym overview /
+ exercise-info screens. The set screen docks its own copy (pushes content up),
+ and when the workout is minimized the countdown shows as a chip in the session
+ pill (ActiveSessionBar) rather than a panel following you around the app. */}
+ {gymOpen && gymPhase !== 'exercise' && <RestTimerBanner />}
+
{/* Active session pill floats above bottom nav */}
<div className="sticky bottom-0 z-50 relative">
<ActiveSessionBar />
diff --git a/web/src/components/RestPicker.tsx b/web/src/components/RestPicker.tsx
new file mode 100644
index 0000000..2f0b997
--- /dev/null
+++ b/web/src/components/RestPicker.tsx
@@ -0,0 +1,70 @@
+import { useState } from 'react'
+import { Clock, TimerOff, Pencil, Minus, Plus } from 'lucide-react'
+
+interface Props {
+ value: number
+ onChange: (secs: number) => void
+}
+
+const PRESETS = [0, 60, 90, 120, 180]
+const SEGMENTS = [
+ { v: 0, label: 'Off', Icon: TimerOff },
+ { v: 60, label: '60s', Icon: Clock },
+ { v: 90, label: '90s', Icon: Clock },
+ { v: 120, label: '120s', Icon: Clock },
+ { v: 180, label: '180s', Icon: Clock },
+]
+
+// Per-exercise rest control: one connected segmented bar (Off · presets · Custom),
+// each segment icon-labelled. Custom reveals a seconds field when chosen.
+export default function RestPicker({ value, onChange }: Props) {
+ const isCustom = !PRESETS.includes(value)
+ const [showCustom, setShowCustom] = useState(false)
+ const customActive = isCustom || showCustom
+
+ const seg = (active: boolean) =>
+ `flex-1 min-w-0 flex flex-col items-center justify-center gap-1 py-2 transition-colors ${
+ active ? 'bg-brand-500 text-white' : 'bg-surface-muted text-tx-secondary hover:text-tx-primary'
+ }`
+
+ return (
+ <div>
+ <div className="flex rounded-xl border border-surface-border overflow-hidden divide-x divide-surface-border">
+ {SEGMENTS.map(({ v, label, Icon }) => (
+ <button key={v} type="button" onClick={() => { setShowCustom(false); onChange(v) }} className={seg(!customActive && value === v)}>
+ <Icon className="w-3.5 h-3.5 flex-shrink-0" />
+ <span className="text-[11px] font-semibold leading-none">{label}</span>
+ </button>
+ ))}
+ <button type="button" onClick={() => setShowCustom(true)} className={seg(customActive)}>
+ <Pencil className="w-3.5 h-3.5 flex-shrink-0" />
+ <span className="text-[11px] font-semibold leading-none">{isCustom ? `${value}s` : 'Custom'}</span>
+ </button>
+ </div>
+ {customActive && (
+ <div className="flex items-center justify-center gap-2 mt-3">
+ <button type="button" aria-label="−5 seconds" onClick={() => onChange(Math.max(0, value - 5))}
+ className="p-2.5 rounded-xl bg-surface-muted border border-surface-border text-tx-secondary active:scale-95 hover:text-tx-primary">
+ <Minus className="w-4 h-4" />
+ </button>
+ <div className="relative">
+ <input
+ type="number"
+ min={0}
+ max={3600}
+ value={value}
+ onChange={e => onChange(Math.max(0, Math.min(3600, Number(e.target.value) || 0)))}
+ className="input w-28 text-center py-2.5 pr-9 text-base font-semibold tabular-nums"
+ aria-label="Rest seconds"
+ />
+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-tx-muted pointer-events-none">sec</span>
+ </div>
+ <button type="button" aria-label="+5 seconds" onClick={() => onChange(Math.min(3600, value + 5))}
+ className="p-2.5 rounded-xl bg-surface-muted border border-surface-border text-tx-secondary active:scale-95 hover:text-tx-primary">
+ <Plus className="w-4 h-4" />
+ </button>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/web/src/components/RestTimerBanner.tsx b/web/src/components/RestTimerBanner.tsx
new file mode 100644
index 0000000..4f07a06
--- /dev/null
+++ b/web/src/components/RestTimerBanner.tsx
@@ -0,0 +1,124 @@
+import { useCallback } from 'react'
+import { Pause, Play, SkipForward, Check } from 'lucide-react'
+import { useWorkoutSession } from '../stores/workoutSession'
+import { useRestTimer } from '../hooks/useRestTimer'
+import { fmtClock, nextIncompleteSet } from '../utils/workoutSets'
+import { IconButton } from './ui'
+
+// Hevy/Strong-style rest panel: a thin draining progress line, a big centred
+// countdown with a pause/resume toggle, and full-width −15/+15/Skip actions.
+// Shown only INSIDE the workout — DOCKED in-flow at the bottom of the gym set screen
+// (pushes the set content up instead of covering it) and FLOATING above the gym
+// overview/exercise-info screens. When the workout is minimized the countdown moves
+// to a compact chip in the session pill (see Layout's ActiveSessionBar) instead of
+// following you around the app. Haptics/sound are left to a future native app.
+export default function RestTimerBanner({ docked = false }: { docked?: boolean }) {
+ const {
+ restEndsAt, restDurationSec, restPausedRemainingMs, restExIdx, restSetIdx,
+ session, adjustRest, clearRest, pauseRest, resumeRest,
+ } = useWorkoutSession()
+ const { active, paused, done, left } = useRestTimer()
+
+ // Drain the progress line over the *actual* remaining time (one linear CSS
+ // transition), not stepping per second. A callback ref (not an effect) so it
+ // fires on the real mount — the bar only renders after restEndsAt is set, which
+ // an effect keyed on restEndsAt would miss. Re-armed when the ref identity
+ // changes (start, ±15s, pause/resume — restPausedRemainingMs is in the deps).
+ const setupLine = useCallback((el: HTMLDivElement | null) => {
+ if (!el) return
+ const total = Math.max(1, (restDurationSec ?? 0) * 1000)
+ // Paused: freeze the line at the parked fraction, no transition.
+ if (restPausedRemainingMs != null) {
+ el.style.transition = 'none'
+ el.style.width = `${Math.min(100, (restPausedRemainingMs / total) * 100)}%`
+ return
+ }
+ if (restEndsAt == null) return
+ const remaining = Math.max(0, restEndsAt - Date.now())
+ el.style.transition = 'none'
+ el.style.width = `${Math.min(100, (remaining / total) * 100)}%`
+ void el.offsetWidth // reflow so the next change animates from here
+ el.style.transition = `width ${remaining}ms linear`
+ el.style.width = '0%'
+ }, [restEndsAt, restDurationSec, restPausedRemainingMs])
+
+ // Hidden when no rest is running or paused (auto-dismiss lives in useRestTimer).
+ if (!active) return null
+
+ // Set ↔ timer linkage (Hevy-style): the store records which set started this rest
+ // (restExIdx/restSetIdx = the just-completed set); label the panel with that set
+ // + the next incomplete one (mirrors gym-mode's auto-advance) so it's clear which
+ // set is resting and which is up next.
+ const restEx = restExIdx != null ? session?.exercises[restExIdx] : undefined
+ const nextIdx = restEx != null && restSetIdx != null ? nextIncompleteSet(restEx.sets, restSetIdx) : -1
+ const doneSetNum = restEx != null && restSetIdx != null ? restSetIdx + 1 : null
+ const label = doneSetNum == null
+ ? (done ? 'Rest over' : paused ? 'Paused' : 'Rest')
+ : done
+ ? (nextIdx !== -1 ? `Rest over · set ${nextIdx + 1} next` : 'Rest over')
+ : paused
+ ? `Set ${doneSetNum} done · paused`
+ : nextIdx !== -1
+ ? `Set ${doneSetNum} done · set ${nextIdx + 1} next`
+ : `Set ${doneSetNum} done · resting`
+
+ const secBtn = 'flex-1 flex items-center justify-center py-2.5 rounded-xl text-sm font-semibold tabular-nums bg-surface-muted border border-surface-border text-tx-secondary active:scale-95'
+ const brandBtn = 'flex-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-sm font-semibold bg-brand-500 text-white active:scale-95'
+
+ const body = (
+ <>
+ {/* draining count-down line */}
+ {done ? (
+ <div className="h-1 bg-success-500" />
+ ) : (
+ <div className="h-1 bg-surface-muted">
+ <div ref={setupLine} className="h-full rounded-r-full bg-brand-500" />
+ </div>
+ )}
+ <div className="px-4 pt-2 pb-3">
+ <p className="text-[11px] font-medium text-tx-muted text-center leading-none">{label}</p>
+ {/* big countdown + pause/resume toggle (the panel's signature element) */}
+ <div className="flex items-center justify-center gap-3 my-2">
+ {done ? (
+ <Check className="w-7 h-7 text-success-500" />
+ ) : (
+ <IconButton
+ icon={paused ? Play : Pause}
+ label={paused ? 'Resume rest timer' : 'Pause rest timer'}
+ onClick={paused ? resumeRest : pauseRest}
+ variant="ghost" size="lg"
+ className="!text-brand-500 hover:!text-brand-500"
+ />
+ )}
+ <span className="font-display text-4xl font-black tabular-nums text-tx-primary leading-none">{fmtClock(left)}</span>
+ </div>
+ {/* full-width actions */}
+ {done ? (
+ <button onClick={() => clearRest()} className={brandBtn}><Check className="w-4 h-4" />Done</button>
+ ) : (
+ <div className="flex gap-2">
+ <button onClick={() => adjustRest(-15)} aria-label="Shorten rest by 15 seconds" className={secBtn}>−15</button>
+ <button onClick={() => adjustRest(15)} aria-label="Extend rest by 15 seconds" className={secBtn}>+15</button>
+ <button onClick={() => clearRest()} className={brandBtn}><SkipForward className="w-4 h-4" />Skip</button>
+ </div>
+ )}
+ </div>
+ </>
+ )
+
+ // Docked: an in-flow block at the bottom of the gym set column, so the flex
+ // layout pushes the set content up above it (nothing is covered).
+ if (docked) {
+ return (
+ <div className="flex-shrink-0 bg-surface-raised border-t border-surface-border animate-slide-up">
+ <div className="max-w-md mx-auto">{body}</div>
+ </div>
+ )
+ }
+ // Floating: above the tab bar on every other screen (e.g. gym minimized).
+ return (
+ <div className="fixed bottom-24 inset-x-3 z-[70] mx-auto max-w-md animate-slide-up">
+ <div className="rounded-2xl border border-surface-border bg-surface-raised overflow-hidden shadow-lg">{body}</div>
+ </div>
+ )
+}
diff --git a/web/src/components/StartWorkoutModal.tsx b/web/src/components/StartWorkoutModal.tsx
index da7670f..ca6c33b 100644
--- a/web/src/components/StartWorkoutModal.tsx
+++ b/web/src/components/StartWorkoutModal.tsx
@@ -47,6 +47,7 @@ export default function StartWorkoutModal({ isOpen, onClose }: Props) {
exercise_id: ex.exercise_id,
exercise: ex.exercise,
notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds,
sets: (ex.sets || []).map(s => ({
set_number: s.set_number,
target_reps: s.target_reps,
diff --git a/web/src/hooks/useCountdown.test.ts b/web/src/hooks/useCountdown.test.ts
new file mode 100644
index 0000000..37da03b
--- /dev/null
+++ b/web/src/hooks/useCountdown.test.ts
@@ -0,0 +1,34 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+import { useCountdown } from './useCountdown'
+
+describe('useCountdown', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ it('returns null when endsAt is null', () => {
+ const { result } = renderHook(() => useCountdown(null))
+ expect(result.current).toBeNull()
+ })
+
+ it('counts down to 0 and fires onComplete exactly once', () => {
+ const onComplete = vi.fn()
+ const endsAt = Date.now() + 2000
+ const { result } = renderHook(() => useCountdown(endsAt, onComplete))
+
+ expect(result.current).toBe(2)
+ act(() => vi.advanceTimersByTime(1500)) // ~1.5s elapsed → 0.5s left → ceil = 1
+ expect(result.current).toBe(1)
+ act(() => vi.advanceTimersByTime(1500)) // ~3s elapsed → past end → 0
+ expect(result.current).toBe(0)
+ // keep ticking past zero — value stays clamped, no extra onComplete
+ act(() => vi.advanceTimersByTime(3000))
+ expect(result.current).toBe(0)
+ expect(onComplete).toHaveBeenCalledTimes(1)
+ })
+
+ it('never returns a negative value', () => {
+ const { result } = renderHook(() => useCountdown(Date.now() - 5000))
+ expect(result.current).toBe(0)
+ })
+})
diff --git a/web/src/hooks/useCountdown.ts b/web/src/hooks/useCountdown.ts
new file mode 100644
index 0000000..9edce74
--- /dev/null
+++ b/web/src/hooks/useCountdown.ts
@@ -0,0 +1,35 @@
+import { useEffect, useRef, useState } from 'react'
+
+// Counts down to an absolute epoch-ms timestamp. Timestamp-based (recomputed each
+// tick, never decremented) so it never drifts and survives component re-mounts.
+// Returns whole seconds remaining (>= 0), or null when `endsAt` is null. Fires
+// `onComplete` exactly once when it first reaches 0.
+export function useCountdown(endsAt: number | null, onComplete?: () => void): number | null {
+ const [left, setLeft] = useState<number | null>(() =>
+ endsAt == null ? null : Math.max(0, Math.ceil((endsAt - Date.now()) / 1000)),
+ )
+ const fired = useRef(false)
+ const onCompleteRef = useRef(onComplete)
+ onCompleteRef.current = onComplete
+
+ useEffect(() => {
+ fired.current = false
+ if (endsAt == null) {
+ setLeft(null)
+ return
+ }
+ const tick = () => {
+ const l = Math.max(0, Math.ceil((endsAt - Date.now()) / 1000))
+ setLeft(l)
+ if (l === 0 && !fired.current) {
+ fired.current = true
+ onCompleteRef.current?.()
+ }
+ }
+ tick()
+ const id = setInterval(tick, 300)
+ return () => clearInterval(id)
+ }, [endsAt])
+
+ return left
+}
diff --git a/web/src/hooks/useRestTimer.ts b/web/src/hooks/useRestTimer.ts
new file mode 100644
index 0000000..e457078
--- /dev/null
+++ b/web/src/hooks/useRestTimer.ts
@@ -0,0 +1,26 @@
+import { useEffect } from 'react'
+import { useWorkoutSession } from '../stores/workoutSession'
+import { useCountdown } from './useCountdown'
+
+// Derived rest-timer state (seconds left, paused/done flags) + the "rest over"
+// auto-dismiss, shared by the full in-workout banner and the minimized session-pill
+// chip so both read one source of truth. The dismiss is anchored to the ABSOLUTE end
+// time and clearRest is idempotent, so it's safe for more than one consumer to mount
+// this at once — whichever is on screen (banner or pill) still clears rest on time.
+export function useRestTimer() {
+ const { restEndsAt, restPausedRemainingMs, clearRest } = useWorkoutSession()
+ const paused = restPausedRemainingMs != null
+ const live = useCountdown(restEndsAt)
+ // While paused, restEndsAt is null (live === null) — show the parked remaining time.
+ const secondsLeft = paused ? Math.max(0, Math.ceil(restPausedRemainingMs! / 1000)) : live
+ const done = !paused && live === 0
+ const active = !(restEndsAt == null && !paused) && secondsLeft != null
+
+ useEffect(() => {
+ if (restEndsAt == null || !done) return
+ const id = setTimeout(() => clearRest(), Math.max(0, restEndsAt + 3000 - Date.now()))
+ return () => clearTimeout(id)
+ }, [restEndsAt, done, clearRest])
+
+ return { active, paused, done, left: secondsLeft ?? 0 }
+}
diff --git a/web/src/pages/AddProgram.tsx b/web/src/pages/AddProgram.tsx
index dc9b997..ea7de82 100644
--- a/web/src/pages/AddProgram.tsx
+++ b/web/src/pages/AddProgram.tsx
@@ -1,10 +1,11 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
-import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target } from 'lucide-react'
+import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target, Timer } from 'lucide-react'
import { programAPI } from '../services/api'
import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'
import WeightInput from '../components/WeightInput'
import ExercisePicker from '../components/ExercisePicker'
+import RestPicker from '../components/RestPicker'
import * as types from '../types'
interface ProgramFormData {
@@ -13,6 +14,7 @@ interface ProgramFormData {
exercises: {
exercise_id: number
notes: string
+ rest_seconds: number
sets: { set_number: number; target_reps: number; target_weight: number }[]
}[]
}
@@ -36,6 +38,7 @@ export default function AddProgram() {
exercises: [...prev.exercises, {
exercise_id: exercise.id,
notes: '',
+ rest_seconds: settings.rest_seconds_default ?? 90,
sets: [{ set_number: 1, target_reps: 0, target_weight: 0 }],
}],
}))
@@ -72,6 +75,14 @@ export default function AddProgram() {
})
}
+ const setExRest = (exIdx: number, secs: number) => {
+ setFormData(prev => {
+ const exercises = [...prev.exercises]
+ exercises[exIdx] = { ...exercises[exIdx], rest_seconds: secs }
+ return { ...prev, exercises }
+ })
+ }
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Program name required'); return }
@@ -218,6 +229,14 @@ export default function AddProgram() {
/>
</div>
+ <div className="mb-4">
+ <div className="flex items-center gap-1.5 mb-1">
+ <Timer className="w-3.5 h-3.5 text-brand-500" />
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Rest between sets</label>
+ </div>
+ <RestPicker value={workoutEx.rest_seconds ?? 90} onChange={secs => setExRest(exIdx, secs)} />
+ </div>
+
<div className="space-y-2 mb-3">
<div className="flex items-center justify-between">
<label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Target Sets</label>
diff --git a/web/src/pages/AddWorkout.tsx b/web/src/pages/AddWorkout.tsx
index 1321f09..ecbb8b6 100644
--- a/web/src/pages/AddWorkout.tsx
+++ b/web/src/pages/AddWorkout.tsx
@@ -1,11 +1,12 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
-import { Plus, ArrowLeft, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge, BookOpen, CalendarDays } from 'lucide-react'
+import { Plus, ArrowLeft, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge, BookOpen, CalendarDays, Timer } from 'lucide-react'
import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'
import WeightInput from '../components/WeightInput'
import ExercisePicker from '../components/ExercisePicker'
import ProgramPicker from '../components/ProgramPicker'
+import RestPicker from '../components/RestPicker'
import * as types from '../types'
interface WorkoutFormData {
@@ -13,7 +14,7 @@ interface WorkoutFormData {
notes: string
duration: number
date: string
- exercises: { exercise_id: number; notes: string; sets: { set_number: number; reps: number; weight: number }[] }[]
+ exercises: { exercise_id: number; notes: string; rest_seconds: number; sets: { set_number: number; reps: number; weight: number }[] }[]
}
export default function AddWorkout() {
@@ -33,7 +34,7 @@ export default function AddWorkout() {
const newMap: Record<number, types.Exercise> = { ...pickerExercises }
const newExercises = (program.exercises || []).map(ex => {
newMap[ex.exercise_id] = ex.exercise
- return { exercise_id: ex.exercise_id, notes: ex.notes || '', sets: (ex.sets || []).map(s => ({ set_number: s.set_number, reps: s.target_reps, weight: s.target_weight })) }
+ return { exercise_id: ex.exercise_id, notes: ex.notes || '', rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90), sets: (ex.sets || []).map(s => ({ set_number: s.set_number, reps: s.target_reps, weight: s.target_weight })) }
})
setPickerExercises(newMap)
setFormData(prev => ({ ...prev, exercises: newExercises }))
@@ -43,7 +44,7 @@ export default function AddWorkout() {
const addExercise = (exercise: types.Exercise) => {
setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))
- setFormData(prev => ({ ...prev, exercises: [...prev.exercises, { exercise_id: exercise.id, notes: '', sets: [{ set_number: 1, reps: 0, weight: 0 }] }] }))
+ setFormData(prev => ({ ...prev, exercises: [...prev.exercises, { exercise_id: exercise.id, notes: '', rest_seconds: settings.rest_seconds_default ?? 90, sets: [{ set_number: 1, reps: 0, weight: 0 }] }] }))
setShowPicker(false)
setError('')
}
@@ -74,6 +75,14 @@ export default function AddWorkout() {
})
}
+ const setExRest = (exIdx: number, secs: number) => {
+ setFormData(prev => {
+ const exercises = [...prev.exercises]
+ exercises[exIdx] = { ...exercises[exIdx], rest_seconds: secs }
+ return { ...prev, exercises }
+ })
+ }
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Workout name required'); return }
@@ -215,6 +224,14 @@ export default function AddWorkout() {
<input type="text" value={workoutEx.notes} onChange={e => { const ex = [...formData.exercises]; ex[exIdx].notes = e.target.value; setFormData(p => ({ ...p, exercises: ex })) }} placeholder="e.g., Felt strong" className="input text-sm" />
</div>
+ <div className="mb-4">
+ <div className="flex items-center gap-1.5 mb-1">
+ <Timer className="w-3.5 h-3.5 text-brand-500" />
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Rest between sets</label>
+ </div>
+ <RestPicker value={workoutEx.rest_seconds ?? 90} onChange={secs => setExRest(exIdx, secs)} />
+ </div>
+
<div className="space-y-2 mb-3">
<div className="flex items-center justify-between">
<label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Sets</label>
diff --git a/web/src/pages/EditProgram.tsx b/web/src/pages/EditProgram.tsx
index 4b57ac9..469c456 100644
--- a/web/src/pages/EditProgram.tsx
+++ b/web/src/pages/EditProgram.tsx
@@ -1,10 +1,11 @@
import { useState, useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
-import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target, Dumbbell } from 'lucide-react'
+import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target, Dumbbell, Timer } from 'lucide-react'
import { programAPI } from '../services/api'
import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'
import WeightInput from '../components/WeightInput'
import ExercisePicker from '../components/ExercisePicker'
+import RestPicker from '../components/RestPicker'
import * as types from '../types'
interface ProgramFormData {
@@ -13,6 +14,7 @@ interface ProgramFormData {
exercises: {
exercise_id: number
notes: string
+ rest_seconds: number
sets: { set_number: number; target_reps: number; target_weight: number }[]
}[]
}
@@ -45,6 +47,7 @@ export default function EditProgram() {
exercises: (p.exercises || []).map(ex => ({
exercise_id: ex.exercise_id,
notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90),
sets: (ex.sets || []).map(s => ({
set_number: s.set_number,
target_reps: s.target_reps,
@@ -61,7 +64,7 @@ export default function EditProgram() {
setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))
setFormData(prev => ({
...prev,
- exercises: [...prev.exercises, { exercise_id: exercise.id, notes: '', sets: [{ set_number: 1, target_reps: 0, target_weight: 0 }] }],
+ exercises: [...prev.exercises, { exercise_id: exercise.id, notes: '', rest_seconds: settings.rest_seconds_default ?? 90, sets: [{ set_number: 1, target_reps: 0, target_weight: 0 }] }],
}))
setShowPicker(false)
setError('')
@@ -95,6 +98,14 @@ export default function EditProgram() {
})
}
+ const setExRest = (exIdx: number, secs: number) => {
+ setFormData(prev => {
+ const exercises = [...prev.exercises]
+ exercises[exIdx] = { ...exercises[exIdx], rest_seconds: secs }
+ return { ...prev, exercises }
+ })
+ }
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Program name required'); return }
@@ -218,6 +229,14 @@ export default function EditProgram() {
<input type="text" value={workoutEx.notes} onChange={e => { const ex = [...formData.exercises]; ex[exIdx].notes = e.target.value; setFormData(p => ({ ...p, exercises: ex })) }} placeholder="e.g., Focus on controlled eccentric" className="input text-sm" />
</div>
+ <div className="mb-4">
+ <div className="flex items-center gap-1.5 mb-1">
+ <Timer className="w-3.5 h-3.5 text-brand-500" />
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Rest between sets</label>
+ </div>
+ <RestPicker value={workoutEx.rest_seconds ?? 90} onChange={secs => setExRest(exIdx, secs)} />
+ </div>
+
<div className="space-y-2 mb-3">
<div className="flex items-center justify-between">
<label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Target Sets</label>
diff --git a/web/src/pages/GymModeWorkout.tsx b/web/src/pages/GymModeWorkout.tsx
index 5f439a5..862efa9 100644
--- a/web/src/pages/GymModeWorkout.tsx
+++ b/web/src/pages/GymModeWorkout.tsx
@@ -3,18 +3,22 @@ import { createPortal } from 'react-dom'
import { useNavigate } from 'react-router-dom'
import {
CheckCircle2, Plus, X, Dumbbell, Flag, ChevronRight, ChevronLeft, Play,
- Minimize2, Trash2, Repeat, Check, Layers,
+ Minimize2, Trash2, Repeat, Check, Layers, Timer,
} from 'lucide-react'
import Model, { IExerciseData } from 'react-body-highlighter'
import * as types from '../types'
import { muscleColor, muscleColorBordered, EQUIPMENT_LABEL, muscleToBodySlugs } from '../utils/exerciseUtils'
import { useTheme } from '../hooks/useTheme'
import { useWorkoutSession } from '../stores/workoutSession'
+import { useSettingsStore } from '../stores/settings'
+import RestPicker from '../components/RestPicker'
+import RestTimerBanner from '../components/RestTimerBanner'
import { workoutAPI } from '../services/api'
import StepperTile from '../components/ui/StepperTile'
import NumberField from '../components/ui/NumberField'
import DiscardConfirm from '../components/DiscardConfirm'
import { clampStep, clampValue } from '../utils/number'
+import { nextIncompleteSet } from '../utils/workoutSets'
import { displayWeight, displayToLbs } from '../stores/settings'
function buildBodyData(exercise: types.Exercise): IExerciseData[] {
@@ -66,7 +70,9 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
gymPhase: phase, gymExIdx: activeIdx, gymSetIdx: activeSetIdx, setGymState,
updateSet, completeSet, addSet, removeSet, removeExercise, updateExerciseNotes,
buildPayload, cancelSession,
+ startRest, clearRest, restExIdx, restSetIdx, setExerciseRest,
} = useWorkoutSession()
+ const { settings } = useSettingsStore()
const [imgFailed, setImgFailed] = useState(false)
const [confirmFinish, setConfirmFinish] = useState(false)
@@ -373,6 +379,16 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
))}
</div>
+ {/* Rest timer for this exercise */}
+ <div className="card p-4">
+ <div className="flex items-center gap-2">
+ <Timer className="w-4 h-4 text-brand-500" />
+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">Rest between sets</p>
+ </div>
+ <p className="text-[11px] text-tx-muted mt-1 mb-3">Auto-starts when you complete a set</p>
+ <RestPicker value={ex.rest_seconds ?? (settings.rest_seconds_default ?? 90)} onChange={secs => setExerciseRest(activeIdx, secs)} />
+ </div>
+
{/* Secondary muscles */}
{exercise.secondary_muscles?.length > 0 && (
<div>
@@ -474,9 +490,20 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
const set = ex.sets[clampedSetIdx]
const handleCompleteSetGym = (setIdx: number) => {
+ const wasCompleted = ex.sets[setIdx].completed
completeSet(activeIdx, setIdx)
+ if (wasCompleted) {
+ // Un-completing: cancel the running rest only if it belongs to this set.
+ if (restExIdx === activeIdx && restSetIdx === setIdx) clearRest()
+ return
+ }
+ // Completing: start rest (per-exercise value, else the global default; 0 = off).
+ if (settings.rest_enabled) {
+ const r = ex.rest_seconds ?? settings.rest_seconds_default ?? 90
+ if (r > 0) startRest(r, activeIdx, setIdx)
+ }
// Auto-advance to next incomplete set
- const next = ex.sets.findIndex((s, i) => i > setIdx && !s.completed)
+ const next = nextIncompleteSet(ex.sets, setIdx)
if (next !== -1) setActiveSetIdx(next)
}
@@ -494,6 +521,14 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
if (!set) return null
+ // Rest-timer view state for this exercise (restExIdx/restSetIdx are cleared or
+ // remapped by the store on structural edits, so they're safe to key on here).
+ const restingHere = restExIdx === activeIdx
+ // The set the rest is "before" — the one auto-advance focuses. We only collapse the
+ // Complete Set control for THAT set, so navigating to a different set stays loggable.
+ const restNextSet = restingHere && restSetIdx != null ? nextIncompleteSet(ex.sets, restSetIdx) : -1
+ const hideCompleteForRest = restingHere && clampedSetIdx === restNextSet
+
return (
<div className="fixed inset-0 z-[60] bg-surface-base flex flex-col">
<TopBar s={session} onBack={() => setPhase('exercise-info')} />
@@ -521,28 +556,41 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
</div>
</div>
- {/* 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">
+ {/* The whole logging group (set chips, target, inputs, action). Scrollable +
+ min-h-0 so when the rest timer docks below and compresses this area the
+ content scrolls instead of clipping; m-auto keeps it centred when it fits. */}
+ <div className="flex-1 min-h-0 overflow-y-auto flex flex-col">
+ {/* m-auto (not justify-center): centres the group when it fits, and when the
+ docked rest panel leaves too little room (short phones) the auto margins
+ collapse and the group scrolls with EVERYTHING reachable — margin-auto is
+ scroll-stable where flex justify-center fights the scroll. No hardcoded
+ heights. Spacing tightens while resting; roomy otherwise. */}
+ <div className={`m-auto w-full flex flex-col items-center px-5 ${restingHere ? 'gap-4 py-2' : 'gap-6 py-4'}`}>
{/* 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>
- ))}
+ {ex.sets.map((s, i) => {
+ // Set ↔ timer linkage: while resting, the chip of the set that started
+ // the timer keeps a subtle brand ring so it reads as "resting after
+ // this one" even though focus auto-advanced to the next set.
+ const resting = restingHere && restSetIdx === i
+ return (
+ <button
+ key={i}
+ onClick={() => setActiveSetIdx(i)}
+ aria-label={`Set ${i + 1}${s.completed ? ', done' : ''}${resting ? ', resting' : ''}`}
+ 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${resting ? ' ring-1 ring-brand-500/60' : ''}` :
+ 'bg-surface-muted text-tx-muted hover:text-tx-secondary'
+ }`}
+ >
+ {s.completed && <Check className="w-3.5 h-3.5" />}
+ {i + 1}
+ </button>
+ )
+ })}
</div>
{/* Target reference for this set (the goal to hit) */}
@@ -593,29 +641,39 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
</StepperTile>
</div>
- {/* Complete button */}
- <button
- onClick={() => handleCompleteSetGym(clampedSetIdx)}
- className={`w-full py-5 rounded-2xl text-base font-bold flex items-center justify-center gap-3 transition-all ${
- set.completed
- ? 'bg-brand-500/15 border-2 border-brand-500/40 text-brand-400'
- : 'bg-brand-500 hover:bg-brand-600 text-white shadow-lg shadow-brand-500/30'
- }`}
- >
- <CheckCircle2 className="w-6 h-6" />
- {set.completed ? 'Completed' : 'Complete 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 && (
+ {/* While resting before this set, collapse + fade the Complete Set / Remove
+ controls out of the way — you Skip the timer to begin it. This also frees
+ the space so the set content never clips behind the docked rest panel.
+ Keyed on the specific up-next set (not the whole exercise) so navigating to
+ another set to log it still shows its Complete button. */}
+ <div className={`w-full flex flex-col items-center gap-6 overflow-hidden transition-all duration-300 ${
+ hideCompleteForRest ? 'max-h-0 opacity-0 pointer-events-none' : 'max-h-40 opacity-100'
+ }`}>
+ {/* Complete button */}
<button
- onClick={() => handleRemoveSet(clampedSetIdx)}
- className="text-xs text-tx-muted/50 hover:text-error-400 transition-colors"
+ onClick={() => handleCompleteSetGym(clampedSetIdx)}
+ className={`w-full py-5 rounded-2xl text-base font-bold flex items-center justify-center gap-3 transition-all ${
+ set.completed
+ ? 'bg-brand-500/15 border-2 border-brand-500/40 text-brand-400'
+ : 'bg-brand-500 hover:bg-brand-600 text-white shadow-lg shadow-brand-500/30'
+ }`}
>
- Remove this set
+ <CheckCircle2 className="w-6 h-6" />
+ {set.completed ? 'Completed' : 'Complete 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>
+ </div>
</div>
{/* Bottom nav */}
@@ -682,6 +740,10 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
</div>
</div>
+ {/* Rest timer — docked here (in-flow, last child) so it pushes the set
+ content up instead of covering it. Renders null when no rest is active. */}
+ <RestTimerBanner docked />
+
{/* ── Finish confirm ── */}
{confirmFinish && createPortal(
<div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">
diff --git a/web/src/pages/ProgramDetail.tsx b/web/src/pages/ProgramDetail.tsx
index 418779d..749e8e5 100644
--- a/web/src/pages/ProgramDetail.tsx
+++ b/web/src/pages/ProgramDetail.tsx
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { format } from 'date-fns'
import {
- ArrowLeft, BookOpen, Dumbbell, Edit2, Trash2, Play, AlertCircle, Loader, ChevronRight,
+ ArrowLeft, BookOpen, Dumbbell, Edit2, Trash2, Play, AlertCircle, Loader, ChevronRight, Pause, TimerOff,
} from 'lucide-react'
import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
@@ -17,6 +17,8 @@ export default function ProgramDetail() {
const { session, startSession } = useWorkoutSession()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
+ const restOn = settings.rest_enabled ?? true
+ const restLabel = (s: number) => (s % 60 === 0 && s >= 60 ? `${s / 60}m` : `${s}s`)
const [program, setProgram] = useState<types.Program | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@@ -44,6 +46,7 @@ export default function ProgramDetail() {
exercise_id: ex.exercise_id,
exercise: ex.exercise,
notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds,
sets: (ex.sets || []).map(s => ({
set_number: s.set_number,
target_reps: s.target_reps,
@@ -190,6 +193,11 @@ export default function ProgramDetail() {
</div>
{/* Exercises */}
+ {!restOn && (
+ <div className="flex items-center gap-1.5 text-[11px] text-tx-muted px-1">
+ <TimerOff className="w-3.5 h-3.5" /> Rest timer is off — turn it on in Settings
+ </div>
+ )}
<div className="space-y-2">
{exs.map((ex) => {
const sets = ex.sets ?? []
@@ -217,31 +225,36 @@ export default function ProgramDetail() {
)}
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-tx-primary truncate">{ex.exercise?.name}</p>
- <div className="flex items-center gap-2 mt-0.5 flex-wrap">
+ <div className="flex items-center gap-2 mt-0.5">
{ex.exercise?.muscle_group && (
- <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${muscleColor(ex.exercise.muscle_group)}`}>
+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0 ${muscleColor(ex.exercise.muscle_group)}`}>
{ex.exercise.muscle_group}
</span>
)}
- <span className="text-xs text-tx-muted">{sets.length} sets</span>
- {maxTarget > 0 && <span className="text-xs text-tx-muted">target {maxTarget} {wUnit}</span>}
+ <span className="text-xs text-tx-muted truncate">{sets.length} sets{maxTarget > 0 ? ` · target ${maxTarget} ${wUnit}` : ''}</span>
</div>
</div>
<ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
</div>
{sets.length > 0 && (
- <div className="flex flex-wrap gap-1.5 px-4 pb-4 border-t border-surface-border/50 pt-3">
- {sets.map((set, i) => {
- const isBest = set.target_weight === maxTargetLbs && maxTargetLbs > 0
- return (
- <div key={i} className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${
- isBest ? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25' : 'bg-surface-raised text-tx-secondary'
- }`}>
- {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${displayWeight(set.target_weight, wUnit)} ${wUnit}` : 'BW'}
- </div>
- )
- })}
+ <div className="flex items-center gap-2 px-4 pb-4 border-t border-surface-border/50 pt-3">
+ <div className="flex flex-wrap gap-1.5 flex-1 min-w-0">
+ {sets.map((set, i) => {
+ const isBest = set.target_weight === maxTargetLbs && maxTargetLbs > 0
+ return (
+ <div key={i} className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${
+ isBest ? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25' : 'bg-surface-raised text-tx-secondary'
+ }`}>
+ {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${displayWeight(set.target_weight, wUnit)} ${wUnit}` : 'BW'}
+ </div>
+ )
+ })}
+ </div>
+ {restOn && (ex.rest_seconds === 0
+ ? <span className="text-xs text-tx-muted flex-shrink-0">No rest</span>
+ : <span className="flex items-center gap-1 text-xs text-tx-muted flex-shrink-0"><Pause className="w-3.5 h-3.5" />{restLabel(ex.rest_seconds ?? 90)}</span>
+ )}
</div>
)}
</button>
diff --git a/web/src/pages/Programs.tsx b/web/src/pages/Programs.tsx
index f8d5e2e..c68279f 100644
--- a/web/src/pages/Programs.tsx
+++ b/web/src/pages/Programs.tsx
@@ -44,6 +44,7 @@ function ProgramCard({
exercise_id: ex.exercise_id,
exercise: ex.exercise,
notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds,
sets: (ex.sets || []).map(s => ({
set_number: s.set_number,
target_reps: s.target_reps,
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 3309306..20aad2e 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -11,7 +11,7 @@ import PageHeader from '../components/ui/PageHeader'
import ServerSettings from '../components/ServerSettings'
import {
User, Shield, Target, Moon, Sun, Server, LogOut, Trash2, ChevronRight, Check, AlertCircle, Loader,
- Dumbbell, RefreshCw,
+ Dumbbell, RefreshCw, Pencil, Clock, Minus, Plus,
} from 'lucide-react'
function SettingRow({ label, description, children }: { label: string; description?: string; children: React.ReactNode }) {
@@ -44,11 +44,12 @@ export default function Settings() {
const serverUrl = useServerStore(s => s.serverUrl)
const serverInfo = useServerInfo()
const { theme, toggleTheme } = useTheme()
- const { settings: storedSettings, update: updateSettings, fetch: fetchSettings, setWorkoutLayout } = useSettingsStore()
+ const { settings: storedSettings, update: updateSettings, fetch: fetchSettings, setWorkoutLayout, setRestEnabled, setRestSeconds } = useSettingsStore()
const [loading, setLoading] = useState(!useSettingsStore.getState().loaded)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState(false)
+ const [showCustomRest, setShowCustomRest] = useState(false)
const [seedStatus, setSeedStatus] = useState<{ count: number; in_progress: boolean } | null>(null)
const [seedAction, setSeedAction] = useState<'sync' | null>(null)
@@ -208,6 +209,79 @@ export default function Settings() {
))}
</div>
</SettingRow>
+
+ <SettingRow label="Rest timer" description="Auto-start a countdown between sets in gym mode">
+ <div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">
+ {([['Off', false], ['On', true]] as const).map(([label, val]) => (
+ <button
+ key={label}
+ onClick={() => setRestEnabled(val)}
+ className={`px-3 py-1 rounded-md text-xs font-medium transition-all ${
+ (storedSettings.rest_enabled ?? true) === val
+ ? 'bg-surface-raised border border-surface-border text-tx-primary shadow-sm'
+ : 'text-tx-muted hover:text-tx-primary'
+ }`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </SettingRow>
+
+ {(() => {
+ const enabled = storedSettings.rest_enabled ?? true
+ const presets = [60, 90, 120, 180]
+ const cur = storedSettings.rest_seconds_default ?? 90
+ const isCustom = !presets.includes(cur)
+ const customActive = isCustom || showCustomRest
+ const seg = (active: boolean) =>
+ `flex-1 min-w-0 flex flex-col items-center justify-center gap-1 py-2 transition-colors ${
+ active ? 'bg-brand-500 text-white' : 'bg-surface-muted text-tx-secondary hover:text-tx-primary'
+ }`
+ return (
+ <div className={`py-4 transition-opacity ${enabled ? '' : 'opacity-40 pointer-events-none select-none'}`} aria-disabled={!enabled}>
+ <p className="text-sm font-medium text-tx-primary">Default rest</p>
+ <p className="text-xs text-tx-muted mt-0.5 mb-3">Seeds new exercises · per-exercise rest overrides it</p>
+ <div className="flex rounded-xl border border-surface-border overflow-hidden divide-x divide-surface-border">
+ {presets.map(sec => (
+ <button key={sec} disabled={!enabled} onClick={() => { setShowCustomRest(false); setRestSeconds(sec) }} className={seg(!customActive && cur === sec)}>
+ <Clock className="w-3.5 h-3.5 flex-shrink-0" />
+ <span className="text-[11px] font-semibold leading-none">{sec}s</span>
+ </button>
+ ))}
+ <button disabled={!enabled} onClick={() => setShowCustomRest(true)} className={seg(customActive)}>
+ <Pencil className="w-3.5 h-3.5 flex-shrink-0" />
+ <span className="text-[11px] font-semibold leading-none">{isCustom ? `${cur}s` : 'Custom'}</span>
+ </button>
+ </div>
+ {customActive && (
+ <div className="flex items-center justify-center gap-2 mt-3">
+ <button type="button" disabled={!enabled} aria-label="−5 seconds" onClick={() => setRestSeconds(Math.max(0, cur - 5))}
+ className="p-2.5 rounded-xl bg-surface-muted border border-surface-border text-tx-secondary active:scale-95 hover:text-tx-primary">
+ <Minus className="w-4 h-4" />
+ </button>
+ <div className="relative">
+ <input
+ type="number"
+ min={0}
+ max={3600}
+ disabled={!enabled}
+ value={cur}
+ onChange={e => setRestSeconds(Math.max(0, Math.min(3600, Number(e.target.value) || 0)))}
+ className="input w-28 text-center py-2.5 pr-9 text-base font-semibold tabular-nums"
+ aria-label="Custom rest seconds"
+ />
+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-tx-muted pointer-events-none">sec</span>
+ </div>
+ <button type="button" disabled={!enabled} aria-label="+5 seconds" onClick={() => setRestSeconds(Math.min(3600, cur + 5))}
+ className="p-2.5 rounded-xl bg-surface-muted border border-surface-border text-tx-secondary active:scale-95 hover:text-tx-primary">
+ <Plus className="w-4 h-4" />
+ </button>
+ </div>
+ )}
+ </div>
+ )
+ })()}
</Section>
{/* Goals & Units */}
diff --git a/web/src/pages/StartWorkout.tsx b/web/src/pages/StartWorkout.tsx
index 9345f9d..265209f 100644
--- a/web/src/pages/StartWorkout.tsx
+++ b/web/src/pages/StartWorkout.tsx
@@ -31,6 +31,7 @@ export default function StartWorkout() {
exercise_id: ex.exercise_id,
exercise: ex.exercise,
notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds,
sets: (ex.sets || []).map(s => ({
set_number: s.set_number,
target_reps: s.target_reps,
diff --git a/web/src/pages/WorkoutDetail.tsx b/web/src/pages/WorkoutDetail.tsx
index d3c1fd5..d911d34 100644
--- a/web/src/pages/WorkoutDetail.tsx
+++ b/web/src/pages/WorkoutDetail.tsx
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { format } from 'date-fns'
import {
- ArrowLeft, Clock, Dumbbell, TrendingUp, Edit2, Trash2, ChevronRight, AlertCircle, Loader,
+ ArrowLeft, Clock, Dumbbell, TrendingUp, Edit2, Trash2, ChevronRight, AlertCircle, Loader, Pause, TimerOff,
} from 'lucide-react'
import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'
@@ -27,6 +27,8 @@ export default function WorkoutDetail() {
const navigate = useNavigate()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
+ const restOn = settings.rest_enabled ?? true
+ const restLabel = (s: number) => (s % 60 === 0 && s >= 60 ? `${s / 60}m` : `${s}s`)
const [workout, setWorkout] = useState<types.Workout | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@@ -190,6 +192,11 @@ export default function WorkoutDetail() {
</div>
{/* Exercises */}
+ {!restOn && (
+ <div className="flex items-center gap-1.5 text-[11px] text-tx-muted px-1">
+ <TimerOff className="w-3.5 h-3.5" /> Rest timer is off — turn it on in Settings
+ </div>
+ )}
<div className="space-y-3">
{exs.map((ex, idx) => {
const sets = ex.sets ?? []
@@ -218,14 +225,13 @@ export default function WorkoutDetail() {
)}
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-tx-primary truncate">{ex.exercise?.name}</p>
- <div className="flex items-center gap-2 mt-0.5 flex-wrap">
+ <div className="flex items-center gap-2 mt-0.5">
{ex.exercise?.muscle_group && (
- <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${muscleColor(ex.exercise.muscle_group)}`}>
+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0 ${muscleColor(ex.exercise.muscle_group)}`}>
{ex.exercise.muscle_group}
</span>
)}
- <span className="text-xs text-tx-muted">{sets.length} sets</span>
- {exVol > 0 && <span className="text-xs text-tx-muted">{exVol.toLocaleString()} {wUnit}</span>}
+ <span className="text-xs text-tx-muted truncate">{sets.length} sets{exVol > 0 ? ` · ${exVol.toLocaleString()} ${wUnit}` : ''}</span>
</div>
</div>
{maxWeight > 0 && (
@@ -238,11 +244,16 @@ export default function WorkoutDetail() {
</div>
{sets.length > 0 && (
- <div className="flex flex-wrap gap-1.5 px-4 pb-4 pt-0 border-t border-surface-border/50">
- <div className="w-full pt-3" />
- {sets.map((set, i) => (
- <SetChip key={i} set={set} isBest={set.weight === maxWeightLbs && maxWeightLbs > 0} unit={wUnit} />
- ))}
+ <div className="flex items-center gap-2 px-4 pb-4 pt-3 border-t border-surface-border/50">
+ <div className="flex flex-wrap gap-1.5 flex-1 min-w-0">
+ {sets.map((set, i) => (
+ <SetChip key={i} set={set} isBest={set.weight === maxWeightLbs && maxWeightLbs > 0} unit={wUnit} />
+ ))}
+ </div>
+ {restOn && (ex.rest_seconds === 0
+ ? <span className="text-xs text-tx-muted flex-shrink-0">No rest</span>
+ : <span className="flex items-center gap-1 text-xs text-tx-muted flex-shrink-0"><Pause className="w-3.5 h-3.5" />{restLabel(ex.rest_seconds ?? 90)}</span>
+ )}
</div>
)}
</button>
diff --git a/web/src/stores/settings.ts b/web/src/stores/settings.ts
index 90d216e..89187e9 100644
--- a/web/src/stores/settings.ts
+++ b/web/src/stores/settings.ts
@@ -3,6 +3,18 @@ import * as types from '../types'
import { userAPI } from '../services/api'
const LAYOUT_KEY = 'lyftr_workout_layout'
+const REST_ON_KEY = 'lyftr_rest_enabled'
+const REST_SEC_KEY = 'lyftr_rest_seconds'
+
+// Client-only prefs (not stored server-side) — re-applied over any backend fetch
+// so a settings GET/PUT never clobbers them.
+function clientPrefs(): Pick<types.UserSettings, 'workout_layout' | 'rest_enabled' | 'rest_seconds_default'> {
+ return {
+ workout_layout: (localStorage.getItem(LAYOUT_KEY) as 'list' | 'gym') ?? 'list',
+ rest_enabled: localStorage.getItem(REST_ON_KEY) !== 'false', // default on
+ rest_seconds_default: Number(localStorage.getItem(REST_SEC_KEY)) || 90,
+ }
+}
interface SettingsStore {
settings: types.UserSettings
@@ -10,6 +22,8 @@ interface SettingsStore {
fetch: () => Promise<void>
update: (patch: Partial<types.UserSettings>) => Promise<void>
setWorkoutLayout: (layout: 'list' | 'gym') => void
+ setRestEnabled: (on: boolean) => void
+ setRestSeconds: (secs: number) => void
reset: () => void
}
@@ -20,7 +34,7 @@ const DEFAULTS: types.UserSettings = {
protein_target: 150,
carb_target: 250,
fat_target: 65,
- workout_layout: (localStorage.getItem(LAYOUT_KEY) as 'list' | 'gym') ?? 'list',
+ ...clientPrefs(),
}
export const useSettingsStore = create<SettingsStore>((set, get) => ({
@@ -31,8 +45,7 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({
if (get().loaded) return
try {
const s = await userAPI.getSettings()
- const layout = localStorage.getItem(LAYOUT_KEY) as 'list' | 'gym' | null
- set({ settings: { ...s, workout_layout: layout ?? 'list' }, loaded: true })
+ set({ settings: { ...s, ...clientPrefs() }, loaded: true })
} catch {
set({ loaded: true })
}
@@ -41,8 +54,7 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({
update: async (patch) => {
set(state => ({ settings: { ...state.settings, ...patch } }))
const updated = await userAPI.updateSettings(patch)
- const layout = localStorage.getItem(LAYOUT_KEY) as 'list' | 'gym' | null
- set({ settings: { ...updated, workout_layout: layout ?? 'list' } })
+ set({ settings: { ...updated, ...clientPrefs() } })
},
setWorkoutLayout: (layout) => {
@@ -50,6 +62,16 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({
set(state => ({ settings: { ...state.settings, workout_layout: layout } }))
},
+ setRestEnabled: (on) => {
+ localStorage.setItem(REST_ON_KEY, String(on))
+ set(state => ({ settings: { ...state.settings, rest_enabled: on } }))
+ },
+
+ setRestSeconds: (secs) => {
+ localStorage.setItem(REST_SEC_KEY, String(secs))
+ set(state => ({ settings: { ...state.settings, rest_seconds_default: secs } }))
+ },
+
reset: () => set({ settings: DEFAULTS, loaded: false }),
}))
diff --git a/web/src/stores/workoutSession.test.ts b/web/src/stores/workoutSession.test.ts
new file mode 100644
index 0000000..f3dece8
--- /dev/null
+++ b/web/src/stores/workoutSession.test.ts
@@ -0,0 +1,114 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useWorkoutSession } from './workoutSession'
+
+const store = () => useWorkoutSession.getState()
+
+describe('workoutSession rest timer (ephemeral)', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ store().cancelSession()
+ })
+
+ it('startRest sets an absolute end timestamp + context', () => {
+ const before = Date.now()
+ store().startRest(90, 1, 2)
+ const s = store()
+ expect(s.restEndsAt!).toBeGreaterThanOrEqual(before + 90000 - 100)
+ expect(s.restDurationSec).toBe(90)
+ expect(s.restExIdx).toBe(1)
+ expect(s.restSetIdx).toBe(2)
+ })
+
+ it('adjustRest extends, and clamps so it never goes below now', () => {
+ store().startRest(60, 0, 0)
+ const end1 = store().restEndsAt!
+ store().adjustRest(15)
+ expect(store().restEndsAt!).toBeGreaterThan(end1)
+ store().adjustRest(-9999)
+ expect(store().restEndsAt!).toBeGreaterThanOrEqual(Date.now() - 100)
+ })
+
+ it('clearRest + cancelSession null all rest fields', () => {
+ store().startRest(60, 0, 0)
+ store().clearRest()
+ expect(store().restEndsAt).toBeNull()
+ expect(store().restDurationSec).toBeNull()
+ store().startRest(60, 0, 0)
+ store().cancelSession()
+ expect(store().restEndsAt).toBeNull()
+ })
+
+ it('pauseRest parks the remaining time and stops the live countdown', () => {
+ store().startRest(60, 0, 0)
+ store().pauseRest()
+ const s = store()
+ expect(s.restEndsAt).toBeNull() // live countdown frozen
+ expect(s.restPausedRemainingMs!).toBeGreaterThan(59000)
+ expect(s.restPausedRemainingMs!).toBeLessThanOrEqual(60000)
+ })
+
+ it('resumeRest restores a live end stamp from the parked time', () => {
+ store().startRest(60, 0, 0)
+ store().pauseRest()
+ const parked = store().restPausedRemainingMs!
+ store().resumeRest()
+ const s = store()
+ expect(s.restPausedRemainingMs).toBeNull()
+ expect(s.restEndsAt!).toBeGreaterThanOrEqual(Date.now() + parked - 100)
+ })
+
+ it('adjustRest shifts the parked time while paused', () => {
+ store().startRest(60, 0, 0)
+ store().pauseRest()
+ const parked = store().restPausedRemainingMs!
+ store().adjustRest(15)
+ expect(store().restPausedRemainingMs!).toBeGreaterThanOrEqual(parked + 15000 - 50)
+ expect(store().restDurationSec).toBe(75)
+ })
+
+ it('startRest clears any prior paused state', () => {
+ store().startRest(60, 0, 0)
+ store().pauseRest()
+ store().startRest(90, 1, 1)
+ expect(store().restPausedRemainingMs).toBeNull()
+ expect(store().restEndsAt).not.toBeNull()
+ })
+
+ it('adjustRest to 0 while paused finishes the rest (no stuck 0:00 · paused)', () => {
+ store().startRest(10, 0, 0)
+ store().pauseRest()
+ store().adjustRest(-15) // parked 10s − 15s ≤ 0
+ const s = store()
+ expect(s.restPausedRemainingMs).toBeNull() // unpaused
+ expect(s.restEndsAt!).toBeLessThanOrEqual(Date.now() + 1) // countdown reads 0 → done
+ })
+
+ it('removeExercise clears the rest so a stale positional restExIdx cannot mislead', () => {
+ store().startSession('T', [
+ { exercise_id: 1, exercise: { id: 1, name: 'A' }, notes: '', sets: [{ set_number: 1 }] },
+ { exercise_id: 2, exercise: { id: 2, name: 'B' }, notes: '', sets: [{ set_number: 1 }] },
+ ] as any)
+ store().startRest(60, 0, 0)
+ store().removeExercise(1)
+ expect(store().restEndsAt).toBeNull()
+ expect(store().restExIdx).toBeNull()
+ })
+
+ it('removeSet clears the rest (set indices shift)', () => {
+ store().startSession('T', [
+ { exercise_id: 1, exercise: { id: 1, name: 'A' }, notes: '', sets: [{ set_number: 1 }, { set_number: 2 }] },
+ ] as any)
+ store().startRest(60, 0, 1)
+ store().removeSet(0, 0)
+ expect(store().restEndsAt).toBeNull()
+ expect(store().restSetIdx).toBeNull()
+ })
+
+ it('rest state is never written to localStorage (ephemeral)', () => {
+ store().startSession('T', [])
+ store().startRest(90, 0, 0)
+ const raw = localStorage.getItem('lyftr_active_session')!
+ expect(raw).not.toContain('restEndsAt')
+ expect(raw).not.toContain('restDurationSec')
+ })
+})
diff --git a/web/src/stores/workoutSession.ts b/web/src/stores/workoutSession.ts
index b1e19e4..12a9c38 100644
--- a/web/src/stores/workoutSession.ts
+++ b/web/src/stores/workoutSession.ts
@@ -57,16 +57,71 @@ interface WorkoutSessionStore {
openGym: () => void
minimizeGym: () => void
setGymState: (phase: GymPhase, exIdx: number, setIdx: number) => void
+ setExerciseRest: (exIdx: number, secs: number) => void
+ // Rest timer — ephemeral (never persisted). Survives minimize/restore via the
+ // module singleton; evaporates on full refresh by design (an absolute timestamp
+ // must not outlive the session moment).
+ restEndsAt: number | null
+ restDurationSec: number | null
+ restExIdx: number | null
+ restSetIdx: number | null
+ // When paused, restEndsAt is nulled and the frozen remaining time is parked here
+ // (ms). This is the single "paused" flag: paused iff restPausedRemainingMs != null.
+ restPausedRemainingMs: number | null
+ startRest: (durationSec: number, exIdx: number, setIdx: number) => void
+ adjustRest: (deltaSec: number) => void
+ pauseRest: () => void
+ resumeRest: () => void
+ clearRest: () => void
}
const _savedGymUi = loadGymUi()
+// All rest-timer fields nulled — the single "no active rest" state, reused wherever
+// rest is cleared (clearRest, cancelSession, and structural edits that invalidate the
+// positional restExIdx/restSetIdx).
+const CLEARED_REST = {
+ restEndsAt: null, restDurationSec: null, restExIdx: null, restSetIdx: null, restPausedRemainingMs: null,
+} as const
+
export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
session: loadLocal(),
gymOpen: false,
gymPhase: _savedGymUi.phase,
gymExIdx: _savedGymUi.exIdx,
gymSetIdx: _savedGymUi.setIdx,
+ ...CLEARED_REST,
+
+ startRest: (durationSec, exIdx, setIdx) =>
+ set({ restEndsAt: Date.now() + durationSec * 1000, restDurationSec: durationSec, restExIdx: exIdx, restSetIdx: setIdx, restPausedRemainingMs: null }),
+ adjustRest: (deltaSec) => set(state => {
+ const nextDuration = Math.max(1, (state.restDurationSec ?? 0) + deltaSec)
+ // Adjusting while paused shifts the parked remaining time, not a live end stamp.
+ if (state.restPausedRemainingMs != null) {
+ const nextMs = state.restPausedRemainingMs + deltaSec * 1000
+ // Adjusted to zero while paused → finish it: unpause into the completed
+ // state (restEndsAt = now → countdown reads 0 → done → auto-dismiss), so it
+ // never sticks at "0:00 · paused" with no completion path.
+ if (nextMs <= 0) return { restPausedRemainingMs: null, restEndsAt: Date.now(), restDurationSec: nextDuration }
+ return { restPausedRemainingMs: nextMs, restDurationSec: nextDuration }
+ }
+ if (state.restEndsAt == null) return {}
+ return {
+ restEndsAt: Math.max(Date.now(), state.restEndsAt + deltaSec * 1000),
+ restDurationSec: nextDuration,
+ }
+ }),
+ // Freeze the countdown: park the remaining time and null the live end stamp so
+ // useCountdown (here and in the minimized-gym mount) stops ticking.
+ pauseRest: () => set(state => {
+ if (state.restEndsAt == null || state.restPausedRemainingMs != null) return {}
+ return { restPausedRemainingMs: Math.max(0, state.restEndsAt - Date.now()), restEndsAt: null }
+ }),
+ resumeRest: () => set(state => {
+ if (state.restPausedRemainingMs == null) return {}
+ return { restEndsAt: Date.now() + state.restPausedRemainingMs, restPausedRemainingMs: null }
+ }),
+ clearRest: () => set({ ...CLEARED_REST }),
openGym: () => set({ gymOpen: true }),
minimizeGym: () => set({ gymOpen: false }),
@@ -123,6 +178,15 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
set({ session: updated })
},
+ setExerciseRest: (exIdx, secs) => {
+ const session = get().session
+ if (!session) return
+ const exercises = session.exercises.map((ex, i) => i !== exIdx ? ex : { ...ex, rest_seconds: secs })
+ const updated = { ...session, exercises }
+ saveLocal(updated)
+ set({ session: updated })
+ },
+
addSet: (exIdx) => {
const session = get().session
if (!session) return
@@ -158,7 +222,9 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
})
const updated = { ...session, exercises }
saveLocal(updated)
- set({ session: updated })
+ // Removing a set shifts set indices, invalidating the positional restSetIdx — cancel
+ // the (ephemeral) rest rather than let it point at the wrong set.
+ set({ session: updated, ...CLEARED_REST })
},
addExercise: (ex) => {
@@ -174,7 +240,9 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
if (!session) return
const updated = { ...session, exercises: session.exercises.filter((_, i) => i !== exIdx) }
saveLocal(updated)
- set({ session: updated })
+ // filter() shifts exercise indices, invalidating the positional restExIdx — cancel
+ // the (ephemeral) rest so it can't collapse controls on the wrong exercise.
+ set({ session: updated, ...CLEARED_REST })
},
buildPayload: () => {
@@ -189,6 +257,7 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
exercises: session.exercises.map(ex => ({
exercise_id: ex.exercise_id,
notes: ex.notes,
+ rest_seconds: ex.rest_seconds,
sets: ex.sets.map((s, i) => ({
set_number: i + 1,
reps: s.actual_reps || s.target_reps,
@@ -201,6 +270,9 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
cancelSession: () => {
saveLocal(null)
localStorage.removeItem(GYM_UI_KEY)
- set({ session: null, gymOpen: false, gymPhase: 'overview', gymExIdx: 0, gymSetIdx: 0 })
+ set({
+ session: null, gymOpen: false, gymPhase: 'overview', gymExIdx: 0, gymSetIdx: 0,
+ ...CLEARED_REST,
+ })
},
}))
diff --git a/web/src/types.ts b/web/src/types.ts
index fee1002..abb36ec 100644
--- a/web/src/types.ts
+++ b/web/src/types.ts
@@ -13,6 +13,9 @@ export interface UserSettings {
carb_target: number
fat_target: number
workout_layout?: 'list' | 'gym'
+ // Client-only (localStorage, not persisted server-side):
+ rest_enabled?: boolean // master rest-timer on/off
+ rest_seconds_default?: number // default rest seconds, seeds new exercises
}
export interface Exercise {
@@ -45,6 +48,7 @@ export interface WorkoutExercise {
order_index?: number
notes?: string
exercise: Exercise
+ rest_seconds?: number
sets: Set[]
}
@@ -154,6 +158,7 @@ export interface ProgramExercise {
order_index?: number
notes?: string
exercise: Exercise
+ rest_seconds?: number
sets: ProgramSet[]
}
@@ -178,6 +183,7 @@ export interface ActiveSessionExercise {
exercise_id: number
exercise: Exercise
notes: string
+ rest_seconds?: number
sets: ActiveSessionSet[]
}
diff --git a/web/src/utils/workoutSets.ts b/web/src/utils/workoutSets.ts
new file mode 100644
index 0000000..9279aa3
--- /dev/null
+++ b/web/src/utils/workoutSets.ts
@@ -0,0 +1,13 @@
+// Format whole seconds as m:ss (e.g. 90 → "1:30"). Shared by the rest banner and
+// the minimized session-pill chip.
+export function fmtClock(totalSeconds: number): string {
+ const m = Math.floor(totalSeconds / 60)
+ return `${m}:${String(totalSeconds % 60).padStart(2, '0')}`
+}
+
+// Index of the first not-completed set after `afterIdx`, or -1 if none. Shared by
+// gym-mode auto-advance (which set to focus after completing one) and the rest
+// banner's "set N next" label so the two can never drift out of sync.
+export function nextIncompleteSet(sets: { completed?: boolean }[], afterIdx: number): number {
+ return sets.findIndex((s, i) => i > afterIdx && !s.completed)
+}