-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise_ui.html
More file actions
2473 lines (2179 loc) · 99.2 KB
/
exercise_ui.html
File metadata and controls
2473 lines (2179 loc) · 99.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Claude Code Exercise Break</title>
<link rel="icon" type="image/x-icon" href="/assets/favicon.ico">
<link rel="icon" type="image/png" sizes="32x32" href="/assets/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/assets/favicon-16x16.png">
<link rel="apple-touch-icon" sizes="180x180" href="/assets/apple-touch-icon.png">
<script>
// Electron detection
window.isElectronApp = !!(window.electronAPI?.isElectron || new URLSearchParams(window.location.search).get('electron'));
// Always use CDN for MediaPipe (local bundling not set up yet)
window.useLocalMediaPipe = false;
window.mediapipeBasePath = 'https://cdn.jsdelivr.net/npm/@mediapipe/pose@0.5.1675469404';
// Dynamically load MediaPipe based on environment
window.mediapipeReady = new Promise((resolve) => {
let poseLoaded = false, cameraLoaded = false;
function checkReady() {
if (poseLoaded && cameraLoaded) resolve();
}
const poseScript = document.createElement('script');
const cameraScript = document.createElement('script');
poseScript.onload = () => { poseLoaded = true; checkReady(); };
cameraScript.onload = () => { cameraLoaded = true; checkReady(); };
poseScript.onerror = () => { console.error('Failed to load MediaPipe Pose'); resolve(); };
cameraScript.onerror = () => { console.error('Failed to load Camera Utils'); resolve(); };
// Always load from CDN (local bundling not set up)
poseScript.src = 'https://cdn.jsdelivr.net/npm/@mediapipe/pose@0.5.1675469404/pose.js';
poseScript.crossOrigin = 'anonymous';
cameraScript.src = 'https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils@0.3.1640029074/camera_utils.js';
cameraScript.crossOrigin = 'anonymous';
document.head.appendChild(poseScript);
document.head.appendChild(cameraScript);
});
</script>
<style>
:root, [data-theme="vscode"] {
--bg: #1e1e1e;
--bg-light: #2d2d2d;
--border: #404040;
--text: #d4d4d4;
--text-dim: #808080;
--accent: #4ec9b0;
--success: #6a9955;
--warn: #dcdcaa;
}
[data-theme="dracula"] {
--bg: #282a36;
--bg-light: #343746;
--border: #44475a;
--text: #f8f8f2;
--text-dim: #6272a4;
--accent: #bd93f9;
--success: #50fa7b;
--warn: #f1fa8c;
}
[data-theme="nord"] {
--bg: #2e3440;
--bg-light: #3b4252;
--border: #4c566a;
--text: #eceff4;
--text-dim: #7b88a1;
--accent: #88c0d0;
--success: #a3be8c;
--warn: #ebcb8b;
}
[data-theme="solarized"] {
--bg: #002b36;
--bg-light: #073642;
--border: #586e75;
--text: #839496;
--text-dim: #657b83;
--accent: #2aa198;
--success: #859900;
--warn: #b58900;
}
[data-theme="monokai"] {
--bg: #272822;
--bg-light: #3e3d32;
--border: #49483e;
--text: #f8f8f2;
--text-dim: #75715e;
--accent: #a6e22e;
--success: #a6e22e;
--warn: #e6db74;
}
[data-theme="gruvbox"] {
--bg: #282828;
--bg-light: #3c3836;
--border: #504945;
--text: #ebdbb2;
--text-dim: #928374;
--accent: #fe8019;
--success: #b8bb26;
--warn: #fabd2f;
}
[data-theme="tokyo-night"] {
--bg: #1a1b26;
--bg-light: #24283b;
--border: #414868;
--text: #c0caf5;
--text-dim: #565f89;
--accent: #7aa2f7;
--success: #9ece6a;
--warn: #e0af68;
}
[data-theme="catppuccin"] {
--bg: #1e1e2e;
--bg-light: #313244;
--border: #45475a;
--text: #cdd6f4;
--text-dim: #7f849c;
--accent: #cba6f7;
--success: #a6e3a1;
--warn: #f9e2af;
}
body {
font-family: "SF Mono", "Fira Code", "JetBrains Mono", Menlo, Monaco, "Courier New", monospace;
display: flex;
flex-direction: column;
align-items: center;
padding: 8px;
background: var(--bg);
color: var(--text);
min-height: 100vh;
margin: 0;
box-sizing: border-box;
font-size: clamp(13px, 1.5vw, 28px);
--scale: 1;
}
/* Responsive scaling for larger windows */
@media (min-width: 800px) {
body { font-size: clamp(16px, 2vw, 32px); }
.counter { font-size: clamp(2.5em, 6vw, 5em) !important; }
.status { font-size: clamp(1.2em, 2.5vw, 2em) !important; }
h1 { font-size: clamp(1.5em, 3vw, 2.5em) !important; }
.subtitle { font-size: clamp(1.1em, 2vw, 1.8em) !important; }
.exercise-toggle { font-size: clamp(16px, 2.5vw, 28px) !important; }
.cam-selector { font-size: clamp(14px, 1.8vw, 22px) !important; }
.finish-btn { font-size: clamp(14px, 2vw, 24px) !important; padding: 12px 20px !important; }
}
@media (min-width: 1200px) {
body { font-size: clamp(18px, 2.2vw, 36px); }
.container { padding: 20px; }
}
/* Distance-based scaling (set via JS) */
body.far-mode {
--scale: 1.3;
}
body.far-mode .counter { font-size: calc(3em * var(--scale)) !important; }
body.far-mode .status { font-size: calc(1.5em * var(--scale)) !important; }
body.far-mode h1 { font-size: calc(2em * var(--scale)) !important; }
body.far-mode .subtitle { font-size: calc(1.4em * var(--scale)) !important; }
.container {
background: var(--bg-light);
border: 1px solid var(--border);
padding: 12px;
max-width: 100%;
width: 100%;
box-sizing: border-box;
}
h1 {
margin: 0 0 8px 0;
font-size: 1.1em;
font-weight: normal;
color: var(--accent);
text-align: center;
}
h1::before { content: "$ "; color: var(--text-dim); }
.subtitle {
text-align: center;
color: var(--text-dim);
margin-bottom: 12px;
font-size: 0.9em;
}
.exercise-selector {
display: flex;
gap: 6px;
margin: 12px 0;
flex-wrap: wrap;
justify-content: center;
}
.session-selector {
display: none; /* Hidden by default, shown in Electron */
margin-bottom: 10px;
padding: 8px;
background: var(--bg);
border-radius: 4px;
align-items: center;
gap: 8px;
}
.session-selector.visible {
display: flex;
}
.session-selector label {
color: var(--text-dim);
font-size: 0.85em;
}
.session-selector select {
flex: 1;
padding: 4px 8px;
background: var(--bg-light);
border: 1px solid var(--border);
color: var(--text);
border-radius: 4px;
font-size: 0.9em;
}
.session-badge {
background: var(--accent);
color: var(--bg);
padding: 2px 6px;
border-radius: 10px;
font-size: 0.75em;
font-weight: bold;
}
button {
padding: 6px 12px;
border: 1px solid var(--border);
background: var(--bg);
color: var(--text);
cursor: pointer;
font-size: 12px;
font-family: inherit;
transition: all 0.15s;
}
button:hover {
border-color: var(--accent);
color: var(--accent);
}
button.active {
background: var(--accent);
color: var(--bg);
border-color: var(--accent);
}
button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
#videoContainer {
position: relative;
margin: 8px 0;
border: 1px solid var(--border);
overflow: hidden;
display: none;
}
#videoContainer.active {
display: block;
}
video {
width: 100%;
max-width: 100%;
height: auto;
display: block;
filter: grayscale(30%) contrast(1.1);
}
canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.counter {
font-size: 2.2em;
font-weight: bold;
margin: 8px 0;
text-align: center;
color: var(--accent);
font-variant-numeric: tabular-nums;
}
.counter::before { content: "["; color: var(--text-dim); }
.counter::after { content: "]"; color: var(--text-dim); }
.status {
text-align: center;
font-size: 0.9em;
margin: 8px 0;
line-height: 1.4;
color: var(--warn);
min-height: 2.8em;
}
.finish-btn {
background: var(--bg);
border-color: var(--success);
color: var(--success);
margin-top: 8px;
width: 100%;
}
.finish-btn:hover {
background: var(--success);
color: var(--bg);
}
.rep-count {
color: var(--accent);
}
.theme-bar {
display: flex;
justify-content: center;
gap: 4px;
margin-bottom: 8px;
flex-wrap: wrap;
}
.theme-btn {
width: 16px;
height: 16px;
padding: 0;
border: 1px solid var(--border);
cursor: pointer;
transition: transform 0.1s;
}
.theme-btn:hover {
transform: scale(1.2);
border-color: var(--text);
}
.theme-btn.active {
border: 2px solid var(--text);
}
.theme-btn[data-t="vscode"] { background: #4ec9b0; }
.theme-btn[data-t="dracula"] { background: #bd93f9; }
.theme-btn[data-t="nord"] { background: #88c0d0; }
.theme-btn[data-t="solarized"] { background: #2aa198; }
.theme-btn[data-t="monokai"] { background: #a6e22e; }
.theme-btn[data-t="gruvbox"] { background: #fe8019; }
.theme-btn[data-t="tokyo-night"] { background: #7aa2f7; }
.theme-btn[data-t="catppuccin"] { background: #cba6f7; }
.loading { text-align: center; color: var(--text-dim); padding: 20px; }
/* Camera selector - terminal style */
.camera-selector {
display: flex;
align-items: center;
gap: 6px;
margin: 8px 0;
padding: 6px 8px;
background: var(--bg);
border: 1px solid var(--border);
font-size: 11px;
}
.camera-selector::before {
content: ">";
color: var(--accent);
font-weight: bold;
}
.camera-selector label {
color: var(--text-dim);
white-space: nowrap;
}
.camera-selector select {
flex: 1;
min-width: 0;
padding: 4px 6px;
background: var(--bg-light);
border: 1px solid var(--border);
color: var(--text);
font-family: inherit;
font-size: 11px;
cursor: pointer;
appearance: none;
-webkit-appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3E%3Cpath fill='%23808080' d='M0 2l4 4 4-4z'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 6px center;
padding-right: 20px;
}
.camera-selector select:hover {
border-color: var(--accent);
}
.camera-selector select:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 1px var(--accent);
}
.camera-selector select option {
background: var(--bg-light);
color: var(--text);
padding: 4px;
}
.camera-selector .cam-status {
color: var(--success);
font-size: 10px;
}
.camera-selector .cam-status.error {
color: var(--warn);
}
/* Claude context display */
.claude-context {
margin: 8px 0;
padding: 8px;
background: var(--bg);
border: 1px solid var(--border);
border-left: 3px solid var(--accent);
font-size: 11px;
max-height: 80px;
overflow-y: auto;
}
.claude-context .context-header {
color: var(--accent);
margin-bottom: 4px;
font-weight: bold;
}
.claude-context .context-summary {
color: var(--text);
margin-bottom: 4px;
}
.claude-context .context-activity {
color: var(--text-dim);
font-size: 10px;
}
.claude-context .context-activity .activity-item {
display: flex;
gap: 4px;
margin: 2px 0;
}
.claude-context .context-activity .tool-badge {
color: var(--warn);
min-width: 50px;
}
.claude-context:empty {
display: none;
}
/* Compact exercise toggle */
.exercise-toggle {
display: none;
align-items: center;
justify-content: center;
gap: 2px;
margin: 4px 0 8px 0;
font-size: 12px;
}
.exercise-toggle.active {
display: flex;
}
.exercise-toggle::before {
content: ">";
color: var(--text-dim);
margin-right: 4px;
}
.exercise-toggle-name {
color: var(--accent);
font-weight: bold;
letter-spacing: 0.5px;
}
.exercise-toggle-btn {
background: var(--bg-light);
border: 1px solid var(--accent);
border-radius: 3px;
color: var(--accent);
cursor: pointer;
padding: 2px 8px;
font-size: 12px;
font-family: inherit;
line-height: 1;
transition: background 0.15s, transform 0.15s;
margin-left: 6px;
}
.exercise-toggle-btn:hover {
background: var(--accent);
color: var(--bg);
}
.exercise-toggle-btn.open {
transform: scaleY(-1);
}
/* Dropdown for exercise selection */
.exercise-dropdown {
position: relative;
display: inline-block;
}
.exercise-dropdown-menu {
display: none;
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
background: var(--bg);
border: 1px solid var(--border);
border-radius: 4px;
min-width: 160px;
z-index: 100;
margin-top: 6px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}
.exercise-dropdown-menu.open {
display: block;
}
.exercise-dropdown-item {
display: block;
width: 100%;
padding: 10px 14px;
background: transparent;
border: none;
color: var(--text);
font-family: inherit;
font-size: 11px;
text-align: left;
cursor: pointer;
transition: background 0.1s;
}
.exercise-dropdown-item:hover {
background: var(--bg-light);
color: var(--accent);
}
.exercise-dropdown-item.current {
color: var(--accent);
}
.exercise-dropdown-item.current::before {
content: "› ";
}
/* Seated exercises link */
.seated-link {
color: var(--accent);
text-decoration: none;
font-size: 0.85em;
opacity: 0.8;
transition: opacity 0.15s;
}
.seated-link:hover {
opacity: 1;
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<div class="theme-bar">
<button class="theme-btn" data-t="vscode" title="VS Code"></button>
<button class="theme-btn" data-t="dracula" title="Dracula"></button>
<button class="theme-btn" data-t="nord" title="Nord"></button>
<button class="theme-btn" data-t="solarized" title="Solarized"></button>
<button class="theme-btn" data-t="monokai" title="Monokai"></button>
<button class="theme-btn" data-t="gruvbox" title="Gruvbox"></button>
<button class="theme-btn" data-t="tokyo-night" title="Tokyo Night"></button>
<button class="theme-btn" data-t="catppuccin" title="Catppuccin"></button>
</div>
<h1 id="title">vibereps</h1>
<p class="subtitle" id="subtitle">time to move</p>
<div class="exercise-toggle" id="exerciseToggle">
<div class="exercise-dropdown">
<span class="exercise-toggle-name" id="exerciseToggleName">squats</span>
<button class="exercise-toggle-btn" id="exerciseToggleBtn" title="Change exercise">▾</button>
<div class="exercise-dropdown-menu" id="exerciseDropdown"></div>
</div>
</div>
<div class="session-selector" id="sessionSelector">
<label>Session:</label>
<select id="sessionSelect">
<option value="">No active sessions</option>
</select>
<span class="session-badge" id="sessionBadge" style="display:none;">0</span>
</div>
<div class="claude-context" id="claudeContext"></div>
<div class="camera-selector" id="cameraSelector">
<label>cam:</label>
<select id="cameraSelect">
<option value="">detecting...</option>
</select>
<span class="cam-status" id="camStatus"></span>
</div>
<!-- Exercise selector hidden - auto-pick on start, switch via dropdown toggle -->
<div class="exercise-selector" id="exerciseSelector" style="display: none">
<div class="loading">Loading exercises...</div>
</div>
<div id="videoContainer">
<video id="video" autoplay playsinline muted></video>
<canvas id="canvas" width="320" height="240"></canvas>
</div>
<div class="counter" id="counter">0</div>
<div class="status" id="status">Select an exercise to begin!</div>
<button class="finish-btn" onclick="finishSession()">Finish Session</button>
</div>
<script>
// ============================================
// Theme handling
// ============================================
const themeColors = {
'vscode': '#4ec9b0', 'dracula': '#bd93f9', 'nord': '#88c0d0', 'solarized': '#2aa198',
'monokai': '#a6e22e', 'gruvbox': '#fe8019', 'tokyo-night': '#7aa2f7', 'catppuccin': '#cba6f7'
};
let currentTheme = localStorage.getItem('vibereps-theme') || 'vscode';
function setTheme(theme) {
currentTheme = theme;
document.body.setAttribute('data-theme', theme);
localStorage.setItem('vibereps-theme', theme);
document.querySelectorAll('.theme-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.t === theme);
});
}
setTheme(currentTheme);
document.querySelectorAll('.theme-btn').forEach(btn => {
btn.addEventListener('click', () => setTheme(btn.dataset.t));
});
// ============================================
// State variables
// ============================================
let exercises = {}; // Loaded exercise definitions
let exerciseConfigs = {}; // Full config for each exercise
let currentExercise = null;
let currentConfig = null;
let repCount = 0;
let exerciseState = null;
let pose = null;
let camera = null;
let frameLoopId = null; // For manual frame loop when camera switching
let startTime = null;
let statusPollInterval = null;
let isQuickMode = false; // Simplified: always use normal reps
let selectedCameraId = localStorage.getItem('vibereps-camera') || '';
let completedExercises = new Set(); // Track exercises done this session
let totalRepsThisSession = 0; // Total reps across all exercises
// Detection state (baselines, history)
let detectionState = {};
// ============================================
// Load exercises from server
// ============================================
async function loadExercises() {
try {
const response = await fetch('/exercises');
const exerciseList = await response.json();
const selector = document.getElementById('exerciseSelector');
selector.innerHTML = '';
for (const ex of exerciseList) {
exercises[ex.id] = ex;
// Load full config
try {
const configResponse = await fetch(`/exercises/${ex.file}`);
exerciseConfigs[ex.id] = await configResponse.json();
} catch (e) {
console.warn(`Failed to load config for ${ex.id}:`, e);
}
// Create button
const btn = document.createElement('button');
btn.id = `${ex.id}Btn`;
btn.onclick = () => startWithStandUpCheck(ex.id);
const reps = isQuickMode ? ex.reps.quick : ex.reps.normal;
btn.innerHTML = `${ex.name} (<span class="rep-count">${reps}</span>)`;
selector.appendChild(btn);
}
// Auto-start with a random exercise (user can change via dropdown)
const exercisesParam = new URLSearchParams(window.location.search).get('exercises');
let availableExercises;
if (exercisesParam) {
availableExercises = exercisesParam.split(',').map(e => e.trim()).filter(e =>
exercises[e]
);
} else {
// Use all loaded exercises
availableExercises = Object.keys(exercises).filter(id => !id.startsWith('_'));
}
if (availableExercises.length > 0) {
const randomExercise = availableExercises[Math.floor(Math.random() * availableExercises.length)];
selector.style.display = 'none';
showExerciseToggle(randomExercise);
if (window.isElectronApp) {
// In Electron mode, defer camera start until window is shown
// Starting camera in a hidden window produces black frames
window._pendingExercise = randomExercise;
} else {
// In browser mode, start immediately
window.mediapipeReady.then(() => {
setTimeout(() => startWithStandUpCheck(randomExercise), 100);
});
}
}
} catch (error) {
console.error('Failed to load exercises:', error);
document.getElementById('exerciseSelector').innerHTML =
'<div class="loading">Failed to load exercises. Using defaults...</div>';
// Fall back to hardcoded exercises after a moment
setTimeout(loadFallbackExercises, 1000);
}
}
function loadFallbackExercises() {
// Fallback hardcoded exercises if server fails
const fallbackExercises = [
{id: 'squats', name: 'Squats', reps: {normal: 10, quick: 10}},
{id: 'jumping_jacks', name: 'Jumping Jacks', reps: {normal: 15, quick: 15}},
{id: 'high_knees', name: 'High Knees', reps: {normal: 20, quick: 20}}
];
const selector = document.getElementById('exerciseSelector');
selector.innerHTML = '';
for (const ex of fallbackExercises) {
exercises[ex.id] = ex;
const btn = document.createElement('button');
btn.id = `${ex.id}Btn`;
btn.onclick = () => startWithStandUpCheck(ex.id);
const reps = isQuickMode ? ex.reps.quick : ex.reps.normal;
btn.innerHTML = `${ex.name} (<span class="rep-count">${reps}</span>)`;
selector.appendChild(btn);
}
// Auto-start with random fallback exercise
const ids = fallbackExercises.map(e => e.id);
const randomExercise = ids[Math.floor(Math.random() * ids.length)];
showExerciseToggle(randomExercise);
// Wait for MediaPipe to load before starting
window.mediapipeReady.then(() => {
setTimeout(() => startWithStandUpCheck(randomExercise), 100);
});
}
// Update subtitle
document.getElementById('subtitle').textContent = 'Tend to your quads while you tend to your Claudes';
// ============================================
// Stand-up detection
// ============================================
let standUpVerified = false;
let pendingExercise = null;
let shownStepBackMessage = false;
async function startWithStandUpCheck(exerciseId) {
pendingExercise = exerciseId;
standUpVerified = false;
shownStepBackMessage = false;
repCount = 0;
exerciseState = 'checking';
startTime = Date.now();
// Show exercise toggle and hide the exercise selector buttons
showExerciseToggle(exerciseId);
document.getElementById('exerciseSelector').style.display = 'none';
document.querySelectorAll('.exercise-selector button').forEach(btn => btn.disabled = true);
document.getElementById('counter').textContent = '?';
// Check if this is a seated exercise (skip standup check)
// Check both exerciseConfigs and exercises list since configs may still be loading
const config = exerciseConfigs[exerciseId];
const isSeated = config?.seated === true || exercises[exerciseId]?.seated === true;
if (isSeated) {
currentExercise = exerciseId;
currentConfig = config;
exerciseState = 'ready';
standUpVerified = true;
document.getElementById('status').textContent = 'Position yourself so your upper body is visible...';
} else {
currentExercise = '_standup_check';
document.getElementById('status').textContent = 'Stand up and step back so your full body is visible...';
}
try {
const video = document.getElementById('video');
// Stop any existing stream/loop
if (video.srcObject) {
video.srcObject.getTracks().forEach(track => track.stop());
}
if (camera) {
camera.stop();
camera = null;
}
if (frameLoopId) {
cancelAnimationFrame(frameLoopId);
frameLoopId = null;
}
const videoConstraints = {
width: { ideal: 320 },
height: { ideal: 240 }
};
// Use selected camera if available (use 'ideal' to avoid OverconstrainedError)
if (selectedCameraId) {
videoConstraints.deviceId = { ideal: selectedCameraId };
}
console.log('Requesting camera with constraints:', videoConstraints);
document.getElementById('status').textContent = 'Requesting camera access...';
const stream = await navigator.mediaDevices.getUserMedia({
video: videoConstraints
});
video.srcObject = stream;
document.getElementById('videoContainer').classList.add('active');
console.log('Camera stream started');
if (!pose) {
document.getElementById('status').textContent = 'Loading pose detection (first time may take a moment)...';
const success = await initPose();
if (!success) return;
}
// Use manual frame loop instead of MediaPipe Camera class
// (Camera class calls getUserMedia internally and ignores our deviceId)
console.log('Starting pose detection frame loop');
const sendFrame = async () => {
if (video.readyState >= 2) {
try {
await pose.send({image: video});
} catch (e) {
console.error('Pose send error:', e);
}
}
frameLoopId = requestAnimationFrame(sendFrame);
};
frameLoopId = requestAnimationFrame(sendFrame);
} catch (error) {
console.error('Exercise start error:', error);
const msg = error?.message || error?.name || String(error) || 'Unknown error';
document.getElementById('status').textContent = 'Error: ' + msg;
document.querySelectorAll('.exercise-selector button').forEach(btn => btn.disabled = false);
}
}
function checkStandUp(landmarks) {
const nose = landmarks[0];
const leftShoulder = landmarks[11];
const rightShoulder = landmarks[12];
const leftHip = landmarks[23];
const rightHip = landmarks[24];
const leftAnkle = landmarks[27];
const rightAnkle = landmarks[28];
// Check upper body vs lower body visibility separately
const upperBodyVisible = [nose, leftShoulder, rightShoulder]
.every(p => p && p.visibility > 0.5);
const lowerBodyVisible = [leftHip, rightHip, leftAnkle, rightAnkle]
.every(p => p && p.visibility > 0.5);
if (!upperBodyVisible) {
// Can't see upper body - they're too close to camera
if (!shownStepBackMessage) {
document.getElementById('status').innerHTML = 'Step back so the camera can see you<br><a href="#" class="seated-link" onclick="switchToSeatedExercise(); return false;">or try seated exercises →</a>';
shownStepBackMessage = true;
}
return false;
}
if (!lowerBodyVisible) {
// Upper body visible but lower body not - likely seated
if (!shownStepBackMessage) {
document.getElementById('status').innerHTML = 'Looks like you\'re seated!<br><a href="#" class="seated-link" onclick="switchToSeatedExercise(); return false;"><strong>Try a seated exercise →</strong></a>';
shownStepBackMessage = true;
}
return false;
}
// Reset flag when body becomes visible
shownStepBackMessage = false;
const shoulderY = (leftShoulder.y + rightShoulder.y) / 2;
const hipY = (leftHip.y + rightHip.y) / 2;
const ankleY = (leftAnkle.y + rightAnkle.y) / 2;
if (shoulderY < hipY && hipY < ankleY) {
document.getElementById('counter').textContent = '✓';
const exName = exercises[pendingExercise]?.name || pendingExercise;
document.getElementById('status').textContent = `Great! Starting ${exName}...`;
standUpVerified = true;
setTimeout(() => {
currentExercise = pendingExercise;
currentConfig = exerciseConfigs[pendingExercise];
exerciseState = 'ready';
repCount = 0;
detectionState = {}; // Reset detection state
document.getElementById('counter').textContent = '0';
}, 1000);
return true;
} else {
document.getElementById('status').textContent = 'Stand up straight facing the camera';
return false;
}
}
// ============================================
// MediaPipe initialization
// ============================================
async function initPose() {
if (typeof Pose === 'undefined') {
document.getElementById('status').textContent = 'Error: MediaPipe libraries not loaded';
console.error('MediaPipe Pose not loaded');
return false;
}
try {
console.log('Initializing MediaPipe Pose...');
console.log('Using MediaPipe from:', window.mediapipeBasePath);
pose = new Pose({
locateFile: (file) => {
const url = `${window.mediapipeBasePath}/${file}`;
console.log('Loading MediaPipe file:', url);
// Update status for large model files
if (file.includes('.tflite') || file.includes('.binarypb')) {
document.getElementById('status').textContent = 'Downloading pose model...';
}
return url;
}
});
pose.setOptions({
modelComplexity: 1,
smoothLandmarks: true,
minDetectionConfidence: 0.5,
minTrackingConfidence: 0.5
});
pose.onResults(onPoseResults);
console.log('MediaPipe Pose initialized successfully');
return true;
} catch (error) {
console.error('MediaPipe init error:', error);
document.getElementById('status').textContent = 'Error initializing pose detection: ' + (error?.message || error);
return false;
}
}
// Distance detection - estimate how far user is from camera
let lastDistanceCheck = 0;
const DISTANCE_CHECK_INTERVAL = 500; // Check every 500ms
function checkUserDistance(landmarks) {
const now = Date.now();
if (now - lastDistanceCheck < DISTANCE_CHECK_INTERVAL) return;
lastDistanceCheck = now;
// Use shoulder width as distance proxy (landmarks 11 & 12)
const leftShoulder = landmarks[11];
const rightShoulder = landmarks[12];
if (!leftShoulder || !rightShoulder) return;
const shoulderWidth = Math.abs(rightShoulder.x - leftShoulder.x);
// Shoulder width < 0.25 means user is far (standing back)
// Shoulder width > 0.4 means user is close (sitting at desk)
const isFar = shoulderWidth < 0.25;
if (isFar && !document.body.classList.contains('far-mode')) {
document.body.classList.add('far-mode');
console.log('User is far - scaling up UI');
} else if (!isFar && document.body.classList.contains('far-mode')) {
document.body.classList.remove('far-mode');
console.log('User is close - normal UI');
}
}
function onPoseResults(results) {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (results.poseLandmarks) {
detectExercise(results.poseLandmarks);
checkUserDistance(results.poseLandmarks);
const accentColor = themeColors[currentTheme] || '#4ec9b0';
ctx.strokeStyle = accentColor;
ctx.lineWidth = 2;
ctx.shadowBlur = 8;
ctx.shadowColor = accentColor;
drawConnectors(ctx, results.poseLandmarks);
ctx.fillStyle = accentColor;
results.poseLandmarks.forEach(landmark => {
ctx.beginPath();
ctx.arc(landmark.x * 320, landmark.y * 240, 3, 0, 2 * Math.PI);
ctx.fill();
});
}
}
// ============================================
// Generic Detection Engine
// ============================================
function detectExercise(landmarks) {
if (!currentExercise) return;