Repository navigation
Expand file tree
/
Copy pathindex_dev.html
More file actions
1543 lines (1393 loc) · 69.8 KB
/
Copy pathindex_dev.html
File metadata and controls
1543 lines (1393 loc) · 69.8 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 lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pebble Gym Tracker Setup</title>
<style>
/* ── Base ── */
:root {
--brand: #FF4700;
--brand-dark: #e64000;
--teal: #17a2b8;
--teal-dark: #138496;
--grey: #6c757d;
--grey-dark: #5a6268;
--red: #dc3545;
--red-dark: #c82333;
--green: #28a745;
--blue: #007bff;
--radius: 4px;
}
body {
font-family: Arial, sans-serif;
background: #f4f4f9;
padding: 20px;
max-width: 400px;
margin: 0 auto;
}
/* ── Form elements ── */
input, select, button, textarea {
width: 100%; padding: 10px; margin-bottom: 10px;
box-sizing: border-box; border: 1px solid #ccc;
border-radius: var(--radius);
}
button {
background: var(--brand); color: white;
font-weight: bold; border: none; cursor: pointer;
}
button:hover { background: var(--brand-dark); }
/* ── Layout helpers ── */
.card {
background: white; padding: 15px; border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,.1); margin-bottom: 20px;
}
.flex-row { display: flex; gap: 10px; }
/* ── Button variants ── */
.secondary-btn { background: var(--grey); }
.secondary-btn:hover { background: var(--grey-dark); }
.delete-btn { background: var(--red); }
.delete-btn:hover { background: var(--red-dark); }
.batch-btn {
background: var(--teal); padding: 12px; font-size: 16px;
margin-bottom: 10px; box-shadow: 0 2px 4px rgba(0,0,0,.1);
width: 100%; color: white; border: none;
border-radius: var(--radius); font-weight: bold; cursor: pointer;
}
.batch-btn:hover { background: var(--teal-dark); }
.small-btn { width: auto; padding: 6px 10px; margin: 0; font-size: 12px; }
/* ── Exercise list ── */
.exercise-item {
background: #eee; padding: 10px; margin-bottom: 5px;
border-radius: var(--radius); font-size: 14px;
display: flex; justify-content: space-between;
align-items: center; cursor: grab; transition: background .2s;
}
.exercise-item:active { cursor: grabbing; }
.exercise-item.drag-over { border-top: 3px solid var(--brand); background: #e2e2e2; }
.exercise-info { display: flex; align-items: flex-start; flex-grow: 1; min-width: 0; padding-right: 10px; }
.exercise-details { flex-grow: 1; min-width: 0; }
.grab-handle { color: #999; margin-right: 10px; font-size: 18px; user-select: none; margin-top: -2px; }
.btn-group { display: flex; flex-wrap: nowrap; gap: 4px; flex-shrink: 0; }
/* ── Modifier badges ── */
.mod-badge {
font-size: 10px; font-weight: bold; padding: 2px 6px;
border-radius: 10px; margin-left: 5px; color: white;
display: inline-block; white-space: nowrap;
vertical-align: middle; margin-bottom: 2px;
}
.badge-drop { background: #e83e8c; }
.badge-super { background: var(--blue); }
.badge-super-2 { background: var(--teal); }
.badge-giant { background: #6f42c1; }
.badge-giant-2 { background: #6f42c1; opacity: .8; }
.badge-giant-3 { background: #6f42c1; opacity: .6; }
.badge-warmup { background: #ffc107; color: #212529; }
.badge-bodyweight { background: var(--green); }
.badge-bw-drop { background: #6f42c1; }
.badge-timed { background: #fd7e14; }
/* ── Superset styling ── */
.superset-link { border-left: 4px solid var(--blue); background: #f4f9ff; }
.superset-link-top { border-bottom: none; border-bottom-left-radius: 0; border-bottom-right-radius: 0; margin-bottom: 0; }
.superset-link-bottom { border-top-left-radius: 0; border-top-right-radius: 0; border-top: 1px dashed #b8daff; }
/* ── Giant Set styling ── */
.giantset-link { border-left: 4px solid #6f42c1; background: #f6f2ff; }
.giantset-link-top { border-bottom: none; border-bottom-left-radius: 0; border-bottom-right-radius: 0; margin-bottom: 0; }
.giantset-link-mid { border-bottom: none; border-top-left-radius: 0; border-top-right-radius: 0; border-top: 1px dashed #d5c4f0; border-bottom: 1px dashed #d5c4f0; margin-bottom: 0; border-radius: 0; }
.giantset-link-bottom { border-top-left-radius: 0; border-top-right-radius: 0; border-top: 1px dashed #d5c4f0; }
/* ── Descriptions ── */
.modifier-desc {
font-size: 12px; color: #555; background: #f8f9fa;
padding: 10px; border-radius: var(--radius);
margin-bottom: 10px; border-left: 3px solid #ccc; line-height: 1.4;
}
/* ── Tabs ── */
.tab-container { display: flex; border-bottom: 2px solid var(--brand); margin-bottom: 20px; }
.tab-btn {
flex: 1; background: #ddd; border: none; padding: 12px 2px;
font-weight: bold; cursor: pointer; color: #555;
transition: .2s; border-radius: 8px 8px 0 0;
margin-right: 2px; font-size: 12px;
}
.tab-btn:last-child { margin-right: 0; }
.tab-btn.active { background: var(--brand); color: white; }
.tab-content { display: none; }
.tab-content.active { display: block; animation: fadeIn .3s; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
/* ── History ── */
.history-item {
font-size: 12px; padding: 8px; border-bottom: 1px solid #eee;
display: flex; align-items: center; gap: 10px; cursor: pointer; transition: background .2s;
}
.history-item:hover { background: #e9ecef; }
.history-item:last-child { border-bottom: none; }
.history-item input[type="checkbox"] { width: auto; margin: 0; pointer-events: none; }
/* ── Search input highlight ── */
#exerciseSearch { border: 2px solid var(--brand); background: #fffaf5; }
</style>
</head>
<body>
<h2 style="text-align:center; margin-top:0;">GymTracker Setup</h2>
<div class="tab-container">
<button class="tab-btn active" onclick="switchTab(event,'tab-builder')">🏋️ Builder</button>
<button class="tab-btn" onclick="switchTab(event,'tab-progression')">📈 Progress</button>
<button class="tab-btn" onclick="switchTab(event,'tab-batch')">📦 Batch</button>
<button class="tab-btn" onclick="switchTab(event,'tab-history-cloud')">☁️ History</button>
</div>
<!-- ════════════ TAB: BUILDER ════════════ -->
<div id="tab-builder" class="tab-content active">
<div class="card">
<h3 style="margin-top:0;">Manage Routines</h3>
<label>Saved on Phone:</label>
<div class="flex-row">
<select id="savedRoutineSelect" onchange="selectRoutine()" style="margin:0; flex:1;">
<option value="">-- New Routine --</option>
</select>
<button type="button" class="small-btn delete-btn" onclick="deleteRoutine()" style="margin:0; white-space:nowrap;">Delete</button>
</div>
</div>
<div class="card">
<label>Routine Name:</label>
<input type="text" id="routineName" placeholder="e.g., Push Day, Leg Day">
</div>
<div class="card">
<h3 id="formTitle">Add Exercise</h3>
<input type="text" id="exerciseSearch" placeholder="🔍 Search exercises..." oninput="filterExercises()">
<select id="exerciseSelect"></select>
<label id="labelTargetSets">Target Sets:</label>
<input type="number" id="targetSets" placeholder="e.g., 3" min="1">
<label id="labelTargetReps">Target Reps:</label>
<input type="number" id="targetReps" placeholder="e.g., 10" min="1">
<label id="labelTargetWeight">Target Weight:</label>
<input type="number" id="targetWeight" placeholder="e.g., 60 (0 for Bodyweight)" min="0">
<label style="font-size:14px; font-weight:bold; margin-top:5px; display:block;">Advanced Modifier:</label>
<select id="exerciseModifier" onchange="updateModifierDesc()">
<option value="0">Normal Sets</option>
<option value="1">Drop Set</option>
<option value="2">Superset</option>
<option value="3">Warmup</option>
<option value="6">Timed (Count up)</option>
<option value="7">Giant Set</option>
</select>
<div id="modifierDesc" class="modifier-desc">Standard exercise execution with regular rest periods.</div>
<label style="font-size:14px; font-weight:bold; display:block;">
Optional Note: <span id="commentCounter" style="font-weight:normal; color:#aaa; font-size:12px;">0 / 31</span>
</label>
<input type="text" id="exerciseComment" placeholder="e.g., Seat at 4, Pin at 3" maxlength="31" oninput="updateCommentCounter()">
<button id="addUpdateBtn" onclick="addExercise()">+ Add to Routine</button>
</div>
<div class="card">
<h3>Your Routine:</h3>
<p style="font-size:11px; color:gray; margin-top:0;">Drag and drop to reorder, or use the arrows on mobile.</p>
<div id="routineList">
<p style="color:gray; font-size:12px;">No exercises added yet.</p>
</div>
<div id="routineLengthBar" style="display:none; margin-top:8px;">
<div style="display:flex; justify-content:space-between; font-size:11px; color:#666; margin-bottom:3px;">
<span>Exercises</span>
<span id="routineLengthText">0 / 15</span>
</div>
<div style="background:#eee; border-radius:4px; height:6px;">
<div id="routineLengthFill" style="height:6px; border-radius:4px; background:var(--green); transition:width .3s, background .3s;"></div>
</div>
<p id="routineLengthWarning" style="display:none; font-size:11px; color:var(--red); margin:5px 0 0 0;">⚠️ Maximum of 15 exercises reached!</p>
</div>
</div>
</div>
<!-- ════════════ TAB: PROGRESSION ════════════ -->
<div id="tab-progression" class="tab-content">
<div class="card">
<h3 style="margin-top:0;">Progression Settings</h3>
<label>Mode:</label>
<select id="progressionMode" onchange="updateProgressionUI()">
<option value="-1" selected>Off</option>
<option value="0">Weight</option>
<option value="1">Reps</option>
</select>
<div id="weightIncrementContainer" style="display:none;">
<label>Weight Increment:</label>
<select id="weightIncrement">
<option value="1">1kg</option>
<option value="2" selected>2kg</option>
<option value="3">3kg</option>
<option value="4">4kg</option>
<option value="5">5kg</option>
<option value="6">6kg</option>
<option value="7">7kg</option>
<option value="8">8kg</option>
<option value="9">9kg</option>
<option value="10">10kg</option>
</select>
</div>
<div id="progressionDesc" class="modifier-desc" style="margin-top:15px;">
Progression is disabled. Your targets will remain exactly as you set them.
</div>
</div>
</div>
<!-- ════════════ TAB: BATCH ════════════ -->
<div id="tab-batch" class="tab-content">
<div class="card">
<h3 style="margin-top:0;">Batch Routine Queue</h3>
<p style="font-size:12px; color:gray; margin-top:0;">Prepare multiple routines and send an entire week to the watch at once.</p>
<div style="background:#fafafa; border:1px solid #ddd; border-radius:4px; margin-bottom:15px; padding:10px;">
<h4 id="batchCount" style="margin-top:0; text-align:center; color:var(--teal);">0 / 7 Routines Prepared</h4>
<div id="batchList">
<p style="color:gray; font-size:12px; text-align:center;">No routines in the batch yet.</p>
</div>
</div>
<button onclick="sendBatchToPebble()" style="padding:15px; font-size:18px; width:100%; box-shadow:0 4px 6px rgba(0,0,0,.2);">🚀 Send Entire Batch to Watch</button>
</div>
<div class="card">
<h3 style="margin-top:0;">Import / Export via Text</h3>
<p style="font-size:12px; color:gray; margin-top:0;">Use this to back up a routine or transfer it from another device. Generate the text on one device, copy it, then paste and import on another.</p>
<textarea id="routineTextArea" rows="3" style="font-family:monospace; font-size:11px; resize:vertical;" placeholder='{"n":"My Routine","e":[]}'></textarea>
<div class="flex-row">
<button type="button" class="small-btn secondary-btn" style="margin:0; flex:1;" onclick="exportToText()">1. Gen Text</button>
<button type="button" class="small-btn secondary-btn" style="margin:0; flex:1;" onclick="copyText()">2. Copy</button>
<button type="button" class="small-btn" style="margin:0; flex:1; background:var(--green);" onclick="importFromText()">⬇️ Import</button>
</div>
</div>
</div>
<!-- ════════════ TAB: HISTORY / CLOUD ════════════ -->
<div id="tab-history-cloud" class="tab-content">
<div class="card">
<h3 style="margin-top:0;">Workout History</h3>
<p style="font-size:12px; color:gray; margin-top:0;">Workouts are saved locally to your phone.</p>
<div style="margin-bottom: 8px;">
<button type="button" class="small-btn secondary-btn" onclick="toggleAllHistory()">☑ Toggle All</button>
</div>
<div id="historyList" style="max-height:250px; overflow-y:auto; background:#fafafa; border:1px solid #ddd; border-radius:4px; margin-bottom:10px; padding:5px;">
<p style="font-size:12px; text-align:center; color:gray;">Loading history...</p>
</div>
<div class="flex-row" style="margin-bottom: 10px;">
<button onclick="generateCSVBox()" style="background: var(--blue);">📄 Copy Selected</button>
<button onclick="retroactiveGoogleSync()" style="background: var(--green);">☁️ Sync Selected</button>
</div>
<button class="delete-btn" onclick="clearHistory()" style="width: 100%; padding: 12px;">🗑️ Delete All History</button>
<div id="csv-export-container"></div>
</div>
<div class="card">
<h3 style="margin-top:0;">Google Sheets Auto-Export</h3>
<div id="googleStatusContainer" style="display:none; padding:10px; background:#e8f5e9; border:1px solid #c8e6c9; border-radius:4px; margin-bottom:15px;">
<span style="color:#2e7d32; font-weight:bold;">✅ Cloud Sync Configured</span>
<p style="font-size:11px; margin:5px 0 0 0; color:#1b5e20;">URL and password are saved on your phone. Leave blank to keep current settings.</p>
<button type="button" class="small-btn delete-btn" style="margin-top:8px;" onclick="flagClearGoogle()">Wipe Saved Credentials</button>
</div>
<p style="font-size:12px; color:gray; margin-top:0;">Paste your Apps Script URL to auto-sync workouts to the cloud.</p>
<label>Google Script URL:</label>
<input type="text" id="googleUrlInput" placeholder="https://script.google.com/macros/s/.../exec">
<label>Export Password:</label>
<input type="password" id="googlePwdInput" placeholder="Your secret password">
</div>
</div>
<!-- ════════════ GLOBAL ACTION BUTTONS ════════════ -->
<div id="global-actions" style="margin-bottom:40px;">
<button id="btn-add-batch" class="batch-btn" onclick="addToBatch()">📦 + Add Current Routine to Batch</button>
<button id="btn-send-single" style="padding:15px; font-size:18px; width:100%; box-shadow:0 4px 6px rgba(0,0,0,.2);" onclick="saveAndSendSingle()">Save & Send Single Routine to Watch</button>
<button id="btn-send-google" style="display:none; padding:15px; font-size:18px; width:100%; box-shadow:0 4px 6px rgba(0,0,0,.2); background:var(--green);" onclick="saveAndSendSingle()">☁️ Save Google Settings to Watch</button>
</div>
<script>
'use strict';
// ============================================================
// CONSTANTS
// ============================================================
const MAX_BATCH = 7;
const MAX_ROUTINE_LEN = 1300; // real worst-case: 15 exercises × ~79 chars + name = ~1216
const MAX_EXERCISES = 15; // mirrors #define MAX_EXERCISES in main.c
const MAX_HISTORY = 30;
// Hard cap on the ENCODED config response (the pebblejs://close# payload).
// The phone app silently drops responses above a platform limit, so a too-long
// routine appeared to "save" while the watch never received it. Measurements
// from a real device: 252 and 279 encoded chars delivered fine, 672 was
// silently dropped — the true limit sits between them (suspected 512, to be
// confirmed via the pkjs webviewclosed length log). The cap is conservative;
// note encodeURIComponent inflates pipes/spaces/commas ~2.1x, so the routine
// string itself must stay well under ~200 raw chars.
const MAX_CONFIG_RESPONSE = 512;
/** Modifier value → { label, badgeClass } */
const MODIFIER_META = {
0: { desc: 'Standard exercise execution with regular rest periods.', borderColor: '#ccc' },
1: { desc: '<strong>Drop Set:</strong> Doubles target sets. Normal targets on odd sets, dynamic reductions on even sets. <strong>(If weight is 0, drops reps instead)</strong>.', borderColor: '#e83e8c' },
2: { desc: '<strong>Superset:</strong> Links this exercise with the <strong>NEXT</strong> exercise. The watch bounces between the two until all sets are done.', borderColor: '#007bff' },
3: { desc: '<strong>Warmup:</strong> Executes normally but the watch cuts the rest timer in half between sets.', borderColor: '#ffc107' },
6: { desc: '<strong>Timed Exercise:</strong> "Target Reps" = Target Seconds. Press Select to start the timer. Target Weight is ignored.', borderColor: '#fd7e14' },
7: { desc: '<strong>Giant Set:</strong> Links this exercise with the <strong>NEXT TWO</strong> exercises. The watch bounces across all three until all sets are done. All three must have the same target sets.', borderColor: '#6f42c1' }
};
const PROGRESSION_META = {
'-1': { desc: 'Progression is disabled. Your targets will remain exactly as you set them.', borderColor: '#ccc', showIncrement: false },
'0': { desc: '<strong>Weight Progression:</strong> Automatically increases target weight after a perfect session.', borderColor: '#28a745', showIncrement: true },
'1': { desc: '<strong>Reps Progression:</strong> Automatically increases target reps by 1 after a perfect session.', borderColor: '#17a2b8', showIncrement: false }
};
// Valid progression header tokens — same fix as in index.js
const PROGRESSION_TOKENS = new Set(['-1', '0', '1']);
const EXERCISE_DB = {
'Chest': ['Bench Press','Incline Bench Press','Decline Bench Press','Dumbbell Flyes','Cable Crossovers','Push-Ups','Pec Deck','Chest Dips'],
'Back': ['Deadlift','Pull-Ups','Chin-Ups','Barbell Row','Dumbbell Row','Lat Pulldown','Seated Cable Row','T-Bar Row','Back Extensions','Facepulls'],
'Shoulders': ['Overhead Press','Arnold Press','Lateral Raises','Front Raises','Upright Rows','Reverse Pec Deck','Shrugs','Push Press'],
'Arms': ['Bicep Curls','Hammer Curls','Preacher Curls','Concentration Curls','Tricep Extensions','Skull Crushers','Tricep Pushdowns','Tricep Dips'],
'Legs': ['Squats','Leg Press','Lunges','Leg Extensions','Leg Curls','Calf Raises','Romanian Deadlifts','Bulgarian Split Squats','Hack Squat'],
'Abdominals': ['Crunches','Leg Raises','Planks','Cable Crunch','Russian Twists','Ab Wheel Rollouts','Hanging Leg Raises','Pallof Press','Target Abs']
};
// ============================================================
// STATE
// ============================================================
let myRoutine = [];
let batchRoutines = [];
let editingIndex = -1;
let draggedIndex = null;
let workoutHistory = [];
let shouldClearHistory = false;
let shouldClearGoogle = false;
// Raw routine strings last synced FROM the watch (name → sync string),
// captured from the 'sync' URL param at page load. Used to detect whether
// the editor's routine is unchanged, so a mode-only change can be sent
// without re-transmitting the whole (potentially oversized) routine.
let syncedRoutinesDict = {};
// ============================================================
// STORAGE HELPERS (mirrors index.js for consistency)
// ============================================================
const Storage = {
get(key, fallback = '') {
const v = localStorage.getItem(key);
return v !== null ? v : fallback;
},
set(key, value) { localStorage.setItem(key, value); },
remove(key) { localStorage.removeItem(key); },
getJSON(key, fallback) {
try {
const v = localStorage.getItem(key);
return v !== null ? JSON.parse(v) : fallback;
} catch (e) {
console.warn('Storage.getJSON failed for', key, e);
return fallback;
}
},
setJSON(key, value) { localStorage.setItem(key, JSON.stringify(value)); }
};
// ============================================================
// URL PARAM HELPER
// ============================================================
function getQueryParam(name, fallback = '') {
const params = new URLSearchParams(location.search);
return params.has(name) ? params.get(name) : fallback;
}
// ============================================================
// TABS
// ============================================================
function switchTab(evt, tabId) {
document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
document.getElementById(tabId).classList.add('active');
evt.currentTarget.classList.add('active');
const showGlobal = tabId === 'tab-builder' || tabId === 'tab-progression';
const showGoogle = tabId === 'tab-history-cloud';
document.getElementById('btn-add-batch').style.display = showGlobal ? 'block' : 'none';
document.getElementById('btn-send-single').style.display = showGlobal ? 'block' : 'none';
document.getElementById('btn-send-google').style.display = showGoogle ? 'block' : 'none';
}
// ============================================================
// ROUTINE STORAGE
// ============================================================
function getSavedRoutines() { return Storage.getJSON('savedRoutines', []); }
function getLastRoutine() { return Storage.get('lastRoutine', ''); }
function saveRoutineToStorage(name, exercises, progressionMode, weightIncrement) {
let routines = getSavedRoutines();
const idx = routines.findIndex(r => r.name === name);
const data = { name, exercises: exercises.map(migrateLegacyExercise), progressionMode, weightIncrement };
if (idx >= 0) routines[idx] = data; else routines.push(data);
Storage.setJSON('savedRoutines', routines);
Storage.set('lastRoutine', name);
}
// ============================================================
// LEGACY MIGRATION
// Converts old array format modifiers 4 and 5 to current values.
// ============================================================
function migrateLegacyExercise(ex) {
if (ex.length > 4) {
const mod = parseInt(ex[4], 10);
if (mod === 4) { ex[4] = 0; ex[3] = 0; }
if (mod === 5) { ex[4] = 1; ex[3] = 0; }
}
return ex;
}
// ============================================================
// LOAD SAVED ROUTINES INTO DROPDOWN
// ============================================================
function loadSavedRoutines() {
const routines = getSavedRoutines();
const lastRoutine = getLastRoutine();
const select = document.getElementById('savedRoutineSelect');
// Clear all options except the first placeholder
while (select.options.length > 1) select.remove(1);
if (routines.length === 0) {
const opt = new Option('-- No saved routines --', '');
opt.disabled = true;
select.appendChild(opt);
} else {
routines.forEach(r => select.appendChild(new Option(`${r.name} (${r.exercises.length} exercises)`, r.name)));
}
const target = (lastRoutine && routines.some(r => r.name === lastRoutine))
? lastRoutine
: (routines.length > 0 ? routines[0].name : '');
if (target) { select.value = target; selectRoutine(); }
}
function selectRoutine() {
const name = document.getElementById('savedRoutineSelect').value;
if (!name) {
document.getElementById('routineName').value = '';
document.getElementById('progressionMode').value = '-1';
document.getElementById('weightIncrement').value = '2';
myRoutine = [];
renderRoutine();
updateProgressionUI();
return;
}
const routine = getSavedRoutines().find(r => r.name === name);
if (!routine) return;
document.getElementById('routineName').value = routine.name;
document.getElementById('progressionMode').value = routine.progressionMode || '-1';
document.getElementById('weightIncrement').value = routine.weightIncrement || '2';
myRoutine = (routine.exercises || []).map(migrateLegacyExercise);
renderRoutine();
updateProgressionUI();
Storage.set('lastRoutine', name);
}
function deleteRoutine() {
const name = document.getElementById('savedRoutineSelect').value;
if (!name || !confirm(`Delete '${name}' from saved routines?`)) return;
let routines = getSavedRoutines().filter(r => r.name !== name);
Storage.setJSON('savedRoutines', routines);
if (getLastRoutine() === name) Storage.remove('lastRoutine');
document.getElementById('routineName').value = '';
document.getElementById('progressionMode').value = '-1';
document.getElementById('weightIncrement').value = '2';
myRoutine = [];
renderRoutine();
updateProgressionUI();
loadSavedRoutines();
}
// ============================================================
// UI UPDATES
// ============================================================
function updateProgressionUI() {
const mode = document.getElementById('progressionMode').value;
const meta = PROGRESSION_META[mode] || PROGRESSION_META['-1'];
document.getElementById('weightIncrementContainer').style.display = meta.showIncrement ? 'block' : 'none';
const desc = document.getElementById('progressionDesc');
desc.innerHTML = meta.desc;
desc.style.borderLeftColor = meta.borderColor;
}
function updateModifierDesc() {
const val = document.getElementById('exerciseModifier').value;
const meta = MODIFIER_META[val] || MODIFIER_META[0];
const desc = document.getElementById('modifierDesc');
desc.innerHTML = meta.desc;
desc.style.borderLeftColor = meta.borderColor;
// UX: adapt form field labels and placeholders to the selected modifier
const isTimed = val === '6';
const repsInput = document.getElementById('targetReps');
const repsLabel = document.getElementById('labelTargetReps');
const weightInput = document.getElementById('targetWeight');
const weightLabel = document.getElementById('labelTargetWeight');
if (isTimed) {
repsInput.placeholder = 'e.g., 60';
repsLabel.textContent = 'Target Seconds:';
weightInput.placeholder = 'Not used for timed (enter 0)';
weightInput.value = '0';
weightLabel.textContent = 'Weight (ignored for timed):';
weightLabel.style.color = '#aaa';
weightInput.style.color = '#aaa';
} else {
repsInput.placeholder = 'e.g., 10';
repsLabel.textContent = 'Target Reps:';
// FIX 1: clear the auto-filled '0' when switching away from timed,
// unless the user has deliberately typed something other than '0'
if (weightInput.value === '0') weightInput.value = '';
weightInput.placeholder = 'e.g., 60 (0 for Bodyweight)';
weightLabel.textContent = 'Target Weight:';
weightLabel.style.color = '';
weightInput.style.color = '';
}
}
// ============================================================
// EXERCISE DROPDOWN
// ============================================================
function renderExerciseDropdown(filterText = '') {
const dropdown = document.getElementById('exerciseSelect');
const lower = filterText.trim().toLowerCase();
const fragment = document.createDocumentFragment();
for (const [group, exercises] of Object.entries(EXERCISE_DB)) {
const matches = lower ? exercises.filter(e => e.toLowerCase().includes(lower)) : exercises;
if (matches.length === 0) continue;
const og = document.createElement('optgroup');
og.label = `── ${group.toUpperCase()} ──`;
matches.forEach(ex => og.appendChild(new Option(ex, ex)));
fragment.appendChild(og);
}
if (filterText.trim()) {
const og = document.createElement('optgroup');
og.label = '── CUSTOM EXERCISE ──';
og.appendChild(new Option(`Add "${filterText.trim()}"`, filterText.trim()));
fragment.appendChild(og);
}
dropdown.innerHTML = '';
dropdown.appendChild(fragment);
}
function filterExercises() {
renderExerciseDropdown(document.getElementById('exerciseSearch').value);
}
// ============================================================
// SMALL UX HELPERS
// ============================================================
function updateCommentCounter() {
const len = document.getElementById('exerciseComment').value.length;
const counter = document.getElementById('commentCounter');
counter.textContent = `${len} / 31`;
counter.style.color = len > 25 ? 'var(--red)' : '#aaa';
}
function updateRoutineLengthBar() {
const count = myRoutine.length;
const pct = (count / MAX_EXERCISES) * 100;
const bar = document.getElementById('routineLengthBar');
const fill = document.getElementById('routineLengthFill');
const text = document.getElementById('routineLengthText');
const warn = document.getElementById('routineLengthWarning');
if (count === 0) { bar.style.display = 'none'; return; }
bar.style.display = 'block';
fill.style.width = pct + '%';
fill.style.background = count >= MAX_EXERCISES ? 'var(--red)' : count >= 12 ? '#ffc107' : 'var(--green)';
text.textContent = `${count} / ${MAX_EXERCISES}`;
warn.style.display = count >= MAX_EXERCISES ? 'block' : 'none';
}
function renderRoutine() {
const listDiv = document.getElementById('routineList');
if (myRoutine.length === 0) {
listDiv.innerHTML = '<p style="color:gray; font-size:12px;">No exercises added yet.</p>';
return;
}
// Use a DocumentFragment to avoid repeated DOM reflows
const fragment = document.createDocumentFragment();
// linkedPosition: 0 = none, 1 = superset 2/2, 2 = giant 2/3, 3 = giant 3/3.
// Determined by the previous exercise(s), not the current one.
let linkedPosition = 0;
myRoutine.forEach((ex, i) => {
const weight = parseInt(ex[3], 10);
let modifier = ex.length > 4 ? parseInt(ex[4], 10) : 0;
// A second-half (superset or giant set) element cannot itself carry a modifier
if (linkedPosition !== 0 && modifier !== 0) { modifier = 0; ex[4] = 0; }
const isSuperSecondHalf = (linkedPosition === 1);
const isGiantSecondHalf = (linkedPosition === 2);
const isGiantThirdHalf = (linkedPosition === 3);
// Build badge HTML
let badges = '';
if (modifier === 2) badges += '<span class="mod-badge badge-super">SUPER 1/2</span> ';
if (isSuperSecondHalf) badges += '<span class="mod-badge badge-super-2">SUPER 2/2</span> ';
if (modifier === 7) badges += '<span class="mod-badge badge-giant">GIANT 1/3</span> ';
if (isGiantSecondHalf) badges += '<span class="mod-badge badge-giant-2">GIANT 2/3</span> ';
if (isGiantThirdHalf) badges += '<span class="mod-badge badge-giant-3">GIANT 3/3</span> ';
if (modifier === 3) badges += '<span class="mod-badge badge-warmup">WARMUP</span> ';
if (modifier === 6) badges += '<span class="mod-badge badge-timed">TIMED</span> ';
if (modifier !== 6 && weight === 0) {
badges += modifier === 1
? '<span class="mod-badge badge-bw-drop">BW DROP</span> '
: '<span class="mod-badge badge-bodyweight">BODYWEIGHT</span> ';
} else if (modifier === 1) {
badges += '<span class="mod-badge badge-drop">DROP SET</span> ';
}
const comment = (ex.length > 5 && ex[5] !== '') ? `<div style="font-size:11px;color:#888;margin-top:2px;">📝 ${ex[5]}</div>` : '';
const handleColor = isSuperSecondHalf ? '#007bff' : (isGiantSecondHalf || isGiantThirdHalf) ? '#6f42c1' : '';
const handleStyle = handleColor ? `color:${handleColor};margin-left:8px;` : '';
const handle = handleColor ? `<div class="grab-handle" style="${handleStyle}">↳</div>` : '<div class="grab-handle">≡</div>';
const upDisabled = i === 0 ? 'disabled style="opacity:.3;"' : '';
const downDisabled= i === myRoutine.length - 1 ? 'disabled style="opacity:.3;"' : '';
const div = document.createElement('div');
let className = 'exercise-item';
if (modifier === 2) className += ' superset-link superset-link-top';
if (isSuperSecondHalf) className += ' superset-link superset-link-bottom';
if (modifier === 7) className += ' giantset-link giantset-link-top';
if (isGiantSecondHalf) className += ' giantset-link giantset-link-mid';
if (isGiantThirdHalf) className += ' giantset-link giantset-link-bottom';
div.className = className;
div.draggable = true;
div.addEventListener('dragstart', e => dragStart(e, i));
div.addEventListener('dragover', e => dragOver(e, div));
div.addEventListener('dragleave', e => dragLeave(e, div));
div.addEventListener('drop', e => drop(e, i, div));
div.innerHTML = `
<div class="exercise-info">
${handle}
<div class="exercise-details">
<div style="line-height:1.2;margin-bottom:4px;"><strong>${ex[0]}</strong> ${badges}</div>
<div>${ex[1]}s × ${modifier === 6 ? ex[2] + 'sec' : ex[2] + 'r'} @ ${weight === 0 ? (modifier === 6 ? '—' : 'BW') : weight + 'kg'}</div>
${comment}
</div>
</div>
<div class="btn-group">
<button class="small-btn secondary-btn" onclick="moveExercise(${i},-1)" ${upDisabled}>▲</button>
<button class="small-btn secondary-btn" onclick="moveExercise(${i}, 1)" ${downDisabled}>▼</button>
<button class="small-btn secondary-btn" onclick="editExercise(${i})">Edit</button>
<button class="small-btn delete-btn" onclick="deleteExercise(${i})">✕</button>
</div>`;
fragment.appendChild(div);
// Compute the linkedPosition for the NEXT exercise based on this one's modifier
// (and whether the current one is itself a 2/3 giant member).
if (modifier === 7) {
linkedPosition = 2; // next is giant 2/3
} else if (isGiantSecondHalf) {
linkedPosition = 3; // next is giant 3/3
} else if (modifier === 2) {
linkedPosition = 1; // next is superset 2/2
} else {
linkedPosition = 0; // next is normal
}
});
listDiv.innerHTML = '';
listDiv.appendChild(fragment);
updateRoutineLengthBar();
}
// ============================================================
// DRAG & DROP
// ============================================================
// ============================================================
function dragStart(e, index) { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; }
function dragOver(e, el) { e.preventDefault(); el.classList.add('drag-over'); }
function dragLeave(e, el) { el.classList.remove('drag-over'); }
function drop(e, targetIndex, el) {
e.preventDefault();
el.classList.remove('drag-over');
if (draggedIndex === null || draggedIndex === targetIndex) return;
myRoutine.splice(targetIndex, 0, myRoutine.splice(draggedIndex, 1)[0]);
renderRoutine();
draggedIndex = null;
}
// ============================================================
// ADD / EDIT / DELETE EXERCISE
// ============================================================
function addExercise() {
const sets = document.getElementById('targetSets').value;
const reps = document.getElementById('targetReps').value;
const weight = document.getElementById('targetWeight').value;
const modifier = parseInt(document.getElementById('exerciseModifier').value, 10);
const isTimed = modifier === 6;
if (sets === '' || reps === '') {
alert(isTimed
? 'Please fill out sets and target seconds!'
: 'Please fill out sets, reps, and weight (use 0 for bodyweight)!');
return;
}
if (!isTimed && weight === '') {
alert('Please fill out target weight (use 0 for bodyweight)!');
return;
}
// Enforce the C-side MAX_EXERCISES limit (only on new adds, not edits)
if (editingIndex === -1 && myRoutine.length >= MAX_EXERCISES) {
alert(`Maximum of ${MAX_EXERCISES} exercises per routine reached.`);
return;
}
const exercise = [
document.getElementById('exerciseSelect').value,
parseInt(sets, 10),
parseInt(reps, 10),
isTimed ? 0 : parseInt(weight, 10), // weight always 0 for timed
modifier,
document.getElementById('exerciseComment').value.trim()
];
// Validate linked-set constraints against the routine as it will look
// once this exercise is added (or after the edit is applied). Use the
// permissive add-time validator so the user can still build a giant
// set one exercise at a time on a blank routine; structural completeness
// is enforced at send time.
const routineForValidation = (editingIndex === -1)
? [...myRoutine, exercise]
: myRoutine.map((e, idx) => idx === editingIndex ? exercise : e);
// On edit, propagate any target_sets change to the other members of
// the same linked set so the routine stays consistent. The cascade
// happens before the validator so the validator then passes, and
// any cascaded target_sets are written back to myRoutine below.
if (editingIndex >= 0) {
applyLinkedSetCascade(routineForValidation, editingIndex);
}
if (!validateLinkedSetAtAdd(routineForValidation, document.getElementById('routineName').value || 'My Routine')) {
return;
}
if (editingIndex === -1) {
myRoutine.push(exercise);
} else {
// Commit the edited exercise and any cascaded target_sets.
myRoutine[editingIndex] = exercise;
for (let i = 0; i < routineForValidation.length; i++) {
if (myRoutine[i][1] !== routineForValidation[i][1]) {
myRoutine[i][1] = routineForValidation[i][1];
}
}
editingIndex = -1;
document.getElementById('formTitle').innerText = 'Add Exercise';
document.getElementById('addUpdateBtn').innerText = '+ Add to Routine';
}
// Reset form
['exerciseSearch','targetSets','targetReps','targetWeight','exerciseComment'].forEach(id => {
document.getElementById(id).value = '';
});
document.getElementById('exerciseModifier').value = '0';
updateCommentCounter();
renderExerciseDropdown();
updateModifierDesc();
renderRoutine();
}
function deleteExercise(index) { myRoutine.splice(index, 1); renderRoutine(); }
function moveExercise(index, direction) {
const target = index + direction;
if (target < 0 || target >= myRoutine.length) return;
[myRoutine[index], myRoutine[target]] = [myRoutine[target], myRoutine[index]];
renderRoutine();
}
function editExercise(index) {
const ex = myRoutine[index];
document.getElementById('exerciseSearch').value = ex[0];
renderExerciseDropdown(ex[0]);
document.getElementById('exerciseSelect').value = ex[0];
document.getElementById('targetSets').value = ex[1];
document.getElementById('targetReps').value = ex[2];
document.getElementById('targetWeight').value = ex[3];
document.getElementById('exerciseModifier').value = ex.length > 4 ? ex[4] : '0';
document.getElementById('exerciseComment').value = ex.length > 5 ? ex[5] : '';
updateCommentCounter();
updateModifierDesc();
editingIndex = index;
document.getElementById('formTitle').innerText = 'Edit Exercise';
document.getElementById('addUpdateBtn').innerText = 'Update Exercise';
document.querySelector('.tab-btn[onclick*="tab-builder"]').click();
document.getElementById('formTitle').scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// ============================================================
// LINKED-SET VALIDATION
//
// A superset (modifier 2) requires a matching partner with the same
// target_sets. A giant set (modifier 7) requires the next two exercises
// to exist and all three to have the same target_sets.
//
// Two entry points so that building a routine in progress is not
// rejected for being "structurally incomplete":
//
// * validateLinkedSetAtAdd — permissive. Only checks target_sets
// match against any partner that is
// already in the routine. Lets the user
// add a giant-set anchor first, then
// add the 2nd and 3rd members later.
// * validateLinkedSetForSend — strict. Calls the add-time check
// and then enforces structural
// completeness (every superset / giant
// set anchor has the required number
// of partners below it).
// ============================================================
function validateLinkedSetAtAdd(routine, name) {
for (let i = 0; i < routine.length; i++) {
const ex = routine[i];
const modifier = ex.length > 4 ? parseInt(ex[4], 10) : 0;
const targetSets = parseInt(ex[1], 10);
if (modifier === 2) {
// Superset: check the partner below if it exists.
if (i + 1 < routine.length) {
const next = routine[i + 1];
if (parseInt(next[1], 10) !== targetSets) {
alert(`Superset mismatch: '${ex[0]}' has ${targetSets} target sets, but '${next[0]}' has ${parseInt(next[1], 10)}. All exercises in a superset must have the same target sets.`);
return false;
}
}
} else if (modifier === 7) {
// Giant set: check the 2nd and 3rd members if they exist.
if (i + 1 < routine.length) {
const second = routine[i + 1];
if (parseInt(second[1], 10) !== targetSets) {
alert(`Giant Set mismatch: '${ex[0]}' has ${targetSets} target sets, but '${second[0]}' (2nd of 3) has ${parseInt(second[1], 10)}. All exercises in a giant set must have the same target sets.`);
return false;
}
}
if (i + 2 < routine.length) {
const third = routine[i + 2];
if (parseInt(third[1], 10) !== targetSets) {
alert(`Giant Set mismatch: '${ex[0]}' has ${targetSets} target sets, but '${third[0]}' (3rd of 3) has ${parseInt(third[1], 10)}. All exercises in a giant set must have the same target sets.`);
return false;
}
}
}
}
return true;
}
function validateLinkedSetForSend(routine, name) {
if (!validateLinkedSetAtAdd(routine, name)) return false;
for (let i = 0; i < routine.length; i++) {
const ex = routine[i];
const modifier = ex.length > 4 ? parseInt(ex[4], 10) : 0;
if (modifier === 2) {
if (i + 1 >= routine.length) {
alert(`Send failed: '${ex[0]}' is a Superset with no partner below it in '${name}'.`);
return false;
}
} else if (modifier === 7) {
if (i + 2 >= routine.length) {
alert(`Send failed: '${ex[0]}' is a Giant Set but needs two more exercises below it in '${name}'.`);
return false;
}
}
}
return true;
}
// ============================================================
// LINKED-SET CASCADE (edit-time)
//
// When the user edits the target_sets of a single member of a linked
// set, propagate the new value to the other members so the whole set
// stays consistent. The validator then passes and the routine list
// re-renders with the new matching values.
//
// linkedPosition is determined by walking the routine up to (but not
// including) editIndex:
// 0 = normal, 1 = superset 2/2, 2 = giant 2/3, 3 = giant 3/3
// ============================================================
function getLinkedPositionAt(routine, editIndex) {
let pos = 0;
for (let i = 0; i < editIndex; i++) {
const prev = routine[i];
const prevModifier = prev.length > 4 ? parseInt(prev[4], 10) : 0;
if (pos === 3) {
pos = 0; // past giant 3/3 -> next is normal
} else if (pos === 2) {
pos = 3; // prev was giant 2/3, current is giant 3/3
} else if (prevModifier === 7) {
pos = 2; // prev is giant anchor, current is giant 2/3
} else if (prevModifier === 2) {
pos = 1; // prev is superset anchor, current is superset 2/2
} else {
pos = 0; // normal
}
}
return pos;
}
function applyLinkedSetCascade(routine, editIndex) {
const ex = routine[editIndex];
if (!ex) return;
const modifier = ex.length > 4 ? parseInt(ex[4], 10) : 0;
const newTargetSets = parseInt(ex[1], 10);
if (modifier === 7) {
// Giant-set anchor: propagate forward to the next 2 members.
for (let i = 1; i <= 2; i++) {
const t = editIndex + i;
if (t < routine.length) routine[t][1] = newTargetSets;
}
} else if (modifier === 2) {
// Superset anchor: propagate forward to the next 1 member.
const t = editIndex + 1;
if (t < routine.length) routine[t][1] = newTargetSets;
} else {
// The edited exercise might be a 2nd/3rd member of an existing
// linked set. Determine its position by walking the previous
// exercises' modifiers.
const pos = getLinkedPositionAt(routine, editIndex);
if (pos === 1) {
// Superset 2/2: cascade backward to the anchor.
routine[editIndex - 1][1] = newTargetSets;
} else if (pos === 2) {
// Giant 2/3: cascade to the anchor and the 3/3.
routine[editIndex - 1][1] = newTargetSets;
const t = editIndex + 1;
if (t < routine.length) routine[t][1] = newTargetSets;
} else if (pos === 3) {
// Giant 3/3: cascade to the anchor and the 2/3.
routine[editIndex - 1][1] = newTargetSets;
routine[editIndex - 2][1] = newTargetSets;
}
// pos === 0: not part of any linked set; nothing to cascade.
}
}
// ============================================================
// ROUTINE SERIALISATION (shared by single send and batch)