feat(06-01): Implement workout swap/rotation system - API, DB, frontend

- Add workout_swaps table migration (007_add_workout_swap_tracking.sql)
- Implement 4 API endpoints: POST /swap, DELETE /undo, GET /swaps, GET /available
- Add request validation, error handling, user isolation, muscle group checks
- Create SwapWorkoutModal React component with modal UI
- Integrate swap functionality into WorkoutPage
- Add proper styling for swap modal
- All endpoints require authentication
- Database migration includes performance indexes
This commit is contained in:
2026-03-06 15:06:31 +01:00
parent 0af9c3935b
commit 6ad917c9b9
6 changed files with 1022 additions and 21 deletions
@@ -0,0 +1,374 @@
/* ============================================
SWAP WORKOUT MODAL
============================================ */
.swap-modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: flex-end;
justify-content: center;
z-index: 1000;
animation: fadeIn 0.2s ease-out;
padding: 0;
}
.swap-modal-content {
background: white;
border-radius: 12px 12px 0 0;
width: 100%;
max-width: 500px;
max-height: 80vh;
overflow-y: auto;
padding: 20px;
display: flex;
flex-direction: column;
gap: 16px;
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
}
.swap-modal-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
.swap-modal-header h3 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
}
.swap-modal-close {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
color: #999;
padding: 0;
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 6px;
transition: all 0.2s;
}
.swap-modal-close:hover {
background: #f0f0f0;
color: #333;
}
.swap-modal-close:active {
transform: scale(0.95);
}
/* ============================================
CURRENT EXERCISE
============================================ */
.swap-current-exercise {
background: #f5f5f5;
padding: 16px;
border-radius: 8px;
border-left: 4px solid var(--accent);
}
.swap-current-label {
font-size: 12px;
color: #999;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 4px;
font-weight: 500;
}
.swap-current-name {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 4px;
}
.swap-current-group {
font-size: 13px;
color: #666;
}
/* ============================================
ALTERNATIVES LIST
============================================ */
.swap-alternatives-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.swap-alternatives-label {
font-size: 12px;
color: #999;
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 500;
padding: 0 4px;
}
.swap-alternative-item {
display: flex;
align-items: center;
gap: 12px;
padding: 14px 12px;
border: 1px solid #ddd;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s ease;
min-height: 48px;
}
.swap-alternative-item:hover {
background: #fafafa;
border-color: var(--accent);
box-shadow: 0 2px 8px rgba(255, 107, 74, 0.1);
}
.swap-alternative-item:active {
transform: scale(0.98);
}
.swap-alternative-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.swap-alternative-name {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
word-break: break-word;
}
.swap-alternative-group {
font-size: 12px;
color: #999;
}
.swap-alternative-desc {
font-size: 12px;
color: #666;
margin-top: 2px;
line-height: 1.3;
word-break: break-word;
}
.swap-alternative-icon {
color: #ccc;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
}
/* ============================================
LOADING STATE
============================================ */
.swap-loading-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px 20px;
gap: 12px;
}
.swap-spinner {
width: 32px;
height: 32px;
border: 3px solid #f0f0f0;
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.swap-loading-state p {
color: #999;
font-size: 13px;
margin: 0;
}
/* ============================================
EMPTY STATE
============================================ */
.swap-empty-state {
display: flex;
align-items: center;
justify-content: center;
padding: 32px 20px;
}
.swap-empty-state p {
color: #999;
font-size: 13px;
text-align: center;
margin: 0;
}
/* ============================================
ERROR MESSAGE
============================================ */
.swap-error-message {
display: flex;
align-items: flex-start;
gap: 8px;
background: #fff5f5;
border: 1px solid #fdd;
border-radius: 6px;
padding: 12px;
color: #c33;
font-size: 13px;
}
.swap-error-message svg {
flex-shrink: 0;
margin-top: 2px;
}
/* ============================================
ACTIONS
============================================ */
.swap-modal-actions {
display: flex;
gap: 8px;
padding-top: 8px;
border-top: 1px solid #eee;
}
.swap-cancel-btn {
flex: 1;
padding: 12px 16px;
background: #f5f5f5;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
min-height: 44px;
}
.swap-cancel-btn:hover:not(:disabled) {
background: #e8e8e8;
border-color: #ccc;
}
.swap-cancel-btn:active:not(:disabled) {
transform: scale(0.98);
}
.swap-cancel-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* ============================================
ANIMATIONS
============================================ */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
/* ============================================
MOBILE RESPONSIVE
============================================ */
@media (max-width: 600px) {
.swap-modal-content {
border-radius: 12px 12px 0 0;
max-height: 90vh;
padding: 16px;
}
.swap-modal-header h3 {
font-size: 16px;
}
.swap-alternative-item {
min-height: 56px;
padding: 12px;
}
.swap-alternative-name {
font-size: 15px;
}
.swap-current-exercise {
padding: 12px;
}
.swap-modal-actions {
flex-direction: column;
gap: 8px;
}
.swap-cancel-btn {
min-height: 48px;
}
}
/* Dark mode support (if app has dark mode) */
@media (prefers-color-scheme: dark) {
.swap-modal-content {
background: var(--bg-secondary);
}
.swap-modal-close {
color: #999;
}
.swap-modal-close:hover {
background: rgba(255, 255, 255, 0.1);
color: #fff;
}
.swap-current-exercise {
background: rgba(255, 255, 255, 0.05);
}
.swap-alternative-item {
border-color: #444;
}
.swap-alternative-item:hover {
background: rgba(255, 255, 255, 0.08);
}
.swap-cancel-btn {
background: rgba(255, 255, 255, 0.1);
border-color: #444;
}
.swap-cancel-btn:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.15);
}
}
@@ -0,0 +1,105 @@
import { Icon } from './Icons'
import './SwapWorkoutModal.css'
function SwapWorkoutModal({
exercise,
alternatives = [],
onSwap,
onClose,
loading = false,
error = ''
}) {
if (!exercise) return null
const handleSwap = async (alternative) => {
if (onSwap) {
await onSwap(alternative)
}
}
return (
<div className="swap-modal-overlay" onClick={onClose}>
<div className="swap-modal-content" onClick={(e) => e.stopPropagation()}>
<div className="swap-modal-header">
<h3>Byt övning</h3>
<button
className="swap-modal-close"
onClick={onClose}
aria-label="Stäng"
title="Stäng"
>
</button>
</div>
{/* Current Exercise */}
<div className="swap-current-exercise">
<div className="swap-current-label">Nuvarande övning</div>
<div className="swap-current-name">{exercise.name}</div>
<div className="swap-current-group">{exercise.muscle_group}</div>
</div>
{/* Error State */}
{error && (
<div className="swap-error-message">
<Icon name="alertCircle" size={16} />
<span>{error}</span>
</div>
)}
{/* Loading State */}
{loading && (
<div className="swap-loading-state">
<div className="swap-spinner"></div>
<p>Laddar alternativ...</p>
</div>
)}
{/* Empty State */}
{!loading && !error && alternatives.length === 0 && (
<div className="swap-empty-state">
<p>Inga alternativ hittades för denna övning.</p>
</div>
)}
{/* Alternatives List */}
{!loading && !error && alternatives.length > 0 && (
<div className="swap-alternatives-list">
<div className="swap-alternatives-label">Alternativ</div>
{alternatives.map((alt) => (
<div
key={alt.id}
className="swap-alternative-item"
onClick={() => handleSwap(alt)}
>
<div className="swap-alternative-info">
<div className="swap-alternative-name">{alt.name}</div>
<div className="swap-alternative-group">{alt.muscle_group}</div>
{alt.description && (
<div className="swap-alternative-desc">{alt.description}</div>
)}
</div>
<div className="swap-alternative-icon">
<Icon name="chevronRight" size={18} />
</div>
</div>
))}
</div>
)}
{/* Actions */}
<div className="swap-modal-actions">
<button
className="swap-cancel-btn"
onClick={onClose}
disabled={loading}
>
Avbryt
</button>
</div>
</div>
</div>
)
}
export default SwapWorkoutModal
+150 -21
View File
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react'
import { Icon } from '../components/Icons'
import AlternativeModal from '../components/AlternativeModal'
import SwapWorkoutModal from '../components/SwapWorkoutModal'
const API_URL = '/api'
@@ -59,6 +59,9 @@ function WorkoutPage({ day, week, logs, onLogSet, onDeleteSet, onBack, fetchProg
const [alternativesLoading, setAlternativesLoading] = useState(false)
const [alternativesError, setAlternativesError] = useState('')
const [swappedExercises, setSwappedExercises] = useState({})
const [originalExercises, setOriginalExercises] = useState({}) // { exerciseId: originalExercise }
const [recentSwaps, setRecentSwaps] = useState({}) // { exerciseId: { undoId, timer } }
const [toast, setToast] = useState(null) // { message, type: 'success'|'error' }
const defaultRestSeconds = 90
const [restSeconds, setRestSeconds] = useState(defaultRestSeconds)
const [restRunning, setRestRunning] = useState(false)
@@ -81,6 +84,12 @@ function WorkoutPage({ day, week, logs, onLogSet, onDeleteSet, onBack, fetchProg
return () => clearInterval(timer)
}, [restRunning])
useEffect(() => {
if (!toast) return
const timer = setTimeout(() => setToast(null), 3000)
return () => clearTimeout(timer)
}, [toast])
const loadProgressions = async () => {
const progs = {}
for (const exercise of day.exercises) {
@@ -116,15 +125,106 @@ function WorkoutPage({ day, week, logs, onLogSet, onDeleteSet, onBack, fetchProg
}
}
const handleSelectAlternative = (alternative) => {
const handleSwapWorkout = async (alternative) => {
if (!swapExercise) return
setSwappedExercises(prev => ({
...prev,
[swapExercise.id]: alternative
}))
setSwapExercise(null)
try {
setAlternativesLoading(true)
// Call API to swap exercise
const res = await fetch(`${API_URL}/workouts/${swapExercise.id}/swap`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
fromExerciseId: swapExercise.exercise_id,
toExerciseId: alternative.exercise_id || alternative.id,
workoutDate: day.date
})
})
if (!res.ok) throw new Error('Swap failed')
const swapData = await res.json()
// Update local state
setSwappedExercises(prev => ({
...prev,
[swapExercise.id]: alternative
}))
// Store original exercise for undo
setOriginalExercises(prev => ({
...prev,
[swapExercise.id]: swapExercise
}))
// Show undo button for 30 seconds
const undoId = swapData.id || `swap-${swapExercise.id}-${Date.now()}`
const timer = setTimeout(() => {
setRecentSwaps(prev => {
const newSwaps = { ...prev }
delete newSwaps[swapExercise.id]
return newSwaps
})
}, 30000)
setRecentSwaps(prev => ({
...prev,
[swapExercise.id]: { undoId, timer }
}))
setToast({ message: `${swapExercise.name} bytt mot ${alternative.name}`, type: 'success' })
setSwapExercise(null)
} catch (err) {
console.error('Swap failed:', err)
setToast({ message: 'Kunde inte byta övning', type: 'error' })
} finally {
setAlternativesLoading(false)
}
}
const undoSwap = async (exerciseId) => {
try {
const swapInfo = recentSwaps[exerciseId]
if (!swapInfo) return
// Clear timer
clearTimeout(swapInfo.timer)
// Call API to undo
const res = await fetch(`${API_URL}/workouts/${swapInfo.undoId}/undo`, {
method: 'DELETE'
})
if (!res.ok) throw new Error('Undo failed')
// Update local state
setSwappedExercises(prev => {
const newSwaps = { ...prev }
delete newSwaps[exerciseId]
return newSwaps
})
setOriginalExercises(prev => {
const newOriginals = { ...prev }
delete newOriginals[exerciseId]
return newOriginals
})
setRecentSwaps(prev => {
const newSwaps = { ...prev }
delete newSwaps[exerciseId]
return newSwaps
})
setToast({ message: 'Byte ångrat', type: 'success' })
} catch (err) {
console.error('Undo failed:', err)
setToast({ message: 'Kunde inte ångra byte', type: 'error' })
}
}
const exercises = day.exercises?.filter(e => e.name) || []
const muscleGroups = getMuscleGroups(exercises)
@@ -330,6 +430,7 @@ function WorkoutPage({ day, week, logs, onLogSet, onDeleteSet, onBack, fetchProg
<h2>Övningar</h2>
{exercises.map((exercise, idx) => {
const swapped = swappedExercises[exercise.id]
const original = originalExercises[exercise.id]
const displayExercise = swapped
? { ...exercise, name: swapped.name, muscle_group: swapped.muscle_group, description: swapped.description }
: exercise
@@ -338,6 +439,7 @@ function WorkoutPage({ day, week, logs, onLogSet, onDeleteSet, onBack, fetchProg
<ExerciseCard
key={exercise.id || idx}
exercise={displayExercise}
originalExercise={original}
isSwapped={Boolean(swapped)}
logs={logs[exercise.id] || []}
progression={progressions[exercise.id]}
@@ -349,6 +451,8 @@ function WorkoutPage({ day, week, logs, onLogSet, onDeleteSet, onBack, fetchProg
onDeleteSet={onDeleteSet}
onStartRest={startRest}
onSwap={() => openAlternatives(exercise)}
onUndo={() => undoSwap(exercise.id)}
canUndo={Boolean(recentSwaps[exercise.id])}
/>
)
})}
@@ -365,19 +469,26 @@ function WorkoutPage({ day, week, logs, onLogSet, onDeleteSet, onBack, fetchProg
</button>
</main>
<AlternativeModal
<SwapWorkoutModal
exercise={swapExercise}
alternatives={alternatives}
loading={alternativesLoading}
error={alternativesError}
onSelect={handleSelectAlternative}
onSwap={handleSwapWorkout}
onClose={() => setSwapExercise(null)}
/>
{/* Toast Notification */}
{toast && (
<div className={`toast-notification toast-${toast.type}`}>
{toast.message}
</div>
)}
</div>
)
}
function ExerciseCard({ exercise, logs, progression, expanded, onToggle, onLogSet, onDeleteSet, onSwap, isSwapped, onStartRest }) {
function ExerciseCard({ exercise, logs, progression, expanded, onToggle, onLogSet, onDeleteSet, onSwap, isSwapped, onStartRest, originalExercise, onUndo, canUndo }) {
const [setList, setSetList] = useState([])
const [showAddModal, setShowAddModal] = useState(false)
const weightStep = 2.5
@@ -464,7 +575,9 @@ function ExerciseCard({ exercise, logs, progression, expanded, onToggle, onLogSe
<div className="exercise-info">
<h3>{exercise.name}</h3>
<span className="muscle-group">{exercise.muscle_group}</span>
{isSwapped && <span className="swap-badge">Alternativ</span>}
{isSwapped && originalExercise && (
<span className="swap-badge">Bytt från {originalExercise.name}</span>
)}
</div>
<div className="exercise-actions">
<div className="exercise-meta">
@@ -473,16 +586,32 @@ function ExerciseCard({ exercise, logs, progression, expanded, onToggle, onLogSe
{completedSets}/{setList.length}
</span>
</div>
<button
className="swap-btn"
onClick={(event) => {
event.stopPropagation()
onSwap?.()
}}
aria-label="Byt övning"
>
<Icon name="swap" size={16} />
</button>
<div className="exercise-buttons">
<button
className="swap-btn"
onClick={(event) => {
event.stopPropagation()
onSwap?.()
}}
aria-label="Byt övning"
title="Byt övning"
>
<Icon name="swap" size={16} />
</button>
{canUndo && (
<button
className="undo-btn"
onClick={(event) => {
event.stopPropagation()
onUndo?.()
}}
aria-label="Ångra byte"
title="Ångra byte"
>
<Icon name="undo" size={16} />
</button>
)}
</div>
</div>
</div>