-
-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathworkout-editor-app.js
More file actions
1780 lines (1629 loc) · 78.1 KB
/
Copy pathworkout-editor-app.js
File metadata and controls
1780 lines (1629 loc) · 78.1 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
(function () {
const state = {
miles: false,
device: 'bike',
intervals: [],
programs: [],
programFiles: {}, // Map of program name -> file object (with url, path, etc.)
showAdvanced: false,
lastSaved: '',
loading: false,
translations: {}
};
const selectors = {};
const DEVICE_KEYS = ['bike', 'treadmill', 'elliptical', 'rower', 'jumprope', 'stairclimber'];
function t(key, fallback) {
if (window.qzTranslate) {
return window.qzTranslate(key, fallback);
}
return fallback || key;
}
const FIELD_DEFS = [
{ key: 'name', labelKey: 'workoutEditor.label', label: 'Label', type: 'text', group: 'basic', devices: 'all' },
{ key: 'duration', labelKey: 'workoutEditor.duration', label: 'Duration', type: 'duration', group: 'basic', devices: 'all' },
{ key: 'distance', labelKey: 'workoutEditor.distance', label: 'Distance', type: 'number', unitKey: 'distance', step: 0.1, min: 0, group: 'basic', devices: 'all', defaultValue: -1 },
{ key: 'speed', labelKey: 'workoutEditor.speed', label: 'Speed', type: 'number', unitKey: 'speed', step: 0.1, min: 0, group: 'basic', devices: ['treadmill'], defaultValue: () => state.miles ? 6.0 : 9.5 },
{ key: 'pace', labelKey: 'workoutEditor.pace', label: 'Pace', type: 'pace', unitKey: 'pace', group: 'basic', devices: ['treadmill'], syncWith: 'speed' },
{ key: 'inclination', labelKey: 'workoutEditor.incline', label: 'Incline', type: 'number', unitSuffix: '%', step: 0.5, min: -10, max: 30, group: 'basic', devices: ['treadmill', 'elliptical'], defaultValue: 1.0 },
{ key: 'resistance', labelKey: 'workoutEditor.resistance', label: 'Resistance', type: 'number', step: 1, min: 0, max: 100, group: 'basic', devices: ['bike', 'elliptical'], defaultValue: 20 },
{ key: 'cadence', labelKey: 'workoutEditor.cadence', label: 'Cadence', type: 'number', unitSuffix: 'rpm', min: 0, max: 240, group: 'basic', devices: ['bike', 'elliptical', 'rower'], defaultValue: 80 },
{ key: 'power', labelKey: 'workoutEditor.power', label: 'Power', type: 'number', unitSuffix: 'W', min: 0, max: 2000, group: 'basic', devices: ['bike', 'rower'], defaultValue: 150 },
{ key: 'powerrampunit', labelKey: 'workoutEditor.powerRampUnit', label: 'Ramp Unit', type: 'select', options: ['W', '% FTP'], group: 'advanced', devices: ['bike', 'rower'], defaultValue: 'W', noToggle: true },
{ key: 'powerfrom', labelKey: 'workoutEditor.powerRampFrom', label: 'Ramp From', type: 'number', min: 0, max: 2000, group: 'advanced', devices: ['bike', 'rower'], defaultValue: 100 },
{ key: 'powerto', labelKey: 'workoutEditor.powerRampTo', label: 'Ramp To', type: 'number', min: 0, max: 2000, group: 'advanced', devices: ['bike', 'rower'], defaultValue: 200 },
{ key: 'forcespeed', labelKey: 'workoutEditor.forceSpeed', label: 'Force Speed', type: 'bool', group: 'basic', devices: ['treadmill'], linkedTo: 'speed' },
{ key: 'fanspeed', labelKey: 'workoutEditor.fan', label: 'Fan', type: 'number', min: 0, max: 8, group: 'advanced', devices: 'all', defaultValue: 0 },
{ key: 'requested_peloton_resistance', labelKey: 'workoutEditor.pelotonResistance', label: 'Peloton Res.', type: 'number', min: -1, max: 100, group: 'advanced', devices: ['bike'] },
{ key: 'loopTimeHR', labelKey: 'workoutEditor.hrLoop', label: 'HR Loop (s)', type: 'number', min: 1, max: 60, group: 'advanced', devices: 'all' },
{ key: 'zoneHR', labelKey: 'workoutEditor.hrZone', label: 'HR Zone', type: 'number', min: -1, max: 5, group: 'advanced', devices: 'all' },
{ key: 'HRmin', labelKey: 'workoutEditor.hrMin', label: 'HR Min', type: 'number', min: -1, max: 240, group: 'advanced', devices: 'all' },
{ key: 'HRmax', labelKey: 'workoutEditor.hrMax', label: 'HR Max', type: 'number', min: -1, max: 240, group: 'advanced', devices: 'all' },
{ key: 'minSpeed', labelKey: 'workoutEditor.minSpeed', label: 'Min Speed', type: 'number', unitKey: 'speed', group: 'advanced', devices: ['treadmill', 'bike'] },
{ key: 'maxSpeed', labelKey: 'workoutEditor.maxSpeed', label: 'Max Speed', type: 'number', unitKey: 'speed', group: 'advanced', devices: ['treadmill', 'bike'] },
{ key: 'maxResistance', labelKey: 'workoutEditor.maxResistance', label: 'Max Resistance', type: 'number', min: -1, max: 100, group: 'advanced', devices: ['bike', 'elliptical'] },
{ key: 'mets', label: 'METS', type: 'number', min: -1, max: 40, group: 'advanced', devices: 'all' }
];
const SERIES_DEFS = {
treadmill: [
{ key: 'speed', label: () => t('workoutEditor.speed', 'Speed'), color: '#42a5f5', unit: () => state.miles ? 'mph' : 'km/h', axis: 'speedAxis', axisLabel: () => state.miles ? t('workoutEditor.speedMph', 'Speed (mph)') : t('workoutEditor.speedKmh', 'Speed (km/h)'), axisPosition: 'left' },
{ key: 'inclination', label: () => t('workoutEditor.incline', 'Incline'), color: '#26c6da', unit: () => '%', axis: 'inclineAxis', axisLabel: () => t('workoutEditor.inclinePercent', 'Incline (%)'), axisPosition: 'right' }
],
bike: [
{ key: 'resistance', label: () => t('workoutEditor.resistance', 'Resistance'), color: '#ab47bc', unit: () => 'lvl', axis: 'resistanceAxis', axisLabel: () => t('workoutEditor.resistance', 'Resistance'), axisPosition: 'left' },
{ key: 'cadence', label: () => t('workoutEditor.cadence', 'Cadence'), color: '#29b6f6', unit: () => 'rpm', axis: 'cadenceAxis', axisLabel: () => t('workoutEditor.cadenceRpm', 'Cadence (rpm)'), axisPosition: 'right' },
{ key: 'power', label: () => t('workoutEditor.power', 'Power'), color: '#ef6c00', unit: () => 'W', axis: 'powerAxis', axisLabel: () => t('workoutEditor.powerW', 'Power (W)'), axisPosition: 'left', stepped: false }
],
elliptical: [
{ key: 'resistance', label: () => t('workoutEditor.resistance', 'Resistance'), color: '#7e57c2', unit: () => 'lvl', axis: 'resistanceAxis', axisLabel: () => t('workoutEditor.resistance', 'Resistance'), axisPosition: 'left' },
{ key: 'inclination', label: () => t('workoutEditor.ramp', 'Ramp'), color: '#66bb6a', unit: () => '%', axis: 'inclineAxis', axisLabel: () => t('workoutEditor.rampPercent', 'Ramp (%)'), axisPosition: 'right' }
],
rower: [
{ key: 'power', label: () => t('workoutEditor.power', 'Power'), color: '#fb8c00', unit: () => 'W', axis: 'powerAxis', axisLabel: () => t('workoutEditor.powerW', 'Power (W)'), axisPosition: 'left', stepped: false },
{ key: 'cadence', label: () => t('workoutEditor.strokeRate', 'Stroke Rate'), color: '#26a69a', unit: () => 'spm', axis: 'cadenceAxis', axisLabel: () => t('workoutEditor.strokesPerMinute', 'Strokes/min'), axisPosition: 'right' }
],
jumprope: [],
stairclimber: []
};
// Default values that indicate a field should not be enabled
const DEFAULT_DISABLED_VALUES = {
distance: -1,
speed: -1,
cadence: -1,
resistance: -1,
power: -1,
inclination: -200,
requested_peloton_resistance: -1,
zoneHR: -1,
HRmin: -1,
HRmax: -1,
minSpeed: -1,
maxSpeed: -1,
maxResistance: -1,
mets: -1
};
// Custom dialog system for iOS WebView compatibility
// iOS WebView doesn't properly support prompt() and confirm()
const dialog = {
elements: {},
init() {
this.elements.container = document.getElementById('customDialog');
this.elements.title = document.getElementById('customDialogTitle');
this.elements.message = document.getElementById('customDialogMessage');
this.elements.input = document.getElementById('customDialogInput');
this.elements.cancelBtn = document.getElementById('customDialogCancel');
this.elements.confirmBtn = document.getElementById('customDialogConfirm');
},
show(title, message, options = {}) {
return new Promise((resolve) => {
console.log('[dialog.show] Title:', title, 'Message:', message, 'Options:', options);
// Set content
this.elements.title.textContent = title;
this.elements.message.textContent = message;
// Configure input field
if (options.input) {
this.elements.input.classList.remove('hidden');
this.elements.input.value = options.defaultValue || '';
this.elements.input.placeholder = options.placeholder || '';
} else {
this.elements.input.classList.add('hidden');
}
// Configure cancel button
if (options.showCancel !== false) {
this.elements.cancelBtn.classList.remove('hidden');
} else {
this.elements.cancelBtn.classList.add('hidden');
}
// Set button labels
this.elements.cancelBtn.textContent = options.cancelLabel || t('common.cancel', 'Cancel');
this.elements.confirmBtn.textContent = options.confirmLabel || t('common.ok', 'OK');
// Show dialog
this.elements.container.classList.remove('hidden');
// Focus input if present
if (options.input) {
setTimeout(() => this.elements.input.focus(), 100);
}
// Handle buttons
const handleConfirm = () => {
cleanup();
const result = options.input ? this.elements.input.value : true;
console.log('[dialog.show] Confirmed with result:', result);
resolve(result);
};
const handleCancel = () => {
cleanup();
console.log('[dialog.show] Cancelled');
resolve(null);
};
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleConfirm();
} else if (e.key === 'Escape') {
e.preventDefault();
handleCancel();
}
};
const cleanup = () => {
this.elements.confirmBtn.removeEventListener('click', handleConfirm);
this.elements.cancelBtn.removeEventListener('click', handleCancel);
this.elements.input.removeEventListener('keypress', handleKeyPress);
this.elements.container.classList.add('hidden');
};
this.elements.confirmBtn.addEventListener('click', handleConfirm);
this.elements.cancelBtn.addEventListener('click', handleCancel);
this.elements.input.addEventListener('keypress', handleKeyPress);
});
},
confirm(message, title = t('common.confirm', 'Confirm')) {
console.log('[dialog.confirm] Message:', message);
return this.show(title, message, { showCancel: true });
},
prompt(message, defaultValue = '', title = t('common.input', 'Input')) {
console.log('[dialog.prompt] Message:', message, 'Default:', defaultValue);
return this.show(title, message, {
input: true,
defaultValue,
showCancel: true
});
},
alert(message, title = t('common.alert', 'Alert')) {
console.log('[dialog.alert] Message:', message);
return this.show(title, message, { showCancel: false });
}
};
document.addEventListener('DOMContentLoaded', () => {
cacheDom();
bindEvents();
bootstrap();
if (window.QZ_OFFLINE) {
announce(t('workoutEditor.offlineLoadSaveStartDisabled', 'Offline mode: load/save/start disabled'), true);
updateControls();
}
});
function cacheDom() {
selectors.name = document.getElementById('workoutName');
selectors.device = document.getElementById('deviceSelect');
selectors.advanced = document.getElementById('advancedToggle');
selectors.intervalList = document.getElementById('intervalList');
selectors.addInterval = document.getElementById('addInterval');
selectors.repeatSelection = document.getElementById('repeatSelection');
selectors.clearIntervals = document.getElementById('clearIntervals');
selectors.newWorkout = document.getElementById('newWorkout');
selectors.pasteClipboard = document.getElementById('pasteClipboard');
selectors.saveWorkout = document.getElementById('saveWorkout');
selectors.saveStartWorkout = document.getElementById('saveStartWorkout');
selectors.programSelect = document.getElementById('programSelect');
selectors.loadProgram = document.getElementById('loadProgram');
selectors.deleteProgram = document.getElementById('deleteProgram');
selectors.refreshPrograms = document.getElementById('refreshPrograms');
selectors.statusDuration = document.getElementById('statusDuration');
selectors.statusIntervals = document.getElementById('statusIntervals');
selectors.statusMessage = document.getElementById('statusMessage');
selectors.offlineBanner = document.getElementById('offlineBanner');
// Initialize custom dialog system for iOS WebView compatibility
dialog.init();
}
function bindEvents() {
selectors.device.addEventListener('change', () => {
if (window.QZ_OFFLINE) {
state.device = selectors.device.value;
renderIntervals();
updateChart();
return;
}
setDevice(selectors.device.value);
});
selectors.advanced.addEventListener('change', () => {
state.showAdvanced = selectors.advanced.checked;
renderIntervals();
updateChart();
});
selectors.addInterval.addEventListener('click', () => {
addInterval();
announce(t('workoutEditor.intervalAdded', 'Interval added'));
});
selectors.repeatSelection.addEventListener('click', () => {
console.log('[button] Repeat Selection button clicked');
repeatSelection();
});
selectors.clearIntervals.addEventListener('click', async () => {
if (state.intervals.length) {
const confirmed = await dialog.confirm(t('workoutEditor.removeAllIntervals', 'Remove all intervals?'));
if (!confirmed) {
return;
}
}
state.intervals = [];
addInterval();
renderIntervals();
updateChart();
updateStatus();
updateControls();
});
selectors.newWorkout.addEventListener('click', () => {
state.lastSaved = '';
selectors.name.value = '';
state.intervals = [];
addInterval();
renderIntervals();
updateChart();
updateStatus();
updateControls();
announce(t('workoutEditor.newWorkoutReady', 'New workout ready'));
});
selectors.pasteClipboard.addEventListener('click', () => pasteXmlFromClipboard());
selectors.saveWorkout.addEventListener('click', () => saveWorkflow(false));
selectors.saveStartWorkout.addEventListener('click', () => saveWorkflow(true));
selectors.loadProgram.addEventListener('click', () => {
if (window.QZ_OFFLINE) {
announce(t('workoutEditor.offlineCannotLoad', 'Offline: cannot load workouts'), true);
return;
}
const name = selectors.programSelect.value;
if (!name) {
announce(t('workoutEditor.selectWorkoutLoad', 'Select a workout to load'), true);
return;
}
loadProgram(name);
});
selectors.deleteProgram.addEventListener('click', () => {
if (window.QZ_OFFLINE) {
announce(t('workoutEditor.offlineCannotDelete', 'Offline: cannot delete workouts'), true);
return;
}
const name = selectors.programSelect.value;
if (!name) {
announce(t('workoutEditor.selectWorkoutDelete', 'Select a workout to delete'), true);
return;
}
deleteProgram(name);
});
selectors.refreshPrograms.addEventListener('click', () => {
if (window.QZ_OFFLINE) {
announce(t('workoutEditor.offlineCannotRefresh', 'Offline: cannot refresh list'), true);
return;
}
refreshProgramList();
});
}
function bootstrap() {
// Always start with one interval
if (!state.intervals.length) {
state.intervals.push(createInterval(1));
}
// Render immediately to show the initial interval
renderIntervals();
updateChart();
updateStatus();
updateControls();
// Then fetch environment and programs in background
Promise.allSettled([fetchEnvironment(), refreshProgramList()]).then(() => {
// Re-render after fetching environment (in case device changed)
renderIntervals();
updateChart();
updateStatus();
updateControls();
});
}
function fetchEnvironment() {
if (window.QZ_OFFLINE) {
return Promise.resolve();
}
return sendMessage('workouteditor_env', {}, 'R_workouteditor_env').then(content => {
if (!content) {
return;
}
state.miles = !!content.miles;
if (content.ftp !== undefined) {
state.ftp = Number(content.ftp);
}
state.translations = content.translations || {};
if (window.qzSetTranslations) {
window.qzSetTranslations(state.translations);
}
const envDevice = normalizeDevice(content.device);
if (envDevice) {
state.device = envDevice;
}
selectors.device.value = state.device;
}).catch(err => {
console.error(err);
announce(t('workoutEditor.environmentNotAvailable', 'Environment not available'), true);
});
}
function refreshProgramList() {
if (window.QZ_OFFLINE) {
state.programs = [];
state.programFiles = {}; // Map of name -> file object
renderProgramOptions();
updateControls();
return Promise.resolve();
}
return sendMessage('loadtrainingprograms', '', 'R_loadtrainingprograms').then(content => {
// Backend returns content.files (array of objects with name, url, isFolder, etc.)
const files = Array.isArray(content && content.files) ? content.files : [];
// Filter out folders
const workoutFiles = files.filter(f => !f.isFolder);
// Store file names for dropdown
state.programs = workoutFiles.map(f => f.name);
// Store file objects for URL lookup
state.programFiles = {};
workoutFiles.forEach(f => {
state.programFiles[f.name] = f;
});
renderProgramOptions();
updateControls();
}).catch(err => {
console.error(err);
announce(t('workoutEditor.cannotLoadProgramList', 'Cannot load program list'), true);
});
}
function renderProgramOptions() {
selectors.programSelect.innerHTML = '';
const placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = state.programs.length ? t('workoutEditor.selectSavedWorkout', 'Select saved workout') : t('workoutEditor.noSavedWorkouts', 'No saved workouts');
selectors.programSelect.appendChild(placeholder);
state.programs.sort((a, b) => a.localeCompare(b));
state.programs.forEach(name => {
const opt = document.createElement('option');
opt.value = name;
opt.textContent = name;
selectors.programSelect.appendChild(opt);
});
if (state.lastSaved && state.programs.includes(state.lastSaved)) {
selectors.programSelect.value = state.lastSaved;
}
}
function loadProgram(name) {
setWorking(true);
// Get file URL from stored program files
const fileObj = state.programFiles[name];
if (!fileObj || !fileObj.url) {
announce(t('workoutEditor.cannotFindWorkoutFile', 'Cannot find workout file'), true);
setWorking(false);
return;
}
const fileUrl = fileObj.url;
// Send message to open the training program file (no response expected)
sendMessage('trainprogram_open_clicked', { url: fileUrl });
// Wait a bit for the file to load, then get the program rows
setTimeout(() => {
sendMessage('gettrainingprogram', '', 'R_gettrainingprogram')
.then(content => {
const rows = Array.isArray(content && content.list) ? content.list : [];
if (!rows.length) {
announce(t('workoutEditor.workoutEmptyCannotRead', 'Workout is empty or cannot be read'), true);
return;
}
applyLoadedRows(rows, name, `Loaded ${name}`, normalizeDevice(content.device));
})
.catch(err => {
console.error(err);
announce(t('workoutEditor.unableLoadWorkout', 'Unable to load workout'), true);
})
.finally(() => setWorking(false));
}, 300); // Give backend time to load the file
}
function applyLoadedRows(rows, name, message, deviceHint) {
state.intervals = rows.map((row, idx) => convertRow(row, idx));
state.device = deviceHint || detectDevice(state.intervals) || state.device;
selectors.device.value = state.device;
selectors.name.value = name;
state.lastSaved = name;
renderIntervals();
updateChart();
updateStatus();
updateControls();
announce(message || `Loaded ${name}`);
}
function pasteXmlFromClipboard() {
if (window.QZ_OFFLINE) {
announce(t('workoutEditor.offlineCannotReadClipboard', 'Offline: cannot read clipboard'), true);
return;
}
const fallbackName = selectors.name.value.trim() || state.lastSaved || '';
setWorking(true);
sendMessage('pastetrainingprogramclipboard', { name: fallbackName }, 'R_pastetrainingprogramclipboard')
.then(content => {
if (!content || !content.ok) {
announce((content && content.message) || t('workoutEditor.unablePasteClipboard', 'Unable to paste XML from clipboard'), true);
return;
}
const rows = Array.isArray(content.list) ? content.list : [];
if (!rows.length) {
announce(t('workoutEditor.clipboardXmlEmpty', 'Clipboard XML is empty or cannot be read'), true);
return;
}
applyLoadedRows(rows, content.name || fallbackName || 'Clipboard_Workout.xml', t('workoutEditor.workoutPastedClipboard', 'Workout pasted from clipboard'));
refreshProgramList();
})
.catch(err => {
console.error(err);
announce(t('workoutEditor.unablePasteClipboard', 'Unable to paste XML from clipboard'), true);
})
.finally(() => setWorking(false));
}
async function deleteProgram(name) {
const confirmed = await dialog.confirm(
t('workoutEditor.deleteWorkoutConfirm', 'Are you sure you want to delete "{name}"? This cannot be undone.').replace('{name}', name),
t('workoutEditor.deleteWorkoutTitle', 'Delete Workout')
);
if (!confirmed) {
return;
}
setWorking(true);
console.log('[deleteProgram] Deleting workout:', name);
// Get file URL from stored program files
const fileObj = state.programFiles[name];
if (!fileObj || !fileObj.url) {
announce(t('workoutEditor.cannotFindWorkoutFile', 'Cannot find workout file'), true);
setWorking(false);
return;
}
// Send delete message to backend
sendMessage('deletetrainingprogram', { url: fileObj.url }, 'R_deletetrainingprogram')
.then(content => {
console.log('[deleteProgram] Delete response:', content);
if (content && content.success) {
announce(`Deleted ${name}`);
// Clear the name field if it matches the deleted workout
if (state.lastSaved === name) {
state.lastSaved = '';
selectors.name.value = '';
}
// Refresh the program list
return refreshProgramList();
} else {
announce(t('workoutEditor.failedDeleteWorkout', 'Failed to delete workout'), true);
}
})
.catch(err => {
console.error('[deleteProgram] Error:', err);
announce(t('workoutEditor.unableDeleteWorkout', 'Unable to delete workout'), true);
})
.finally(() => setWorking(false));
}
function extractRowLabel(row) {
if (row.name && row.name !== 'null') {
return row.name;
}
const textEvents = Array.isArray(row.textEvents) ? row.textEvents : [];
for (const event of textEvents) {
if (!event || typeof event.message !== 'string') {
continue;
}
const message = event.message.trim();
if (message) {
return message;
}
}
return '';
}
function convertRow(row, idx) {
const out = {};
out.name = extractRowLabel(row) || `Interval ${idx + 1}`;
if (!out.name || out.name === 'null') {
out.name = `Interval ${idx + 1}`;
}
if (row.duration && typeof row.duration === 'string') {
out.duration = row.duration;
} else if (typeof row.duration_s === 'number') {
out.duration = formatDuration(row.duration_s);
} else {
out.duration = '00:05:00';
}
FIELD_DEFS.forEach(def => {
if (def.key === 'name' || def.key === 'duration') {
return;
}
if (row[def.key] !== undefined && row[def.key] !== null) {
let value;
if (def.type === 'bool') {
value = row[def.key] === true || row[def.key] === 1;
out[def.key] = value;
out['__enabled_' + def.key] = true;
} else if (def.type === 'number') {
value = Number(row[def.key]);
// Check if value is the default disabled value BEFORE conversion
const isDefaultValue = DEFAULT_DISABLED_VALUES[def.key] !== undefined &&
value === DEFAULT_DISABLED_VALUES[def.key];
// Convert distance/speed from km to miles if needed (XML always stores in km)
// Only convert if NOT a disabled value
if ((def.unitKey === 'distance' || def.unitKey === 'speed') && state.miles && !isDefaultValue) {
value = value / 1.60934;
}
// Truncate speed values to 1 decimal place to avoid floating-point precision issues
if (def.unitKey === 'speed' && !isDefaultValue) {
value = Math.round(value * 10) / 10;
}
if (!isDefaultValue) {
out[def.key] = value;
// Mark field as enabled if it has a non-default value
out['__enabled_' + def.key] = true;
// Handle linked fields (like forcespeed)
if (def.key === 'speed') {
// Enable forcespeed when speed is enabled
out['__enabled_forcespeed'] = true;
// Set forcespeed value from row, or default to false
if (row.forcespeed !== undefined && row.forcespeed !== null) {
out['forcespeed'] = row.forcespeed === true || row.forcespeed === 1;
} else {
out['forcespeed'] = false;
}
}
} else {
// Value is default, mark as disabled
out['__enabled_' + def.key] = false;
// Disable linked fields too
if (def.key === 'speed') {
out['__enabled_forcespeed'] = false;
}
}
} else {
out[def.key] = row[def.key];
out['__enabled_' + def.key] = true;
}
} else {
// Field not present in saved workout, mark as disabled
out['__enabled_' + def.key] = false;
}
});
// FTP% ramp (from backend that collapsed the rows)
if (row.powerzonefrom !== undefined && row.powerzonefrom !== null && Number(row.powerzonefrom) >= 0) {
out.powerrampunit = '% FTP';
out['__enabled_powerrampunit'] = true;
out.powerfrom = Math.round(Number(row.powerzonefrom) * 100);
out['__enabled_powerfrom'] = true;
out.powerto = Math.round(Number(row.powerzoneto) * 100);
out['__enabled_powerto'] = true;
}
// Watts ramp
else if (row.powerfrom !== undefined && row.powerfrom !== null && Number(row.powerfrom) >= 0) {
out.powerrampunit = 'W';
out['__enabled_powerrampunit'] = true;
// powerfrom/powerto already read by the FIELD_DEFS loop above
}
out.__enabled_duration = out.__enabled_distance === true ? false : true;
out.__selected = false;
return out;
}
function detectDevice(rows) {
// Helper to check if a field has a valid (non-default) value
const hasValidValue = (row, key) => {
if (row[key] === undefined || row[key] === null) return false;
if (DEFAULT_DISABLED_VALUES[key] !== undefined) {
return row[key] !== DEFAULT_DISABLED_VALUES[key];
}
return true;
};
// Check for elliptical before treadmill because elliptical rows also use inclination.
for (const row of rows) {
if ((hasValidValue(row, 'resistance') || hasValidValue(row, 'maxResistance')) &&
hasValidValue(row, 'inclination')) {
return 'elliptical';
}
}
// Check for treadmill: has speed or inclination
for (const row of rows) {
if (hasValidValue(row, 'speed') || hasValidValue(row, 'inclination')) {
return 'treadmill';
}
}
// Check for bike: has resistance without treadmill-style incline
for (const row of rows) {
if (hasValidValue(row, 'resistance') || hasValidValue(row, 'maxResistance')) {
return 'bike';
}
}
// Check for rower/bike: has power
for (const row of rows) {
if (hasValidValue(row, 'power')) {
if (hasValidValue(row, 'cadence') && !rows.some(r => hasValidValue(r, 'resistance'))) {
return 'rower';
}
return 'bike';
}
}
return null;
}
function setDevice(key) {
if (!normalizeDevice(key)) {
return;
}
state.device = key;
selectors.device.value = key;
renderIntervals();
updateChart();
}
function addInterval(afterIndex) {
const interval = createInterval(state.intervals.length + 1);
if (typeof afterIndex === 'number' && afterIndex >= 0) {
state.intervals.splice(afterIndex + 1, 0, interval);
} else {
state.intervals.push(interval);
}
renderIntervals();
updateChart();
updateStatus();
}
function createInterval(count) {
const base = {
name: `Interval ${count}`,
duration: '00:05:00'
};
// Initialize all fields as disabled by default
FIELD_DEFS.forEach(def => {
if (def.key !== 'name' && def.key !== 'duration') {
base['__enabled_' + def.key] = false;
}
});
switch (state.device) {
case 'bike':
base.resistance = 20;
base.__enabled_resistance = true;
base.cadence = 80;
base.__enabled_cadence = true;
base.power = 180;
base.__enabled_power = false; // disabled by default, user chooses resistance OR power
break;
case 'elliptical':
base.resistance = 12;
base.__enabled_resistance = true;
base.inclination = 5;
base.__enabled_inclination = true;
base.cadence = 60;
base.__enabled_cadence = true;
break;
case 'rower':
base.power = 180;
base.__enabled_power = true;
base.cadence = 28;
base.__enabled_cadence = true;
break;
case 'treadmill':
base.speed = state.miles ? 6.0 : 9.5;
base.__enabled_speed = true;
base.inclination = 1.0;
base.__enabled_inclination = true;
base.__enabled_duration = true;
base.__enabled_distance = false;
break;
case 'jumprope':
case 'stairclimber':
default:
base.__enabled_duration = true;
base.__enabled_distance = false;
break;
}
base.__selected = false;
return base;
}
function renderIntervals() {
selectors.intervalList.innerHTML = '';
if (!state.intervals.length) {
return;
}
state.intervals.forEach((row, index) => {
const card = document.createElement('div');
card.className = 'interval-card';
if (row.__selected) {
card.classList.add('selected');
}
if (row.__selected === undefined) {
row.__selected = false;
}
const header = document.createElement('div');
header.className = 'card-header';
const headerLeft = document.createElement('div');
headerLeft.className = 'card-header-left';
const selectBox = document.createElement('input');
selectBox.type = 'checkbox';
selectBox.checked = !!row.__selected;
selectBox.title = t('workoutEditor.selectInterval', 'Select interval');
selectBox.addEventListener('change', event => {
row.__selected = event.target.checked;
card.classList.toggle('selected', row.__selected);
console.log('[checkbox] Interval', index, 'selected:', row.__selected);
updateControls();
});
headerLeft.appendChild(selectBox);
const title = document.createElement('div');
title.className = 'card-header-name';
title.textContent = row.name ? `${row.name}` : t('workoutEditor.intervalNumber', 'Interval {number}').replace('{number}', index + 1);
headerLeft.appendChild(title);
header.appendChild(headerLeft);
const actions = document.createElement('div');
actions.className = 'card-actions';
actions.appendChild(actionButton('↑', () => moveInterval(index, -1), index === 0));
actions.appendChild(actionButton('↓', () => moveInterval(index, 1), index === state.intervals.length - 1));
actions.appendChild(actionButton(t('common.copy', 'Copy'), () => duplicateInterval(index)));
actions.appendChild(actionButton(t('common.del', 'Del'), () => removeInterval(index), state.intervals.length === 1));
header.appendChild(actions);
card.appendChild(header);
const grid = document.createElement('div');
grid.className = 'field-grid';
FIELD_DEFS.forEach(field => {
if (!shouldRenderField(field)) {
return;
}
// Skip linked fields entirely from UI rendering
if (field.linkedTo) {
return;
}
const value = row[field.key];
// For pace field, use speed's enabled state; fields without a toggle are always enabled
const isEnabled = field.noToggle ? true : (field.syncWith ? (row['__enabled_' + field.syncWith] !== false) : (row['__enabled_' + field.key] !== false));
const fieldWrap = document.createElement('div');
fieldWrap.className = 'field';
if (!isEnabled) {
fieldWrap.classList.add('disabled');
}
// Create label with enable/disable checkbox (except for name, linked fields, and synced fields like pace)
// Duration can be disabled for treadmill (mutually exclusive with distance)
const labelWrap = document.createElement('label');
labelWrap.className = 'field-label';
const allowToggle = field.key !== 'name' && !field.linkedTo && !field.syncWith && !field.noToggle;
if (allowToggle) {
const enableCheckbox = document.createElement('input');
enableCheckbox.type = 'checkbox';
enableCheckbox.checked = isEnabled;
enableCheckbox.dataset.index = index;
enableCheckbox.dataset.key = field.key;
enableCheckbox.addEventListener('change', (e) => {
const checked = e.target.checked;
row['__enabled_' + field.key] = checked;
if (checked) {
fieldWrap.classList.remove('disabled');
// Set default value if field is empty
if (row[field.key] === undefined || row[field.key] === null || row[field.key] === '') {
const defaultVal = typeof field.defaultValue === 'function' ? field.defaultValue() : field.defaultValue;
if (defaultVal !== undefined) {
row[field.key] = defaultVal;
}
}
// Handle linked fields (like forcespeed)
if (field.key === 'speed') {
row['__enabled_forcespeed'] = true;
row['forcespeed'] = false; // default to false
}
// Duration and distance are mutually exclusive.
if (field.key === 'distance') {
row['__enabled_duration'] = false;
} else if (field.key === 'duration') {
row['__enabled_distance'] = false;
}
} else {
fieldWrap.classList.add('disabled');
// Disable linked fields
if (field.key === 'speed') {
row['__enabled_forcespeed'] = false;
}
}
// Re-render to update the UI
renderIntervals();
updateChart();
updateStatus();
});
labelWrap.appendChild(enableCheckbox);
}
const labelText = document.createElement('span');
labelText.textContent = resolveFieldLabel(field, row);
labelWrap.appendChild(labelText);
fieldWrap.appendChild(labelWrap);
if (field.type === 'bool') {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = !!value;
checkbox.dataset.index = index;
checkbox.dataset.key = field.key;
checkbox.dataset.type = field.type;
checkbox.addEventListener('change', handleFieldChange);
fieldWrap.appendChild(checkbox);
} else if (field.type === 'select') {
const sel = document.createElement('select');
sel.className = 'field-input field-select';
(field.options || []).forEach(opt => {
const option = document.createElement('option');
option.value = opt;
option.textContent = opt;
const currentVal = String(row[field.key] !== undefined ? row[field.key] : (field.defaultValue !== undefined ? field.defaultValue : ''));
if (currentVal === opt) {
option.selected = true;
}
sel.appendChild(option);
});
sel.addEventListener('change', () => {
row[field.key] = sel.value;
renderIntervals();
});
fieldWrap.appendChild(sel);
} else {
const inputWrapper = document.createElement('div');
inputWrapper.className = 'field-with-buttons';
const input = document.createElement('input');
input.dataset.index = index;
input.dataset.key = field.key;
input.dataset.type = field.type;
if (field.type === 'duration') {
input.type = 'text';
input.value = value || '00:05:00';
input.placeholder = 'hh:mm:ss';
} else if (field.type === 'pace') {
input.type = 'text';
// Calculate pace from speed
const speedValue = field.syncWith ? row[field.syncWith] : null;
input.value = speedValue ? speedToPace(speedValue) : '';
input.placeholder = 'mm:ss';
} else if (field.type === 'text') {
input.type = 'text';
input.value = value || '';
} else {
input.type = 'number';
if (field.step !== undefined) input.step = field.step;
if (field.min !== undefined) input.min = field.min;
if (field.max !== undefined) input.max = field.max;
input.value = value !== undefined ? value : '';
}
// Use 'change' event for duration, pace, and number fields to prevent keyboard from closing during typing
input.addEventListener(field.type === 'duration' || field.type === 'pace' || field.type === 'number' ? 'change' : 'input', handleFieldChange);
// Add +/- buttons for duration, number, and pace fields
if (field.type === 'duration' || field.type === 'number' || field.type === 'pace') {
const decreaseBtn = document.createElement('button');
decreaseBtn.textContent = '-';
decreaseBtn.type = 'button';
decreaseBtn.title = t('common.decrease', 'Decrease');
decreaseBtn.addEventListener('click', () => handleIncrement(input, field, -1));
const increaseBtn = document.createElement('button');
increaseBtn.textContent = '+';
increaseBtn.type = 'button';
increaseBtn.title = t('common.increase', 'Increase');
increaseBtn.addEventListener('click', () => handleIncrement(input, field, 1));
inputWrapper.appendChild(decreaseBtn);
inputWrapper.appendChild(input);
inputWrapper.appendChild(increaseBtn);
fieldWrap.appendChild(inputWrapper);
} else {
fieldWrap.appendChild(input);
}
}
grid.appendChild(fieldWrap);
});
card.appendChild(grid);
selectors.intervalList.appendChild(card);
});
updateControls();
}
function shouldRenderField(field) {
// Linked fields are shown conditionally in the render loop
if (field.group === 'advanced' && !state.showAdvanced) {
return false;
}
if (field.devices === 'all') {
return true;
}
return Array.isArray(field.devices) && field.devices.indexOf(state.device) >= 0;
}
function resolveFieldLabel(field, interval) {
if (typeof field.label === 'function') {
return field.label();
}
const label = field.labelKey ? t(field.labelKey, field.label) : field.label;
if (field.unitKey === 'distance') {
return `${label} (${state.miles ? 'mi' : 'km'})`;
}
if (field.unitKey === 'speed') {
return `${label} (${state.miles ? 'mph' : 'km/h'})`;
}
if (field.unitKey === 'pace') {
return `${label} (${state.miles ? 'min/mi' : 'min/km'})`;