Skip to content

armgit / lyftr

Public Imported from GitHub
0

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

feat: gym mode active workout layout with full E2E coverage

Cawlummd1b6f19aa861
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index 3c47f36..c8e26b1 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -19,8 +19,48 @@ jobs:
- run: cd backend && go mod download
- run: cd backend && go test ./controllers/ -timeout 30s
+ e2e:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Create .env
+ run: |
+ echo "JWT_SECRET=ci-test-secret-$(openssl rand -hex 16)" >> .env
+ echo "PORT=80" >> .env
+
+ - name: Build and start stack
+ run: docker compose up -d --build --wait
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ cache: 'npm'
+ cache-dependency-path: web/package-lock.json
+
+ - run: cd web && npm ci
+
+ - run: cd web && npx playwright install chromium --with-deps
+
+ - name: Wait for demo user to be seeded
+ run: |
+ timeout 90 bash -c 'until curl -sf -X POST http://localhost/api/v1/auth/login \
+ -H "Content-Type: application/json" \
+ -d "{\"email\":\"[email protected]\",\"password\":\"password123\"}" \
+ | grep -q "token"; do sleep 3; done'
+
+ - name: Run E2E tests
+ run: cd web && npm run test:e2e:docker
+
+ - uses: actions/upload-artifact@v4
+ if: failure()
+ with:
+ name: playwright-report
+ path: web/playwright-report/
+ retention-days: 7
+
build-backend:
- needs: test
+ needs: [test, e2e]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -48,7 +88,7 @@ jobs:
cache-to: type=gha,mode=max
build-frontend:
- needs: test
+ needs: [test, e2e]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
diff --git a/web/e2e/auth.setup.ts b/web/e2e/auth.setup.ts
index be472fa..62e0e81 100644
--- a/web/e2e/auth.setup.ts
+++ b/web/e2e/auth.setup.ts
@@ -1,14 +1,15 @@
import { test as setup, expect } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
+import { TEST_EMAIL, TEST_PASSWORD } from './config'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const authFile = path.join(__dirname, '.auth/user.json')
setup('authenticate', async ({ page }) => {
await page.goto('/login')
- await page.getByPlaceholder('[email protected]').fill('[email protected]')
- await page.locator('input[type="password"]').fill('password123')
+ await page.getByPlaceholder('[email protected]').fill(TEST_EMAIL)
+ await page.locator('input[type="password"]').fill(TEST_PASSWORD)
await page.getByRole('button', { name: /sign in|log in/i }).click()
await page.waitForURL('/')
await expect(page.locator('h1, h2').first()).toBeVisible()
diff --git a/web/e2e/config.ts b/web/e2e/config.ts
new file mode 100644
index 0000000..2b8c015
--- /dev/null
+++ b/web/e2e/config.ts
@@ -0,0 +1,16 @@
+// Configure E2E tests for self-hosted instances by setting env vars.
+// Both Vite (dev) and nginx (prod) proxy /api through the frontend host,
+// so BASE_URL is the only var you normally need to change.
+//
+// Dev: BASE_URL defaults to http://localhost:5173 (Vite proxy → :3000)
+// Docker: BASE_URL=http://localhost (nginx proxy → backend:3000)
+// Custom: BASE_URL=https://lyftr.example.com
+//
+// Override just the API separately only if it's on a different host:
+// API_URL=https://api.example.com/api/v1
+
+const base = (process.env.BASE_URL ?? 'http://localhost:5173').replace(/\/$/, '')
+
+export const API_BASE = process.env.API_URL ?? `${base}/api/v1`
+export const TEST_EMAIL = process.env.TEST_EMAIL ?? '[email protected]'
+export const TEST_PASSWORD = process.env.TEST_PASSWORD ?? 'password123'
diff --git a/web/e2e/exercises.spec.ts b/web/e2e/exercises.spec.ts
index c5c6d77..7ebd8a7 100644
--- a/web/e2e/exercises.spec.ts
+++ b/web/e2e/exercises.spec.ts
@@ -1,15 +1,15 @@
import { test, expect } from '@playwright/test'
-
-const API = 'http://localhost:3000/api/v1'
+import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'
let authToken: string
let exerciseId: number
let workoutId: number
+let workoutId2: number
test.describe('Exercise Detail', () => {
test.beforeAll(async ({ request }) => {
const res = await request.post(`${API}/auth/login`, {
- data: { email: '[email protected]', password: 'password123' }
+ data: { email: TEST_EMAIL, password: TEST_PASSWORD }
})
authToken = (await res.json()).data.token
@@ -20,32 +20,35 @@ test.describe('Exercise Detail', () => {
const exBody = await exRes.json()
exerciseId = exBody.data[0].id
- // Seed a workout with that exercise so PR/history data exists
- const w = await request.post(`${API}/workouts`, {
+ // Seed two workouts on different days so history.length >= 2 (chart requires 2+ points)
+ const yesterday = new Date(Date.now() - 86400000).toISOString()
+ const w1 = await request.post(`${API}/workouts`, {
+ headers: { Authorization: `Bearer ${authToken}` },
+ data: {
+ name: 'E2E Exercise History Seed 1',
+ duration: 1800,
+ started_at: yesterday,
+ exercises: [{ exercise_id: exerciseId, notes: '', sets: [{ set_number: 1, reps: 5, weight: 100 }] }]
+ }
+ })
+ workoutId = (await w1.json()).data.id
+
+ const w2 = await request.post(`${API}/workouts`, {
headers: { Authorization: `Bearer ${authToken}` },
data: {
- name: 'E2E Exercise History Seed',
+ name: 'E2E Exercise History Seed 2',
duration: 1800,
started_at: new Date().toISOString(),
- exercises: [{
- exercise_id: exerciseId,
- notes: '',
- sets: [
- { set_number: 1, reps: 5, weight: 100 },
- { set_number: 2, reps: 5, weight: 100 },
- ]
- }]
+ exercises: [{ exercise_id: exerciseId, notes: '', sets: [{ set_number: 1, reps: 5, weight: 110 }] }]
}
})
- workoutId = (await w.json()).data.id
+ workoutId2 = (await w2.json()).data.id
})
test.afterAll(async ({ request }) => {
- if (workoutId) {
- await request.delete(`${API}/workouts/${workoutId}`, {
- headers: { Authorization: `Bearer ${authToken}` }
- })
- }
+ const headers = { Authorization: `Bearer ${authToken}` }
+ if (workoutId) await request.delete(`${API}/workouts/${workoutId}`, { headers })
+ if (workoutId2) await request.delete(`${API}/workouts/${workoutId2}`, { headers })
})
test('exercise detail page loads', async ({ page }) => {
diff --git a/web/e2e/programs.spec.ts b/web/e2e/programs.spec.ts
index 490aded..f92f0d8 100644
--- a/web/e2e/programs.spec.ts
+++ b/web/e2e/programs.spec.ts
@@ -1,6 +1,5 @@
import { test, expect } from '@playwright/test'
-
-const API = 'http://localhost:3000/api/v1'
+import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'
const E2E_PROGRAM_NAME = 'Test Program E2E'
const SEED_PROGRAM_NAME = 'Seeded Test Program'
@@ -10,7 +9,7 @@ let authToken: string
test.describe('Programs', () => {
test.beforeAll(async ({ request }) => {
const res = await request.post(`${API}/auth/login`, {
- data: { email: '[email protected]', password: 'password123' }
+ data: { email: TEST_EMAIL, password: TEST_PASSWORD }
})
const body = await res.json()
authToken = body.data.token
@@ -103,15 +102,18 @@ test.describe('Programs', () => {
})
test('delete program shows confirm and cancels', async ({ page }) => {
+ // Wait for programs to load before checking for buttons
+ await expect(page.getByText(SEED_PROGRAM_NAME)).toBeVisible({ timeout: 5000 })
+
// On mobile the delete button is behind a kebab (⋯) menu — open it first if present
const optionsBtn = page.getByRole('button', { name: /options/i }).first()
if (await optionsBtn.isVisible()) {
await optionsBtn.click()
- await page.waitForTimeout(300)
+ await expect(page.getByRole('button', { name: /delete program/i })).toBeVisible({ timeout: 3000 })
await page.getByRole('button', { name: /delete program/i }).first().click()
} else {
- const deleteButtons = page.getByRole('button', { name: /delete/i })
- await expect(deleteButtons.first()).toBeVisible()
+ const deleteButtons = page.getByRole('button', { name: /^delete$/i })
+ await expect(deleteButtons.first()).toBeVisible({ timeout: 3000 })
await deleteButtons.first().click()
}
await expect(page.getByText(/this cannot be undone/i)).toBeVisible({ timeout: 5000 })
diff --git a/web/e2e/workouts.spec.ts b/web/e2e/workouts.spec.ts
index 474e51b..4b42b05 100644
--- a/web/e2e/workouts.spec.ts
+++ b/web/e2e/workouts.spec.ts
@@ -1,8 +1,9 @@
import { test, expect } from '@playwright/test'
-
-const API = 'http://localhost:3000/api/v1'
+import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'
const E2E_WORKOUT_NAME = 'Test Workout E2E'
const SEED_WORKOUT_NAME = 'Seeded Test Workout'
+const LAYOUT_KEY = 'lyftr_workout_layout'
+const SESSION_KEY = 'lyftr_active_session'
let workoutId: number
let authToken: string
@@ -10,7 +11,7 @@ let authToken: string
test.describe('Workouts', () => {
test.beforeAll(async ({ request }) => {
const res = await request.post(`${API}/auth/login`, {
- data: { email: '[email protected]', password: 'password123' }
+ data: { email: TEST_EMAIL, password: TEST_PASSWORD }
})
const body = await res.json()
authToken = body.data.token
@@ -126,3 +127,269 @@ test.describe('Workouts', () => {
await page.getByRole('button', { name: 'lbs' }).click()
})
})
+
+// ── Gym Mode (active workout route, alternative layout) ───────────────────────
+
+let gymAuthToken: string
+let gymExerciseId: number
+
+test.describe('Gym Mode', () => {
+ test.beforeAll(async ({ request }) => {
+ const res = await request.post(`${API}/auth/login`, {
+ data: { email: TEST_EMAIL, password: TEST_PASSWORD }
+ })
+ gymAuthToken = (await res.json()).data.token
+
+ const exRes = await request.get(`${API}/exercises?limit=1`, {
+ headers: { Authorization: `Bearer ${gymAuthToken}` }
+ })
+ gymExerciseId = (await exRes.json()).data[0].id
+ })
+
+ function seedGymSession(page: any, name: string, exerciseName: string, sets: any[], extraExercises?: any[]) {
+ const exId = gymExerciseId
+ const session = {
+ name,
+ started_at: new Date().toISOString(),
+ exercises: [
+ {
+ exercise_id: exId,
+ exercise: { id: exId, name: exerciseName, muscle_group: 'Chest', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: 'Stand with feet shoulder-width apart.', image_url: null },
+ notes: '',
+ sets,
+ },
+ ...(extraExercises || []),
+ ],
+ }
+ return page.addInitScript(({ sk, lk, s }: { sk: string; lk: string; s: any }) => {
+ localStorage.setItem(sk, JSON.stringify(s))
+ localStorage.setItem(lk, 'gym')
+ }, { sk: SESSION_KEY, lk: LAYOUT_KEY, s: session })
+ }
+
+ test('settings toggle switches layout and persists', async ({ page }) => {
+ await page.goto('/settings')
+ await expect(page.getByRole('heading', { name: /settings/i })).toBeVisible()
+
+ await page.getByRole('button', { name: /gym mode/i }).click()
+
+ const stored = await page.evaluate((key: string) => localStorage.getItem(key), LAYOUT_KEY)
+ expect(stored).toBe('gym')
+
+ await page.reload()
+ await expect(page.getByRole('heading', { name: /settings/i })).toBeVisible()
+ const storedAfter = await page.evaluate((key: string) => localStorage.getItem(key), LAYOUT_KEY)
+ expect(storedAfter).toBe('gym')
+
+ // Switch back to list
+ await page.getByRole('button', { name: /^list$/i }).click()
+ const storedList = await page.evaluate((key: string) => localStorage.getItem(key), LAYOUT_KEY)
+ expect(storedList).toBe('list')
+ })
+
+ test('gym mode overlay opens when navigating to active workout', async ({ page }) => {
+ await seedGymSession(page, 'E2E Gym Test', 'Bench Press',
+ [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }]
+ )
+
+ await page.goto('/workout/active')
+ // Overlay header shows "Workout" label above session name
+ await expect(page.getByText('Workout').first()).toBeVisible({ timeout: 5000 })
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 3000 })
+ })
+
+ test('gym mode overview shows exercise list and stats', async ({ page }) => {
+ await seedGymSession(page, 'E2E Stats Test', 'Bench Press', [
+ { set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false },
+ { set_number: 2, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false },
+ ])
+
+ await page.goto('/workout/active')
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })
+ await expect(page.getByText('Total Sets')).toBeVisible()
+ await expect(page.getByText('Bench Press').first()).toBeVisible()
+ })
+
+ test('gym mode cancel button shows confirm dialog', async ({ page }) => {
+ await seedGymSession(page, 'E2E Cancel Test', 'Bench Press',
+ [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }]
+ )
+
+ 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 })
+ await page.getByRole('button', { name: /keep going/i }).click()
+ await expect(page.getByText('Cancel Workout?')).not.toBeVisible()
+ })
+
+ test('gym mode navigates overview → exercise info → sets', async ({ page }) => {
+ await seedGymSession(page, 'E2E Navigation Test', 'Squat',
+ [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }]
+ )
+
+ await page.goto('/workout/active')
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })
+
+ // Overview → exercise info
+ await page.getByRole('button', { name: /start workout/i }).click()
+ await expect(page.getByRole('button', { name: /begin exercise/i })).toBeVisible({ timeout: 3000 })
+ await expect(page.getByText('Squat').first()).toBeVisible()
+
+ // Exercise info → sets
+ await page.getByRole('button', { name: /begin exercise/i }).click()
+ await expect(page.getByText('Reps').first()).toBeVisible({ timeout: 3000 })
+ await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible()
+ })
+
+ test('gym mode minimize shows active session pill', async ({ page }) => {
+ await seedGymSession(page, 'E2E Minimize Test', 'Deadlift',
+ [{ set_number: 1, target_reps: 3, target_weight: 150, actual_reps: 3, actual_weight: 150, completed: false }]
+ )
+
+ await page.goto('/workout/active')
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })
+
+ const minimizeBtn = page.getByRole('button', { name: /minimize/i }).first()
+ await expect(minimizeBtn).toBeVisible({ timeout: 3000 })
+ await minimizeBtn.click()
+
+ // Overlay gone — Start Workout CTA no longer visible
+ await expect(page.getByRole('button', { name: /start workout/i })).not.toBeVisible()
+ // Session name appears in pill
+ await expect(page.getByText('E2E Minimize Test').first()).toBeVisible({ timeout: 3000 })
+
+ // Tap pill → overlay reopens
+ await page.getByText('E2E Minimize Test').first().click()
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 3000 })
+ })
+
+ test('gym mode set stepper updates reps input', async ({ page }) => {
+ await seedGymSession(page, 'E2E Stepper Test', 'OHP',
+ [{ set_number: 1, target_reps: 8, target_weight: 60, actual_reps: 0, actual_weight: 0, completed: false }]
+ )
+
+ await page.goto('/workout/active')
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })
+
+ await page.getByRole('button', { name: /start workout/i }).click()
+ await page.getByRole('button', { name: /begin exercise/i }).click()
+ await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible({ timeout: 3000 })
+
+ // nth(1) — gym overlay renders after main content in DOM, list-mode input is nth(0)
+ const repsInput = page.locator('input[inputmode="numeric"]').nth(1)
+ await repsInput.fill('7')
+ await expect(repsInput).toHaveValue('7', { timeout: 2000 })
+ })
+
+ test('gym mode complete set marks it done', async ({ page }) => {
+ // Single set — completing it shows "Completed" (no auto-advance to next set)
+ await seedGymSession(page, 'E2E Complete Test', 'Row', [
+ { set_number: 1, target_reps: 5, target_weight: 80, actual_reps: 5, actual_weight: 80, completed: false },
+ ])
+
+ await page.goto('/workout/active')
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })
+
+ await page.getByRole('button', { name: /start workout/i }).click()
+ await page.getByRole('button', { name: /begin exercise/i }).click()
+ await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible({ timeout: 3000 })
+
+ await page.getByRole('button', { name: /complete set/i }).click()
+ await expect(page.getByRole('button', { name: /completed/i })).toBeVisible({ timeout: 2000 })
+ })
+
+ test('gym mode restores phase after minimize and reopen', async ({ page }) => {
+ const exId = gymExerciseId
+ await page.addInitScript(({ sk, lk, id }: { sk: string; lk: string; id: number }) => {
+ const session = {
+ name: 'E2E Restore Test',
+ started_at: new Date().toISOString(),
+ exercises: [
+ {
+ exercise_id: id,
+ exercise: { id, name: 'Exercise One', muscle_group: 'Chest', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
+ notes: '',
+ sets: [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }],
+ },
+ {
+ exercise_id: id,
+ exercise: { id, name: 'Exercise Two', muscle_group: 'Back', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
+ notes: '',
+ sets: [{ set_number: 1, target_reps: 5, target_weight: 80, actual_reps: 5, actual_weight: 80, completed: false }],
+ },
+ ],
+ }
+ localStorage.setItem(sk, JSON.stringify(session))
+ localStorage.setItem(lk, 'gym')
+ }, { sk: SESSION_KEY, lk: LAYOUT_KEY, id: exId })
+
+ await page.goto('/workout/active')
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })
+
+ // Navigate to Exercise Two's info page
+ await page.getByRole('button', { name: /start workout/i }).click()
+ await expect(page.getByRole('button', { name: /begin exercise/i })).toBeVisible({ timeout: 3000 })
+ await page.getByRole('button', { name: /begin exercise/i }).click()
+ await expect(page.getByRole('button', { name: /next exercise/i })).toBeVisible({ timeout: 3000 })
+ await page.getByRole('button', { name: /next exercise/i }).click()
+ await expect(page.getByText('Exercise Two').first()).toBeVisible({ timeout: 3000 })
+
+ // Minimize
+ await page.getByRole('button', { name: /minimize/i }).first().click()
+ await expect(page.getByText('E2E Restore Test').first()).toBeVisible({ timeout: 3000 })
+
+ // Reopen via pill — phase persisted in Zustand store
+ await page.getByText('E2E Restore Test').first().click()
+ await expect(page.getByText('Exercise Two').first()).toBeVisible({ timeout: 3000 })
+ })
+
+ test('gym mode restores phase after page refresh', async ({ page }) => {
+ const exId = gymExerciseId
+ await page.addInitScript(({ sk, lk, id }: { sk: string; lk: string; id: number }) => {
+ const session = {
+ name: 'E2E Refresh Test',
+ started_at: new Date().toISOString(),
+ exercises: [
+ {
+ exercise_id: id,
+ exercise: { id, name: 'Squat', muscle_group: 'Legs', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
+ notes: '',
+ sets: [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }],
+ },
+ {
+ exercise_id: id,
+ exercise: { id, name: 'Deadlift', muscle_group: 'Back', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
+ notes: '',
+ sets: [{ set_number: 1, target_reps: 3, target_weight: 140, actual_reps: 3, actual_weight: 140, completed: false }],
+ },
+ ],
+ }
+ localStorage.setItem(sk, JSON.stringify(session))
+ localStorage.setItem(lk, 'gym')
+ }, { sk: SESSION_KEY, lk: LAYOUT_KEY, id: exId })
+
+ await page.goto('/workout/active')
+ await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })
+
+ // Navigate into sets for exercise 2
+ await page.getByRole('button', { name: /start workout/i }).click()
+ await page.getByRole('button', { name: /begin exercise/i }).click()
+ await page.getByRole('button', { name: /next exercise/i }).click()
+ await expect(page.getByText('Deadlift').first()).toBeVisible({ timeout: 3000 })
+ await page.getByRole('button', { name: /begin exercise/i }).click()
+ await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible({ timeout: 3000 })
+
+ // Minimize then full page refresh
+ await page.getByRole('button', { name: /minimize/i }).first().click()
+ await page.reload()
+
+ // Tap pill to reopen — should land on sets phase for Deadlift
+ await expect(page.getByText('E2E Refresh Test').first()).toBeVisible({ timeout: 5000 })
+ await page.getByText('E2E Refresh Test').first().click()
+ await expect(page.getByText('Deadlift').first()).toBeVisible({ timeout: 3000 })
+ await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible({ timeout: 3000 })
+ })
+})
diff --git a/web/package-lock.json b/web/package-lock.json
index 012625b..bddccfc 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -28,6 +28,7 @@
"@typescript-eslint/parser": "^6.14.0",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.16",
+ "cross-env": "^10.1.0",
"eslint": "^8.55.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
@@ -338,6 +339,12 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@epic-web/invariant": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz",
+ "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==",
+ "dev": true
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
@@ -2077,6 +2084,23 @@
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
"dev": true
},
+ "node_modules/cross-env": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz",
+ "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==",
+ "dev": true,
+ "dependencies": {
+ "@epic-web/invariant": "^1.0.0",
+ "cross-spawn": "^7.0.6"
+ },
+ "bin": {
+ "cross-env": "dist/bin/cross-env.js",
+ "cross-env-shell": "dist/bin/cross-env-shell.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
diff --git a/web/package.json b/web/package.json
index dc7a744..ef89c47 100644
--- a/web/package.json
+++ b/web/package.json
@@ -10,6 +10,7 @@
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"type-check": "tsc --noEmit",
"test:e2e": "playwright test",
+ "test:e2e:docker": "cross-env E2E_DOCKER=1 playwright test",
"test:e2e:ui": "playwright test --ui"
},
"dependencies": {
@@ -33,6 +34,7 @@
"@typescript-eslint/parser": "^6.14.0",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.16",
+ "cross-env": "^10.1.0",
"eslint": "^8.55.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
diff --git a/web/playwright.config.ts b/web/playwright.config.ts
index 02d342d..e814c0b 100644
--- a/web/playwright.config.ts
+++ b/web/playwright.config.ts
@@ -1,4 +1,22 @@
import { defineConfig, devices } from '@playwright/test'
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// When running against docker-compose, read PORT from root .env automatically
+// so `npm run test:e2e:docker` works with zero extra config.
+function dockerBaseURL(): string {
+ try {
+ const env = readFileSync(resolve(__dirname, '../.env'), 'utf8')
+ const match = env.match(/^PORT=(\d+)/m)
+ const port = match?.[1] ?? '80'
+ return `http://localhost:${port}`
+ } catch {
+ return 'http://localhost:80'
+ }
+}
+
+const baseURL = process.env.BASE_URL
+ ?? (process.env.E2E_DOCKER ? dockerBaseURL() : 'http://localhost:5173')
export default defineConfig({
testDir: './e2e',
@@ -8,7 +26,7 @@ export default defineConfig({
workers: 1,
reporter: 'list',
use: {
- baseURL: 'http://localhost:5173',
+ baseURL,
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsx
index 1b5f983..8f4d6e8 100644
--- a/web/src/components/Layout.tsx
+++ b/web/src/components/Layout.tsx
@@ -8,6 +8,8 @@ import {
import { useAuthStore } from '../stores/auth'
import { useTheme } from '../hooks/useTheme'
import { useWorkoutSession } from '../stores/workoutSession'
+import { useSettingsStore, weightShort } from '../stores/settings'
+import GymModeWorkout from '../pages/GymModeWorkout'
import Logo from './Logo'
const NAV = [
@@ -27,7 +29,8 @@ function formatElapsed(seconds: number) {
}
function ActiveSessionBar() {
- const { session } = useWorkoutSession()
+ const { session, gymOpen, openGym } = useWorkoutSession()
+ const { settings } = useSettingsStore()
const navigate = useNavigate()
const { pathname } = useLocation()
const [elapsed, setElapsed] = useState(0)
@@ -41,15 +44,26 @@ function ActiveSessionBar() {
return () => clearInterval(id)
}, [session])
- if (!session || pathname === '/workout/active') return null
+ if (!session) return null
+ // Hide pill when gym mode overlay is open or when on active workout page in list mode
+ if (gymOpen && settings.workout_layout === 'gym') return null
+ if (pathname === '/workout/active' && settings.workout_layout !== 'gym') return null
const completedSets = session.exercises.reduce((s, ex) => s + ex.sets.filter(set => set.completed).length, 0)
const totalSets = session.exercises.reduce((s, ex) => s + ex.sets.length, 0)
+ const handleClick = () => {
+ if (settings.workout_layout === 'gym') {
+ openGym()
+ } else {
+ navigate('/workout/active')
+ }
+ }
+
return (
<div className="absolute bottom-full left-0 right-0 flex justify-center pb-3 pointer-events-none">
<button
- onClick={() => navigate('/workout/active')}
+ onClick={handleClick}
className="pointer-events-auto flex items-center gap-2.5 px-4 py-2.5 bg-brand-500 hover:bg-brand-600 active:scale-95 shadow-lg shadow-brand-500/40 rounded-full transition-all"
>
<div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center flex-shrink-0">
@@ -145,6 +159,9 @@ function UserMenu() {
export default function Layout() {
const { pathname } = useLocation()
+ const { session, gymOpen } = useWorkoutSession()
+ const { settings } = useSettingsStore()
+ const wUnit = weightShort(settings.weight_unit)
return (
<div className="min-h-screen flex flex-col bg-surface-base">
@@ -159,6 +176,11 @@ export default function Layout() {
<Outlet />
</main>
+ {/* Gym mode overlay — rendered at root so it persists across routes */}
+ {session && settings.workout_layout === 'gym' && gymOpen && (
+ <GymModeWorkout wUnit={wUnit} />
+ )}
+
{/* Active session pill floats above bottom nav */}
<div className="sticky bottom-0 z-50 relative">
<ActiveSessionBar />
diff --git a/web/src/pages/ActiveWorkout.tsx b/web/src/pages/ActiveWorkout.tsx
index 8b4257d..5c606b1 100644
--- a/web/src/pages/ActiveWorkout.tsx
+++ b/web/src/pages/ActiveWorkout.tsx
@@ -56,7 +56,7 @@ function formatElapsed(seconds: number) {
export default function ActiveWorkout() {
const navigate = useNavigate()
- const { session, updateSet, updateExerciseNotes, completeSet, addSet, removeSet, removeExercise, buildPayload, cancelSession } =
+ const { session, updateSet, updateExerciseNotes, completeSet, addSet, removeSet, removeExercise, buildPayload, cancelSession, openGym } =
useWorkoutSession()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
@@ -70,6 +70,11 @@ export default function ActiveWorkout() {
const cardRefs = useRef<(HTMLDivElement | null)[]>([])
+ // Open gym mode overlay immediately when landing on this route
+ useEffect(() => {
+ if (settings.workout_layout === 'gym' && session) openGym()
+ }, [])
+
// Workout elapsed timer
useEffect(() => {
if (!session) return
@@ -212,6 +217,7 @@ export default function ActiveWorkout() {
)}
{/* ── Exercise list ───────────────────────────────────── */}
+ <>
<div className="space-y-3">
{session.exercises.length === 0 ? (
<div className="empty-state py-16">
@@ -453,6 +459,7 @@ export default function ActiveWorkout() {
Cancel Workout
</button>
</div>
+ </>
{/* ── Finish confirm ─────────────────────────────────── */}
{confirmFinish && createPortal(
diff --git a/web/src/pages/GymModeWorkout.tsx b/web/src/pages/GymModeWorkout.tsx
new file mode 100644
index 0000000..f9fcecf
--- /dev/null
+++ b/web/src/pages/GymModeWorkout.tsx
@@ -0,0 +1,731 @@
+import { useState, useEffect, useRef } from 'react'
+import { createPortal } from 'react-dom'
+import { useNavigate } from 'react-router-dom'
+import {
+ CheckCircle2, Plus, X, Dumbbell, Flag, ChevronRight, ChevronLeft, Play,
+ Minimize2, Trash2,
+} 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 { workoutAPI } from '../services/api'
+
+function buildBodyData(exercise: types.Exercise): IExerciseData[] {
+ const primarySlugs = muscleToBodySlugs(exercise.muscle_group)
+ const secondarySlugs = (exercise.secondary_muscles || [])
+ .flatMap(m => muscleToBodySlugs(m))
+ .filter(s => !primarySlugs.includes(s))
+ const data: IExerciseData[] = []
+ if (primarySlugs.length > 0) data.push({ name: 'Primary', muscles: primarySlugs as any, frequency: 2 })
+ if (secondarySlugs.length > 0) data.push({ name: 'Secondary', muscles: secondarySlugs as any, frequency: 1 })
+ return data
+}
+
+function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string; onSave: (i: number, v: string) => void }) {
+ const [editing, setEditing] = useState(false)
+ const [val, setVal] = useState(notes)
+ const commit = () => { onSave(exIdx, val); setEditing(false) }
+ if (editing) {
+ return (
+ <input
+ autoFocus type="text" value={val}
+ onChange={e => setVal(e.target.value)}
+ onBlur={commit}
+ onKeyDown={e => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') { setVal(notes); setEditing(false) } }}
+ placeholder="Add a note…"
+ className="input text-sm w-full"
+ />
+ )
+ }
+ return (
+ <button
+ onClick={() => { setVal(notes); setEditing(true) }}
+ className="text-xs text-tx-muted hover:text-tx-secondary transition-colors text-left w-full"
+ >
+ {notes ? <span className="italic">{notes}</span> : <span className="opacity-50">+ Add note</span>}
+ </button>
+ )
+}
+
+interface GymModeWorkoutProps {
+ wUnit: string
+}
+
+export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
+ const navigate = useNavigate()
+ const { isDark } = useTheme()
+ const {
+ session, minimizeGym,
+ gymPhase: phase, gymExIdx: activeIdx, gymSetIdx: activeSetIdx, setGymState,
+ updateSet, completeSet, addSet, removeSet, removeExercise, updateExerciseNotes,
+ buildPayload, cancelSession,
+ } = useWorkoutSession()
+
+ const [imgFailed, setImgFailed] = useState(false)
+ const [confirmFinish, setConfirmFinish] = useState(false)
+ const [confirmCancel, setConfirmCancel] = useState(false)
+ const [saving, setSaving] = useState(false)
+ const [saveError, setSaveError] = useState('')
+
+ const setPhase = (p: typeof phase) => setGymState(p, activeIdx, activeSetIdx)
+ const onSetActiveIdx = (i: number) => setGymState(phase, i, 0)
+ const setActiveSetIdx = (i: number) => setGymState(phase, activeIdx, i)
+
+ useEffect(() => { setImgFailed(false) }, [activeIdx])
+
+ if (!session) return null
+
+ const handleFinish = async () => {
+ setSaving(true)
+ setSaveError('')
+ try {
+ const payload = buildPayload()
+ await workoutAPI.create(payload)
+ cancelSession()
+ minimizeGym()
+ navigate('/workouts')
+ } catch (err: any) {
+ setSaveError(err.response?.data?.error || 'Failed to save workout')
+ setSaving(false)
+ setConfirmFinish(false)
+ }
+ }
+
+ const handleMinimize = () => {
+ minimizeGym()
+ // Navigate away from /workout/active so list mode doesn't show underneath
+ if (window.location.pathname === '/workout/active') navigate('/')
+ }
+
+ // Jump to newly added exercise
+ const prevLenRef = useRef(session.exercises.length)
+ useEffect(() => {
+ if (session.exercises.length > prevLenRef.current) {
+ onSetActiveIdx(session.exercises.length - 1)
+ }
+ prevLenRef.current = session.exercises.length
+ }, [session.exercises.length])
+
+ const totalSets = session.exercises.reduce((s, ex) => s + ex.sets.length, 0)
+ const completedSets = session.exercises.reduce((s, ex) => s + ex.sets.filter(st => st.completed).length, 0)
+
+ const bodyColor = isDark ? '#162240' : '#e2e8f0'
+ const highlightColors = ['#0e7490', '#22d3ee']
+
+ // ── Shared top bar (exercise-info + exercise phases) ──────────────────
+ function TopBar({ onBack, s }: { onBack: () => void; s: types.ActiveSession }) {
+ const allDone = completedSets === totalSets && totalSets > 0
+ return (
+ <div className="flex items-center gap-3 px-4 pt-4 pb-3 border-b border-surface-border flex-shrink-0">
+ <button
+ onClick={onBack}
+ className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted"
+ >
+ <ChevronLeft className="w-5 h-5" />
+ </button>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1.5">
+ {s.exercises.map((_, i) => (
+ <button
+ key={i}
+ onClick={() => setGymState('exercise-info', i, 0)}
+ className={`h-1.5 rounded-full 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>
+ </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>
+ )
+ }
+
+ // ── Overview ──────────────────────────────────────────────────────────
+ if (phase === 'overview') {
+ return (
+ <div className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col">
+ <div className="flex items-center justify-between px-5 pt-5 pb-4 border-b border-surface-border flex-shrink-0">
+ <div>
+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-0.5">Workout</p>
+ <h1 className="font-display font-bold text-xl text-tx-primary leading-tight">{session.name}</h1>
+ </div>
+ <div className="flex items-center gap-1">
+ <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">
+ <X className="w-5 h-5" />
+ </button>
+ </div>
+ </div>
+
+ {/* Stats strip */}
+ <div className="grid grid-cols-3 gap-3 px-5 py-4 border-b border-surface-border flex-shrink-0">
+ <div className="text-center">
+ <p className="text-xl font-bold text-tx-primary tabular-nums">{session.exercises.length}</p>
+ <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">Exercises</p>
+ </div>
+ <div className="text-center">
+ <p className="text-xl font-bold text-tx-primary tabular-nums">{totalSets}</p>
+ <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">Total Sets</p>
+ </div>
+ <div className="text-center">
+ <p className="text-xl font-bold text-tx-primary tabular-nums">
+ {[...new Set(session.exercises.map(e => e.exercise.muscle_group))].length}
+ </p>
+ <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">Muscles</p>
+ </div>
+ </div>
+
+ {/* Exercise list */}
+ <div className="flex-1 overflow-y-auto px-5 py-3">
+ {session.exercises.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-16 gap-3">
+ <Dumbbell className="w-10 h-10 text-tx-muted/30" />
+ <p className="text-sm text-tx-muted">No exercises added yet</p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {session.exercises.map((ex, i) => {
+ const done = ex.sets.length > 0 && ex.sets.every(s => s.completed)
+ return (
+ <div key={i} className={`flex items-center gap-3 p-3 rounded-2xl border transition-all ${
+ done ? 'border-brand-500/30 bg-brand-500/[0.04]' : 'border-surface-border bg-surface-base'
+ }`}>
+ <div className="flex-shrink-0 w-8 h-8 rounded-full bg-surface-muted border border-surface-border flex items-center justify-center">
+ <span className={`text-sm font-bold ${done ? 'text-brand-400' : 'text-tx-muted'}`}>{i + 1}</span>
+ </div>
+ {ex.exercise.image_url ? (
+ <img src={ex.exercise.image_url} alt="" className="w-10 h-10 rounded-xl object-cover flex-shrink-0 bg-surface-muted"
+ onError={e => { (e.target as HTMLImageElement).style.display = 'none' }} />
+ ) : (
+ <div className="w-10 h-10 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
+ <Dumbbell className="w-4 h-4 text-brand-500" />
+ </div>
+ )}
+ <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">
+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${muscleColor(ex.exercise.muscle_group)}`}>
+ {ex.exercise.muscle_group}
+ </span>
+ <span className="text-[10px] text-tx-muted">{ex.sets.length} sets</span>
+ </div>
+ </div>
+ {done && <CheckCircle2 className="w-4 h-4 text-brand-400 flex-shrink-0" />}
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+
+ {/* Bottom actions */}
+ <div className="px-5 pb-6 pt-4 border-t border-surface-border flex-shrink-0 space-y-2">
+ <button
+ onClick={() => navigate('/workout/active/add-exercise')}
+ className="w-full py-3 bg-surface-muted/60 hover:bg-surface-muted border border-surface-border hover:border-brand-500/40 rounded-2xl text-sm font-medium text-tx-secondary hover:text-brand-400 transition-colors flex items-center justify-center gap-2"
+ >
+ <Plus className="w-4 h-4" />
+ Add Exercise
+ </button>
+ {session.exercises.length > 0 && (
+ <button
+ onClick={() => setGymState('exercise-info', 0, 0)}
+ className="w-full py-4 bg-brand-500 hover:bg-brand-600 text-white rounded-2xl text-base font-bold flex items-center justify-center gap-2 shadow-lg shadow-brand-500/30 transition-colors"
+ >
+ <Play className="w-5 h-5 fill-current" />
+ Start Workout
+ </button>
+ )}
+ </div>
+
+ {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">
+ <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">Finish Workout?</h3>
+ <p className="text-sm text-tx-muted mb-5">{completedSets} of {totalSets} sets completed. Workout will be saved.</p>
+ {saveError && <p className="text-xs text-error-400 mb-3">{saveError}</p>}
+ <div className="flex gap-3">
+ <button onClick={() => setConfirmFinish(false)} disabled={saving} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 disabled:opacity-50 text-tx-secondary rounded-xl transition-colors font-medium text-sm">Keep Going</button>
+ <button onClick={handleFinish} disabled={saving} className="flex-1 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
+ <Flag className="w-3.5 h-3.5" />{saving ? 'Saving…' : 'Finish'}
+ </button>
+ </div>
+ </div>
+ </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
+ )}
+ </div>
+ )
+ }
+
+ const ex = session.exercises[activeIdx]
+ if (!ex) { onSetActiveIdx(0); return null }
+
+ const isFirst = activeIdx === 0
+ const isLast = activeIdx === session.exercises.length - 1
+
+ // ── Exercise info ─────────────────────────────────────────────────────
+ if (phase === 'exercise-info') {
+ const exercise = ex.exercise
+ const equipLabel = EQUIPMENT_LABEL[exercise.equipment?.toLowerCase()] || exercise.equipment
+ const descLines = exercise.description
+ ? exercise.description.split('\n').filter(l => l.trim())
+ : []
+ const bodyData = buildBodyData(exercise)
+
+ return (
+ <div className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col">
+ <TopBar s={session} onBack={() => isFirst ? setPhase('overview') : setGymState('exercise', activeIdx - 1, 0)} />
+
+ <div className="flex-1 overflow-y-auto">
+ {/* Hero image */}
+ {exercise.image_url && !imgFailed && (
+ <img
+ src={exercise.image_url}
+ alt={exercise.name}
+ onError={() => setImgFailed(true)}
+ className="w-full h-52 object-cover bg-surface-muted"
+ />
+ )}
+
+ <div className="px-5 pt-5 pb-4 space-y-5">
+ {/* Name + muscle */}
+ <div>
+ <h2 className="font-display font-bold text-2xl text-tx-primary leading-tight">{exercise.name}</h2>
+ <div className="flex flex-wrap items-center gap-2 mt-2">
+ <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium border ${muscleColorBordered(exercise.muscle_group)}`}>
+ {exercise.muscle_group}
+ </span>
+ {equipLabel && exercise.equipment !== 'other' && (
+ <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">
+ {equipLabel}
+ </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">
+ {exercise.category}
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Secondary muscles */}
+ {exercise.secondary_muscles?.length > 0 && (
+ <div>
+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-2">Also works</p>
+ <div className="flex flex-wrap gap-1.5">
+ {exercise.secondary_muscles.map(m => (
+ <span key={m} className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${muscleColor(m)}`}>{m}</span>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Muscle diagram */}
+ {bodyData.length > 0 && (
+ <div className="card p-4">
+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">Muscles Worked</p>
+ <div className="flex items-start justify-center gap-6">
+ <div className="flex flex-col items-center gap-1">
+ <Model data={bodyData} type="anterior" bodyColor={bodyColor} highlightedColors={highlightColors} style={{ width: '120px' }} />
+ <span className="text-xs text-tx-muted">Front</span>
+ </div>
+ <div className="flex flex-col items-center gap-1">
+ <Model data={bodyData} type="posterior" bodyColor={bodyColor} highlightedColors={highlightColors} style={{ width: '120px' }} />
+ <span className="text-xs text-tx-muted">Back</span>
+ </div>
+ </div>
+ <div className="flex items-center gap-4 mt-3 justify-center">
+ <div className="flex items-center gap-1.5">
+ <div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#22d3ee' }} />
+ <span className="text-xs text-tx-muted">Primary</span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#0e7490' }} />
+ <span className="text-xs text-tx-muted">Secondary</span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Instructions */}
+ {descLines.length > 0 && (
+ <div className="card p-4">
+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">Instructions</p>
+ <div className="space-y-2.5">
+ {descLines.map((line, i) => {
+ const stepMatch = line.match(/^(\d+\.)\s*(.*)/)
+ if (stepMatch) {
+ return (
+ <p key={i} className="text-sm text-tx-secondary leading-relaxed">
+ <span className="font-semibold text-tx-primary">{stepMatch[1]}</span>{' '}{stepMatch[2]}
+ </p>
+ )
+ }
+ return <p key={i} className="text-sm text-tx-secondary leading-relaxed">{line}</p>
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* CTA */}
+ <div className="px-5 pb-6 pt-4 border-t border-surface-border flex-shrink-0">
+ <button
+ onClick={() => setPhase('exercise')}
+ className="w-full py-4 bg-brand-500 hover:bg-brand-600 text-white rounded-2xl text-base font-bold flex items-center justify-center gap-2 shadow-lg shadow-brand-500/30 transition-colors"
+ >
+ <Play className="w-5 h-5 fill-current" />
+ Begin Exercise
+ </button>
+ </div>
+
+ {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">
+ <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">Finish Workout?</h3>
+ <p className="text-sm text-tx-muted mb-5">{completedSets} of {totalSets} sets completed. Workout will be saved.</p>
+ {saveError && <p className="text-xs text-error-400 mb-3">{saveError}</p>}
+ <div className="flex gap-3">
+ <button onClick={() => setConfirmFinish(false)} disabled={saving} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 disabled:opacity-50 text-tx-secondary rounded-xl transition-colors font-medium text-sm">Keep Going</button>
+ <button onClick={handleFinish} disabled={saving} className="flex-1 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
+ <Flag className="w-3.5 h-3.5" />{saving ? 'Saving…' : 'Finish'}
+ </button>
+ </div>
+ </div>
+ </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
+ )}
+ </div>
+ )
+ }
+
+ // ── Exercise sets ─────────────────────────────────────────────────────
+ const allSetsComplete = ex.sets.length > 0 && ex.sets.every(s => s.completed)
+ const completedHere = ex.sets.filter(s => s.completed).length
+ const clampedSetIdx = Math.min(activeSetIdx, ex.sets.length - 1)
+ const set = ex.sets[clampedSetIdx]
+
+ const handleCompleteSetGym = (setIdx: number) => {
+ completeSet(activeIdx, setIdx)
+ // Auto-advance to next incomplete set
+ const next = ex.sets.findIndex((s, i) => i > setIdx && !s.completed)
+ if (next !== -1) setActiveSetIdx(next)
+ }
+
+ const handleRemoveSet = (setIdx: number) => {
+ removeSet(activeIdx, setIdx)
+ setActiveSetIdx(Math.max(0, Math.min(setIdx, ex.sets.length - 2)))
+ }
+
+ const handleRemoveExercise = () => {
+ removeExercise(activeIdx)
+ const newLen = session.exercises.length - 1
+ if (newLen === 0) { setPhase('overview'); return }
+ onSetActiveIdx(Math.min(activeIdx, newLen - 1))
+ }
+
+ if (!set) return null
+
+ return (
+ <div className="fixed inset-0 z-[60] bg-surface-base flex flex-col">
+ <TopBar s={session} onBack={() => setPhase('exercise-info')} />
+
+ {/* Exercise name + muscle (compact) */}
+ <div className="px-5 pt-4 pb-3 border-b border-surface-border flex-shrink-0">
+ <div className="flex items-center justify-between gap-2">
+ <div className="min-w-0">
+ <h2 className="font-display font-bold text-lg text-tx-primary leading-tight truncate">{ex.exercise.name}</h2>
+ <div className="flex items-center gap-2 mt-1">
+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${muscleColor(ex.exercise.muscle_group)}`}>
+ {ex.exercise.muscle_group}
+ </span>
+ <span className="text-xs text-tx-muted tabular-nums">{completedHere}/{ex.sets.length} sets done</span>
+ </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>
+ )}
+ </div>
+ <div className="mt-2">
+ <ExerciseNotes exIdx={activeIdx} notes={ex.notes} onSave={updateExerciseNotes} />
+ </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 */}
+ <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>
+ </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>
+
+ {/* 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="flex items-center gap-2 w-full">
+ <button
+ onClick={() => updateSet(activeIdx, clampedSetIdx, 'actual_weight', Math.max(0, (set.actual_weight || 0) - 2.5))}
+ 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="decimal"
+ value={set.actual_weight || ''}
+ onChange={e => updateSet(activeIdx, clampedSetIdx, 'actual_weight', Number(e.target.value) || 0)}
+ placeholder={set.target_weight > 0 ? String(set.target_weight) : '0'}
+ className={`input text-2xl font-bold text-center flex-1 py-3 transition-opacity ${set.completed ? 'opacity-40' : ''}`}
+ disabled={set.completed} step="2.5"
+ />
+ <button
+ onClick={() => updateSet(activeIdx, clampedSetIdx, 'actual_weight', (set.actual_weight || 0) + 2.5)}
+ 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>
+ </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 */}
+ <button
+ onClick={() => handleRemoveSet(clampedSetIdx)}
+ className="text-xs text-tx-muted/50 hover:text-error-400 transition-colors"
+ >
+ Remove this set
+ </button>
+ </div>
+
+ {/* Bottom nav */}
+ <div className="px-5 pb-6 pt-3 border-t border-surface-border flex-shrink-0 space-y-2">
+ {/* Set prev/next + add */}
+ <div className="flex gap-2">
+ <button
+ onClick={() => setActiveSetIdx(clampedSetIdx - 1)}
+ disabled={clampedSetIdx === 0}
+ className="p-3 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border text-tx-secondary transition-colors disabled:opacity-30 disabled:pointer-events-none"
+ >
+ <ChevronLeft className="w-4 h-4" />
+ </button>
+ <button
+ onClick={() => { addSet(activeIdx); setActiveSetIdx(ex.sets.length) }}
+ className="flex-1 py-3 flex items-center justify-center gap-1.5 rounded-xl border border-dashed border-surface-border hover:border-brand-500/40 hover:bg-brand-500/5 text-xs font-medium text-tx-muted hover:text-brand-400 transition-colors"
+ >
+ <Plus className="w-3.5 h-3.5" />
+ Add Set
+ </button>
+ <button
+ onClick={() => setActiveSetIdx(clampedSetIdx + 1)}
+ disabled={clampedSetIdx >= ex.sets.length - 1}
+ className="p-3 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border text-tx-secondary transition-colors disabled:opacity-30 disabled:pointer-events-none"
+ >
+ <ChevronRight className="w-4 h-4" />
+ </button>
+ </div>
+
+ {/* Exercise prev/next */}
+ <div className="flex gap-2">
+ <button
+ onClick={() => setPhase('exercise-info')}
+ className="flex items-center gap-1.5 px-4 py-3 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border text-tx-secondary text-sm font-medium transition-colors"
+ >
+ <ChevronLeft className="w-4 h-4" />
+ Info
+ </button>
+ {isLast ? (
+ <button
+ onClick={() => setConfirmFinish(true)}
+ className={`flex-1 py-3 rounded-xl text-sm font-bold flex items-center justify-center gap-2 transition-all ${
+ allSetsComplete
+ ? 'bg-brand-500 hover:bg-brand-600 text-white shadow-lg shadow-brand-500/30'
+ : 'bg-brand-500/10 hover:bg-brand-500/20 text-brand-400 border border-brand-500/30'
+ }`}
+ >
+ <Flag className="w-4 h-4" />
+ Finish Workout
+ </button>
+ ) : (
+ <button
+ onClick={() => setGymState('exercise-info', activeIdx + 1, 0)}
+ className={`flex-1 py-3 rounded-xl text-sm font-bold flex items-center justify-center gap-2 transition-all ${
+ allSetsComplete
+ ? 'bg-brand-500 hover:bg-brand-600 text-white shadow-lg shadow-brand-500/30'
+ : 'bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary border border-surface-border'
+ }`}
+ >
+ Next Exercise
+ <ChevronRight className="w-4 h-4" />
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* ── 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">
+ <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">Finish Workout?</h3>
+ <p className="text-sm text-tx-muted mb-5">{completedSets} of {totalSets} sets completed. Workout will be saved.</p>
+ {saveError && <p className="text-xs text-error-400 mb-3">{saveError}</p>}
+ <div className="flex gap-3">
+ <button onClick={() => setConfirmFinish(false)} disabled={saving} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 disabled:opacity-50 text-tx-secondary rounded-xl transition-colors font-medium text-sm">
+ Keep Going
+ </button>
+ <button onClick={handleFinish} disabled={saving} className="flex-1 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
+ <Flag className="w-3.5 h-3.5" />
+ {saving ? 'Saving…' : 'Finish'}
+ </button>
+ </div>
+ </div>
+ </div>,
+ document.body
+ )}
+
+ {/* ── 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
+ )}
+ </div>
+ )
+}
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 32d6088..4b2574b 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -38,7 +38,7 @@ function Section({ title, children }: { title: string; children: React.ReactNode
export default function Settings() {
const { user, logout } = useAuthStore()
const { theme, toggleTheme } = useTheme()
- const { settings: storedSettings, update: updateSettings, fetch: fetchSettings } = useSettingsStore()
+ const { settings: storedSettings, update: updateSettings, fetch: fetchSettings, setWorkoutLayout } = useSettingsStore()
const [loading, setLoading] = useState(!useSettingsStore.getState().loaded)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -187,6 +187,27 @@ export default function Settings() {
</SettingRow>
</Section>
+ {/* Workout */}
+ <Section title="Workout">
+ <SettingRow label="Active workout layout" description="How exercises are shown during a workout">
+ <div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">
+ {(['list', 'gym'] as const).map(mode => (
+ <button
+ key={mode}
+ onClick={() => setWorkoutLayout(mode)}
+ className={`px-3 py-1 rounded-md text-xs font-medium transition-all ${
+ storedSettings.workout_layout === mode
+ ? 'bg-surface-raised border border-surface-border text-tx-primary shadow-sm'
+ : 'text-tx-muted hover:text-tx-primary'
+ }`}
+ >
+ {mode === 'list' ? 'List' : 'Gym Mode'}
+ </button>
+ ))}
+ </div>
+ </SettingRow>
+ </Section>
+
{/* Goals & Units */}
<Section title="Goals & Units">
<SettingRow label="Weight unit" description="Changes apply immediately across the app">
diff --git a/web/src/stores/settings.ts b/web/src/stores/settings.ts
index 4116dca..0a4ab17 100644
--- a/web/src/stores/settings.ts
+++ b/web/src/stores/settings.ts
@@ -2,11 +2,14 @@ import { create } from 'zustand'
import * as types from '../types'
import { userAPI } from '../services/api'
+const LAYOUT_KEY = 'lyftr_workout_layout'
+
interface SettingsStore {
settings: types.UserSettings
loaded: boolean
fetch: () => Promise<void>
update: (patch: Partial<types.UserSettings>) => Promise<void>
+ setWorkoutLayout: (layout: 'list' | 'gym') => void
reset: () => void
}
@@ -17,6 +20,7 @@ const DEFAULTS: types.UserSettings = {
protein_target: 150,
carb_target: 250,
fat_target: 65,
+ workout_layout: (localStorage.getItem(LAYOUT_KEY) as 'list' | 'gym') ?? 'list',
}
export const useSettingsStore = create<SettingsStore>((set, get) => ({
@@ -27,7 +31,8 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({
if (get().loaded) return
try {
const s = await userAPI.getSettings()
- set({ settings: s, loaded: true })
+ const layout = localStorage.getItem(LAYOUT_KEY) as 'list' | 'gym' | null
+ set({ settings: { ...s, workout_layout: layout ?? 'list' }, loaded: true })
} catch {
set({ loaded: true })
}
@@ -36,7 +41,13 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({
update: async (patch) => {
set(state => ({ settings: { ...state.settings, ...patch } }))
const updated = await userAPI.updateSettings(patch)
- set({ settings: updated })
+ const layout = localStorage.getItem(LAYOUT_KEY) as 'list' | 'gym' | null
+ set({ settings: { ...updated, workout_layout: layout ?? 'list' } })
+ },
+
+ setWorkoutLayout: (layout) => {
+ localStorage.setItem(LAYOUT_KEY, layout)
+ set(state => ({ settings: { ...state.settings, workout_layout: layout } }))
},
reset: () => set({ settings: DEFAULTS, loaded: false }),
diff --git a/web/src/stores/workoutSession.ts b/web/src/stores/workoutSession.ts
index 8983576..b1e19e4 100644
--- a/web/src/stores/workoutSession.ts
+++ b/web/src/stores/workoutSession.ts
@@ -2,6 +2,7 @@ import { create } from 'zustand'
import * as types from '../types'
const SESSION_KEY = 'lyftr_active_session'
+const GYM_UI_KEY = 'lyftr_gym_ui'
function saveLocal(session: types.ActiveSession | null) {
if (session) {
@@ -20,8 +21,29 @@ function loadLocal(): types.ActiveSession | null {
}
}
+type GymPhase = 'overview' | 'exercise-info' | 'exercise'
+
+type GymUiState = { phase: GymPhase; exIdx: number; setIdx: number }
+
+function saveGymUi(s: GymUiState) {
+ localStorage.setItem(GYM_UI_KEY, JSON.stringify(s))
+}
+
+function loadGymUi(): GymUiState {
+ try {
+ const raw = localStorage.getItem(GYM_UI_KEY)
+ return raw ? JSON.parse(raw) : { phase: 'overview', exIdx: 0, setIdx: 0 }
+ } catch {
+ return { phase: 'overview', exIdx: 0, setIdx: 0 }
+ }
+}
+
interface WorkoutSessionStore {
session: types.ActiveSession | null
+ gymOpen: boolean
+ gymPhase: GymPhase
+ gymExIdx: number
+ gymSetIdx: number
startSession: (name: string, exercises: types.ActiveSessionExercise[], programId?: number) => void
updateSet: (exIdx: number, setIdx: number, field: 'actual_reps' | 'actual_weight', val: number) => void
completeSet: (exIdx: number, setIdx: number) => void
@@ -32,10 +54,26 @@ interface WorkoutSessionStore {
removeExercise: (exIdx: number) => void
buildPayload: () => any
cancelSession: () => void
+ openGym: () => void
+ minimizeGym: () => void
+ setGymState: (phase: GymPhase, exIdx: number, setIdx: number) => void
}
+const _savedGymUi = loadGymUi()
+
export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
session: loadLocal(),
+ gymOpen: false,
+ gymPhase: _savedGymUi.phase,
+ gymExIdx: _savedGymUi.exIdx,
+ gymSetIdx: _savedGymUi.setIdx,
+
+ openGym: () => set({ gymOpen: true }),
+ minimizeGym: () => set({ gymOpen: false }),
+ setGymState: (gymPhase, gymExIdx, gymSetIdx) => {
+ saveGymUi({ phase: gymPhase, exIdx: gymExIdx, setIdx: gymSetIdx })
+ set({ gymPhase, gymExIdx, gymSetIdx })
+ },
startSession: (name, exercises, programId) => {
const session: types.ActiveSession = {
@@ -162,6 +200,7 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
cancelSession: () => {
saveLocal(null)
- set({ session: null })
+ localStorage.removeItem(GYM_UI_KEY)
+ set({ session: null, gymOpen: false, gymPhase: 'overview', gymExIdx: 0, gymSetIdx: 0 })
},
}))
diff --git a/web/src/types.ts b/web/src/types.ts
index ab64305..7d7917c 100644
--- a/web/src/types.ts
+++ b/web/src/types.ts
@@ -12,6 +12,7 @@ export interface UserSettings {
protein_target: number
carb_target: number
fat_target: number
+ workout_layout?: 'list' | 'gym'
}
export interface Exercise {