Self hosted FLOSS fitness/workout, nutrition and weight tracker
Working on timer for exercises
tbouri2570e4fbb1c9
diff --git a/extras/docker/development/Dockerfile b/extras/docker/development/Dockerfileindex 41c437cf8..90cdce1d6 100644--- a/extras/docker/development/Dockerfile+++ b/extras/docker/development/Dockerfile@@ -9,7 +9,7 @@ FROM wger/server:latestUSER rootWORKDIR /home/wger/src-RUN wget -O- https://deb.nodesource.com/setup_22.x | bash - \+RUN wget -O- https://deb.nodesource.com/setup_22.x | bash - && \apt update && \apt install --no-install-recommends -y \git \diff --git a/wger/core/api/serializers.py b/wger/core/api/serializers.pyindex 855875cf9..90b016fa7 100644--- a/wger/core/api/serializers.py+++ b/wger/core/api/serializers.py@@ -187,7 +187,7 @@ class RepetitionUnitSerializer(serializers.ModelSerializer):class Meta:model = RepetitionUnit- fields = ('id', 'name')+ fields = ('id', 'name', 'unit_type')class RoutineWeightUnitSerializer(serializers.ModelSerializer):diff --git a/wger/core/fixtures/setting_repetition_units.json b/wger/core/fixtures/setting_repetition_units.jsonindex 96313610a..f2a5853dd 100644--- a/wger/core/fixtures/setting_repetition_units.json+++ b/wger/core/fixtures/setting_repetition_units.json@@ -2,42 +2,48 @@{"pk": 1,"fields": {- "name": "Repetitions"+ "name": "Repetitions",+ "unit_type": "REPETITIONS"},"model": "core.repetitionunit"},{"pk": 2,"fields": {- "name": "Until Failure"+ "name": "Until Failure",+ "unit_type": "REPETITIONS"},"model": "core.repetitionunit"},{"pk": 3,"fields": {- "name": "Seconds"+ "name": "Seconds",+ "unit_type": "TIME"},"model": "core.repetitionunit"},{"pk": 4,"fields": {- "name": "Minutes"+ "name": "Minutes",+ "unit_type": "TIME"},"model": "core.repetitionunit"},{"pk": 5,"fields": {- "name": "Miles"+ "name": "Miles",+ "unit_type": "DISTANCE"},"model": "core.repetitionunit"},{"pk": 6,"fields": {- "name": "Kilometers"+ "name": "Kilometers",+ "unit_type": "DISTANCE"},"model": "core.repetitionunit"},@@ -45,7 +51,8 @@"model": "core.repetitionunit","pk": 7,"fields": {- "name": "Max Reps"+ "name": "Max Reps",+ "unit_type": "REPETITIONS"}}]diff --git a/wger/core/migrations/0020_add_unit_type_to_repetitionunit.py b/wger/core/migrations/0020_add_unit_type_to_repetitionunit.pynew file mode 100644index 000000000..524611173--- /dev/null+++ b/wger/core/migrations/0020_add_unit_type_to_repetitionunit.py@@ -0,0 +1,59 @@+# Generated by Django 5.2.9 on 2025-12-07 18:34++from django.db import migrations, models+++def set_unit_types(apps, schema_editor):+ """+ Set the unit_type for existing RepetitionUnit records based on their ID.++ Default units (from fixture):+ - ID 1: Repetitions -> REPETITIONS+ - ID 2: Until Failure -> REPETITIONS+ - ID 3: Seconds -> TIME+ - ID 4: Minutes -> TIME+ - ID 5: Miles -> DISTANCE+ - ID 6: Kilometers -> DISTANCE+ - ID 7: Max Reps -> REPETITIONS+ """+ RepetitionUnit = apps.get_model('core', 'RepetitionUnit')++ # Time-based units+ RepetitionUnit.objects.filter(id__in=[3, 4]).update(unit_type='TIME')++ # Distance-based units+ RepetitionUnit.objects.filter(id__in=[5, 6]).update(unit_type='DISTANCE')++ # Repetition-based units (already default, but explicit for clarity)+ RepetitionUnit.objects.filter(id__in=[1, 2, 7]).update(unit_type='REPETITIONS')+++def reverse_unit_types(apps, schema_editor):+ """Reverse migration - no action needed since field will be removed"""+ pass+++class Migration(migrations.Migration):++ dependencies = [+ ('core', '0019_delete_daysofweek'),+ ]++ operations = [+ migrations.AddField(+ model_name='repetitionunit',+ name='unit_type',+ field=models.CharField(+ choices=[+ ('REPETITIONS', 'Repetitions'),+ ('TIME', 'Time'),+ ('DISTANCE', 'Distance'),+ ],+ default='REPETITIONS',+ help_text='The type of unit (repetitions, time, or distance)',+ max_length=20,+ verbose_name='Unit Type',+ ),+ ),+ migrations.RunPython(set_unit_types, reverse_unit_types),+ ]diff --git a/wger/core/models/rep_unit.py b/wger/core/models/rep_unit.pyindex 5cbeda557..fc3490787 100644--- a/wger/core/models/rep_unit.py+++ b/wger/core/models/rep_unit.py@@ -24,6 +24,16 @@ class RepetitionUnit(models.Model):Setting unit, used in combination with an amount such as '10 reps', '5 km'"""+ UNIT_TYPE_REPETITIONS = 'REPETITIONS'+ UNIT_TYPE_TIME = 'TIME'+ UNIT_TYPE_DISTANCE = 'DISTANCE'++ UNIT_TYPE_CHOICES = [+ (UNIT_TYPE_REPETITIONS, _('Repetitions')),+ (UNIT_TYPE_TIME, _('Time')),+ (UNIT_TYPE_DISTANCE, _('Distance')),+ ]+class Meta:"""Set Meta options@@ -34,6 +44,13 @@ class RepetitionUnit(models.Model):]name = models.CharField(max_length=100, verbose_name=_('Name'))+ unit_type = models.CharField(+ max_length=20,+ choices=UNIT_TYPE_CHOICES,+ default=UNIT_TYPE_REPETITIONS,+ verbose_name=_('Unit Type'),+ help_text=_('The type of unit (repetitions, time, or distance)'),+ )def __str__(self):"""@@ -58,3 +75,19 @@ class RepetitionUnit(models.Model):This is done basically to not litter the code with magic IDs"""return self.id == 1++ @property+ def is_time(self):+ """+ Checks if this unit represents a time-based measurement (seconds, minutes)++ Used by the frontend to determine if a countdown timer should be displayed+ """+ return self.unit_type == self.UNIT_TYPE_TIME++ @property+ def is_distance(self):+ """+ Checks if this unit represents a distance measurement (km, miles)+ """+ return self.unit_type == self.UNIT_TYPE_DISTANCEdiff --git a/wger/core/static/css/countdown-timer.css b/wger/core/static/css/countdown-timer.cssnew file mode 100644index 000000000..a11983f24--- /dev/null+++ b/wger/core/static/css/countdown-timer.css@@ -0,0 +1,254 @@+/*+ * wger Countdown Timer Styles+ */++.countdown-timer {+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: 1rem;+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;+}++/* Timer Circle Container */+.timer-circle {+ position: relative;+ width: 200px;+ height: 200px;+ margin-bottom: 1rem;+}++/* SVG Circle */+.timer-svg {+ width: 100%;+ height: 100%;+ transform: rotate(-90deg);+}++.timer-bg {+ fill: none;+ stroke: #e9ecef;+ stroke-width: 8;+}++.timer-progress {+ fill: none;+ stroke: #2a8fbd; /* wger-blue */+ stroke-width: 8;+ stroke-linecap: round;+ transition: stroke-dashoffset 0.1s linear, stroke 0.3s ease;+}++.timer-progress.timer-warning {+ stroke: #ffc107; /* warning yellow */+}++.timer-progress.timer-danger {+ stroke: #dc3545; /* danger red */+}++/* Time Display */+.timer-display {+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ text-align: center;+}++.timer-time {+ font-size: 2.5rem;+ font-weight: 700;+ color: #212529;+ font-variant-numeric: tabular-nums;+ letter-spacing: -0.02em;+}++/* Completion Animation */+.timer-circle.timer-complete {+ animation: pulse 0.5s ease-in-out 3;+}++.timer-circle.timer-complete .timer-progress {+ stroke: #28a745; /* success green */+}++.timer-circle.timer-complete .timer-time {+ color: #28a745;+}++@keyframes pulse {+ 0%, 100% {+ transform: scale(1);+ }+ 50% {+ transform: scale(1.05);+ }+}++/* Timer Controls */+.timer-controls {+ display: flex;+ gap: 0.75rem;+ justify-content: center;+}++.timer-btn {+ width: 50px;+ height: 50px;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 1.25rem;+ transition: transform 0.15s ease, box-shadow 0.15s ease;+ border: none;+ cursor: pointer;+}++.timer-btn:hover {+ transform: scale(1.1);+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);+}++.timer-btn:active {+ transform: scale(0.95);+}++.timer-start {+ background-color: #28a745;+ color: white;+}++.timer-start:hover {+ background-color: #218838;+ color: white;+}++.timer-pause {+ background-color: #ffc107;+ color: #212529;+}++.timer-pause:hover {+ background-color: #e0a800;+ color: #212529;+}++.timer-reset {+ background-color: #6c757d;+ color: white;+}++.timer-reset:hover {+ background-color: #5a6268;+ color: white;+}++/* Responsive adjustments */+@media (max-width: 576px) {+ .timer-circle {+ width: 160px;+ height: 160px;+ }++ .timer-time {+ font-size: 2rem;+ }++ .timer-btn {+ width: 44px;+ height: 44px;+ font-size: 1rem;+ }+}++/* Dark mode support (if theme supports it) */+@media (prefers-color-scheme: dark) {+ .timer-bg {+ stroke: #495057;+ }++ .timer-time {+ color: #f8f9fa;+ }+}++/* Timer in card/modal context */+.card .countdown-timer,+.modal .countdown-timer {+ padding: 0.5rem;+}++.card .timer-circle,+.modal .timer-circle {+ width: 150px;+ height: 150px;+}++.card .timer-time,+.modal .timer-time {+ font-size: 1.75rem;+}++/* Inline timer (smaller version) */+.countdown-timer.timer-inline {+ flex-direction: row;+ padding: 0.5rem;+ gap: 1rem;+}++.countdown-timer.timer-inline .timer-circle {+ width: 80px;+ height: 80px;+ margin-bottom: 0;+}++.countdown-timer.timer-inline .timer-time {+ font-size: 1.25rem;+}++.countdown-timer.timer-inline .timer-btn {+ width: 36px;+ height: 36px;+ font-size: 0.875rem;+}++/* Injected exercise timer (compact, next to exercise) */+.wger-exercise-timer-inline .countdown-timer {+ flex-direction: row;+ padding: 0.25rem 0.5rem;+ gap: 0.5rem;+ background: #f8f9fa;+ border-radius: 8px;+ border: 1px solid #dee2e6;+}++.wger-exercise-timer-inline .timer-circle {+ width: 60px;+ height: 60px;+ margin-bottom: 0;+}++.wger-exercise-timer-inline .timer-time {+ font-size: 1rem;+}++.wger-exercise-timer-inline .timer-controls {+ gap: 0.25rem;+}++.wger-exercise-timer-inline .timer-btn {+ width: 28px;+ height: 28px;+ font-size: 0.75rem;+}++.wger-exercise-timer-inline .timer-svg {+ stroke-width: 6;+}++.wger-exercise-timer-inline .timer-bg,+.wger-exercise-timer-inline .timer-progress {+ stroke-width: 6;+}diff --git a/wger/core/static/js/countdown-timer.js b/wger/core/static/js/countdown-timer.jsnew file mode 100644index 000000000..bf448d887--- /dev/null+++ b/wger/core/static/js/countdown-timer.js@@ -0,0 +1,665 @@+/*+ This file is part of wger Workout Manager.++ wger Workout Manager is free software: you can redistribute it and/or modify+ it under the terms of the GNU Affero General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ wger Workout Manager is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU Affero General Public License+ */++/*+ * wger Countdown Timer for timed exercises+ */++'use strict';++class CountdownTimer {+ constructor(container, options = {}) {+ this.container = typeof container === 'string'+ ? document.querySelector(container)+ : container;++ this.duration = options.duration || 60; // Duration in seconds+ this.onComplete = options.onComplete || null;+ this.onTick = options.onTick || null;+ this.autoStart = options.autoStart || false;+ this.showMilliseconds = options.showMilliseconds || false;++ this.timeRemaining = this.duration;+ this.isRunning = false;+ this.isPaused = false;+ this.intervalId = null;+ this.audioContext = null;++ this.init();+ }++ init() {+ this.render();+ this.bindEvents();+ this.updateDisplay();++ if (this.autoStart) {+ this.start();+ }+ }++ render() {+ this.container.innerHTML = `+ <div class="countdown-timer">+ <div class="timer-circle">+ <svg class="timer-svg" viewBox="0 0 100 100">+ <circle class="timer-bg" cx="50" cy="50" r="45" />+ <circle class="timer-progress" cx="50" cy="50" r="45" />+ </svg>+ <div class="timer-display">+ <span class="timer-time">00:00</span>+ </div>+ </div>+ <div class="timer-controls">+ <button class="btn btn-success timer-btn timer-start" title="Start">+ <i class="fa-solid fa-play"></i>+ </button>+ <button class="btn btn-warning timer-btn timer-pause" title="Pause" style="display: none;">+ <i class="fa-solid fa-pause"></i>+ </button>+ <button class="btn btn-secondary timer-btn timer-reset" title="Reset">+ <i class="fa-solid fa-rotate-left"></i>+ </button>+ </div>+ </div>+ `;++ // Cache DOM elements+ this.elements = {+ circle: this.container.querySelector('.timer-progress'),+ timeDisplay: this.container.querySelector('.timer-time'),+ startBtn: this.container.querySelector('.timer-start'),+ pauseBtn: this.container.querySelector('.timer-pause'),+ resetBtn: this.container.querySelector('.timer-reset'),+ timerCircle: this.container.querySelector('.timer-circle')+ };++ // Calculate circle circumference for progress animation+ this.circumference = 2 * Math.PI * 45;+ this.elements.circle.style.strokeDasharray = this.circumference;+ this.elements.circle.style.strokeDashoffset = 0;+ }++ bindEvents() {+ this.elements.startBtn.addEventListener('click', () => this.start());+ this.elements.pauseBtn.addEventListener('click', () => this.pause());+ this.elements.resetBtn.addEventListener('click', () => this.reset());+ }++ start() {+ if (this.isRunning) return;++ this.isRunning = true;+ this.isPaused = false;++ this.elements.startBtn.style.display = 'none';+ this.elements.pauseBtn.style.display = 'inline-block';++ this.lastTick = Date.now();+ this.intervalId = setInterval(() => this.tick(), 100);+ }++ pause() {+ if (!this.isRunning) return;++ this.isRunning = false;+ this.isPaused = true;++ this.elements.startBtn.style.display = 'inline-block';+ this.elements.pauseBtn.style.display = 'none';++ if (this.intervalId) {+ clearInterval(this.intervalId);+ this.intervalId = null;+ }+ }++ reset() {+ this.pause();+ this.timeRemaining = this.duration;+ this.isPaused = false;+ this.updateDisplay();+ this.elements.timerCircle.classList.remove('timer-complete');+ }++ tick() {+ const now = Date.now();+ const delta = (now - this.lastTick) / 1000;+ this.lastTick = now;++ this.timeRemaining -= delta;++ if (this.timeRemaining <= 0) {+ this.timeRemaining = 0;+ this.complete();+ }++ this.updateDisplay();++ if (this.onTick) {+ this.onTick(this.timeRemaining);+ }+ }++ updateDisplay() {+ // Update time display+ const minutes = Math.floor(this.timeRemaining / 60);+ const seconds = Math.floor(this.timeRemaining % 60);+ const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;+ this.elements.timeDisplay.textContent = timeString;++ // Update progress circle+ const progress = this.timeRemaining / this.duration;+ const offset = this.circumference * (1 - progress);+ this.elements.circle.style.strokeDashoffset = offset;++ // Change color as time runs low+ if (this.timeRemaining <= 10 && this.timeRemaining > 5) {+ this.elements.circle.classList.add('timer-warning');+ this.elements.circle.classList.remove('timer-danger');+ } else if (this.timeRemaining <= 5) {+ this.elements.circle.classList.remove('timer-warning');+ this.elements.circle.classList.add('timer-danger');+ } else {+ this.elements.circle.classList.remove('timer-warning', 'timer-danger');+ }+ }++ complete() {+ this.pause();+ this.elements.timerCircle.classList.add('timer-complete');+ this.playCompletionSound();++ if (this.onComplete) {+ this.onComplete();+ }+ }++ playCompletionSound() {+ try {+ // Create audio context on demand (browsers require user interaction)+ if (!this.audioContext) {+ this.audioContext = new (window.AudioContext || window.webkitAudioContext)();+ }++ // Play a simple beep sequence+ const playBeep = (time, frequency, duration) => {+ const oscillator = this.audioContext.createOscillator();+ const gainNode = this.audioContext.createGain();++ oscillator.connect(gainNode);+ gainNode.connect(this.audioContext.destination);++ oscillator.frequency.value = frequency;+ oscillator.type = 'sine';++ gainNode.gain.setValueAtTime(0.3, time);+ gainNode.gain.exponentialRampToValueAtTime(0.01, time + duration);++ oscillator.start(time);+ oscillator.stop(time + duration);+ };++ const now = this.audioContext.currentTime;+ playBeep(now, 880, 0.15);+ playBeep(now + 0.2, 880, 0.15);+ playBeep(now + 0.4, 1760, 0.3);+ } catch (e) {+ console.log('Audio not available:', e);+ }+ }++ setDuration(seconds) {+ this.duration = seconds;+ this.reset();+ }++ destroy() {+ if (this.intervalId) {+ clearInterval(this.intervalId);+ }+ if (this.audioContext) {+ this.audioContext.close();+ }+ this.container.innerHTML = '';+ }+}+++/*+ * Timer initialization for workout pages+ * Checks for timed exercises and initializes timers+ */+function wgerInitTimers() {+ // Find all timer containers on the page+ const timerContainers = document.querySelectorAll('[data-timer-duration]');++ timerContainers.forEach(container => {+ const duration = parseInt(container.dataset.timerDuration, 10);+ const unitType = container.dataset.timerUnitType;++ // Only initialize timer for TIME unit types+ if (unitType === 'TIME' && duration > 0) {+ new CountdownTimer(container, {+ duration: duration,+ onComplete: () => {+ console.log('Timer completed!');+ }+ });+ }+ });+}+++/*+ * Utility function to create a timer programmatically+ */+function wgerCreateTimer(selector, durationSeconds, options = {}) {+ return new CountdownTimer(selector, {+ duration: durationSeconds,+ ...options+ });+}+++// Auto-initialize timers when DOM is ready+document.addEventListener('DOMContentLoaded', function() {+ wgerInitTimers();+ // Use button-based timer injection on routine pages+ wgerInitTimerButtons();+});+++/*+ * Workout Page Timer Injection+ * Automatically detects timed exercises in the React workout UI and injects timers+ * Only runs on routine view pages to avoid performance issues+ */+function wgerInitWorkoutTimerInjection() {+ // Only run on routine/workout pages+ const path = window.location.pathname;+ if (!path.includes('/routine/') && !path.includes('/workout/')) {+ return;+ }++ // Time-based unit names (matches the RepetitionUnit fixtures)+ const TIME_UNITS = ['seconds', 'minutes', 'second', 'minute', 'sec', 'min'];++ // Track if we've already injected timers+ let timersInjected = false;+ let debounceTimer = null;++ // Debounced injection function+ function debouncedInject() {+ if (debounceTimer) clearTimeout(debounceTimer);+ debounceTimer = setTimeout(injectTimersIntoWorkout, 500);+ }++ // Watch for DOM changes (React renders dynamically)+ const observer = new MutationObserver(function(mutations) {+ // Only re-run if we haven't injected yet+ if (!timersInjected) {+ debouncedInject();+ }+ });++ // Start observing the document for React component renders+ observer.observe(document.body, {+ childList: true,+ subtree: true+ });++ // Also run with delays for React hydration+ setTimeout(injectTimersIntoWorkout, 1000);+ setTimeout(injectTimersIntoWorkout, 2500);++ function injectTimersIntoWorkout() {+ // Skip if already injected+ if (document.querySelector('.wger-exercise-timer')) {+ timersInjected = true;+ observer.disconnect(); // Stop watching once done+ return;+ }++ // Look for exercise entries that mention time units+ // The React UI typically shows something like "60 Seconds" or "2 Minutes"++ // Search text-containing elements (limited scope)+ const allElements = document.querySelectorAll('div, span, td, li, p');++ // Find all elements that directly contain "X Seconds" or "X Minutes" text+ const matches = [];++ allElements.forEach(el => {+ // Skip if already has a timer+ if (el.querySelector('.wger-exercise-timer') || el.classList.contains('wger-exercise-timer')) return;++ // Check direct text content only (not nested children)+ // This helps find the most specific element+ let hasDirectTimeText = false;+ let duration = null;+ let unitName = null;++ // Check the element's own text (excluding children)+ const ownText = Array.from(el.childNodes)+ .filter(node => node.nodeType === Node.TEXT_NODE)+ .map(node => node.textContent)+ .join(' ');++ // Also check if this element has very little child content (meaning it's specific)+ const fullText = el.textContent;++ for (const unit of TIME_UNITS) {+ const regex = new RegExp(`(\\d+(?:\\.\\d+)?)\\s*${unit}`, 'i');++ // First try own text+ let match = ownText.match(regex);+ if (match) {+ hasDirectTimeText = true;+ duration = parseFloat(match[1]);+ unitName = unit;+ break;+ }++ // Then try full text but only for small elements (< 100 chars)+ if (fullText.length < 100) {+ match = fullText.match(regex);+ if (match) {+ duration = parseFloat(match[1]);+ unitName = unit;+ break;+ }+ }+ }++ if (duration && unitName) {+ matches.push({+ element: el,+ duration: duration,+ unitName: unitName,+ textLength: fullText.length,+ hasDirectText: hasDirectTimeText+ });+ }+ });++ // Sort by specificity: prefer direct text matches, then smaller text length+ matches.sort((a, b) => {+ if (a.hasDirectText !== b.hasDirectText) return b.hasDirectText - a.hasDirectText;+ return a.textLength - b.textLength;+ });++ // Inject timer for each unique match (avoid duplicates by tracking parent chains)+ const processedElements = new Set();++ matches.forEach(match => {+ const { element, duration, unitName } = match;++ // Skip if any parent already has a timer+ let parent = element;+ let skipThis = false;+ while (parent) {+ if (processedElements.has(parent)) {+ skipThis = true;+ break;+ }+ parent = parent.parentElement;+ }+ if (skipThis) return;++ // Mark this element and its parents as processed+ processedElements.add(element);++ // Convert to seconds if needed+ let durationSeconds = duration;+ if (unitName.startsWith('min')) {+ durationSeconds = duration * 60;+ }++ console.log('Timer injection: injecting timer for', durationSeconds, 'seconds next to:', element.textContent.substring(0, 50));++ // Create a compact inline timer container+ const timerContainer = document.createElement('div');+ timerContainer.className = 'wger-exercise-timer wger-exercise-timer-inline';+ timerContainer.style.cssText = 'display: inline-flex; align-items: center; margin-left: 10px; vertical-align: middle;';++ // Insert right after the element (as a sibling)+ if (element.nextSibling) {+ element.parentNode.insertBefore(timerContainer, element.nextSibling);+ } else {+ element.parentNode.appendChild(timerContainer);+ }++ // Initialize the timer with compact size+ new CountdownTimer(timerContainer, {+ duration: Math.round(durationSeconds),+ onComplete: () => {+ // Visual feedback on completion+ element.style.backgroundColor = '#d4edda';+ setTimeout(() => {+ element.style.backgroundColor = '';+ }, 2000);+ }+ });++ // Mark as injected and stop observer+ timersInjected = true;+ observer.disconnect();+ });+ }+}+++/*+ * API-based Timer Injection (Alternative approach)+ * Fetches repetition unit info from API to determine if timer should show+ */+async function wgerFetchAndInjectTimers() {+ try {+ // Fetch repetition units from API+ const response = await fetch('/api/v2/setting-repetitionunit/');+ const data = await response.json();++ // Find TIME units+ const timeUnitIds = data.results+ .filter(unit => unit.unit_type === 'TIME')+ .map(unit => unit.id);++ console.log('Time-based unit IDs:', timeUnitIds);++ // Store globally for use by other functions+ window.wgerTimeUnitIds = timeUnitIds;+ } catch (e) {+ console.log('Could not fetch repetition units:', e);+ }+}++// Fetch time units on page load+document.addEventListener('DOMContentLoaded', wgerFetchAndInjectTimers);+++/*+ * Timer Button Injection+ * Adds a small timer button next to timed exercises that opens a floating timer+ */+function wgerInitTimerButtons() {+ // Only run on routine/workout pages+ const path = window.location.pathname;+ if (!path.includes('/routine/') || !path.includes('/view')) {+ return;+ }++ const TIME_UNITS = ['seconds', 'minutes', 'second', 'minute'];+ let buttonsAdded = false;+ let attempts = 0;+ const maxAttempts = 10;++ // Create the floating timer modal (hidden by default)+ createTimerModal();++ // Try to find and add buttons with retry+ const interval = setInterval(function() {+ attempts++;+ if (buttonsAdded || attempts > maxAttempts) {+ clearInterval(interval);+ return;+ }+ buttonsAdded = addTimerButtons();+ }, 1000);++ function createTimerModal() {+ // Check if modal already exists+ if (document.getElementById('wger-timer-modal')) return;++ const modal = document.createElement('div');+ modal.id = 'wger-timer-modal';+ modal.className = 'wger-timer-modal';+ modal.style.cssText = `+ display: none;+ position: fixed;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ z-index: 10000;+ background: white;+ border-radius: 16px;+ box-shadow: 0 10px 40px rgba(0,0,0,0.3);+ padding: 20px;+ min-width: 280px;+ `;++ modal.innerHTML = `+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">+ <h5 style="margin: 0; font-weight: 600;">Exercise Timer</h5>+ <button id="wger-timer-close" style="background: none; border: none; font-size: 24px; cursor: pointer; color: #666;">×</button>+ </div>+ <div id="wger-timer-container"></div>+ `;++ // Create backdrop+ const backdrop = document.createElement('div');+ backdrop.id = 'wger-timer-backdrop';+ backdrop.style.cssText = `+ display: none;+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background: rgba(0,0,0,0.5);+ z-index: 9999;+ `;++ document.body.appendChild(backdrop);+ document.body.appendChild(modal);++ // Close handlers+ document.getElementById('wger-timer-close').addEventListener('click', closeTimerModal);+ backdrop.addEventListener('click', closeTimerModal);+ }++ function openTimerModal(duration) {+ const modal = document.getElementById('wger-timer-modal');+ const backdrop = document.getElementById('wger-timer-backdrop');+ const container = document.getElementById('wger-timer-container');++ // Clear previous timer+ container.innerHTML = '';++ // Create new timer+ new CountdownTimer(container, {+ duration: duration,+ onComplete: function() {+ // Flash the modal on completion+ modal.style.animation = 'pulse 0.5s ease-in-out 3';+ }+ });++ modal.style.display = 'block';+ backdrop.style.display = 'block';+ }++ function closeTimerModal() {+ document.getElementById('wger-timer-modal').style.display = 'none';+ document.getElementById('wger-timer-backdrop').style.display = 'none';+ }++ function addTimerButtons() {+ // Find all text nodes containing time patterns+ const walker = document.createTreeWalker(+ document.body,+ NodeFilter.SHOW_TEXT,+ null,+ false+ );++ const timeNodes = [];+ let node;+ while (node = walker.nextNode()) {+ const text = node.textContent.trim();+ for (const unit of TIME_UNITS) {+ const regex = new RegExp(`^(\\d+)\\s*${unit}$`, 'i');+ const match = text.match(regex);+ if (match) {+ timeNodes.push({+ node: node,+ duration: parseInt(match[1]),+ unit: unit+ });+ break;+ }+ }+ }++ if (timeNodes.length === 0) return false;++ // Add timer button next to each time text+ timeNodes.forEach(item => {+ const parent = item.node.parentElement;+ if (!parent || parent.querySelector('.wger-timer-btn')) return;++ // Convert to seconds+ let durationSeconds = item.duration;+ if (item.unit.startsWith('min')) {+ durationSeconds = item.duration * 60;+ }++ // Create timer button+ const btn = document.createElement('button');+ btn.className = 'wger-timer-btn btn btn-sm btn-outline-primary ms-2';+ btn.innerHTML = '<i class="fa-solid fa-stopwatch"></i>';+ btn.title = 'Start Timer';+ btn.style.cssText = 'padding: 2px 8px; font-size: 12px; vertical-align: middle;';++ btn.addEventListener('click', function(e) {+ e.preventDefault();+ e.stopPropagation();+ openTimerModal(durationSeconds);+ });++ // Insert button after the text+ parent.appendChild(btn);+ });++ return true;+ }+}+++// Export for use in other modules+if (typeof module !== 'undefined' && module.exports) {+ module.exports = { CountdownTimer, wgerInitTimers, wgerCreateTimer, wgerInitTimerButtons };+}diff --git a/wger/core/templates/navigation.html b/wger/core/templates/navigation.htmlindex bfcd8c6c4..800f38691 100644--- a/wger/core/templates/navigation.html+++ b/wger/core/templates/navigation.html@@ -46,6 +46,15 @@</a></li>+ <li>+ <a class="dropdown-item"+ href="{% url 'manager:add-timed-exercise' %}"+ rel="nofollow">+ <span class="{% fa_class 'stopwatch' %}"></span>+ {% translate "Add Timed Exercise" %}+ </a>+ </li>+<li><a class="dropdown-item"href="{% url 'measurements:overview' %}" rel="nofollow">diff --git a/wger/core/templates/template.html b/wger/core/templates/template.htmlindex f4dbcd707..371a6a4b5 100644--- a/wger/core/templates/template.html+++ b/wger/core/templates/template.html@@ -50,6 +50,7 @@<link rel="stylesheet" type="text/css" href="{% static 'bootstrap-compiled.css' %}"><link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap-custom.css' %}"><link rel="stylesheet" type="text/css" href="{% static 'fontawesomefree/css/all.min.css' %}">+ <link rel="stylesheet" type="text/css" href="{% static 'css/countdown-timer.css' %}"><link rel="stylesheet" type="text/css" href="{% static 'node/@wger-project/react-components/build/assets/index.css' %}" id="react-css">{% endcompress %}@@ -66,6 +67,7 @@</script><script src="{% static 'node/masonry-layout/dist/masonry.pkgd.min.js' %}"></script><script src="{% static 'js/nutrition.js' %}"></script>+ <script src="{% static 'js/countdown-timer.js' %}"></script>{% endcompress %}{# this needs to be outside of the compress block! #}diff --git a/wger/manager/consts.py b/wger/manager/consts.pyindex 06916cfaa..63f9cb2a7 100644--- a/wger/manager/consts.py+++ b/wger/manager/consts.py@@ -18,5 +18,16 @@ RIR_OPTIONS = [None, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]REP_UNIT_REPETITIONS = 1REP_UNIT_TILL_FAILURE = 2+REP_UNIT_SECONDS = 3+REP_UNIT_MINUTES = 4+REP_UNIT_MILES = 5+REP_UNIT_KILOMETERS = 6+REP_UNIT_MAX_REPS = 7+WEIGHT_UNIT_KG = 1WEIGHT_UNIT_LB = 2++# Unit type constants (matching RepetitionUnit.UNIT_TYPE_* choices)+UNIT_TYPE_REPETITIONS = 'REPETITIONS'+UNIT_TYPE_TIME = 'TIME'+UNIT_TYPE_DISTANCE = 'DISTANCE'diff --git a/wger/manager/forms.py b/wger/manager/forms.pynew file mode 100644index 000000000..a50de23ff--- /dev/null+++ b/wger/manager/forms.py@@ -0,0 +1,96 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# Django+from django import forms+from django.utils.translation import gettext_lazy as _++# wger+from wger.core.models import RepetitionUnit+from wger.exercises.models import Translation+from wger.manager.models import (+ Day,+ Routine,+ Slot,+ SlotEntry,+)+++class TimedExerciseForm(forms.Form):+ """+ Form for creating a timed exercise (e.g., 60 seconds plank)+ """++ routine = forms.ModelChoiceField(+ queryset=Routine.objects.none(),+ label=_('Routine'),+ help_text=_('Select the routine to add this exercise to'),+ )++ day = forms.ModelChoiceField(+ queryset=Day.objects.none(),+ label=_('Day'),+ help_text=_('Select the day within the routine'),+ required=False,+ )++ exercise = forms.ModelChoiceField(+ queryset=Translation.objects.none(),+ label=_('Exercise'),+ help_text=_('Select the exercise (e.g., Plank, Wall Sit)'),+ )++ duration = forms.IntegerField(+ min_value=1,+ max_value=3600,+ label=_('Duration'),+ help_text=_('How long should the exercise last?'),+ )++ unit = forms.ModelChoiceField(+ queryset=RepetitionUnit.objects.filter(unit_type='TIME'),+ label=_('Time Unit'),+ help_text=_('Seconds or Minutes'),+ )++ def __init__(self, user, *args, **kwargs):+ super().__init__(*args, **kwargs)+ # Filter routines to only show user's routines+ self.fields['routine'].queryset = Routine.objects.filter(user=user)++ # Get exercises that are in the user's routines+ from wger.manager.models import SlotEntry+ user_exercise_ids = SlotEntry.objects.filter(+ slot__day__routine__user=user+ ).values_list('exercise_id', flat=True).distinct()++ # Show only exercises from user's routines (English translations)+ self.fields['exercise'].queryset = Translation.objects.filter(+ language_id=2,+ exercise_id__in=user_exercise_ids+ ).select_related('exercise').order_by('name')++ def clean(self):+ cleaned_data = super().clean()+ routine = cleaned_data.get('routine')+ day = cleaned_data.get('day')++ # If day is provided, make sure it belongs to the selected routine+ if day and routine and day.routine != routine:+ raise forms.ValidationError(_('The selected day does not belong to the selected routine.'))++ return cleaned_datadiff --git a/wger/manager/templates/add_timed_exercise.html b/wger/manager/templates/add_timed_exercise.htmlnew file mode 100644index 000000000..0c84d8e65--- /dev/null+++ b/wger/manager/templates/add_timed_exercise.html@@ -0,0 +1,153 @@+{% extends "base.html" %}+{% load i18n static crispy_forms_tags %}++{% block title %}{% translate "Add Timed Exercise" %}{% endblock %}++{% block content %}+<div class="container py-4">+ <div class="row justify-content-center">+ <div class="col-md-8 col-lg-6">+ <div class="card">+ <div class="card-header bg-primary text-white">+ <h4 class="mb-0">+ <i class="fa-solid fa-stopwatch me-2"></i>+ {% translate "Add Timed Exercise" %}+ </h4>+ </div>+ <div class="card-body">+ <p class="text-muted mb-4">+ {% translate "Add an exercise with a time-based duration (e.g., 60 second plank, 2 minute wall sit). A countdown timer will automatically appear when viewing the routine." %}+ </p>++ <form method="post" id="timed-exercise-form">+ {% csrf_token %}++ <div class="mb-3">+ <label for="id_routine" class="form-label">{% translate "Routine" %}</label>+ <select name="routine" id="id_routine" class="form-select" required>+ <option value="">{% translate "Select a routine..." %}</option>+ {% for routine in form.routine.field.queryset %}+ <option value="{{ routine.id }}">{{ routine.name }}</option>+ {% endfor %}+ </select>+ <div class="form-text">{% translate "Select the routine to add this exercise to" %}</div>+ </div>++ <div class="mb-3">+ <label for="id_day" class="form-label">{% translate "Day" %} ({% translate "optional" %})</label>+ <select name="day" id="id_day" class="form-select">+ <option value="">{% translate "Auto-select or create day" %}</option>+ </select>+ <div class="form-text">{% translate "Leave empty to use the first day or create a new one" %}</div>+ </div>++ <div class="mb-3">+ <label for="id_exercise" class="form-label">{% translate "Exercise" %}</label>+ <select name="exercise" id="id_exercise" class="form-select" required>+ <option value="">{% translate "Select an exercise..." %}</option>+ {% for exercise in form.exercise.field.queryset %}+ <option value="{{ exercise.id }}">{{ exercise.name }}</option>+ {% endfor %}+ </select>+ <div class="form-text">{% translate "Select the exercise (e.g., Plank, Wall Sit)" %}</div>+ </div>++ <div class="row mb-3">+ <div class="col-8">+ <label for="id_duration" class="form-label">{% translate "Duration" %}</label>+ <input type="number" name="duration" id="id_duration" class="form-control"+ min="1" max="3600" value="60" required>+ </div>+ <div class="col-4">+ <label for="id_unit" class="form-label">{% translate "Unit" %}</label>+ <select name="unit" id="id_unit" class="form-select" required>+ {% for unit in form.unit.field.queryset %}+ <option value="{{ unit.id }}" {% if unit.name == "Seconds" %}selected{% endif %}>+ {{ unit.name }}+ </option>+ {% endfor %}+ </select>+ </div>+ </div>++ <!-- Timer Preview -->+ <div class="mb-4">+ <label class="form-label">{% translate "Preview" %}</label>+ <div class="border rounded p-3 bg-light">+ <div id="timer-preview" data-timer-duration="60" data-timer-unit-type="TIME"></div>+ </div>+ </div>++ <div class="d-grid gap-2">+ <button type="submit" class="btn btn-primary btn-lg">+ <i class="fa-solid fa-plus me-2"></i>+ {% translate "Add Timed Exercise" %}+ </button>+ <a href="{% url 'manager:routine:overview' %}" class="btn btn-outline-secondary">+ {% translate "Cancel" %}+ </a>+ </div>+ </form>+ </div>+ </div>+ </div>+ </div>+</div>++<script>+document.addEventListener('DOMContentLoaded', function() {+ // Initialize preview timer+ const previewContainer = document.getElementById('timer-preview');+ let previewTimer = new CountdownTimer(previewContainer, {+ duration: 60+ });++ // Update preview when duration or unit changes+ const durationInput = document.getElementById('id_duration');+ const unitSelect = document.getElementById('id_unit');++ function updatePreview() {+ let duration = parseInt(durationInput.value) || 60;+ const unitText = unitSelect.options[unitSelect.selectedIndex].text.toLowerCase();++ // Convert minutes to seconds for preview+ if (unitText.includes('minute')) {+ duration = duration * 60;+ }++ // Recreate timer with new duration+ previewContainer.innerHTML = '';+ previewTimer = new CountdownTimer(previewContainer, {+ duration: duration+ });+ }++ durationInput.addEventListener('change', updatePreview);+ durationInput.addEventListener('input', updatePreview);+ unitSelect.addEventListener('change', updatePreview);++ // Load days when routine changes+ const routineSelect = document.getElementById('id_routine');+ const daySelect = document.getElementById('id_day');++ routineSelect.addEventListener('change', function() {+ const routineId = this.value;+ daySelect.innerHTML = '<option value="">{% translate "Auto-select or create day" %}</option>';++ if (routineId) {+ fetch(`/en/routine/api/days/${routineId}/`)+ .then(response => response.json())+ .then(days => {+ days.forEach(day => {+ const option = document.createElement('option');+ option.value = day.id;+ option.textContent = day.name;+ daySelect.appendChild(option);+ });+ })+ .catch(err => console.log('Could not load days:', err));+ }+ });+});+</script>+{% endblock %}diff --git a/wger/manager/templates/timer_demo.html b/wger/manager/templates/timer_demo.htmlnew file mode 100644index 000000000..b53a5ff94--- /dev/null+++ b/wger/manager/templates/timer_demo.html@@ -0,0 +1,87 @@+{% extends "base.html" %}+{% load i18n static %}++{% block title %}Timer Demo{% endblock %}++{% block content %}+<div class="container py-4">+ <h1 class="mb-4">Countdown Timer Demo</h1>++ <div class="row">+ <!-- Timer Example 1: 60 seconds -->+ <div class="col-md-4 mb-4">+ <div class="card">+ <div class="card-header">+ <h5 class="mb-0">Plank - 60 Seconds</h5>+ </div>+ <div class="card-body">+ <div id="timer-60s" data-timer-duration="60" data-timer-unit-type="TIME"></div>+ </div>+ </div>+ </div>++ <!-- Timer Example 2: 30 seconds -->+ <div class="col-md-4 mb-4">+ <div class="card">+ <div class="card-header">+ <h5 class="mb-0">Wall Sit - 30 Seconds</h5>+ </div>+ <div class="card-body">+ <div id="timer-30s" data-timer-duration="30" data-timer-unit-type="TIME"></div>+ </div>+ </div>+ </div>++ <!-- Timer Example 3: 2 minutes -->+ <div class="col-md-4 mb-4">+ <div class="card">+ <div class="card-header">+ <h5 class="mb-0">Rest Period - 2 Minutes</h5>+ </div>+ <div class="card-body">+ <div id="timer-2m" data-timer-duration="120" data-timer-unit-type="TIME"></div>+ </div>+ </div>+ </div>+ </div>++ <hr class="my-4">++ <h2 class="mb-3">Manual Timer Creation</h2>+ <div class="row">+ <div class="col-md-6">+ <div class="card">+ <div class="card-header">+ <h5 class="mb-0">Custom Timer</h5>+ </div>+ <div class="card-body">+ <div class="mb-3">+ <label for="custom-duration" class="form-label">Duration (seconds):</label>+ <input type="number" id="custom-duration" class="form-control" value="45" min="1" max="3600">+ </div>+ <button id="create-timer-btn" class="btn btn-primary mb-3">Create Timer</button>+ <div id="custom-timer-container"></div>+ </div>+ </div>+ </div>+ </div>+</div>++<script>+document.addEventListener('DOMContentLoaded', function() {+ // Manual timer creation+ document.getElementById('create-timer-btn').addEventListener('click', function() {+ const duration = parseInt(document.getElementById('custom-duration').value, 10);+ const container = document.getElementById('custom-timer-container');+ container.innerHTML = ''; // Clear previous timer++ new CountdownTimer(container, {+ duration: duration,+ onComplete: function() {+ alert('Timer completed!');+ }+ });+ });+});+</script>+{% endblock %}diff --git a/wger/manager/urls.py b/wger/manager/urls.pyindex 111ff5d3a..93be35f4e 100644--- a/wger/manager/urls.py+++ b/wger/manager/urls.py@@ -25,6 +25,7 @@ from wger.manager.views import (ical,pdf,routine,+ timer,)@@ -129,4 +130,7 @@ urlpatterns = [path('', include((patterns_routine, 'routine'), namespace='routine')),path('templates/', include((patterns_templates, 'template'), namespace='template')),path('<int:routine_pk>/day/', include((patterns_days, 'day'), namespace='day')),+ path('timer-demo/', timer.timer_demo, name='timer-demo'),+ path('add-timed-exercise/', timer.add_timed_exercise, name='add-timed-exercise'),+ path('api/days/<int:routine_id>/', timer.get_days_for_routine, name='api-days'),]diff --git a/wger/manager/views/timer.py b/wger/manager/views/timer.pynew file mode 100644index 000000000..36f8b6678--- /dev/null+++ b/wger/manager/views/timer.py@@ -0,0 +1,120 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# Django+from django.contrib import messages+from django.contrib.auth.decorators import login_required+from django.http import JsonResponse+from django.shortcuts import (+ redirect,+ render,+)+from django.utils.translation import gettext as _++# wger+from wger.manager.forms import TimedExerciseForm+from wger.manager.models import (+ Day,+ RepetitionsConfig,+ Slot,+ SlotEntry,+)+++def timer_demo(request):+ """+ Demo page for the countdown timer component.+ This page showcases the timer functionality for timed exercises.+ """+ return render(request, 'timer_demo.html')+++@login_required+def add_timed_exercise(request):+ """+ Form page for adding a timed exercise to a routine.+ Allows users to select an exercise and set a duration in seconds or minutes.+ """+ if request.method == 'POST':+ form = TimedExerciseForm(request.user, request.POST)+ if form.is_valid():+ routine = form.cleaned_data['routine']+ day = form.cleaned_data['day']+ exercise = form.cleaned_data['exercise']+ duration = form.cleaned_data['duration']+ unit = form.cleaned_data['unit']++ # If no day selected, create one or use the first day+ if not day:+ day = routine.days.first()+ if not day:+ # Create a new day+ day = Day.objects.create(+ routine=routine,+ name=_('Timed Exercises'),+ order=1,+ )++ # Get or create a slot for this day+ slot = day.slots.first()+ if not slot:+ slot = Slot.objects.create(+ day=day,+ order=1,+ )++ # Create the slot entry with the time-based unit+ # exercise is a Translation object, we need the actual Exercise+ slot_entry = SlotEntry.objects.create(+ slot=slot,+ exercise=exercise.exercise, # Get the Exercise from Translation+ repetition_unit=unit,+ order=slot.entries.count() + 1,+ )++ # Create the repetitions config with the duration+ RepetitionsConfig.objects.create(+ slot_entry=slot_entry,+ iteration=1,+ value=duration,+ )++ messages.success(+ request,+ _('Timed exercise added: %(exercise)s for %(duration)s %(unit)s') % {+ 'exercise': exercise.name,+ 'duration': duration,+ 'unit': unit.name,+ }+ )++ return redirect('manager:routine:view', pk=routine.pk)+ else:+ form = TimedExerciseForm(request.user)++ return render(request, 'add_timed_exercise.html', {'form': form})+++@login_required+def get_days_for_routine(request, routine_id):+ """+ AJAX endpoint to get days for a specific routine.+ Used to dynamically populate the day dropdown when routine changes.+ """+ days = Day.objects.filter(routine_id=routine_id, routine__user=request.user)+ data = [{'id': day.id, 'name': day.name or f'Day {day.order}'} for day in days]+ return JsonResponse(data, safe=False)