summaryrefslogtreecommitdiff
path: root/web/templates.templ
blob: 8e7c0f101fad20c567286922728ee517ea263801 (plain) (blame)
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
package web

templ Layout(title string, content templ.Component) {
	<!doctype html>
	<html lang="en">
		<head>
		<meta charset="utf-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1"/>
		<title>{ title } · biking_home</title>
		<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
		<link rel="stylesheet" href="/static/style.css"/>
		</head>
		<body>
			<header class="site-header">
				<a class="brand" href="/">biking_home</a>
				<nav class="nav"><a href="/">Rides</a><a href="/sync">Sync Strava</a></nav>
			</header>
			<main class="container">
				@content
			</main>
		</body>
	</html>
}

templ RidesPage(items []RideView, headers []RideSortHeader) {
	@Layout("Rides", RidesContent(items, headers))
}

templ RidesContent(items []RideView, headers []RideSortHeader) {
	<p class="eyebrow">Ride library</p>
	<div class="toolbar">
		<div><h1>All rides</h1><p class="lead">Your imported rides, ready for climb analysis.</p></div>
		<a class="button" href="/sync">Sync Strava</a>
	</div>
	<section class="panel">
		if len(items) == 0 {
			<div class="empty">No rides stored yet. <a href="/sync">Import your first Strava rides.</a></div>
		} else {
			<table>
				<thead><tr>
					for _, header := range headers {
						<th class={ header.Class } scope="col" aria-sort={ header.AriaSort }><a class="sort-link" href={ templ.URL(header.URL) }>{ header.Label }<span class="sort-indicator" aria-hidden="true">{ header.Indicator }</span></a></th>
					}
				</tr></thead>
				<tbody>
					for _, item := range items {
						<tr><td><strong><a href={ templ.URL(rideDetailURL(item.ID)) }>{ item.Name }</a></strong><br/><small>{ item.Type }</small></td><td>{ formatRideDate(item.StartDate) }</td><td class="numeric">{ formatDistance(item.DistanceM) }</td><td class="numeric">{ formatDuration(item.MovingTimeS) }</td><td class="numeric">{ formatElevation(item.TotalElevationGainM) }</td><td class="numeric">{ item.Cotacol }</td><td class="numeric">{ item.CotacolPer100Km }</td></tr>
					}
				</tbody>
			</table>
		}
	</section>
}

templ RideDetailPage(data RideDetailView) {
	@Layout("Ride detail", RideDetailContent(data))
}

