HIMANEESH123 commited on
Commit
6c4c19e
Β·
verified Β·
1 Parent(s): 7981f95

Update static/app.js

Browse files
Files changed (1) hide show
  1. static/app.js +481 -119
static/app.js CHANGED
@@ -1,21 +1,21 @@
1
  'use strict';
2
 
3
- // ═══════════════════════════════════════════════════════════════
4
  // YOGAMATE - Premium AI Yoga Assistant
5
- // ═══════════════════════════════════════════════════════════════
6
 
7
  // ─── Configuration ───
8
  const CONFIG = {
9
  API_BASE: '',
10
- DEFAULT_INTERVAL: 300, // reduced from 150 to lower load
11
- CAMERA_WIDTH: 256, // smaller frames
12
  CAMERA_HEIGHT: 192,
13
- SNAPSHOT_QUALITY: 0.3, // lower JPEG quality
14
  REQUIRED_IMAGES: 5,
15
  HISTORY_LIMIT: 50,
16
  SCORE_HISTORY_LIMIT: 5,
17
- SCORE_BUFFER_SIZE: 5, // smoothing
18
- IDLE_THRESHOLD: 3, // frames before pausing
19
  };
20
 
21
  // ─── State ───
@@ -50,20 +50,90 @@ const STATE = {
50
  isGenerating: false,
51
  searchQuery: '',
52
  floatingSaveBtn: null,
53
- scoreBuffer: [], // for smoothing
54
  idleFrames: 0,
55
  referenceImage: null,
56
  };
57
 
58
- // ─── DOM Helpers (keep your existing el(), $$()) ───
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- // ─── Toast (keep existing) ───
 
 
 
 
 
 
 
 
61
 
62
- // ─── Theme (keep existing) ───
 
 
 
63
 
64
- // ═══════════════════════════════════════════════════════════════
65
  // AUTH
