Continued rebuild

This commit is contained in:
Ccjcarkbla
2026-06-30 10:15:18 -04:00
parent 7d16b921f9
commit e192aecb2f
16 changed files with 620 additions and 194 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ app.use(helmet({
mediaSrc: ["'self'"],
connectSrc: ["'self'", "wss:"],
fontSrc: ["'self'"],
frameSrc: ["'none'"],
frameSrc: ["'self'"],
objectSrc: ["'none'"],
baseUri: ["'none'"],
formAction: ["'none'"],
+3 -1
View File
@@ -16,4 +16,6 @@ const createWorkout = z.object({
number4: z.number().int().min(0).nullable().optional(),
});
module.exports = { createWorkout };
const updateWorkout = createWorkout.partial();
module.exports = { createWorkout, updateWorkout };
+2 -1
View File
@@ -3,6 +3,7 @@
const express = require('express');
const multer = require('multer');
const path = require('path');
const os = require('os');
const fs = require('fs');
const { models } = require('../../core/db');
const { authenticateToken, authenticateRole } = require('../../core/auth');
@@ -17,7 +18,7 @@ router.prefix = 'org';
const OWNERS = ['Owner', 'SystemAdmin'];
const upload = multer({
dest: process.env.UPLOAD_TEMP_DIR || '/tmp/vitfit-uploads',
dest: process.env.UPLOAD_TEMP_DIR || os.tmpdir(),
limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB for logos
});
+4 -32
View File
@@ -7,20 +7,6 @@ const { log: auditLog } = require('../../core/audit');
const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads');
function contrastRatio(hex, bgHex = '#1a1a1a') {
const toLuminance = (h) => {
const r = parseInt(h.slice(1, 3), 16) / 255;
const g = parseInt(h.slice(3, 5), 16) / 255;
const b = parseInt(h.slice(5, 7), 16) / 255;
const chan = (c) => c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
return 0.2126 * chan(r) + 0.7152 * chan(g) + 0.0722 * chan(b);
};
const L1 = toLuminance(hex);
const L2 = toLuminance(bgHex);
const lighter = Math.max(L1, L2);
const darker = Math.min(L1, L2);
return (lighter + 0.05) / (darker + 0.05);
}
async function getOrg(models, orgId) {
const org = await models.Organization.findByPk(orgId);
@@ -50,22 +36,6 @@ async function getBranding(models, orgId) {
}
async function updateBranding(models, req, orgId, data) {
const colorFields = ['primaryColor', 'secondaryColor', 'workColor', 'restColor', 'moveColor', 'btnPrimaryBg', 'btnSecondaryBg'];
const failures = [];
for (const field of colorFields) {
if (data[field]) {
const ratio = contrastRatio(data[field]);
if (ratio < 4.5) {
failures.push({ field, color: data[field], ratio: ratio.toFixed(2) });
}
}
}
if (failures.length > 0) {
throw new AppError('VALIDATION_FAILED', `Colors fail minimum contrast ratio (4.5:1) against display background: ${failures.map(f => `${f.field} (${f.ratio}:1)`).join(', ')}`, 400);
}
const branding = await getBranding(models, orgId);
await branding.update(data);
await auditLog(req, 'branding.update', 'branding', branding.id, data);
@@ -85,11 +55,13 @@ async function uploadLogo(models, req, orgId, file) {
fs.closeSync(fd);
const result = await fileTypeFromBuffer(buf);
detectedMime = result?.mime;
} finally {
} catch {
await fs.promises.unlink(file.path).catch(() => {});
throw new AppError('UPLOAD_TYPE_INVALID', 'Could not read uploaded file.', 400);
}
if (!detectedMime || !ALLOWED.includes(detectedMime)) {
await fs.promises.unlink(file.path).catch(() => {});
throw new AppError('UPLOAD_TYPE_INVALID', 'Only PNG, JPG, GIF, and WebP images are supported.', 400);
}
@@ -112,4 +84,4 @@ async function uploadLogo(models, req, orgId, file) {
return branding;
}
module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo, contrastRatio };
module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo };
+2 -1
View File
@@ -3,6 +3,7 @@
const express = require('express');
const multer = require('multer');
const path = require('path');
const os = require('os');
const { models } = require('../../core/db');
const { authenticateToken, authenticateRole } = require('../../core/auth');
const { ok, created, collection, noContent } = require('../../core/respond');
@@ -17,7 +18,7 @@ router.prefix = 'videos';
const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin'];
const upload = multer({
dest: process.env.UPLOAD_TEMP_DIR || '/tmp/vitfit-uploads',
dest: process.env.UPLOAD_TEMP_DIR || os.tmpdir(),
limits: { fileSize: parseInt(process.env.UPLOAD_MAX_BYTES || '524288000', 10) },
});
+8 -1
View File
@@ -5,7 +5,7 @@ const { models } = require('../../core/db');
const { authenticateToken, authenticateRole } = require('../../core/auth');
const { ok, created, collection, noContent } = require('../../core/respond');
const { AppError } = require('../../core/errors');
const { createWorkout: createWorkoutSchema } = require('../../core/schemas/workouts');
const { createWorkout: createWorkoutSchema, updateWorkout: updateWorkoutSchema } = require('../../core/schemas/workouts');
const svc = require('./service');
const router = express.Router();
@@ -54,6 +54,13 @@ router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req,
} catch (err) { next(err); }
});
router.patch('/:id', authenticateToken, authenticateRole(COACH_PLUS), validate(updateWorkoutSchema), async (req, res, next) => {
try {
const workout = await svc.updateWorkout(models, req, parseInt(req.params.id, 10), req.user.organizationId, req.body);
ok(res, workout);
} catch (err) { next(err); }
});
router.delete('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
await svc.deleteWorkout(models, req, parseInt(req.params.id, 10), req.user.organizationId);
+23 -4
View File
@@ -50,9 +50,11 @@ async function getWorkoutById(models, id, orgId) {
async function getTodayWorkouts(models, orgId) {
const org = await models.Organization.findByPk(orgId, { attributes: ['timezone'] });
const tz = org?.timezone || 'UTC';
const now = DateTime.now().setZone(tz);
const start = now.startOf('day').toUTC().toJSDate();
const end = now.endOf('day').toUTC().toJSDate();
// workoutDate is stored as UTC midnight when submitted as a date string ("YYYY-MM-DD"),
// so we compare against the UTC date range matching today's local date.
const todayStr = DateTime.now().setZone(tz).toFormat('yyyy-MM-dd');
const start = new Date(`${todayStr}T00:00:00.000Z`);
const end = new Date(`${todayStr}T23:59:59.999Z`);
const rows = await models.Workout.findAll({
where: { organizationId: orgId, workoutDate: { [Op.between]: [start, end] } },
@@ -77,6 +79,23 @@ async function createWorkout(models, req, orgId, data) {
return getWorkoutById(models, workout.id, orgId);
}
async function updateWorkout(models, req, id, orgId, data) {
const workout = await models.Workout.findOne({ where: { id, organizationId: orgId } });
if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404);
for (const slot of [1, 2, 3, 4]) {
const vid = data[`video${slot}`];
if (vid) {
const exists = await models.Video.findOne({ where: { id: vid, organizationId: orgId } });
if (!exists) throw new AppError('VALIDATION_FAILED', `Video ${vid} not found in your library.`, 400, `video${slot}`);
}
}
await workout.update(data);
await auditLog(req, 'workout.update', 'workout', id, { name: workout.name });
return getWorkoutById(models, id, orgId);
}
async function deleteWorkout(models, req, id, orgId) {
const workout = await models.Workout.findOne({ where: { id, organizationId: orgId } });
if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404);
@@ -89,4 +108,4 @@ async function deleteWorkout(models, req, id, orgId) {
await workout.destroy();
}
module.exports = { getWorkouts, getWorkoutById, getTodayWorkouts, createWorkout, deleteWorkout };
module.exports = { getWorkouts, getWorkoutById, getTodayWorkouts, createWorkout, updateWorkout, deleteWorkout };
+160 -73
View File
@@ -8,6 +8,18 @@
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
<style>
.preview-grid { display:grid; gap:3px; background:#000; width:100%; height:100%; }
.preview-grid.panes-1 { grid-template-columns:1fr; grid-template-rows:1fr; }
.preview-grid.panes-2 { grid-template-columns:1fr 1fr; grid-template-rows:1fr; }
.preview-grid.panes-3,
.preview-grid.panes-4 { grid-template-columns:1fr 1fr; grid-template-rows:1fr 1fr; }
.preview-pane { position:relative; background:#111; overflow:hidden; min-height:0; }
.preview-pane video { width:100%; height:100%; object-fit:cover; display:block; }
.preview-pane-missing { width:100%; height:100%; display:flex; align-items:center; justify-content:center; color:rgba(255,255,255,0.3); font-size:14px; }
.preview-pane-corner { position:absolute; bottom:8px; right:12px; font-size:clamp(24px,5vw,72px); font-weight:900; color:#fff; text-shadow:0 2px 12px rgba(0,0,0,0.9); line-height:1; }
.preview-empty { display:flex; align-items:center; justify-content:center; height:100%; color:rgba(255,255,255,0.3); font-size:14px; }
</style>
</head>
<body>
<header class="banner">
@@ -19,57 +31,72 @@
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Create Workout</h1>
<a href="/workouts.html" class="btn btn-ghost">Back</a>
<div class="page-header" style="flex-direction:column;align-items:center;text-align:center;">
<h1 class="page-title" style="margin:0;">Create Workout</h1>
<div class="flex gap-3" style="margin-top:var(--space-3);">
<a href="/workouts.html" class="btn btn-ghost">Back</a>
<button class="btn btn-primary" id="save-btn">Save Workout</button>
</div>
</div>
<form id="workout-form" novalidate style="max-width:640px;">
<div class="card" style="margin-bottom:var(--space-6);">
<div class="form-group">
<label class="form-label" for="name">Workout Name <span class="required">*</span></label>
<!-- Meta -->
<div class="card" style="margin-bottom:var(--space-6);">
<div class="card-body" style="display:flex;flex-direction:column;gap:var(--space-4);">
<div class="form-group" style="margin:0;">
<label class="form-label">Workout Name <span class="required">*</span></label>
<input class="form-input" type="text" id="name" maxlength="120" required>
</div>
<div class="form-group">
<label class="form-label" for="workout-date">Date</label>
<div class="form-group" style="margin:0;">
<label class="form-label">Date</label>
<input class="form-input" type="date" id="workout-date">
</div>
<div class="form-group">
<label class="form-label" for="notes">Notes</label>
<textarea class="form-input" id="notes" rows="3" maxlength="2000"></textarea>
<div class="form-group" style="margin:0;">
<label class="form-label">Notes</label>
<textarea class="form-input" id="notes" rows="2" maxlength="2000"></textarea>
</div>
</div>
</div>
<div class="card" style="margin-bottom:var(--space-6);">
<div class="card-header">
<h2 class="card-title">Exercises <span id="slot-count" class="badge" style="font-size:var(--text-xs);margin-left:var(--space-2);">0 / 4</span></h2>
<button class="btn btn-secondary btn-sm" type="button" id="add-slot-btn">+ Add Exercise</button>
</div>
<div id="slots-list"></div>
<!-- Exercises -->
<div class="card" style="margin-bottom:var(--space-6);">
<div class="card-header">
<h2 class="card-title">Exercises</h2>
<button class="btn btn-secondary btn-sm" id="add-slot-btn">+ Add Exercise</button>
</div>
<div id="exercise-list">
<div class="empty-state"><p class="empty-state-text">No exercises yet. Add up to 4.</p></div>
</div>
<div id="form-error" class="form-error" style="display:none;margin-top:var(--space-4);"></div>
</div>
<div id="form-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="save-btn">Save Workout</button>
</form>
<!-- Video picker modal -->
<div class="modal-overlay" id="video-modal" style="display:none;">
<div class="modal modal-wide">
<div class="modal-header">
<h2 class="modal-title">Pick a Video</h2>
<button class="modal-close" id="modal-close">&times;</button>
<!-- TV Preview -->
<div class="card">
<h2 class="card-title" style="margin-bottom:var(--space-4);">TV Preview</h2>
<div style="position:relative;width:100%;padding-top:56.25%;background:#000;border-radius:var(--radius-md);overflow:hidden;">
<div id="preview-grid" class="preview-grid" style="position:absolute;inset:0;">
<div class="preview-empty">Add exercises to see preview</div>
</div>
<div style="padding:var(--space-4) var(--space-6) var(--space-3);display:flex;gap:var(--space-3);">
<input class="form-input" type="search" id="modal-search" placeholder="Search videos…" style="flex:1;">
<select class="form-select" id="modal-category" style="width:180px;">
<option value="">All Categories</option>
</select>
</div>
<div id="modal-video-list" class="modal-scroll modal-video-grid" style="padding:0 var(--space-6) var(--space-6);"></div>
</div>
</div>
</main>
<!-- Video picker modal -->
<div class="modal-overlay" id="video-modal" style="display:none;">
<div class="modal modal-wide">
<div class="modal-header">
<h2 class="modal-title">Pick a Video</h2>
<button class="modal-close" id="modal-close">&times;</button>
</div>
<div style="padding:var(--space-4) var(--space-6) var(--space-3);display:flex;gap:var(--space-3);">
<input class="form-input" type="search" id="modal-search" placeholder="Search videos…" style="flex:1;">
<select class="form-select" id="modal-category" style="width:180px;">
<option value="">All Categories</option>
</select>
</div>
<div id="modal-video-list" class="modal-scroll modal-video-grid" style="padding:0 var(--space-6) var(--space-6);"></div>
</div>
</div>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
@@ -77,33 +104,74 @@
<script src="/js/core.js"></script>
<script>
const MAX_SLOTS = 4;
let _slots = [];
let _pickingSlotIdx = null;
let _slots = []; // [{video: {id, description, streamUrl, fileExists}, reps: null}]
let _pickingIdx = null;
function esc(s) { return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function renderSlots() {
const el = document.getElementById('slots-list');
document.getElementById('slot-count').textContent = `${_slots.length} / ${MAX_SLOTS}`;
const el = document.getElementById('exercise-list');
document.getElementById('add-slot-btn').disabled = _slots.length >= MAX_SLOTS;
if (!_slots.length) {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No exercises yet. Add up to 4.</p></div>';
renderPreview();
return;
}
el.innerHTML = _slots.map((s, i) => `
<div class="slot-row" data-idx="${i}">
<div class="slot-pick" style="flex:1;">
${s.video
? `<span class="slot-video-name">${s.video.description}</span>
<button class="btn btn-ghost btn-sm" type="button" data-action="pick" data-idx="${i}" style="margin-left:var(--space-2);">Change</button>`
: `<button class="btn btn-ghost btn-sm" type="button" data-action="pick" data-idx="${i}">Pick Video</button>`}
</div>
<input class="form-input slot-reps" type="number" placeholder="#" min="1" value="${s.reps ?? i + 1}" data-action="reps" data-idx="${i}" style="width:64px;">
<button class="btn btn-danger btn-sm" type="button" data-action="remove" data-idx="${i}">✕</button>
</div>`).join('');
el.innerHTML = `<table class="table"><thead><tr><th>#</th><th>Exercise</th><th>Overlay #</th><th></th></tr></thead><tbody>
${_slots.map((s, i) => `<tr>
<td>${i + 1}</td>
<td>
<button class="btn btn-ghost btn-sm" data-action="pick" data-idx="${i}">
${s.video ? esc(s.video.description || 'Untitled') : 'Pick Video'}
</button>
</td>
<td>
<input class="form-input" type="number" min="0" placeholder="—" data-action="reps" data-idx="${i}" value="${s.reps ?? ''}" style="width:72px;">
</td>
<td class="table-actions">
${_slots.length > 1
? `<button class="btn btn-ghost btn-sm" data-action="remove" data-idx="${i}" style="color:var(--color-danger);">✕</button>`
: ''}
</td>
</tr>`).join('')}
</tbody></table>`;
renderPreview();
}
function renderPreview() {
const gridEl = document.getElementById('preview-grid');
const filled = _slots.filter(s => s.video);
const count = Math.min(filled.length, 4);
if (!count) {
gridEl.className = 'preview-grid';
gridEl.innerHTML = '<div class="preview-empty">Add exercises to see preview</div>';
return;
}
const jwt = Auth.getJwt();
const selectedOrg = Auth.getSelectedOrg();
const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : '';
gridEl.className = `preview-grid panes-${count}`;
gridEl.innerHTML = filled.slice(0, 4).map(s => {
const src = s.video.streamUrl
? `${s.video.streamUrl}?token=${encodeURIComponent(jwt)}${orgParam}`
: '';
return `<div class="preview-pane">
${src
? `<video src="${src}" preload="none" muted playsinline style="width:100%;height:100%;object-fit:cover;display:block;"></video>`
: `<div class="preview-pane-missing">Missing Video</div>`}
${s.reps != null ? `<div class="preview-pane-corner">${s.reps}</div>` : ''}
</div>`;
}).join('');
}
function openPicker(idx) {
_pickingSlotIdx = idx;
_pickingIdx = idx;
document.getElementById('modal-search').value = '';
document.getElementById('modal-category').value = '';
document.getElementById('video-modal').style.display = 'flex';
@@ -119,28 +187,28 @@
const jwt = Auth.getJwt();
const selectedOrg = Auth.getSelectedOrg();
const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : '';
const res = await Api.get('/api/v1/videos', { limit: 60, search: search || undefined, category: category || undefined });
const params = { limit: 60 };
if (search) params.search = search;
if (category) params.category = category;
const res = await Api.get('/api/v1/videos', params);
if (!res.ok) throw new Error();
const { data } = await res.json();
if (!data.length) {
el.innerHTML = '<p class="text-secondary" style="grid-column:1/-1;padding:var(--space-4);">No videos found.</p>';
return;
}
el.innerHTML = data.map(v => `
<div class="modal-video-card" data-video-id="${v.id}" data-video-desc="${(v.description || '').replace(/"/g, '&quot;')}">
<div class="modal-video-card" data-video-id="${v.id}" data-video-desc="${esc(v.description || '')}" data-stream-url="${esc(v.streamUrl || '')}" data-file-exists="${v.fileExists}">
<div class="modal-video-thumb">
${v.fileExists
? `<video preload="metadata" src="${v.streamUrl}?token=${encodeURIComponent(jwt)}${orgParam}" muted></video>`
: `<div class="video-missing-placeholder"><span>Missing</span></div>`}
</div>
<div class="modal-video-info">
<p class="modal-video-name">${v.description || 'Untitled'}</p>
${v.category ? `<span class="badge" style="font-size:10px;">${v.category}</span>` : ''}
<p class="modal-video-name">${esc(v.description || 'Untitled')}</p>
${v.category ? `<span class="badge" style="font-size:10px;">${esc(v.category)}</span>` : ''}
</div>
</div>`).join('');
el.querySelectorAll('video').forEach(vid => {
vid.addEventListener('error', () => {
vid.closest('.modal-video-thumb').innerHTML = '<div class="video-missing-placeholder"><span>Missing</span></div>';
@@ -153,9 +221,10 @@
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
renderSlots();
// Load categories for modal filter
document.getElementById('workout-date').value = new Date().toLocaleDateString('en-CA');
// Load categories
try {
const res = await Api.get('/api/v1/categories');
if (res.ok) {
@@ -169,13 +238,16 @@
}
} catch {}
// Add slot
document.getElementById('add-slot-btn').addEventListener('click', () => {
if (_slots.length >= MAX_SLOTS) return;
_slots.push({ video: null, reps: _slots.length + 1 });
_slots.push({ video: null, reps: null });
renderSlots();
openPicker(_slots.length - 1);
});
document.getElementById('slots-list').addEventListener('click', (e) => {
// Exercise list delegation
document.getElementById('exercise-list').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-action]');
if (!btn) return;
const idx = parseInt(btn.dataset.idx, 10);
@@ -183,20 +255,35 @@
if (btn.dataset.action === 'remove') { _slots.splice(idx, 1); renderSlots(); }
});
document.getElementById('slots-list').addEventListener('change', (e) => {
document.getElementById('exercise-list').addEventListener('input', (e) => {
const input = e.target.closest('input[data-action="reps"]');
if (input) { const idx = parseInt(input.dataset.idx, 10); _slots[idx].reps = input.value ? parseInt(input.value) : null; }
if (!input) return;
const idx = parseInt(input.dataset.idx, 10);
_slots[idx].reps = input.value !== '' ? parseInt(input.value, 10) : null;
renderPreview();
});
// Modal pick
document.getElementById('modal-video-list').addEventListener('click', (e) => {
const card = e.target.closest('[data-video-id]');
if (!card || _pickingSlotIdx === null) return;
_slots[_pickingSlotIdx].video = { id: parseInt(card.dataset.videoId, 10), description: card.dataset.videoDesc };
if (!card || _pickingIdx === null) return;
_slots[_pickingIdx].video = {
id: parseInt(card.dataset.videoId, 10),
description: card.dataset.videoDesc,
streamUrl: card.dataset.streamUrl,
fileExists: card.dataset.fileExists === 'true',
};
document.getElementById('video-modal').style.display = 'none';
renderSlots();
});
document.getElementById('modal-close').addEventListener('click', () => {
// If the new slot has no video picked, remove it
if (_pickingIdx !== null && !_slots[_pickingIdx]?.video) {
_slots.splice(_pickingIdx, 1);
renderSlots();
}
_pickingIdx = null;
document.getElementById('video-modal').style.display = 'none';
});
@@ -206,14 +293,14 @@
});
document.getElementById('modal-category').addEventListener('change', loadModalVideos);
document.getElementById('workout-form').addEventListener('submit', async (e) => {
e.preventDefault();
// Save
document.getElementById('save-btn').addEventListener('click', async () => {
const errEl = document.getElementById('form-error');
errEl.style.display = 'none';
const btn = document.getElementById('save-btn');
const name = document.getElementById('name').value.trim();
if (!name) { errEl.textContent = 'Name is required.'; errEl.style.display = 'block'; return; }
if (!name) { errEl.textContent = 'Workout name is required.'; errEl.style.display = 'block'; return; }
const payload = {
name,
@@ -221,20 +308,20 @@
notes: document.getElementById('notes').value.trim() || null,
};
// Map slots → video1..4 / number1..4
_slots.filter(s => s.video).slice(0, MAX_SLOTS).forEach((s, i) => {
payload[`video${i + 1}`] = s.video.id;
if (s.reps) payload[`number${i + 1}`] = s.reps;
if (s.reps != null) payload[`number${i + 1}`] = s.reps;
});
btn.disabled = true; btn.textContent = 'Saving…';
try {
const res = await Api.post('/api/v1/workouts', payload);
if (res.ok) {
const { data } = await res.json();
toast('Workout created!', 'success');
setTimeout(() => { window.location.href = '/workouts.html'; }, 1000);
setTimeout(() => { window.location.href = `/workout-view.html?id=${data.id}`; }, 800);
} else {
const b = await res.json();
const b = await res.json().catch(() => ({}));
errEl.textContent = b.message || 'Failed to save.'; errEl.style.display = 'block';
}
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
+61 -37
View File
@@ -22,12 +22,13 @@
</nav>
<main class="main-content">
<h1 class="page-title">Dashboard</h1>
<h1 class="page-title" style="text-align:center;">Dashboard</h1>
<!-- Today's Workout -->
<div id="today-workout" class="card" style="margin-bottom:var(--space-6);">
<div class="card-header">
<div class="card-header" style="flex-direction:column;align-items:center;gap:var(--space-1);text-align:center;">
<h2 class="card-title">Today's Workout</h2>
<a href="/workouts.html" class="btn btn-ghost btn-sm">View All</a>
<p id="today-date" class="card-meta" style="margin:0;"></p>
</div>
<div id="today-workout-body">
<div class="empty-state">
@@ -37,16 +38,21 @@
</div>
</div>
<div class="card">
<div class="card-header">
<h2 class="card-title">Quick Links</h2>
<!-- Stats row -->
<div class="card" style="padding:var(--space-3);">
<div style="display:flex;align-items:center;gap:var(--space-4);">
<div style="flex:1;display:flex;justify-content:space-between;align-items:center;gap:var(--space-3);">
<span style="font-weight:var(--weight-bold);white-space:nowrap;">Total Workouts</span>
<span id="total-workouts" style="font-size:var(--text-xl);font-weight:var(--weight-bold);">—</span>
<a href="/workouts.html" class="btn btn-ghost btn-sm" style="flex-shrink:0;">View All</a>
</div>
<div style="width:1px;align-self:stretch;background:var(--surface-border);"></div>
<div style="flex:1;display:flex;justify-content:space-between;align-items:center;gap:var(--space-3);">
<span style="font-weight:var(--weight-bold);white-space:nowrap;">Videos Uploaded</span>
<span id="total-videos" style="font-size:var(--text-xl);font-weight:var(--weight-bold);">—</span>
<a href="/videos.html" class="btn btn-ghost btn-sm" style="flex-shrink:0;">View All</a>
</div>
</div>
<ul class="quick-links">
<li><a href="/upload-video.html" class="btn btn-secondary btn-full">Upload Video</a></li>
<li><a href="/create-workout.html" class="btn btn-secondary btn-full">Create Workout</a></li>
<li><a href="/create-timer.html" class="btn btn-secondary btn-full">Create Timer</a></li>
<li><a href="/create-crossfit.html" class="btn btn-secondary btn-full">Create CrossFit WOD</a></li>
</ul>
</div>
</main>
@@ -62,32 +68,50 @@
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
// Load today's workouts
try {
const res = await Api.get('/api/v1/workouts/today');
if (res.ok) {
const { data } = await res.json();
if (data?.length) {
document.getElementById('today-workout-body').innerHTML = data.map(w => `
<div style="padding:var(--space-4) 0;border-bottom:1px solid var(--surface-border);">
<div style="display:flex;justify-content:space-between;align-items:center;gap:var(--space-3);">
<div>
<p style="font-weight:var(--weight-semibold);">${w.name}</p>
<p class="card-meta">${w.videos?.length ?? 0} exercise${w.videos?.length !== 1 ? 's' : ''}</p>
</div>
<div style="display:flex;gap:var(--space-2);flex-shrink:0;">
<a href="/workout-view.html?id=${w.id}" class="btn btn-ghost btn-sm">View</a>
<a href="/workout-display.html?id=${w.id}" class="btn btn-primary btn-sm" target="_blank">Display</a>
</div>
</div>
</div>`).join('') +
`<div style="padding-top:var(--space-3);">
<a href="/create-workout.html" class="btn btn-ghost btn-sm">+ Add Another</a>
</div>`;
}
}
} catch {}
// Display today's date
const today = new Date();
document.getElementById('today-date').textContent = today.toLocaleDateString(undefined, {
weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'
});
// Load today's workouts, workout count, and video count in parallel
const [todayRes, totalRes, videosRes] = await Promise.allSettled([
Api.get('/api/v1/workouts/today'),
Api.get('/api/v1/workouts', { page: 1, limit: 1 }),
Api.get('/api/v1/videos', { page: 1, limit: 1 }),
]);
if (todayRes.status === 'fulfilled' && todayRes.value.ok) {
const { data } = await todayRes.value.json();
if (data?.length) {
document.getElementById('today-workout-body').innerHTML = data.map(w => `
<div style="padding:var(--space-4) 0;border-bottom:1px solid var(--surface-border);">
<div style="display:flex;justify-content:space-between;align-items:center;gap:var(--space-3);">
<div>
<p style="font-weight:var(--weight-semibold);">${w.name}</p>
<p class="card-meta">${w.videos?.length ?? 0} exercise${w.videos?.length !== 1 ? 's' : ''}</p>
</div>
<div style="display:flex;gap:var(--space-2);flex-shrink:0;">
<a href="/workout-view.html?id=${w.id}" class="btn btn-ghost btn-sm">View</a>
<a href="/workout-display.html?id=${w.id}" class="btn btn-primary btn-sm" target="_blank">Display</a>
</div>
</div>
</div>`).join('') +
`<div style="padding-top:var(--space-3);">
<a href="/create-workout.html" class="btn btn-ghost btn-sm">+ Add Another</a>
</div>`;
}
}
if (totalRes.status === 'fulfilled' && totalRes.value.ok) {
const { meta } = await totalRes.value.json();
document.getElementById('total-workouts').textContent = meta?.total ?? 0;
}
if (videosRes.status === 'fulfilled' && videosRes.value.ok) {
const { meta } = await videosRes.value.json();
document.getElementById('total-videos').textContent = meta?.total ?? 0;
}
});
</script>
</body>
+4 -2
View File
@@ -20,16 +20,18 @@ const Display = (() => {
const selectedOrg = Auth.getSelectedOrg();
const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : '';
const isPreview = new URLSearchParams(window.location.search).get('preview') === '1';
gridEl.className = `display-video-grid panes-${count}`;
gridEl.innerHTML = slots.slice(0, 4).map(slot => {
const streamSrc = slot.video.streamUrl
const streamSrc = (!isPreview && slot.video.streamUrl)
? `${slot.video.streamUrl}?token=${encodeURIComponent(jwt || '')}${orgParam}`
: '';
return `
<div class="display-pane">
${streamSrc
? `<video class="display-pane-video" src="${streamSrc}" autoplay loop muted playsinline></video>`
: `<div class="display-pane-missing">Missing Video</div>`}
: `<div class="display-pane-missing">${isPreview ? (slot.video.description || 'Video') : 'Missing Video'}</div>`}
${slot.reps ? `<div class="display-pane-corner">${slot.reps}</div>` : ''}
</div>`;
}).join('');
+1 -1
View File
@@ -1,7 +1,7 @@
/* VitFit Service Worker — shell-only caching for PWA install */
'use strict';
const CACHE_NAME = 'vitfit-v11';
const CACHE_NAME = 'vitfit-v12';
const SHELL_ASSETS = [
'/',
'/index.html',
+1 -1
View File
@@ -19,7 +19,7 @@
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<div class="page-header" style="flex-direction:column;align-items:center;text-align:center;">
<h1 class="page-title">Videos</h1>
<a href="/upload-video.html" class="btn btn-primary">Upload Video</a>
</div>
+334 -38
View File
@@ -19,9 +19,10 @@
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title" id="workout-name">Workout</h1>
<div class="flex gap-3">
<div class="page-header" style="flex-direction:column;align-items:center;text-align:center;">
<div id="title-area"></div>
<div class="flex gap-3" style="margin-top:var(--space-3);">
<a href="/workouts.html" class="btn btn-ghost">Back</a>
<a id="display-link" href="#" class="btn btn-secondary" target="_blank">Display on TV</a>
<button id="delete-btn" class="btn btn-danger">Delete</button>
</div>
@@ -30,19 +31,219 @@
<div id="workout-meta" class="card" style="margin-bottom:var(--space-6);"></div>
<div class="card">
<h2 class="card-title" style="margin-bottom:var(--space-6);">Exercises</h2>
<div class="card-header">
<h2 class="card-title">Exercises</h2>
<button id="add-slot-btn" class="btn btn-secondary btn-sm" style="display:none;">+ Add Exercise</button>
</div>
<div id="exercise-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</div>
<div class="card" style="margin-top:var(--space-6);">
<h2 class="card-title" style="margin-bottom:var(--space-4);">TV Preview</h2>
<div style="position:relative;width:100%;padding-top:56.25%;background:#000;border-radius:var(--radius-md);overflow:hidden;">
<iframe id="display-preview" src="about:blank" style="position:absolute;inset:0;width:100%;height:100%;border:none;" allowfullscreen></iframe>
</div>
</div>
</main>
<!-- Video picker modal -->
<div class="modal-overlay" id="video-modal" style="display:none;">
<div class="modal modal-wide">
<div class="modal-header">
<h2 class="modal-title">Pick a Video</h2>
<button class="modal-close" id="modal-close">&times;</button>
</div>
<div style="padding:var(--space-4) var(--space-6) var(--space-3);display:flex;gap:var(--space-3);">
<input class="form-input" type="search" id="modal-search" placeholder="Search videos…" style="flex:1;">
<select class="form-select" id="modal-category" style="width:180px;">
<option value="">All Categories</option>
</select>
</div>
<div id="modal-video-list" class="modal-scroll modal-video-grid" style="padding:0 var(--space-6) var(--space-6);"></div>
</div>
</div>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _workout = null;
let _slots = []; // [{videoId, desc, pendingId, pendingDesc}]
let _editingIdx = null; // which slot row is in edit mode
let _pickingIdx = null; // which slot the modal is open for
let _metaEditing = false;
function esc(s) { return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function renderTitle() {
document.getElementById('title-area').innerHTML = `<h1 class="page-title" style="margin:0;">${esc(_workout.name)}</h1>`;
document.title = `${_workout.name} — VitFit`;
}
function renderMeta() {
const el = document.getElementById('workout-meta');
if (_metaEditing) {
el.innerHTML = `
<div class="card-body" style="display:flex;flex-direction:column;gap:var(--space-4);">
<div class="form-group" style="margin:0;">
<label class="form-label">Name</label>
<input class="form-input" id="meta-name" value="${esc(_workout.name)}">
</div>
<div class="form-group" style="margin:0;">
<label class="form-label">Date</label>
<input class="form-input" type="date" id="meta-date" value="${_workout.workoutDate ? _workout.workoutDate.slice(0,10) : ''}">
</div>
<div style="display:flex;gap:var(--space-3);">
<button class="btn btn-primary btn-sm" id="meta-save-btn">Save</button>
<button class="btn btn-ghost btn-sm" id="meta-cancel-btn">Cancel</button>
</div>
</div>`;
document.getElementById('meta-save-btn').addEventListener('click', saveMeta);
document.getElementById('meta-cancel-btn').addEventListener('click', () => { _metaEditing = false; renderMeta(); });
} else {
const dateStr = _workout.workoutDate
? new Date(_workout.workoutDate).toLocaleDateString()
: 'No date set';
el.innerHTML = `
<div class="card-body flex gap-6 flex-wrap" style="align-items:center;">
<span><strong>Date:</strong> ${dateStr}</span>
<span><strong>Exercises:</strong> ${_slots.length}</span>
<button class="btn btn-ghost btn-sm" id="meta-edit-btn" style="margin-left:auto;">Edit Info</button>
</div>`;
document.getElementById('meta-edit-btn').addEventListener('click', () => { _metaEditing = true; renderMeta(); });
}
}
function renderSlots() {
const el = document.getElementById('exercise-list');
const addBtn = document.getElementById('add-slot-btn');
addBtn.style.display = _slots.length < 4 ? '' : 'none';
if (!_slots.length) {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No exercises. Add one above.</p></div>';
return;
}
el.innerHTML = `<table class="table"><thead><tr><th>#</th><th>Exercise</th><th>Overlay #</th><th></th></tr></thead><tbody>
${_slots.map((s, i) => {
const inEdit = _editingIdx === i;
const hasPending = s.pendingId != null;
const displayDesc = hasPending ? s.pendingDesc : (s.desc || '—');
return `<tr>
<td>${i + 1}</td>
<td>
${inEdit
? `<button class="btn btn-ghost btn-sm" data-action="change-slot" data-idx="${i}">${esc(displayDesc)}</button>`
: esc(displayDesc)}
</td>
<td>
${inEdit
? `<input class="form-input" type="number" min="0" placeholder="—" data-action="reps-slot" data-idx="${i}" value="${s.reps ?? ''}" style="width:72px;">`
: (s.reps != null ? s.reps : '—')}
</td>
<td class="table-actions">
${inEdit
? `<button class="btn btn-primary btn-sm" data-action="save-slot" data-idx="${i}">Save</button>
<button class="btn btn-ghost btn-sm" data-action="cancel-slot" data-idx="${i}">Cancel</button>`
: `<button class="btn btn-ghost btn-sm" data-action="edit-slot" data-idx="${i}">Edit</button>`}
${_slots.length > 1 && !inEdit
? `<button class="btn btn-ghost btn-sm" data-action="remove-slot" data-idx="${i}" style="color:var(--color-danger);">✕</button>`
: ''}
</td>
</tr>`;
}).join('')}
</tbody></table>`;
}
async function saveMeta() {
const name = document.getElementById('meta-name').value.trim();
if (!name) { toast('Name is required.', 'error'); return; }
const workoutDate = document.getElementById('meta-date').value || null;
const res = await Api.patch(`/api/v1/workouts/${_workout.id}`, { name, workoutDate });
if (res.ok) {
const { data } = await res.json();
_workout = data;
_metaEditing = false;
renderTitle();
renderMeta();
toast('Saved.', 'success');
} else {
const b = await res.json().catch(() => ({}));
toast(b.message || 'Failed.', 'error');
}
}
async function patchSlots() {
const body = {};
[0, 1, 2, 3].forEach(i => {
body[`video${i + 1}`] = _slots[i]?.videoId ?? null;
body[`number${i + 1}`] = _slots[i]?.reps ?? null;
});
const res = await Api.patch(`/api/v1/workouts/${_workout.id}`, body);
if (res.ok) {
const { data } = await res.json();
_workout = data;
document.getElementById('display-preview').src = `/workout-display.html?id=${_workout.id}&preview=1`;
toast('Saved.', 'success');
} else {
const b = await res.json().catch(() => ({}));
toast(b.message || 'Failed.', 'error');
}
}
function openPicker(idx) {
_pickingIdx = idx;
document.getElementById('modal-search').value = '';
document.getElementById('modal-category').value = '';
document.getElementById('video-modal').style.display = 'flex';
loadModalVideos();
}
async function loadModalVideos() {
const el = document.getElementById('modal-video-list');
const search = document.getElementById('modal-search').value.trim();
const category = document.getElementById('modal-category').value;
el.innerHTML = '<p class="text-secondary" style="grid-column:1/-1;padding:var(--space-4);">Loading…</p>';
try {
const jwt = Auth.getJwt();
const selectedOrg = Auth.getSelectedOrg();
const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : '';
const params = { limit: 60 };
if (search) params.search = search;
if (category) params.category = category;
const res = await Api.get('/api/v1/videos', params);
if (!res.ok) throw new Error();
const { data } = await res.json();
if (!data.length) {
el.innerHTML = '<p class="text-secondary" style="grid-column:1/-1;padding:var(--space-4);">No videos found.</p>';
return;
}
el.innerHTML = data.map(v => `
<div class="modal-video-card" data-video-id="${v.id}" data-video-desc="${esc(v.description || '')}">
<div class="modal-video-thumb">
${v.fileExists
? `<video preload="metadata" src="${v.streamUrl}?token=${encodeURIComponent(jwt)}${orgParam}" muted></video>`
: `<div class="video-missing-placeholder"><span>Missing</span></div>`}
</div>
<div class="modal-video-info">
<p class="modal-video-name">${esc(v.description || 'Untitled')}</p>
${v.category ? `<span class="badge" style="font-size:10px;">${esc(v.category)}</span>` : ''}
</div>
</div>`).join('');
el.querySelectorAll('video').forEach(vid => {
vid.addEventListener('error', () => {
vid.closest('.modal-video-thumb').innerHTML = '<div class="video-missing-placeholder"><span>Missing</span></div>';
});
});
} catch {
el.innerHTML = '<p class="text-secondary" style="grid-column:1/-1;padding:var(--space-4);">Failed to load videos.</p>';
}
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
@@ -51,46 +252,141 @@
if (!id) { window.location.href = '/workouts.html'; return; }
document.getElementById('display-link').href = `/workout-display.html?id=${id}`;
document.getElementById('display-preview').src = `/workout-display.html?id=${id}&preview=1`;
const workoutRes = await Api.get(`/api/v1/workouts/${id}`);
if (!workoutRes.ok) { window.location.href = '/workouts.html'; return; }
const { data: w } = await workoutRes.json();
_workout = w;
_slots = (w.videos || []).filter(s => s.video).map(s => ({
videoId: s.video.id,
desc: s.video.description || '',
reps: s.reps ?? null,
pendingId: null,
pendingDesc: null,
}));
renderTitle();
renderMeta();
renderSlots();
// Load categories for modal filter
try {
const res = await Api.get(`/api/v1/workouts/${id}`);
if (!res.ok) { window.location.href = '/workouts.html'; return; }
const { data: w } = await res.json();
document.getElementById('workout-name').textContent = w.name;
document.title = `${w.name} — VitFit`;
document.getElementById('workout-meta').innerHTML = `
<div class="card-body flex gap-6 flex-wrap">
${w.workoutDate ? `<span><strong>Date:</strong> ${new Date(w.workoutDate).toLocaleDateString()}</span>` : ''}
<span><strong>Exercises:</strong> ${w.videos?.length ?? 0}</span>
${w.notes ? `<p class="text-secondary mt-2" style="width:100%;">${w.notes}</p>` : ''}
</div>`;
const listEl = document.getElementById('exercise-list');
if (!w.videos?.length) {
listEl.innerHTML = '<div class="empty-state"><p class="empty-state-text">No exercises.</p></div>';
} else {
listEl.innerHTML = `<table class="table"><thead><tr><th>#</th><th>Exercise</th><th>Reps</th><th>Sets</th></tr></thead><tbody>
${w.videos.map((s, i) => `<tr>
<td>${i + 1}</td>
<td>${s.video?.description || '—'}</td>
<td>${s.reps ?? '—'}</td>
<td>${s.sets ?? '—'}</td>
</tr>`).join('')}
</tbody></table>`;
const res = await Api.get('/api/v1/categories');
if (res.ok) {
const { data } = await res.json();
const sel = document.getElementById('modal-category');
data.forEach(c => {
const opt = document.createElement('option');
opt.value = c.name; opt.textContent = c.name;
sel.appendChild(opt);
});
}
} catch {
document.getElementById('workout-meta').innerHTML = '<p class="text-secondary">Failed to load workout.</p>';
}
} catch {}
// Add slot
document.getElementById('add-slot-btn').addEventListener('click', () => {
if (_slots.length >= 4) return;
_slots.push({ videoId: null, desc: '', reps: null, pendingId: null, pendingDesc: null });
_editingIdx = _slots.length - 1;
renderSlots();
openPicker(_editingIdx);
});
// Exercise list delegation
document.getElementById('exercise-list').addEventListener('click', async (e) => {
const btn = e.target.closest('button[data-action]');
if (!btn) return;
const idx = parseInt(btn.dataset.idx, 10);
const action = btn.dataset.action;
if (action === 'edit-slot') {
_editingIdx = idx;
renderSlots();
openPicker(idx);
}
if (action === 'change-slot') {
openPicker(idx);
}
if (action === 'cancel-slot') {
// If it was a newly added empty slot, remove it
if (!_slots[idx].videoId) _slots.splice(idx, 1);
else { _slots[idx].pendingId = null; _slots[idx].pendingDesc = null; }
_editingIdx = null;
renderSlots();
}
if (action === 'save-slot') {
const s = _slots[idx];
if (s.pendingId != null) {
s.videoId = s.pendingId;
s.desc = s.pendingDesc;
s.pendingId = null;
s.pendingDesc = null;
} else if (!s.videoId) {
toast('Pick a video first.', 'error');
return;
}
_editingIdx = null;
renderSlots();
await patchSlots();
}
if (action === 'remove-slot') {
if (_slots.length <= 1) return;
_slots.splice(idx, 1);
_editingIdx = null;
renderSlots();
await patchSlots();
}
});
document.getElementById('exercise-list').addEventListener('input', (e) => {
const input = e.target.closest('input[data-action="reps-slot"]');
if (!input) return;
const idx = parseInt(input.dataset.idx, 10);
_slots[idx].reps = input.value !== '' ? parseInt(input.value, 10) : null;
});
// Modal pick
document.getElementById('modal-video-list').addEventListener('click', (e) => {
const card = e.target.closest('[data-video-id]');
if (!card || _pickingIdx === null) return;
_slots[_pickingIdx].pendingId = parseInt(card.dataset.videoId, 10);
_slots[_pickingIdx].pendingDesc = card.dataset.videoDesc;
document.getElementById('video-modal').style.display = 'none';
renderSlots();
});
document.getElementById('modal-close').addEventListener('click', () => {
// If we opened picker for a brand-new empty slot and nothing was picked, remove it
if (_pickingIdx !== null) {
const s = _slots[_pickingIdx];
if (!s.videoId && s.pendingId == null) {
_slots.splice(_pickingIdx, 1);
_editingIdx = null;
renderSlots();
}
}
_pickingIdx = null;
document.getElementById('video-modal').style.display = 'none';
});
let debounce;
document.getElementById('modal-search').addEventListener('input', () => {
clearTimeout(debounce); debounce = setTimeout(loadModalVideos, 300);
});
document.getElementById('modal-category').addEventListener('change', loadModalVideos);
// Delete
document.getElementById('delete-btn').addEventListener('click', async () => {
if (!confirm('Delete this workout?')) return;
try {
const res = await Api.del(`/api/v1/workouts/${id}`);
if (res.ok) { toast('Workout deleted.', 'success'); setTimeout(() => window.location.href = '/workouts.html', 800); }
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
const res = await Api.del(`/api/v1/workouts/${id}`);
if (res.ok) { toast('Workout deleted.', 'success'); setTimeout(() => window.location.href = '/workouts.html', 800); }
else { const b = await res.json().catch(() => ({})); toast(b.message || 'Failed.', 'error'); }
});
});
</script>
+16 -1
View File
@@ -19,7 +19,7 @@
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<div class="page-header" style="flex-direction:column;align-items:center;text-align:center;">
<h1 class="page-title">Workouts</h1>
<a href="/create-workout.html" class="btn btn-primary">Create Workout</a>
</div>
@@ -43,6 +43,16 @@
<script>
let _page = 1, _search = '';
async function deleteWorkout(id, name) {
if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
const res = await Api.del(`/api/v1/workouts/${id}`);
if (res.ok) {
loadWorkouts();
} else {
alert('Failed to delete workout.');
}
}
async function loadWorkouts() {
const el = document.getElementById('workout-list');
try {
@@ -59,10 +69,15 @@
<td class="table-actions">
<a href="/workout-view.html?id=${w.id}" class="btn btn-ghost btn-sm">View</a>
<a href="/workout-display.html?id=${w.id}" class="btn btn-ghost btn-sm" target="_blank">Display</a>
<button class="btn btn-ghost btn-sm" data-action="delete" data-id="${w.id}" data-name="${w.name.replace(/"/g, '&quot;')}">Delete</button>
</td>
</tr>`).join('')}
</tbody></table>`;
el.querySelectorAll('button[data-action="delete"]').forEach(btn => {
btn.addEventListener('click', () => deleteWorkout(parseInt(btn.dataset.id, 10), btn.dataset.name));
});
renderPagination(meta);
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading workouts.</p></div>';
Binary file not shown.
Binary file not shown.