templ RideDetailContent(data RideDetailView) {
	<p class="eyebrow">Ride detail</p>
	<div class="toolbar">
		<div><h1>{ data.Ride.Name }</h1><p class="lead">{ data.Ride.Type } · { formatRideDate(data.Ride.StartDate) }</p></div>
		<a class="button secondary" href="/">Back to rides</a>
	</div>
	<section class="panel">
		<dl>
			<div><dt>Distance</dt><dd>{ formatDistance(data.Ride.DistanceM) }</dd></div>
			<div><dt>Moving time</dt><dd>{ formatDuration(data.Ride.MovingTimeS) }</dd></div>
			<div><dt>Elevation</dt><dd>{ formatElevation(data.Ride.TotalElevationGainM) }</dd></div>
		</dl>
	</section>
	if data.RouteError != "" {
		<div class="error">{ data.RouteError }</div>
	}
	if data.HasRoute {
		<section class="panel profile-panel">
			<div class="profile-heading">
				<h2>Elevation profile</h2>
				<p>Hover or focus the profile to inspect the ride at that distance.</p>
			</div>
			<div class="profile-chart">
				<canvas id="ride-profile-chart" tabindex="0" role="img" aria-describedby="ride-profile-hover" aria-label="Interactive ride elevation profile"></canvas>
			</div>
			<output id="ride-profile-hover" class="profile-hover" aria-live="polite">Hover or focus the profile to inspect elevation.</output>
		</section>
		<section class="panel map-panel">
			<div id="ride-map" class="ride-map" role="img" aria-label="Recorded ride route map"></div>
		</section>
		@templ.JSONScript("ride-route", data.Route)
		@templ.JSONScript("ride-profile", data.Profile)
		<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
		<script>
			(() => {
				const mapElement = document.getElementById("ride-map");
				const routeElement = document.getElementById("ride-route");
				const profileElement = document.getElementById("ride-profile");
				const canvas = document.getElementById("ride-profile-chart");
				const hoverOutput = document.getElementById("ride-profile-hover");
				if (!mapElement || !routeElement || !profileElement || !canvas || !hoverOutput) return;
				const colorProbe = document.createElement("span");
				colorProbe.hidden = true;
				document.body.append(colorProbe);
				const resolveColor = (name) => {
					colorProbe.style.color = `var(${name})`;
					return getComputedStyle(colorProbe).color;
				};
				const colors = {
					accent: resolveColor("--color-accent"),
					forest: resolveColor("--color-forest"),
					subtle: resolveColor("--color-subtle"),
					plotSurface: resolveColor("--color-plot-surface"),
					plotSurfaceOverlay: resolveColor("--color-plot-surface-overlay"),
					grid: resolveColor("--color-plot-grid"),
					accentFill: resolveColor("--color-accent-fill"),
					climbLabel: resolveColor("--color-climb-label"),
					crossing: resolveColor("--color-crossing"),
					crossingLabel: resolveColor("--color-crossing-label"),
					hoverLine: resolveColor("--color-hover-line"),
				};
				colorProbe.remove();
				const route = JSON.parse(routeElement.textContent);
				const profile = JSON.parse(profileElement.textContent);
				const map = L.map(mapElement);
				const tiles = L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
					maxZoom: 19,
					attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
				});
				tiles.addTo(map);
				const routeLayer = L.geoJSON(route, {
					style: { color: colors.accent, weight: 4, opacity: 0.9 },
				}).addTo(map);
				const bounds = routeLayer.getBounds();
				if (bounds.isValid()) {
					map.fitBounds(bounds, { padding: [24, 24], maxZoom: 15 });
				}

				const points = profile.points || [];
				if (points.length === 0) return;
				const routeCursor = L.circleMarker([points[0].latitude, points[0].longitude], {
					color: colors.forest,
					fillColor: colors.accent,
					fillOpacity: 0,
					opacity: 0,
					radius: 7,
					weight: 3,
					interactive: false,
				}).addTo(map);

				const context = canvas.getContext("2d");
				if (!context) return;
				const state = { hoveredIndex: -1, plot: null, width: 0, height: 0 };
				const minDistance = points[0].distanceKm;
				const maxDistance = points[points.length - 1].distanceKm;
				let minElevation = points[0].elevationM;
				let maxElevation = points[0].elevationM;
				for (const point of points) {
					minElevation = Math.min(minElevation, point.elevationM);
					maxElevation = Math.max(maxElevation, point.elevationM);
				}
				const elevationPadding = Math.max((maxElevation - minElevation) * 0.1, 20);
				minElevation -= elevationPadding;
				maxElevation += elevationPadding;

				const formatDistance = (distance) => `${distance.toFixed(distance < 10 ? 1 : 0)} km`;
				const formatElevation = (elevation) => `${Math.round(elevation)} m`;
				const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
				const xForDistance = (distance) => {
					const span = Math.max(maxDistance - minDistance, 1);
					return state.plot.left + (distance - minDistance) / span * (state.plot.right - state.plot.left);
				};
				const yForElevation = (elevation) => {
					const span = Math.max(maxElevation - minElevation, 1);
					return state.plot.bottom - (elevation - minElevation) / span * (state.plot.bottom - state.plot.top);
				};
				const nearestPointIndex = (distance) => {
					let low = 0;
					let high = points.length - 1;
					while (low < high) {
						const middle = Math.floor((low + high) / 2);
						if (points[middle].distanceKm < distance) low = middle + 1;
						else high = middle;
					}
					if (low === 0) return low;
					const previous = points[low - 1];
					return distance - previous.distanceKm < points[low].distanceKm - distance ? low - 1 : low;
				};

				const draw = () => {
					const rect = canvas.getBoundingClientRect();
					if (rect.width === 0 || rect.height === 0) return;
					const ratio = window.devicePixelRatio || 1;
					canvas.width = Math.floor(rect.width * ratio);
					canvas.height = Math.floor(rect.height * ratio);
					context.setTransform(ratio, 0, 0, ratio, 0, 0);
					state.width = rect.width;
					state.height = rect.height;
					state.plot = { left: 52, right: rect.width - 20, top: 24, bottom: rect.height - 34 };
					const plot = state.plot;
					context.clearRect(0, 0, rect.width, rect.height);
					context.fillStyle = colors.plotSurface;
					context.fillRect(0, 0, rect.width, rect.height);

					context.font = "12px system-ui, sans-serif";
					context.textBaseline = "middle";
					for (let step = 0; step <= 4; step++) {
						const fraction = step / 4;
						const y = plot.top + fraction * (plot.bottom - plot.top);
						const elevation = maxElevation - fraction * (maxElevation - minElevation);
						context.strokeStyle = colors.grid;
						context.lineWidth = 1;
						context.beginPath();
						context.moveTo(plot.left, y);
						context.lineTo(plot.right, y);
						context.stroke();
						context.fillStyle = colors.subtle;
						context.textAlign = "right";
						context.fillText(formatElevation(elevation), plot.left - 8, y);
					}

					for (const climb of profile.climbs || []) {
						const startX = clamp(xForDistance(climb.startKm), plot.left, plot.right);
						const endX = clamp(xForDistance(climb.endKm), plot.left, plot.right);
						context.fillStyle = colors.accentFill;
						context.fillRect(startX, plot.top, Math.max(endX - startX, 1), plot.bottom - plot.top);
						const label = climb.name || `${climb.category} ${Math.round(climb.score)}`;
						context.fillStyle = colors.climbLabel;
						context.textAlign = "center";
						context.textBaseline = "top";
						context.fillText(label, clamp((startX + endX) / 2, plot.left + 24, plot.right - 24), plot.top + 4);
					}

					for (const crossing of profile.crossings || []) {
						const x = xForDistance(crossing.distanceKm);
						context.strokeStyle = colors.crossing;
						context.lineWidth = 1;
						context.setLineDash([4, 3]);
						context.beginPath();
						context.moveTo(x, plot.top);
						context.lineTo(x, plot.bottom);
						context.stroke();
						context.setLineDash([]);
					}

					context.beginPath();
					context.moveTo(xForDistance(points[0].distanceKm), plot.bottom);
					for (const point of points) context.lineTo(xForDistance(point.distanceKm), yForElevation(point.elevationM));
					context.lineTo(xForDistance(points[points.length - 1].distanceKm), plot.bottom);
					context.closePath();
					context.fillStyle = colors.accentFill;
					context.fill();
					context.beginPath();
					for (let i = 0; i < points.length; i++) {
						const point = points[i];
						if (i === 0) context.moveTo(xForDistance(point.distanceKm), yForElevation(point.elevationM));
						else context.lineTo(xForDistance(point.distanceKm), yForElevation(point.elevationM));
					}
					context.strokeStyle = colors.accent;
					context.lineWidth = 2.5;
					context.stroke();
					for (const crossing of profile.crossings || []) {
						const x = xForDistance(crossing.distanceKm);
						const label = `${crossing.name} ${Math.round(crossing.passElevationM)} m`;
						const labelWidth = context.measureText(label).width;
						const labelX = clamp(x, plot.left + labelWidth / 2 + 3, plot.right - labelWidth / 2 - 3);
						const labelY = plot.top - 6;
						context.fillStyle = colors.plotSurfaceOverlay;
						context.fillRect(labelX - labelWidth / 2 - 3, labelY - 15, labelWidth + 6, 16);
						context.fillStyle = colors.crossingLabel;
						context.textAlign = "center";
						context.textBaseline = "bottom";
						context.fillText(label, labelX, labelY);
					}

					context.fillStyle = colors.subtle;
					context.textAlign = "center";
					context.textBaseline = "top";
					for (let step = 0; step <= 4; step++) {
						const distance = minDistance + step / 4 * (maxDistance - minDistance);
						context.fillText(formatDistance(distance), xForDistance(distance), plot.bottom + 10);
					}

					if (state.hoveredIndex >= 0) {
						const point = points[state.hoveredIndex];
						const x = xForDistance(point.distanceKm);
						const y = yForElevation(point.elevationM);
						context.strokeStyle = colors.hoverLine;
						context.lineWidth = 1;
						context.setLineDash([3, 3]);
						context.beginPath();
						context.moveTo(x, plot.top);
						context.lineTo(x, plot.bottom);
						context.stroke();
						context.setLineDash([]);
						context.fillStyle = colors.forest;
						context.beginPath();
						context.arc(x, y, 5, 0, 2 * Math.PI);
						context.fill();
					}
				};

				const clearHover = () => {
					state.hoveredIndex = -1;
					routeCursor.setStyle({ opacity: 0, fillOpacity: 0 });
					hoverOutput.textContent = "Hover or focus the profile to inspect elevation.";
					draw();
				};
				const showPoint = (index) => {
					state.hoveredIndex = clamp(index, 0, points.length - 1);
					const point = points[state.hoveredIndex];
					routeCursor.setLatLng([point.latitude, point.longitude]);
					routeCursor.setStyle({ opacity: 1, fillOpacity: 0.9 });
					hoverOutput.textContent = `${formatDistance(point.distanceKm)} · ${formatElevation(point.elevationM)}`;
					draw();
				};
				canvas.addEventListener("pointermove", (event) => {
					if (!state.plot) return;
					const rect = canvas.getBoundingClientRect();
					const x = event.clientX - rect.left;
					if (x < state.plot.left || x > state.plot.right) {
						clearHover();
						return;
					}
					const distance = minDistance + (x - state.plot.left) / (state.plot.right - state.plot.left) * (maxDistance - minDistance);
					showPoint(nearestPointIndex(distance));
				});
				canvas.addEventListener("pointerleave", clearHover);
				canvas.addEventListener("pointercancel", clearHover);
				canvas.addEventListener("keydown", (event) => {
					if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
					event.preventDefault();
					const direction = event.key === "ArrowRight" ? 1 : -1;
					const index = state.hoveredIndex < 0 ? (direction > 0 ? 0 : points.length - 1) : state.hoveredIndex + direction;
					showPoint(index);
				});
				window.addEventListener("resize", draw);
				draw();
			})();
		</script>
	}
}

