-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
852 lines (775 loc) · 29.6 KB
/
index.html
File metadata and controls
852 lines (775 loc) · 29.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="favicon.png" type="image/png">
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'selector',
}
</script>
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<script src=" https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js "></script>
<title>Race Nutrition Planner</title>
<style type="text/tailwindcss">
button {
@apply border-gray-300 border rounded p-1 pl-2 pr-2 m-1 font-normal bg-white;
}
th {
@apply font-normal;
}
textarea {
height: 34px;
@apply p-1;
margin-top: 1px;
}
input, textarea {
@apply border-gray-300 border rounded;
}
</style>
</head>
<body class="text-gray-800 bg-slate-100">
<div class="m-2 mb-0">
<div class="flex flex-row justify-start items-center">
<h1 class="text-2xl">Race Nutrition Planner</h1>
<div class="ml-auto mr-4">
<button id="show-instructions" class="hidden" onclick="toggleInstructions(true)">Show info</button>
<button id="hide-instructions" class="ml-0" onclick="toggleInstructions(false)">Hide info</button>
<button class="mt-0 ml-2" id="reset" title="Delete all rows and load sample data">Reset</button>
<button class="mt-0" id="copy-json" title="Copy data in JSON format to share or transfer">Copy JSON</button>
<button class="mt-0" id="import-json" title="Import JSON exported from another session">Import JSON</button>
<button class="mt-0" id="copy-csv" title="Copy plan in CSV format to use in spreadsheet">Copy CSV</button>
</div>
<div>
<script type='text/javascript' src='https://storage.ko-fi.com/cdn/widget/Widget_2.js'></script>
<script
type='text/javascript'>kofiwidget2.init('Support me', '#91c0d6', 'M4M114E6DD'); kofiwidget2.draw();</script>
</div>
</div>
<div id="instructions" class="hidden mb-2">
<p>Interactively create and visualize your fueling strategy for the next race.</p>
<p>Begin by entering the distance and planned duration of the race.</p>
<p>Markers can be placed based on either time or distance. Examples of acceptable values for distance: "100
m", "3.4 km", "2 mi".</p>
<p>For time and duration, acceptable values are: "4min", "1.5 h", "-44 sec", "1:15" (1 hour and 15 minutes),
or "2:13:09".</p>
<p>Each marker can optionally have an "effect" range, specified by an offset and duration. This is useful
for visualizing when certain nutritional items, like a coffee shot, will take effect.</p>
<p>Move markers up and down with "Track" to separate them visually.</p>
<p class="pt-2">
Created by <a class="underline" href="https://github.com/metaflow" target="_blank">Mikhail Goncharov</a>, 2024.
</p>
<p>
<a class="underline" href="https://www.flaticon.com/free-icons/running-shoes" title="running shoes icons">Running shoes icons created by Freepik - Flaticon</a>
</p>
</div>
</div>
</div>
<div class="h-full w-full">
<div id="message" class="invisible ml-2">messages</div>
<div id="timeline-container" class="w-full"></div>
<div class="p-4 flex flex-row items-center">
<div class="mr-4">
<label for="race-distance" class="inline-block">Distance</label>
<input type="text" id="race-distance" class="border p-1 w-20"></input>
</div>
<div class="mr-4">
<label for="race-duration" class="inline-block">Duration</label>
<input type="text" id="race-duration" class="border p-1 w-20"></input>
</div>
<div>
<span class="inline-block">Pace is</span>
<span id="race-pace" class="inline-block">0:00 min/km 0:00 min/mile.</span>
</div>
</div>
<div class="p-3" id="table-container"></div>
</div>
<script>
let appData = {};
function resetData() {
localStorage.removeItem("race_data");
loadData();
render();
updateControls();
}
document.getElementById("reset").addEventListener("click", resetData);
function updateDataFormat(data) {
if (data.formatVersion === "1") {
data.formatVersion = "2";
data.points = data.points.map((p) => ({
label: p.label,
color: p.color,
notes: p.notes,
position: p.position,
effects: [
{
start: p.start,
duration: p.duration,
track: p.track,
},
],
}));
}
if (data.formatVersion !== "2") {
console.error("Unknown format version", data.formatVersion);
}
return data;
}
const loadData = () => {
let s = localStorage.getItem("race_data");
if (s == null)
s = `{
"formatVersion": "1",
"raceDistance": "21.1km",
"raceDuration": "2:30:00",
"points": [
{
"label": "Start",
"position": "0km",
"color": "#d7284b",
"notes": "",
"effects": [{
"start": "0min",
"duration": "1km",
"track": 1
}]
},
{
"color": "#6f4e37",
"position": "0:10",
"label": "Gel ☕",
"notes": "Caffeine gel",
"effects": [
{
"start": "20min",
"duration": "10km",
"track": 3
},
{
"start": "1h",
"duration": "5km",
"track": 2
}
]
},
{
"label": "Aid 1 💧",
"position": "5km",
"notes": "",
"color": "#0080ff",
"effects": []
},
{
"label": "Aid 2 💧",
"position": "10km",
"notes": "",
"color": "#0080ff",
"effects": [{
"start": "",
"duration": "",
"track": 2
}]
},
{
"color": "#6f4e37",
"position": "1:20",
"label": "Gel ☕",
"notes": "Caffeine gel",
"effects": [
{
"start": "20min",
"duration": "8km",
"track": 3
}
]
},
{
"label": "Aid 3 💧🍌",
"position": "15km",
"notes": "",
"color": "#0080ff",
"effects": [ {
"start": "",
"duration": "",
"track": 2}
]
},
{
"label": "Finish",
"position": "21.1km",
"notes": "You did it!",
"color": "#ff0000",
"effects": [
{ "start": "",
"duration": "",
"track": 1}
]
}
]
}`;
appData = updateDataFormat(JSON.parse(s));
console.log('appData', appData);
save(); // To save an updated format.
};
const margin = { top: 50, right: 50, bottom: 35, left: 30 };
const svg = d3
.select("#timeline-container")
.append("svg")
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
function dd(i) {
return i.toString().padStart(2, "0");
}
const tooltip = d3
.select("body")
.append("div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("visibility", "hidden")
.style("background", "lightsteelblue")
.style("padding", "5px")
.style("border-radius", "4px");
function save() {
const s = JSON.stringify(appData);
localStorage.setItem("race_data", s);
}
function raceDistance() {
return parseDistance(appData.raceDistance);
}
function raceDuration() {
return parseTime(appData.raceDuration);
}
function formatHHMM(sec) {
const m = Math.round(sec / 60);
return `${dd(Math.floor(m / 60))}:${dd(m % 60)}`;
}
function markers() {
return appData.points.flatMap((point) => {
const at = parseDistanceOrTime(point.position);
const results = point.effects.map(e => ({
'label': point.label,
'color': point.color,
'notes': point.notes,
'distance': at.distance,
'time': at.time,
'rangeStart': parseDistanceOrTime(e.start),
'rangeDuration': parseDistanceOrTime(e.duration),
'track': e.track
}));
return results;
});
}
function render() {
try {
// Process data first to catch errors.
const data = markers();
let pace = raceDuration() / (raceDistance() / 1000);
let paceMinPerKm = pace * 60;
let paceMinPerMile = paceMinPerKm * 1.609;
document.getElementById("race-pace").innerHTML = `${formatHHMM(paceMinPerKm)} min/km or ${formatHHMM(paceMinPerMile)} min/mile.`;
// -20px for scroll.
const width = document.getElementById('timeline-container').clientWidth - margin.left - margin.right - 20;
const height = 220 - margin.top - margin.bottom;
d3
.select("#timeline-container")
.select('svg')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.selectAll("circle").remove();
svg.selectAll("text").remove();
svg.selectAll("g").remove();
svg.selectAll("rect").remove();
// Scales will be updated in `render()` based on current data.
const xScale = d3.scaleLinear().domain([0, raceDistance()]).range([0, width]);
const timeScale = d3.scaleLinear().domain([0, raceDuration()]).range([0, width]);
const trackHeight = 20;
// Periods, before markers to make all markers hoverable.
svg
.selectAll("rect")
.data(data.filter((d) => d.rangeDuration.distance > 0))
.enter()
.append("rect")
.attr("x", (d) => xScale(d.distance + d.rangeStart.distance))
.attr("y", (d) => height / 2 + (d.track - 2 - 0.5) * trackHeight + 2)
.attr("width", (d) => xScale(d.rangeDuration.distance))
.attr("height", trackHeight - 4)
.style("fill", (d) => d.color)
.style("opacity", 0.5);
// Add labels
svg
.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("x", (d) => xScale(d.distance) + 10)
.attr("y", (d) => height / 2 + (d.track - 2) * trackHeight + 6)
.attr("text-anchor", "left")
.text((d) => d.label);
// Markers - created last to make an interactive tooltip.
svg
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", (d) => xScale(d.distance))
.attr("cy", (d) => height / 2 + (d.track - 2) * trackHeight)
.attr("r", 5)
.style("fill", (d) => d.color)
.on("mouseover", (event, d) => {
let s = `${d.label}<br/>${_.round(d.distance / 1000, 2)}`;
if (d.rangeDuration.distance > 0) {
s += ` [${_.round((d.distance + d.rangeStart.distance) / 1000, 2)}..${_.round((d.distance + d.rangeStart.distance + d.rangeDuration.distance) / 1000, 2)}] km`;
} else {
s += ' km';
}
s += `<br/>${formatHHMM(d.time)} `;
if (d.rangeDuration.distance > 0) {
s += ` [${formatHHMM(d.time + d.rangeStart.time)}..${formatHHMM(d.time + d.rangeStart.time + d.rangeDuration.time)}]`;
}
if (d.notes) s += `<br/>${d.notes}`;
tooltip
.html(s)
.style("visibility", "visible")
.style("top", event.pageY - 20 + "px")
.style("left", event.pageX + 10 + "px");
})
.on("mouseout", () => tooltip.style("visibility", "hidden"));
// Distance axis.
svg
.append("g")
.attr("class", "x-axis")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale))
.append("text")
.attr("x", width / 2)
.attr("y", 32)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("fill", "rgb(31 41 55 / var(--tw-text-opacity))")
.text("Distance, m");
// Time axis.
svg
.append("g")
.attr("class", "x-axis")
.attr("transform", `translate(0,0)`)
.call(
d3.axisTop(timeScale).tickFormat((d) => formatHHMM(d))
)
.append("text")
.attr("x", width / 2)
.attr("y", -30)
.attr("text-anchor", "middle")
.attr("fill", "rgb(31 41 55 / var(--tw-text-opacity))")
.attr("font-size", "14px")
.text("Time, hh:mm");
svg.selectAll(".x-axis text")
.style("font-size", "12px");
} catch (e) {
showError(e.message);
}
}
function updateControls() {
document.getElementById("race-distance").value = appData.raceDistance;
document.getElementById("race-duration").value = appData.raceDuration;
const tableContainer = document.getElementById("table-container");
tableContainer.innerHTML = ""; // Clear previous content
const table = document.createElement("table");
table.className = "table-auto";
// Create table header
const thead = document.createElement("thead");
const headerRow = document.createElement("tr");
[
{ label: "", classes: "", sort: true },
{ label: "", classes: "" },
{ label: "Color", classes: "" },
{ label: "Label", classes: "" },
{ label: "Position", classes: "" },
{ label: "Notes", classes: "" },
{ label: "Effects", classes: "" },
].forEach((header) => {
const th = document.createElement("th");
th.textContent = header.label;
th.className = header.classes;
if (header.sort === true) {
const btn = document.createElement("button");
btn.innerHTML = `Sort`;
btn.title = "Sort rows by track and position"
btn.className = "border-1 p-1 m-0 align-bottom"
btn.addEventListener("click", sortPoints);
th.appendChild(btn);
}
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// Create table body
const tbody = document.createElement("tbody");
const addCellInput = (row, v, set, type = "text", inputClassName = "") => {
const td = document.createElement("td");
const input = document.createElement("input");
input.className = inputClassName;
input.type = type;
input.value = v;
input.addEventListener("input", (e) => {
set(e.target.value);
onDataUpdated();
});
td.appendChild(input);
row.appendChild(td);
};
const addCellTextArea = (row, v, set, className = "") => {
const td = document.createElement("td");
const input = document.createElement("textarea");
input.value = v;
input.className = className;
input.addEventListener("input", (e) => {
set(e.target.value);
onDataUpdated();
});
td.appendChild(input);
row.appendChild(td);
};
const addCellButton = (row, label, tooltip, click) => {
const td = document.createElement("td");
const btn = document.createElement("button");
btn.title = tooltip;
btn.innerHTML = label;
btn.addEventListener("click", click);
td.appendChild(btn);
row.appendChild(td);
};
const createEffectsTable = (point, showHeader = false) => {
const effectsTable = document.createElement("table");
effectsTable.className = "table-auto border-collapse";
if (showHeader) {
// Effects header
const effectsHeader = document.createElement("thead");
const effectsHeaderRow = document.createElement("tr");
["Track", "Offset", "Duration", ""].forEach(label => {
const th = document.createElement("th");
th.textContent = label;
th.className = "text-sm font-normal";
effectsHeaderRow.appendChild(th);
});
effectsHeader.appendChild(effectsHeaderRow);
effectsTable.appendChild(effectsHeader);
}
// Effects body
const effectsBody = document.createElement("tbody");
point.effects.forEach((effect, effectIdx) => {
const effectRow = document.createElement("tr");
// Track input
addCellInput(effectRow, effect.track, (v) => {
effect.track = _.clamp(parseInt(v), 0, 4);
}, "number", "w-11 border p-1");
// Offset input
addCellInput(effectRow, effect.start, (v) => {
effect.start = v;
}, "text", "border p-1 w-20");
// Duration input
addCellInput(effectRow, effect.duration, (v) => {
effect.duration = v;
}, "text", "border p-1 w-20");
// Action cell (delete and add)
const actionCell = document.createElement("td");
// Add effect button (only for the first effect)
if (effectIdx === 0) {
const addBtn = document.createElement("button");
addBtn.innerHTML = `<svg class=\"w-[16px] h-[16px] text-gray-800 dark:text-white\" aria-hidden=\"true\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" fill=\"none\" viewBox=\"0 0 24 24\"><path stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M5 12h14m-7 7V5\"/></svg>`;
addBtn.title = "Add new effect";
addBtn.className = "p-1";
addBtn.addEventListener("click", () => {
point.effects.push({
start: "",
duration: "",
track: 0
});
onDataUpdated();
updateControls();
});
actionCell.appendChild(addBtn);
}
// Delete effect button (not for the first effect)
if (effectIdx !== 0) {
const deleteBtn = document.createElement("button");
deleteBtn.innerHTML = `<svg class=\"w-[16px] h-[16px] text-gray-800 dark:text-white\" aria-hidden=\"true\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" fill=\"none\" viewBox=\"0 0 24 24\"><path stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M5 7h14m-9 3v8m4-8v8M10 3h4a1 1 0 0 1 1 1v3H9V4a1 1 0 0 1 1-1Z\"/></svg>`;
deleteBtn.title = "Delete effect";
deleteBtn.className = "p-1";
deleteBtn.addEventListener("click", () => {
point.effects.splice(effectIdx, 1);
onDataUpdated();
updateControls();
});
actionCell.appendChild(deleteBtn);
}
effectRow.appendChild(actionCell);
effectsBody.appendChild(effectRow);
});
effectsTable.appendChild(effectsBody);
return effectsTable;
};
appData.points.forEach((d, i) => {
const row = document.createElement("tr");
addCellButton(row, `<svg class="w-[20px] h-[20px] text-gray-800 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linejoin="round" stroke-width="2" d="M9 8v3a1 1 0 0 1-1 1H5m11 4h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-7a1 1 0 0 0-1 1v1m4 3v10a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-7.13a1 1 0 0 1 .24-.65L7.7 8.35A1 1 0 0 1 8.46 8H13a1 1 0 0 1 1 1Z"/>
</svg>
`, "Duplicate", () => {
appData.points.splice(i + 1, 0, { ...d });
onDataUpdated();
updateControls();
});
addCellButton(row, `<svg class="w-[20px] h-[20px] text-gray-800 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 7h14m-9 3v8m4-8v8M10 3h4a1 1 0 0 1 1 1v3H9V4a1 1 0 0 1 1-1ZM6 7h12v13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V7Z"/>
</svg>`, "Delete", () => {
appData.points.splice(i, 1);
onDataUpdated();
updateControls();
});
addCellInput(row, d.color, (v) => (d.color = v), "color", "w-6 h-6");
addCellInput(row, d.label, (v) => (d.label = v), "text", "border p-1");
addCellInput(row, d.position, (v) => (d.position = v), "text", "border p-1 w-20");
addCellTextArea(row, d.notes, (v) => (d.notes = v), "border w-72");
// Add effects table cell
const effectsCell = document.createElement("td");
effectsCell.appendChild(createEffectsTable(d, i === 0));
row.appendChild(effectsCell);
tbody.appendChild(row);
});
const row = document.createElement("tr");
addCellButton(row, `<svg class="w-[20px] h-[20px] text-gray-800 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14m-7 7V5"/>
</svg>`, "add new", () => {
addPoint();
onDataUpdated();
updateControls();
});
tbody.appendChild(row);
table.appendChild(tbody);
tableContainer.appendChild(table);
}
const strToMeters = (value, unit) => {
const val = parseFloat(value);
switch (unit) {
case "m":
return val; // meters
case "mi":
return val * 1609.34; // miles to meters
case "km":
case "k":
default:
return val * 1000; // kilometers to meters
}
};
function parseDistance(input) {
input = input.toString().trim();
if (input === "") return 0;
const distanceRegex = /^([+-]?\d*\.?\d*) *(m|km|k|mi|)$/; // Matches distances like "12km", "5mi"
let match = input.match(distanceRegex);
if (match) {
const value = match[1];
const unit = match[2];
return strToMeters(value, unit);
}
throw new Error(`cannot parse '${input}' as distance, format is <number>(m|km|mi)`);
}
function parseTime(input) {
input = input.toString().trim();
if (input === "") return 0;
const timeRegex = /^([+-]?\d*\.?\d*) *(s|sec|min|h)|[+-]?(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/; // Matches time like "1.5h", "45min", "01:30"
const convertTimeToSeconds = (value, unit) => {
const val = parseFloat(value);
switch (unit) {
case "s":
case "sec":
return val;
case "min":
return val * 60;
case "h":
return val * 3600;
default:
return 0;
}
};
const parseHHMMSS = (hours, minutes, seconds = 0) => {
return parseInt(hours) * 3600 + parseInt(minutes) * 60 + parseInt(seconds);
};
let match = input.match(timeRegex);
if (match) {
let sec = 0;
if (match[1]) {
// Time in "float h/min/s" format, like "1.5h" or "45min".
const value = match[1];
const unit = match[2];
sec = convertTimeToSeconds(value, unit);
} else if (match[3] && match[4]) {
// Time in "hh:mm" or "hh:mm:ss" format.
const hours = match[3];
const minutes = match[4];
const seconds = match[5] || 0;
sec = parseHHMMSS(hours, minutes, seconds);
if (input.startsWith("-")) sec *= -1;
}
return sec;
}
throw new Error(`cannot parse '${input}' as time`);
}
function parseDistanceOrTime(input) {
input = input.trim();
if (input === "") {
return { time: 0, distance: 0 };
}
const timeToDistance = (s) => {
return (s / raceDuration()) * raceDistance();
};
const distanceToTime = (d) => {
return (d / raceDistance()) * raceDuration();
};
try {
const d = parseDistance(input);
return { time: distanceToTime(d), distance: d };
} catch (e) {
}
try {
const sec = parseTime(input);
return { time: sec, distance: timeToDistance(sec) };
} catch (e) {
}
throw new Error(`cannot parse '${input}' as distance or time`);
}
function sortPoints() {
appData.points.sort((a, b) => parseDistanceOrTime(a.position).distance - parseDistanceOrTime(b.position).distance);
save();
updateControls();
}
function addPoint() {
appData.points.push({
"color": "#000000",
"position": "0:00",
"label": `#${appData.points.length + 1}`,
"notes": "",
"effects": [{
"start": "",
"duration": "",
"track": 0
}]
});
onDataUpdated();
updateControls();
}
document.getElementById("race-distance").addEventListener("input", (e) => {
appData.raceDistance = e.target.value;
onDataUpdated();
});
document.getElementById("race-duration").addEventListener("input", (e) => {
appData.raceDuration = e.target.value;
onDataUpdated();
});
function onDataUpdated() {
hideMessage();
save();
render();
}
document.getElementById("copy-json").addEventListener("click", () => {
navigator.clipboard.writeText(JSON.stringify(appData)).then(function () {
showMessage('Copied JSON to clipboard', 'text-green-600', 3000);
}).catch(function (error) {
showError('failed to copy to clipboard');
});
});
document.getElementById("import-json").addEventListener("click", () => {
const s = prompt("insert one-line JSON");
if (s == null) return;
appData = updateDataFormat(JSON.parse(s));
console.log('loaded data', appData);
onDataUpdated();
updateControls();
});
function maybeEscapeCSVString(s) {
let value = String(s || '');
if (/[",\n]/.test(value)) {
value = `"${value.replace(/"/g, '""')}"`;
}
return value;
}
function toCSV() {
const headers = [
{ label: 'Label', value: 'label' },
{ label: 'Position', value: 'position' },
{ label: 'Position seconds', value: 'time' },
{ label: 'Position meters', value: 'distance' },
{ label: 'Offset', value: 'start' },
{ label: 'Offset seconds', value: 'range_start_time' },
{ label: 'Offset meters', value: 'range_start_distance' },
{ label: 'Duration', value: 'duration' },
{ label: 'Duration seconds', value: 'range_duration_time' },
{ label: 'Duration meters', value: 'range_duration_distance' },
{ label: 'Notes', value: 'notes' },
];
const data = markers();
// Use lodash to map the points array and append metadata
const rows = data.map((d) => {
return {
...d,
'range_start_time': _.round(d.rangeStart.time),
'range_start_distance': _.round(d.rangeStart.distance),
'range_duration_time': _.round(d.rangeDuration.time),
'range_duration_distance': _.round(d.rangeDuration.distance),
};
});
// Generate the CSV string
const csvRows = [
headers.map(h => h.label),
...rows.map(row => headers.map(h => maybeEscapeCSVString(row[h.value] || '')).join(','))
];
return csvRows.join('\n');
}
document.getElementById("copy-csv").addEventListener("click", () => {
const s = toCSV();
navigator.clipboard.writeText(s).then(function () {
showMessage('Copied CSV to clipboard', 'text-green-600', 3000);
}).catch(function (error) {
showError('failed to copy to clipboard');
});
});
function showError(err) {
showMessage(err, 'text-red-600');
}
function showMessage(content, classes, timeout = null) {
const m = document.getElementById('message');
m.className = 'ml-2 ' + classes;
m.innerText = content;
if (timeout != null) {
setTimeout(() => {
m.className = 'invisible';
}, timeout)
}
}
function hideMessage() {
document.getElementById('message').className = 'invisible';
}
function toggleInstructions(show) {
document.getElementById('instructions').classList.toggle("hidden", !show);
document.getElementById('hide-instructions').classList.toggle("hidden", !show);
document.getElementById('show-instructions').classList.toggle("hidden", show);
if (show) {
localStorage.removeItem('hide-instructions');
} else {
localStorage.setItem('hide-instructions', 'hide');
}
}
// TODO: count site visits without cookies.
// TODO: move sort button to the first column.
setTimeout(() => {
loadData();
render();
updateControls();
toggleInstructions(localStorage.getItem('hide-instructions') == null);
}, 0);
window.addEventListener('resize', _.throttle(render, 500));
</script>
<script async defer src="https://scripts.simpleanalyticscdn.com/latest.js"></script>
<noscript><img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt="" referrerpolicy="no-referrer-when-downgrade" /></noscript>
</body>
</html>