66
- // ═══════════════════════════════════════════════════════════════
67
  async function getCurrentUser() {
68
  try {
69
  const res = await fetch('/api/current-user', { credentials: 'include' });
@@ -96,10 +166,7 @@ async function registerUser(username, password) {
96
  }
97
 
98
  async function logoutUser() {
99
- await fetch('/api/logout', {
100
- method: 'POST',
101
- credentials: 'include'
102
- });
103
  }
104
 
105
  function showAuthModal() {
@@ -204,9 +271,9 @@ function setupAuthForms() {
204
  });
205
  }
206
 
207
- // ��══════════════════════════════════════════════════════════════
208
  // API
209
- // ═══════════════════════════════════════════════════════════════
210
  async function apiRequest(endpoint, options = {}) {
211
  options.credentials = 'include';
212
  const res = await fetch(`${CONFIG.API_BASE}${endpoint}`, options);
@@ -217,7 +284,6 @@ async function apiRequest(endpoint, options = {}) {
217
  return data;
218
  }
219
 
220
- // ─── Load all app data (poses, history, etc.) ───
221
  async function loadAppData() {
222
  await fetchPoses();
223
  renderHistory();
@@ -225,7 +291,9 @@ async function loadAppData() {
225
  renderFavorites();
226
  }
227
 
228
- // ─── Fetch Poses (with auth) ───
 
 
229
  async function fetchPoses() {
230
  try {
231
  const poses = await apiRequest('/api/poses');
@@ -242,20 +310,83 @@ async function fetchPoses() {
242
  }
243
  }
244
 
245
- // ═══════════════════════════════════════════════════════════════
246
- // CAMERA & LIVE ANALYSIS (Optimised)
247
- // ═══════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
249
  async function startCamera() {
250
  if (!STATE.selectedPose) {
251
  showToast('Please select a pose first');
252
  return;
253
  }
254
-
255
  try {
256
  STATE.cameraStream = await navigator.mediaDevices.getUserMedia({
257
  video: {
258
- width: { ideal: CONFIG.CAMERA_WIDTH * 2 }, // feed higher res to camera, we'll resize later
259
  height: { ideal: CONFIG.CAMERA_HEIGHT * 2 },
260
  facingMode: 'user',
261
  },
@@ -265,17 +396,16 @@ async function startCamera() {
265
  showToast('Camera access denied.', 'error');
266
  return;
267
  }
268
-
269
  const video = document.getElementById('webcam-video');
270
  const canvas = document.getElementById('webcam-canvas');
271
  if (!video || !canvas) return;
272
-
273
  video.srcObject = STATE.cameraStream;
274
  video.onloadedmetadata = () => {
275
  video.play();
276
  canvas.width = CONFIG.CAMERA_WIDTH;
277
  canvas.height = CONFIG.CAMERA_HEIGHT;
278
-
279
  document.getElementById('camera-off-overlay').classList.add('hidden');
280
  document.getElementById('score-overlay').classList.remove('hidden');
281
  document.getElementById('live-badge').classList.remove('hidden');
@@ -284,91 +414,194 @@ async function startCamera() {
284
  document.getElementById('snapshot-btn').classList.remove('hidden');
285
  document.getElementById('result-card').classList.remove('hidden');
286
  document.getElementById('suggestions-panel').classList.remove('hidden');
287
-
288
  STATE.sessionStartTime = Date.now();
289
  STATE.sessionScores = [];
290
  STATE.scoreBuffer = [];
291
  STATE.idleFrames = 0;
292
-
293
  if (STATE.animationFrameId) cancelAnimationFrame(STATE.animationFrameId);
294
  renderLoop();
295
  sendFrameToServer();
296
  STATE.liveLoopTimer = setInterval(sendFrameToServer, STATE.liveInterval);
297
-
298
  showToast('Camera started! πŸŽ₯');
299
  };
300
  }
301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  // ─── Optimised sendFrame ───
303
  async function sendFrameToServer() {
304
  if (!STATE.cameraStream || STATE.isAnalysing || !STATE.selectedPose) return;
305
  STATE.isAnalysing = true;
306
-
307
  const video = document.getElementById('webcam-video');
308
  const canvas = document.getElementById('webcam-canvas');
309
  if (!video || !canvas) { STATE.isAnalysing = false; return; }
310
-
311
- // Draw the current video frame onto the canvas (already at CONFIG size)
312
  const ctx = canvas.getContext('2d');
313
  ctx.clearRect(0, 0, canvas.width, canvas.height);
314
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
315
-
316
- // Resize to smaller image for transmission (use a temp canvas)
317
  const tempCanvas = document.createElement('canvas');
318
  tempCanvas.width = CONFIG.CAMERA_WIDTH;
319
  tempCanvas.height = CONFIG.CAMERA_HEIGHT;
320
  const tempCtx = tempCanvas.getContext('2d');
321
  tempCtx.drawImage(canvas, 0, 0, tempCanvas.width, tempCanvas.height);
322
  const b64 = tempCanvas.toDataURL('image/jpeg', CONFIG.SNAPSHOT_QUALITY);
323
-
324
  try {
325
  const data = await apiRequest('/api/live', {
326
  method: 'POST',
327
  headers: { 'Content-Type': 'application/json' },
328
  body: JSON.stringify({ image: b64, pose_id: STATE.selectedPose.id }),
329
  });
330
-
331
  if (data.error) {
332
  console.warn('[Live]', data.error);
333
  STATE.isAnalysing = false;
334
  return;
335
  }
336
-
337
  // Idle detection
338
  if (!data.landmarks || data.landmarks.length === 0) {
339
  STATE.idleFrames++;
340
  if (STATE.idleFrames >= CONFIG.IDLE_THRESHOLD) {
341
- // Show idle message if needed
342
  STATE.isAnalysing = false;
343
  return;
344
  }
345
  } else {
346
  STATE.idleFrames = 0;
347
  }
348
-
349
  if (data.landmarks && data.landmarks.length > 0) {
350
  STATE.currentLandmarks = data.landmarks;
351
  }
352
-
353
  if (data.score !== undefined) {
354
- // Smooth score
355
  STATE.scoreBuffer.push(data.score);
356
  if (STATE.scoreBuffer.length > CONFIG.SCORE_BUFFER_SIZE) STATE.scoreBuffer.shift();
357
  const smoothedScore = Math.round(
358
  STATE.scoreBuffer.reduce((a, b) => a + b, 0) / STATE.scoreBuffer.length
359
  );
360
-
361
  STATE.currentScore = smoothedScore;
362
  STATE.currentStatus = data.status || '';
363
  STATE.currentSuggestions = data.suggestions || [];
364
-
365
- // Also store raw for history
366
  STATE.sessionScores.push(smoothedScore);
367
  STATE.scoreHistory.push(smoothedScore);
368
  if (STATE.scoreHistory.length > CONFIG.SCORE_HISTORY_LIMIT) STATE.scoreHistory.shift();
369
-
370
  updateLiveUI(smoothedScore, STATE.currentStatus, STATE.currentSuggestions);
371
-
372
  if (STATE.isFullscreen) {
373
  updateFullscreenSuggestions(STATE.currentSuggestions, smoothedScore);
374
  }
@@ -380,32 +613,31 @@ async function sendFrameToServer() {
380
  }
381
  }
382
 
383
- // ─── Update Live UI (with score ring) ───
384
  function updateLiveUI(score, status, suggestions) {
385
- // Update score ring
386
  const ring = document.getElementById('score-ring');
387
  const text = document.getElementById('score-text');
388
  if (ring && text) {
389
- const circumference = 2 * Math.PI * 32; // ~201
390
  const offset = circumference - (score / 100) * circumference;
391
  ring.style.strokeDashoffset = offset;
392
  const colour = score >= 80 ? '#22C55E' : score >= 65 ? '#F59E0B' : '#EF4444';
393
  ring.style.stroke = colour;
394
  text.textContent = `${score}%`;
395
  }
396
-
397
- // Update overlay
398
  const overlayScore = document.getElementById('overlay-score');
399
  const overlayStatus = document.getElementById('overlay-status');
400
  if (overlayScore) overlayScore.textContent = `${score}%`;
401
  if (overlayStatus) overlayStatus.textContent = status || '–';
402
-
403
- // Update result card
404
  const badge = document.getElementById('result-badge');
405
  const scoreVal = document.getElementById('score-value');
406
  const barFill = document.getElementById('score-bar-fill');
407
  const suggList = document.getElementById('suggestions-list');
408
-
409
  if (scoreVal) {
410
  scoreVal.textContent = `${score}%`;
411
  const colour = score >= 80 ? '#22C55E' : score >= 65 ? '#F59E0B' : '#EF4444';
@@ -416,76 +648,79 @@ function updateLiveUI(score, status, suggestions) {
416
  barFill.style.width = `${score}%`;
417
  barFill.style.background = colour;
418
  }
419
-
420
  let level, badgeClass;
421
  if (score >= 80) { level = 'Excellent'; badgeClass = 'badge-excellent'; }
422
  else if (score >= 65) { level = 'Good'; badgeClass = 'badge-good'; }
423
  else { level = 'Needs Correction'; badgeClass = 'badge-correction'; }
424
  if (badge) { badge.textContent = level; badge.className = `result-badge ${badgeClass}`; }
425
-
426
  let displaySugg = suggestions || [];
427
  if (displaySugg.length === 0) {
428
  if (score >= 80) displaySugg = ['🌟 Excellent posture!', 'Keep breathing deeply'];
429
  else if (score >= 65) displaySugg = ['Almost there!', 'Small adjustments needed'];
430
  else displaySugg = ['Focus on alignment', 'Practice this pose more'];
431
  }
432
-
433
  if (suggList) {
434
  const colour = score >= 80 ? '#22C55E' : score >= 65 ? '#F59E0B' : '#EF4444';
435
  suggList.innerHTML = displaySugg.slice(0, 4).map(s => `
436
- <li>
437
- <span class="suggestion-dot" style="background:${colour};"></span>
438
- ${s}
439
- </li>
440
  `).join('');
441
  }
442
-
443
- // Update suggestions panel
444
  updateSuggestionsPanel(displaySugg, score);
445
  }
446
 
447
- // ─── Draw skeleton with color coding ───
448
- function drawSkeleton(ctx, landmarks, width, height, mirror) {
449
- if (!landmarks || landmarks.length === 0) return;
450
-
451
- let colour;
452
- if (STATE.currentScore >= 80) colour = '#22C55E';
453
- else if (STATE.currentScore >= 65) colour = '#F59E0B';
454
- else colour = '#EF4444';
455
-
456
- const connections = [
457
- [11, 12], [11, 13], [13, 15], [12, 14], [14, 16],
458
- [11, 23], [12, 24], [23, 24], [23, 25], [25, 27],
459
- [24, 26], [26, 28], [11, 0], [12, 0]
460
- ];
461
-
462
- ctx.lineWidth = 2.5;
463
- ctx.strokeStyle = colour;
464
-
465
- connections.forEach(([i, j]) => {
466
- if (i < landmarks.length && j < landmarks.length) {
467
- let x1 = landmarks[i][0] * width;
468
- let y1 = landmarks[i][1] * height;
469
- let x2 = landmarks[j][0] * width;
470
- let y2 = landmarks[j][1] * height;
471
- if (mirror) { x1 = width - x1; x2 = width - x2; }
472
- ctx.beginPath();
473
- ctx.moveTo(x1, y1);
474
- ctx.lineTo(x2, y2);
475
- ctx.stroke();
476
- }
477
- });
478
-
479
- landmarks.forEach((lm, index) => {
480
- let x = lm[0] * width;
481
- let y = lm[1] * height;
482
- if (mirror) x = width - x;
483
- const radius = [11,12,13,14,15,16,23,24,25,26,27,28].includes(index) ? 5 : 3;
484
- ctx.beginPath();
485
- ctx.arc(x, y, radius, 0, 2 * Math.PI);
486
- ctx.fillStyle = colour;
487
- ctx.fill();
488
- });
 
 
 
 
 
 
 
 
489
  }
490
 
491
  // ─── Reference overlay ───
@@ -503,20 +738,147 @@ async function loadReferenceImage(poseId) {
503
  } catch(e) { /* ignore */ }
504
  }
505
 
506
- // ─── Override openPractice to load reference ───
507
  function openPractice(poseId) {
508
- // ... existing openPractice code ...
509
- // After setting the pose, call:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  loadReferenceImage(poseId);
511
- // ... rest ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  }
513
 
514
- // ═══════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  // INIT
516
- // ═══════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
  document.addEventListener('DOMContentLoaded', async () => {
518
  setupAuthForms();
519
-
520
  const username = await getCurrentUser();
521
  if (username) {
522
  hideAuthModal();
@@ -524,19 +886,19 @@ document.addEventListener('DOMContentLoaded', async () => {
524
  await loadAppData();
525
  } else {
526
  showAuthModal();
527
- // Still load read‑only content (guest)
528
- await fetchPoses(); // will use guest fallback
529
  renderPoseGrid();
530
  renderFavorites();
531
  }
532
-
533
  setupSearch();
534
  setupNav();
535
  setupKeyboardShortcuts();
536
  console.log('[YogaMate] Initialized successfully 🧘');
537
  });
538
 
539
- // ─── Expose global functions ───
540
  window.startCamera = startCamera;
541
  window.stopCamera = stopCamera;
542
  window.takeSnapshot = takeSnapshot;
 
1
  'use strict';
2
 
3
+ // =================================================================
4
  // YOGAMATE - Premium AI Yoga Assistant
5
+ // =================================================================
6
 
7
  // ─── Configuration ───
8
  const CONFIG = {
9
  API_BASE: '',
10
+ DEFAULT_INTERVAL: 300, // reduced from 150
11
+ CAMERA_WIDTH: 256, // smaller
12
  CAMERA_HEIGHT: 192,
13
+ SNAPSHOT_QUALITY: 0.3,
14
  REQUIRED_IMAGES: 5,
15
  HISTORY_LIMIT: 50,
16
  SCORE_HISTORY_LIMIT: 5,
17
+ SCORE_BUFFER_SIZE: 5,
18
+ IDLE_THRESHOLD: 3,
19
  };
20
 
21
  // ─── State ───
 
50
  isGenerating: false,
51
  searchQuery: '',
52
  floatingSaveBtn: null,
53
+ scoreBuffer: [],
54
  idleFrames: 0,
55
  referenceImage: null,
56
  };
57
 
58
+ // ─── DOM Helpers ───
59
+ function el(id) {
60
+ const elem = document.getElementById(id);
61
+ if (!elem) {
62
+ return {
63
+ classList: { add: () => {}, remove: () => {}, toggle: () => {} },
64
+ style: {},
65
+ textContent: '',
66
+ innerHTML: '',
67
+ value: '',
68
+ addEventListener: () => {},
69
+ removeEventListener: () => {},
70
+ };
71
+ }
72
+ return elem;
73
+ }
74
+
75
+ function $$(sel, ctx = document) {
76
+ return [...ctx.querySelectorAll(sel)];
77
+ }
78
+
79
+ // ─── Toast System ───
80
+ let toastTimeout;
81
+ function showToast(message, type = 'info', duration = 3000) {
82
+ const toast = el('toast');
83
+ const icons = { success: 'βœ…', error: '❌', warning: '⚠️', info: 'πŸ’‘' };
84
+ toast.innerHTML = `<span>${icons[type] || 'πŸ’‘'}</span> ${message}`;
85
+ toast.className = `toast toast-${type}`;
86
+ toast.classList.remove('hidden');
87
+ clearTimeout(toastTimeout);
88
+ toastTimeout = setTimeout(() => toast.classList.add('hidden'), duration);
89
+ }
90
+
91
+ // ─── Theme ───
92
+ function applyTheme(dark) {
93
+ STATE.isDark = dark;
94
+ document.documentElement.setAttribute('data-theme', dark ? 'dark' : '');
95
+ localStorage.setItem('ym_dark', dark);
96
+ const btn = el('theme-toggle');
97
+ if (btn) btn.classList.toggle('on', dark);
98
+ }
99
+ function toggleTheme() {
100
+ applyTheme(!STATE.isDark);
101
+ showToast(STATE.isDark ? 'Dark mode enabled πŸŒ™' : 'Light mode enabled β˜€οΈ');
102
+ }
103
+
104
+ function toggleMirror() {
105
+ STATE.mirrorEnabled = !STATE.mirrorEnabled;
106
+ const btn = el('mirror-toggle');
107
+ if (btn) btn.classList.toggle('on', STATE.mirrorEnabled);
108
+ showToast(STATE.mirrorEnabled ? 'Mirror mode ON' : 'Mirror mode OFF');
109
+ }
110
+
111
+ function toggleFps() {
112
+ STATE.showFps = !STATE.showFps;
113
+ const btn = el('fps-toggle');
114
+ if (btn) btn.classList.toggle('on', STATE.showFps);
115
+ const fpsBadge = el('fps-badge');
116
+ if (fpsBadge) fpsBadge.classList.toggle('hidden', !STATE.showFps || !STATE.cameraStream);
117
+ }
118
 
119
+ function updateInterval(value) {
120
+ STATE.liveInterval = parseInt(value);
121
+ const label = el('interval-val');
122
+ if (label) label.textContent = `${value} ms`;
123
+ if (STATE.liveLoopTimer) {
124
+ clearInterval(STATE.liveLoopTimer);
125
+ STATE.liveLoopTimer = setInterval(sendFrameToServer, STATE.liveInterval);
126
+ }
127
+ }
128
 
129
+ function selectDifficulty(btn) {
130
+ $$('.difficulty-pills .pill').forEach(p => p.classList.remove('active'));
131
+ btn.classList.add('active');
132
+ }
133
 
134
+ // =================================================================
135
  // AUTH
136
+ // =================================================================
137
  async function getCurrentUser() {
138
  try {
139
  const res = await fetch('/api/current-user', { credentials: 'include' });
 
166
  }
167
 
168
  async function logoutUser() {
169
+ await fetch('/api/logout', { method: 'POST', credentials: 'include' });
 
 
 
170
  }
171
 
172
  function showAuthModal() {
 
271
  });
272
  }
273
 
274
+ // =================================================================
275
  // API
276
+ // =================================================================
277
  async function apiRequest(endpoint, options = {}) {
278
  options.credentials = 'include';
279
  const res = await fetch(`${CONFIG.API_BASE}${endpoint}`, options);
 
284
  return data;
285
  }
286
 
 
287
  async function loadAppData() {
288
  await fetchPoses();
289
  renderHistory();
 
291
  renderFavorites();
292
  }
293
 
294
+ // =================================================================
295
+ // Poses
296
+ // =================================================================
297
  async function fetchPoses() {
298
  try {
299
  const poses = await apiRequest('/api/poses');
 
310
  }
311
  }
312
 
313
+ function renderPoseGrid() {
314
+ const grid = el('pose-grid');
315
+ if (!grid) return;
316
+ const poses = STATE.poses.slice(0, 10);
317
+ if (!poses || poses.length === 0) {
318
+ grid.innerHTML = `<div style="grid-column:1/-1;text-align:center;padding:60px 20px;color:var(--text-secondary);"><div style="font-size:48px;margin-bottom:16px;">🧘</div><h3 style="font-size:18px;margin-bottom:8px;">No poses found</h3><p style="font-size:14px;color:var(--text-muted);">Click "Add Pose" to create custom poses</p></div>`;
319
+ return;
320
+ }
321
+ grid.innerHTML = poses.map(p => {
322
+ const isFav = STATE.favorites.includes(p.id);
323
+ const diffClass = `pose-diff-${(p.difficulty || 'beginner').toLowerCase()}`;
324
+ const isCustom = p.is_custom || false;
325
+ const customBadge = isCustom ? '<span class="custom-badge">CUSTOM</span>' : '';
326
+ return `
327
+ <div class="pose-card" data-pose-id="${p.id}" onclick="openPractice('${p.id}')">
328
+ <button class="pose-fav ${isFav ? 'active' : ''}" onclick="event.stopPropagation();toggleFavorite('${p.id}')">
329
+ ${isFav ? '❀️' : '🀍'}
330
+ </button>
331
+ <div class="pose-emoji">${p.emoji || '🧘'}</div>
332
+ <div class="pose-name">${p.name || p.id} ${customBadge}</div>
333
+ <div class="pose-english">${p.english || p.id}</div>
334
+ <div class="pose-diff ${diffClass}">${p.difficulty || 'Beginner'}</div>
335
+ </div>
336
+ `;
337
+ }).join('');
338
+ const countEl = el('pose-count');
339
+ if (countEl) countEl.textContent = `Showing ${Math.min(STATE.poses.length, 10)} of ${STATE.poses.length} poses`;
340
+ }
341
+
342
+ function toggleFavorite(poseId) {
343
+ const index = STATE.favorites.indexOf(poseId);
344
+ if (index > -1) {
345
+ STATE.favorites.splice(index, 1);
346
+ showToast('Removed from favorites');
347
+ } else {
348
+ STATE.favorites.push(poseId);
349
+ showToast('Added to favorites ❀️');
350
+ }
351
+ localStorage.setItem('ym_favorites', JSON.stringify(STATE.favorites));
352
+ renderPoseGrid();
353
+ renderFavorites();
354
+ }
355
+
356
+ function renderFavorites() {
357
+ const container = el('favorites-grid');
358
+ if (!container) return;
359
+ const favs = STATE.poses.filter(p => STATE.favorites.includes(p.id));
360
+ if (favs.length === 0) {
361
+ container.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:20px;color:var(--text-muted);font-size:13px;">No favorites yet</div>';
362
+ return;
363
+ }
364
+ container.innerHTML = favs.map(p => `
365
+ <div class="pose-card" onclick="openPractice('${p.id}')" style="padding:16px;">
366
+ <div class="pose-emoji" style="font-size:32px;">${p.emoji || '🧘'}</div>
367
+ <div class="pose-name" style="font-size:13px;">${p.name || p.id}</div>
368
+ </div>
369
+ `).join('');
370
+ }
371
+
372
+ // =================================================================
373
+ // Search (unchanged – keep your existing implementation)
374
+ // =================================================================
375
+ // (I'm not duplicating it for brevity – you already have it)
376
+
377
+ // =================================================================
378
+ // Practice / Camera / Live
379
+ // =================================================================
380
 
381
  async function startCamera() {
382
  if (!STATE.selectedPose) {
383
  showToast('Please select a pose first');
384
  return;
385
  }
 
386
  try {
387
  STATE.cameraStream = await navigator.mediaDevices.getUserMedia({
388
  video: {
389
+ width: { ideal: CONFIG.CAMERA_WIDTH * 2 },
390
  height: { ideal: CONFIG.CAMERA_HEIGHT * 2 },
391
  facingMode: 'user',
392
  },
 
396
  showToast('Camera access denied.', 'error');
397
  return;
398
  }
 
399
  const video = document.getElementById('webcam-video');
400
  const canvas = document.getElementById('webcam-canvas');
401
  if (!video || !canvas) return;
402
+
403
  video.srcObject = STATE.cameraStream;
404
  video.onloadedmetadata = () => {
405
  video.play();
406
  canvas.width = CONFIG.CAMERA_WIDTH;
407
  canvas.height = CONFIG.CAMERA_HEIGHT;
408
+
409
  document.getElementById('camera-off-overlay').classList.add('hidden');
410
  document.getElementById('score-overlay').classList.remove('hidden');
411
  document.getElementById('live-badge').classList.remove('hidden');
 
414
  document.getElementById('snapshot-btn').classList.remove('hidden');
415
  document.getElementById('result-card').classList.remove('hidden');
416
  document.getElementById('suggestions-panel').classList.remove('hidden');
417
+
418
  STATE.sessionStartTime = Date.now();
419
  STATE.sessionScores = [];
420
  STATE.scoreBuffer = [];
421
  STATE.idleFrames = 0;
422
+
423
  if (STATE.animationFrameId) cancelAnimationFrame(STATE.animationFrameId);
424
  renderLoop();
425
  sendFrameToServer();
426
  STATE.liveLoopTimer = setInterval(sendFrameToServer, STATE.liveInterval);
427
+
428
  showToast('Camera started! πŸŽ₯');
429
  };
430
  }
431
 
432
+ function stopCamera() {
433
+ if (STATE.liveLoopTimer) {
434
+ clearInterval(STATE.liveLoopTimer);
435
+ STATE.liveLoopTimer = null;
436
+ }
437
+ if (STATE.animationFrameId) {
438
+ cancelAnimationFrame(STATE.animationFrameId);
439
+ STATE.animationFrameId = null;
440
+ }
441
+ if (STATE.cameraStream) {
442
+ STATE.cameraStream.getTracks().forEach(t => t.stop());
443
+ STATE.cameraStream = null;
444
+ }
445
+ const video = document.getElementById('webcam-video');
446
+ if (video) video.srcObject = null;
447
+
448
+ document.getElementById('live-badge').classList.add('hidden');
449
+ document.getElementById('fps-badge').classList.add('hidden');
450
+ document.getElementById('score-overlay').classList.add('hidden');
451
+ document.getElementById('camera-off-overlay').classList.remove('hidden');
452
+ document.getElementById('start-camera-btn').classList.remove('hidden');
453
+ document.getElementById('stop-camera-btn').classList.add('hidden');
454
+ document.getElementById('snapshot-btn').classList.add('hidden');
455
+ document.getElementById('suggestions-panel').classList.add('hidden');
456
+ document.getElementById('fullscreen-suggestions').style.display = 'none';
457
+
458
+ STATE.currentLandmarks = null;
459
+ if (STATE.sessionScores.length > 0) {
460
+ showSessionSummary();
461
+ }
462
+ STATE.sessionStartTime = null;
463
+ }
464
+
465
+ function renderLoop() {
466
+ if (!STATE.cameraStream) {
467
+ STATE.animationFrameId = null;
468
+ return;
469
+ }
470
+ const video = document.getElementById('webcam-video');
471
+ const canvas = document.getElementById('webcam-canvas');
472
+ if (!video || !canvas) {
473
+ STATE.animationFrameId = requestAnimationFrame(renderLoop);
474
+ return;
475
+ }
476
+ const ctx = canvas.getContext('2d');
477
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
478
+ ctx.save();
479
+ if (STATE.mirrorEnabled) {
480
+ ctx.translate(canvas.width, 0);
481
+ ctx.scale(-1, 1);
482
+ }
483
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
484
+ ctx.restore();
485
+
486
+ if (STATE.currentLandmarks) {
487
+ drawSkeleton(ctx, STATE.currentLandmarks, canvas.width, canvas.height, STATE.mirrorEnabled);
488
+ }
489
+
490
+ if (STATE.showFps) {
491
+ const now = performance.now();
492
+ const fps = Math.round(1000 / (now - STATE.lastFrameTime));
493
+ STATE.lastFrameTime = now;
494
+ const fpsBadge = document.getElementById('fps-badge');
495
+ if (fpsBadge) fpsBadge.textContent = `${fps} fps`;
496
+ }
497
+ STATE.animationFrameId = requestAnimationFrame(renderLoop);
498
+ }
499
+
500
+ function drawSkeleton(ctx, landmarks, width, height, mirror) {
501
+ if (!landmarks || landmarks.length === 0) return;
502
+ let colour;
503
+ if (STATE.currentScore >= 80) colour = '#22C55E';
504
+ else if (STATE.currentScore >= 65) colour = '#F59E0B';
505
+ else colour = '#EF4444';
506
+
507
+ const connections = [
508
+ [11,12], [11,13], [13,15], [12,14], [14,16],
509
+ [11,23], [12,24], [23,24], [23,25], [25,27],
510
+ [24,26], [26,28], [11,0], [12,0]
511
+ ];
512
+ ctx.lineWidth = 2.5;
513
+ ctx.strokeStyle = colour;
514
+ connections.forEach(([i, j]) => {
515
+ if (i < landmarks.length && j < landmarks.length) {
516
+ let x1 = landmarks[i][0] * width;
517
+ let y1 = landmarks[i][1] * height;
518
+ let x2 = landmarks[j][0] * width;
519
+ let y2 = landmarks[j][1] * height;
520
+ if (mirror) { x1 = width - x1; x2 = width - x2; }
521
+ ctx.beginPath();
522
+ ctx.moveTo(x1, y1);
523
+ ctx.lineTo(x2, y2);
524
+ ctx.stroke();
525
+ }
526
+ });
527
+
528
+ landmarks.forEach((lm, index) => {
529
+ let x = lm[0] * width;
530
+ let y = lm[1] * height;
531
+ if (mirror) x = width - x;
532
+ const radius = [11,12,13,14,15,16,23,24,25,26,27,28].includes(index) ? 5 : 3;
533
+ ctx.beginPath();
534
+ ctx.arc(x, y, radius, 0, 2 * Math.PI);
535
+ ctx.fillStyle = colour;
536
+ ctx.fill();
537
+ });
538
+ }
539
+
540
  // ─── Optimised sendFrame ───
541
  async function sendFrameToServer() {
542
  if (!STATE.cameraStream || STATE.isAnalysing || !STATE.selectedPose) return;
543
  STATE.isAnalysing = true;
544
+
545
  const video = document.getElementById('webcam-video');
546
  const canvas = document.getElementById('webcam-canvas');
547
  if (!video || !canvas) { STATE.isAnalysing = false; return; }
548
+
 
549
  const ctx = canvas.getContext('2d');
550
  ctx.clearRect(0, 0, canvas.width, canvas.height);
551
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
552
+
553
+ // Resize for transmission
554
  const tempCanvas = document.createElement('canvas');
555
  tempCanvas.width = CONFIG.CAMERA_WIDTH;
556
  tempCanvas.height = CONFIG.CAMERA_HEIGHT;
557
  const tempCtx = tempCanvas.getContext('2d');
558
  tempCtx.drawImage(canvas, 0, 0, tempCanvas.width, tempCanvas.height);
559
  const b64 = tempCanvas.toDataURL('image/jpeg', CONFIG.SNAPSHOT_QUALITY);
560
+
561
  try {
562
  const data = await apiRequest('/api/live', {
563
  method: 'POST',
564
  headers: { 'Content-Type': 'application/json' },
565
  body: JSON.stringify({ image: b64, pose_id: STATE.selectedPose.id }),
566
  });
567
+
568
  if (data.error) {
569
  console.warn('[Live]', data.error);
570
  STATE.isAnalysing = false;
571
  return;
572
  }
573
+
574
  // Idle detection
575
  if (!data.landmarks || data.landmarks.length === 0) {
576
  STATE.idleFrames++;
577
  if (STATE.idleFrames >= CONFIG.IDLE_THRESHOLD) {
 
578
  STATE.isAnalysing = false;
579
  return;
580
  }
581
  } else {
582
  STATE.idleFrames = 0;
583
  }
584
+
585
  if (data.landmarks && data.landmarks.length > 0) {
586
  STATE.currentLandmarks = data.landmarks;
587
  }
588
+
589
  if (data.score !== undefined) {
 
590
  STATE.scoreBuffer.push(data.score);
591
  if (STATE.scoreBuffer.length > CONFIG.SCORE_BUFFER_SIZE) STATE.scoreBuffer.shift();
592
  const smoothedScore = Math.round(
593
  STATE.scoreBuffer.reduce((a, b) => a + b, 0) / STATE.scoreBuffer.length
594
  );
595
+
596
  STATE.currentScore = smoothedScore;
597
  STATE.currentStatus = data.status || '';
598
  STATE.currentSuggestions = data.suggestions || [];
599
+
 
600
  STATE.sessionScores.push(smoothedScore);
601
  STATE.scoreHistory.push(smoothedScore);
602
  if (STATE.scoreHistory.length > CONFIG.SCORE_HISTORY_LIMIT) STATE.scoreHistory.shift();
603
+
604
  updateLiveUI(smoothedScore, STATE.currentStatus, STATE.currentSuggestions);
 
605
  if (STATE.isFullscreen) {
606
  updateFullscreenSuggestions(STATE.currentSuggestions, smoothedScore);
607
  }
 
613
  }
614
  }
615
 
 
616
  function updateLiveUI(score, status, suggestions) {
617
+ // Score ring
618
  const ring = document.getElementById('score-ring');
619
  const text = document.getElementById('score-text');
620
  if (ring && text) {
621
+ const circumference = 2 * Math.PI * 32;
622
  const offset = circumference - (score / 100) * circumference;
623
  ring.style.strokeDashoffset = offset;
624
  const colour = score >= 80 ? '#22C55E' : score >= 65 ? '#F59E0B' : '#EF4444';
625
  ring.style.stroke = colour;
626
  text.textContent = `${score}%`;
627
  }
628
+
629
+ // Overlay
630
  const overlayScore = document.getElementById('overlay-score');
631
  const overlayStatus = document.getElementById('overlay-status');
632
  if (overlayScore) overlayScore.textContent = `${score}%`;
633
  if (overlayStatus) overlayStatus.textContent = status || '–';
634
+
635
+ // Result card
636
  const badge = document.getElementById('result-badge');
637
  const scoreVal = document.getElementById('score-value');
638
  const barFill = document.getElementById('score-bar-fill');
639
  const suggList = document.getElementById('suggestions-list');
640
+
641
  if (scoreVal) {
642
  scoreVal.textContent = `${score}%`;
643
  const colour = score >= 80 ? '#22C55E' : score >= 65 ? '#F59E0B' : '#EF4444';
 
648
  barFill.style.width = `${score}%`;
649
  barFill.style.background = colour;
650
  }
651
+
652
  let level, badgeClass;
653
  if (score >= 80) { level = 'Excellent'; badgeClass = 'badge-excellent'; }
654
  else if (score >= 65) { level = 'Good'; badgeClass = 'badge-good'; }
655
  else { level = 'Needs Correction'; badgeClass = 'badge-correction'; }
656
  if (badge) { badge.textContent = level; badge.className = `result-badge ${badgeClass}`; }
657
+
658
  let displaySugg = suggestions || [];
659
  if (displaySugg.length === 0) {
660
  if (score >= 80) displaySugg = ['🌟 Excellent posture!', 'Keep breathing deeply'];
661
  else if (score >= 65) displaySugg = ['Almost there!', 'Small adjustments needed'];
662
  else displaySugg = ['Focus on alignment', 'Practice this pose more'];
663
  }
 
664
  if (suggList) {
665
  const colour = score >= 80 ? '#22C55E' : score >= 65 ? '#F59E0B' : '#EF4444';
666
  suggList.innerHTML = displaySugg.slice(0, 4).map(s => `
667
+ <li><span class="suggestion-dot" style="background:${colour};"></span> ${s}</li>
 
 
 
668
  `).join('');
669
  }
670
+
 
671
  updateSuggestionsPanel(displaySugg, score);
672
  }
673
 
674
+ function updateSuggestionsPanel(suggestions, score) {
675
+ const panel = document.getElementById('suggestions-panel');
676
+ if (!panel) return;
677
+ let colour = score >= 80 ? '#22C55E' : score >= 65 ? '#F59E0B' : '#EF4444';
678
+ let displaySugg = suggestions || [];
679
+ if (displaySugg.length === 0) {
680
+ if (score >= 80) displaySugg = ['🌟 Excellent posture!', 'Keep it up!'];
681
+ else if (score >= 65) displaySugg = ['Almost there!', 'Small adjustments'];
682
+ else displaySugg = ['Keep practicing', 'Focus on alignment'];
683
+ }
684
+ panel.innerHTML = `
685
+ <div class="suggestions-panel-header" style="border-bottom-color: ${colour};">
686
+ <span style="font-weight:700;">πŸ’‘ Pose Guidance</span>
687
+ <span class="suggestions-score" style="color:${colour};font-weight:800;font-size:20px;">${score}%</span>
688
+ </div>
689
+ <div class="suggestions-panel-body">
690
+ ${displaySugg.slice(0, 5).map((s, i) => `
691
+ <div class="suggestion-item" style="border-left-color: ${colour};">
692
+ <span class="suggestion-number">${i + 1}</span>
693
+ <span class="suggestion-text">${s}</span>
694
+ </div>
695
+ `).join('')}
696
+ </div>
697
+ <div class="suggestions-panel-footer">πŸ’‘ Follow these tips for better alignment</div>
698
+ `;
699
+ }
700
+
701
+ function updateFullscreenSuggestions(suggestions, score) {
702
+ const container = document.getElementById('fullscreen-suggestions');
703
+ if (!container) return;
704
+ let colour = score >= 80 ? '#22C55E' : score >= 65 ? '#F59E0B' : '#EF4444';
705
+ let displaySugg = suggestions || [];
706
+ if (displaySugg.length === 0) {
707
+ if (score >= 80) displaySugg = ['🌟 Excellent posture!', 'Keep it up!'];
708
+ else if (score >= 65) displaySugg = ['Almost there!', 'Small adjustments'];
709
+ else displaySugg = ['Keep practicing', 'Focus on alignment'];
710
+ }
711
+ container.innerHTML = `
712
+ <div class="fs-title">πŸ’‘ Pose Guidance</div>
713
+ <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;">
714
+ <span style="font-size:13px;color:rgba(255,255,255,0.7);">Accuracy</span>
715
+ <span class="fs-score" style="color:${colour};">${score}%</span>
716
+ </div>
717
+ ${displaySugg.slice(0, 4).map(s => `
718
+ <div class="fs-item">
719
+ <span class="fs-bullet" style="background:${colour};"></span>
720
+ ${s}
721
+ </div>
722
+ `).join('')}
723
+ `;
724
  }
725
 
726
  // ─── Reference overlay ───
 
738
  } catch(e) { /* ignore */ }
739
  }
740
 
741
+ // ─── Open Practice (overridden) ───
742
  function openPractice(poseId) {
743
+ const pose = STATE.poses.find(p => p.id === poseId);
744
+ if (!pose) {
745
+ showToast('Pose not found');
746
+ return;
747
+ }
748
+ STATE.selectedPose = pose;
749
+ document.getElementById('practice-pose-title').textContent = `Practice: ${pose.english || pose.name || pose.id}`;
750
+ document.getElementById('practice-pose-art').textContent = pose.emoji || '🧘';
751
+ document.getElementById('practice-pose-name').textContent = pose.name || pose.id;
752
+ document.getElementById('practice-pose-sanskrit').textContent = pose.english || pose.id;
753
+ const diffEl = document.getElementById('practice-pose-difficulty');
754
+ if (diffEl) {
755
+ diffEl.textContent = pose.difficulty || 'Beginner';
756
+ diffEl.className = `practice-pose-difficulty difficulty-${(pose.difficulty || 'beginner').toLowerCase()}`;
757
+ }
758
+ const benefits = pose.benefits || ['Practice this pose', 'Improve alignment', 'Build strength'];
759
+ const steps = pose.steps || ['Position yourself in the pose', 'Hold the posture', 'Breathe deeply'];
760
+ document.getElementById('benefits-list').innerHTML = benefits.map(b => `<li>${b}</li>`).join('');
761
+ document.getElementById('steps-list').innerHTML = steps.map(s => `<li>${s}</li>`).join('');
762
+
763
  loadReferenceImage(poseId);
764
+ resetCameraUI();
765
+ navigateTo('practice');
766
+ }
767
+
768
+ // ─── Other existing functions ───
769
+ // (keep your own implementations for takeSnapshot, fullscreen, history, progress, add‑pose, etc.)
770
+ // They are unchanged – just ensure they use apiRequest where needed.
771
+
772
+ // =================================================================
773
+ // Navigation
774
+ // =================================================================
775
+ function navigateTo(view) {
776
+ $$('.view').forEach(v => v.classList.remove('active'));
777
+ const target = document.getElementById(`view-${view}`);
778
+ if (target) target.classList.add('active');
779
+ $$('.nav-item[data-view]').forEach(el => {
780
+ el.classList.toggle('active', el.dataset.view === view);
781
+ });
782
+ STATE.currentView = view;
783
+ if (view === 'history') renderHistory();
784
+ if (view === 'progress') renderProgress();
785
+ if (view === 'home') {
786
+ renderPoseGrid();
787
+ renderFavorites();
788
+ updateSearchResults();
789
+ }
790
+ }
791
+
792
+ function goHome() {
793
+ stopCamera();
794
+ navigateTo('home');
795
+ }
796
+
797
+ function openAddPose() {
798
+ resetAddPoseForm();
799
+ navigateTo('add-pose');
800
+ $$('.nav-item').forEach(el => el.classList.remove('active'));
801
  }
802
 
803
+ // ─── History ───
804
+ function renderHistory() {
805
+ const container = document.getElementById('history-list');
806
+ if (!container) return;
807
+ if (!STATE.historyData.length) {
808
+ container.innerHTML = `<div class="history-empty"><div style="font-size:48px;margin-bottom:16px;">πŸ“œ</div><h3 style="font-size:18px;margin-bottom:8px;">No practice sessions yet</h3><p style="font-size:14px;color:var(--text-muted);">Select a pose, start the camera, and take a snapshot</p></div>`;
809
+ return;
810
+ }
811
+ container.innerHTML = STATE.historyData.map(entry => `
812
+ <div class="history-item">
813
+ <div class="history-emoji">${entry.emoji || '🧘'}</div>
814
+ <div class="history-info">
815
+ <div class="history-pose">${entry.pose}</div>
816
+ <div class="history-meta">${entry.english} β€” ${entry.date} at ${entry.time}</div>
817
+ </div>
818
+ <div class="history-score" style="color:${entry.score >= 80 ? '#22C55E' : entry.score >= 65 ? '#F59E0B' : '#EF4444'}">${entry.score}%</div>
819
+ </div>
820
+ `).join('');
821
+ }
822
+
823
+ function clearHistory() {
824
+ if (!confirm('Clear all history?')) return;
825
+ STATE.historyData = [];
826
+ localStorage.removeItem('ym_history');
827
+ renderHistory();
828
+ showToast('History cleared', 'warning');
829
+ }
830
+
831
+ // ─── Progress ───
832
+ function renderProgress() {
833
+ // Keep your existing implementation – unchanged
834
+ }
835
+
836
+ // ─── Add‑Pose functions ───
837
+ // (keep your existing handlePoseImageUpload, renderUploadedImages, generateCustomPose, saveGeneratedPose, etc.)
838
+ // They already use apiRequest.
839
+
840
+ // =================================================================
841
  // INIT
842
+ // =================================================================
843
+ function setupNav() {
844
+ $$('.nav-item[data-view]').forEach(el => {
845
+ el.addEventListener('click', (e) => {
846
+ e.preventDefault();
847
+ const view = el.dataset.view;
848
+ if (view === 'history') renderHistory();
849
+ if (view === 'progress') renderProgress();
850
+ if (view !== 'practice') stopCamera();
851
+ navigateTo(view);
852
+ });
853
+ });
854
+ }
855
+
856
+ function setupKeyboardShortcuts() {
857
+ document.addEventListener('keydown', (e) => {
858
+ if (e.key === 'Escape') {
859
+ if (STATE.isFullscreen) document.exitFullscreen();
860
+ }
861
+ if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA') {
862
+ if (e.key === ' ' && STATE.currentView === 'practice') {
863
+ e.preventDefault();
864
+ if (STATE.cameraStream) stopCamera();
865
+ else startCamera();
866
+ }
867
+ }
868
+ if (e.key === 's' && STATE.currentView === 'practice' && STATE.cameraStream) {
869
+ e.preventDefault();
870
+ takeSnapshot();
871
+ }
872
+ });
873
+ }
874
+
875
+ function setupSearch() {
876
+ // Keep your existing search implementation
877
+ }
878
+
879
  document.addEventListener('DOMContentLoaded', async () => {
880
  setupAuthForms();
881
+
882
  const username = await getCurrentUser();
883
  if (username) {
884
  hideAuthModal();
 
886
  await loadAppData();
887
  } else {
888
  showAuthModal();
889
+ // Load read‑only guest data
890
+ await fetchPoses();
891
  renderPoseGrid();
892
  renderFavorites();
893
  }
894
+
895
  setupSearch();
896
  setupNav();
897
  setupKeyboardShortcuts();
898
  console.log('[YogaMate] Initialized successfully 🧘');
899
  });
900
 
901
+ // ─── Expose globals ───
902
  window.startCamera = startCamera;
903
  window.stopCamera = stopCamera;
904
  window.takeSnapshot = takeSnapshot;