templ SyncPage(data SyncPageData) {
	@Layout("Sync Strava", SyncContent(data))
}

templ SyncContent(data SyncPageData) {
	<p class="eyebrow">Data import</p>
	<h1>Sync Strava rides</h1>
	<p class="lead">Choose a date range. New rides are downloaded as GPX files and recorded in the local library.</p>
	if data.Notice != "" {
		<div id="sync-notice" class="notice">{ data.Notice }</div>
	} else {
		<div id="sync-notice" class="notice" hidden></div>
	}
	if data.Error != "" {
		<div id="sync-error" class="error">{ data.Error }</div>
	} else {
		<div id="sync-error" class="error" hidden></div>
	}
	<section class="panel">
		if !data.HasAuth {
			<p>Strava authorization is required before the first sync.</p>
			<a class="button secondary" href={ templ.URL("/strava/login?return_to=/sync") }>Authorize Strava</a>
		} else {
			<form id="sync-form" method="post" action="/sync">
				<div class="form-row">
					<label>From<input type="date" name="from" value={ data.From } required/></label>
					<label>To<input type="date" name="to" value={ data.To } required/></label>
					<button class="button" type="submit">Sync rides</button>
				</div>
			</form>
			<div id="sync-progress" class="sync-progress" role="status" aria-live="polite" hidden>
				<div class="progress-heading"><strong>Importing rides</strong><span id="sync-progress-count">0 / 0</span></div>
				<progress id="sync-progress-bar" max="1" value="0" aria-label="Strava import progress"></progress>
				<span id="sync-progress-details">0 imported · 0 skipped</span>
			</div>
		}
	</section>
	<script>
		(() => {
			const form = document.getElementById("sync-form");
			if (!form) return;
			const button = form.querySelector("button[type=submit]");
			const progressPanel = document.getElementById("sync-progress");
			const progressBar = document.getElementById("sync-progress-bar");
			const progressCount = document.getElementById("sync-progress-count");
			const progressDetails = document.getElementById("sync-progress-details");
			const notice = document.getElementById("sync-notice");
			const error = document.getElementById("sync-error");

			const showError = (message) => {
				error.textContent = message;
				error.hidden = false;
			};
			const updateProgress = (progress) => {
				progressPanel.hidden = false;
				progressBar.max = Math.max(progress.total, 1);
				progressBar.value = progress.completed;
				progressCount.textContent = `${progress.completed} / ${progress.total}`;
				progressDetails.textContent = `${progress.imported} imported · ${progress.skipped} skipped`;
			};
			const handleEvent = (eventName, data) => {
				if (eventName === "progress") {
					updateProgress(data);
					return false;
				}
				if (eventName === "complete") {
					updateProgress(data);
					notice.textContent = `Sync complete: ${data.imported} imported, ${data.skipped} skipped.`;
					notice.hidden = false;
					return true;
				}
				if (eventName === "error") {
					if (data.progress) updateProgress(data.progress);
					throw new Error(data.message || "Strava sync failed");
				}
				return false;
			};
			const consumeEvents = async (response) => {
				const reader = response.body.getReader();
				const decoder = new TextDecoder();
				let buffer = "";
				let completed = false;
				const consumeBlock = (block) => {
					let eventName = "message";
					let data = "";
					for (const line of block.split(/\r?\n/)) {
						if (line.startsWith("event: ")) eventName = line.slice(7);
						if (line.startsWith("data: ")) data += line.slice(6);
					}
					if (data) completed = handleEvent(eventName, JSON.parse(data)) || completed;
				};
				while (true) {
					const { value, done } = await reader.read();
					buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
					const blocks = buffer.split(/\r?\n\r?\n/);
					buffer = blocks.pop();
					for (const block of blocks) consumeBlock(block);
					if (done) break;
				}
				if (buffer.trim()) consumeBlock(buffer);
				if (!completed) throw new Error("Strava sync ended before completion");
			};

			form.addEventListener("submit", async (event) => {
				event.preventDefault();
				button.disabled = true;
				button.textContent = "Syncing...";
				notice.hidden = true;
				error.hidden = true;
				progressPanel.hidden = false;
				progressCount.textContent = "0 / 0";
				progressDetails.textContent = "Preparing import...";
				try {
					const response = await fetch(form.action, {
						method: "POST",
						body: new FormData(form),
						headers: { Accept: "text/event-stream" },
					});
					if (response.redirected) {
						window.location.assign(response.url);
						return;
					}
					if (!response.ok) throw new Error(await response.text() || `Sync failed (HTTP ${response.status})`);
					if (!response.body) throw new Error("The browser does not support streaming responses");
					await consumeEvents(response);
				} catch (caught) {
					showError(caught instanceof Error ? caught.message : "Strava sync failed");
				} finally {
					button.disabled = false;
					button.textContent = "Sync rides";
				}
			});
		})();
	</script>
}