Files
vitfit-r2/V2/app/public/workout-view.html
T
2026-06-30 10:15:18 -04:00

395 lines
16 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Workout — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<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>
</div>
<div id="workout-meta" class="card" style="margin-bottom:var(--space-6);"></div>
<div class="card">
<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']);
const params = new URLSearchParams(window.location.search);
const id = params.get('id');
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/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 {}
// 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;
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>
</body>
</html>