aboutsummaryrefslogtreecommitdiff
path: root/web/frontend/ride-detail.ts
blob: dcebbe40a13171a04677a345b30766dd89bc1dbf (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

import { OfficialClimbProfileController } from "./official-climb-profile.js";
import { RideBoundaryController } from "./ride-detail-boundaries.js";
import { RideProfileCanvas } from "./ride-detail-canvas.js";
import { RideDetailMap } from "./ride-detail-map.js";
import { formatDistance, formatElevation } from "./ride-detail-logic.js";
import type { ClimbBounds, RideMapColors, RideMapPass, RideProfile, RideProfileColors, RideProfilePoint, RideRoute } from "./types.js";

export const mountRideDetail = (): void => {
  const mapElement = document.getElementById("ride-map");
  const routeElement = document.getElementById("ride-route");
  const profileElement = document.getElementById("ride-profile");
  const passesElement = document.getElementById("ride-passes");
  const canvas = document.getElementById("ride-profile-chart");
  const hoverOutput = document.getElementById("ride-profile-hover");
  if (!mapElement || !routeElement || !profileElement || !passesElement || !canvas || !hoverOutput) return;
  const routeScript = routeElement as HTMLScriptElement;
  const profileScript = profileElement as HTMLScriptElement;
  const passesScript = passesElement as HTMLScriptElement;
  const profileCanvasElement = canvas as HTMLCanvasElement;
  const leaflet = window.L;
  if (!leaflet) return;

  const colorProbe = document.createElement("span");
  colorProbe.hidden = true;
  document.body.append(colorProbe);
  const resolveColor = (name: string): string => {
    colorProbe.style.color = `var(${name})`;
    return getComputedStyle(colorProbe).color;
  };
  const profileColors: RideProfileColors = {
    subtle: resolveColor("--color-subtle"),
    plotSurface: resolveColor("--color-plot-surface"),
    plotSurfaceOverlay: resolveColor("--color-plot-surface-overlay"),
    grid: resolveColor("--color-plot-grid"),
    profileFill: resolveColor("--color-profile-fill"),
    profileLine: resolveColor("--color-profile-line"),
    accentFill: resolveColor("--color-accent-fill"),
    climbLabel: resolveColor("--color-climb-label"),
    crossing: resolveColor("--color-crossing"),
    crossingLabel: resolveColor("--color-crossing-label"),
    hoverLine: resolveColor("--color-hover-line"),
    forest: resolveColor("--color-forest"),
    climbFocusFill: resolveColor("--color-climb-focus-fill"),
  };
  const mapColors: RideMapColors = {
    accent: resolveColor("--color-accent"),
    forest: resolveColor("--color-forest"),
    climbRoute: resolveColor("--color-climb-route"),
  };
  colorProbe.remove();

  const route = JSON.parse(routeScript.textContent ?? "") as RideRoute;
  const profile = JSON.parse(profileScript.textContent ?? "") as RideProfile;
  const passes = JSON.parse(passesScript.textContent ?? "") as RideMapPass[];
  const points: RideProfilePoint[] = profile.points;
  if (points.length === 0) return;

  const climbItems = [...document.querySelectorAll<HTMLElement>("[data-climb-item]")];
  const climbItemIndices = climbItems.map((item) => Number.parseInt(item.dataset.climbIndex ?? "", 10));
  const previousClimbButton = document.querySelector<HTMLButtonElement>("[data-climb-previous]");
  const nextClimbButton = document.querySelector<HTMLButtonElement>("[data-climb-next]");
  const climbPosition = document.querySelector<HTMLElement>("[data-climb-position]");
  const climbBounds: ClimbBounds[] = profile.climbs.map((climb) => ({ startIndex: climb.startIndex, endIndex: climb.endIndex }));
  const state = {
    focusedClimbItemIndex: 0,
    focusedClimbIndex: climbItemIndices[0] ?? 0,
  };

  const mapController = new RideDetailMap({
    leaflet,
    element: mapElement,
    route,
    points,
    climbs: climbBounds,
    passes,
    colors: mapColors,
  });
  const officialProfileController = new OfficialClimbProfileController(points);
  let boundaryController: RideBoundaryController | undefined;
  const profileCanvas = new RideProfileCanvas({
    canvas: profileCanvasElement,
    points,
    profile,
    colors: profileColors,
    getClimbBounds: () => climbBounds,
    canSelectPoint: (source) => boundaryController?.isSelecting(source) ?? false,
    onPointSelected: (index) => boundaryController?.choosePoint(index),
    onPointHover: (index) => {
      if (index < 0) {
        mapController.clearPoint();
        hoverOutput.textContent = "Hover or focus the profile to inspect elevation.";
        return;
      }
      const point = points[index];
      mapController.showPoint(index);
      hoverOutput.textContent = `#${point.index ?? index} · ${formatDistance(point.distanceKm)} · ${formatElevation(point.elevationM)}`;
    },
  });

  const updateClimbLayer = (index: number): void => {
    mapController.updateClimbLayer(index, climbBounds[index], index === state.focusedClimbIndex);
  };
  boundaryController = new RideBoundaryController({
    forms: [...document.querySelectorAll<HTMLFormElement>("[data-official-climb-form]")],
    points,
    climbBounds,
    onBoundaryChanged: (index) => {
      updateClimbLayer(index);
      profileCanvas.redraw();
    },
    onPointSelected: (index) => profileCanvas.showPoint(index),
    setMessage: (message) => {
      hoverOutput.textContent = message;
    },
  });

  mapController.onClick((event) => {
    if (!boundaryController?.isSelecting("map")) return;
    boundaryController.choosePoint(mapController.nearestPointIndex(event.latlng.lat, event.latlng.lng));
  });

  const updateClimbFocus = (index: number, zoom: boolean): void => {
    if (climbItems.length === 0) return;
    state.focusedClimbItemIndex = Math.max(0, Math.min(climbItems.length - 1, index));
    state.focusedClimbIndex = climbItemIndices[state.focusedClimbItemIndex];
    for (let itemIndex = 0; itemIndex < climbItems.length; itemIndex++) {
      const active = itemIndex === state.focusedClimbItemIndex;
      climbItems[itemIndex].hidden = !active;
      climbItems[itemIndex].setAttribute("aria-hidden", String(!active));
      climbItems[itemIndex].classList.toggle("focused", active);
      updateClimbLayer(climbItemIndices[itemIndex]);
    }
    if (climbPosition) climbPosition.textContent = `Climb ${state.focusedClimbItemIndex + 1} of ${climbItems.length}`;
    if (previousClimbButton) previousClimbButton.disabled = state.focusedClimbItemIndex === 0;
    if (nextClimbButton) nextClimbButton.disabled = state.focusedClimbItemIndex === climbItems.length - 1;
    boundaryController?.clearSelection();
    profileCanvas.setFocusedClimbIndex(state.focusedClimbIndex);
    if (zoom) mapController.zoomToClimb(climbBounds[state.focusedClimbIndex]);
  };

  if (previousClimbButton) previousClimbButton.addEventListener("click", () => updateClimbFocus(state.focusedClimbItemIndex - 1, true));
  if (nextClimbButton) nextClimbButton.addEventListener("click", () => updateClimbFocus(state.focusedClimbItemIndex + 1, true));
  window.addEventListener("resize", () => {
    profileCanvas.redraw();
    officialProfileController.redrawOpen();
  });
  if (climbItems.length > 0) updateClimbFocus(0, false);
  else profileCanvas.redraw();
  mountPreviewSave([...document.querySelectorAll<HTMLFormElement>("form[data-preview-form]")]);
};

// Preview ride forms save official climbs via fetch so the un-persisted preview stays on screen.
const mountPreviewSave = (forms: HTMLFormElement[]): void => {
  for (const form of forms) {
    if (!form.dataset.previewForm) continue;
    const item = form.closest<HTMLElement>("[data-climb-item]");
    form.addEventListener("submit", async (event) => {
      event.preventDefault();
      const submitButton = form.querySelector<HTMLButtonElement>("button[type=submit]");
      if (submitButton) submitButton.disabled = true;
      let message: string;
      try {
        const response = await fetch(form.action, { method: "POST", body: new FormData(form) });
        const payload = (await response.json()) as { ok?: boolean; name?: string; error?: string };
        message =
          response.ok && payload.ok && payload.name
            ? `Official climb “${payload.name}” saved. Re-upload the file to see it matched.`
            : `Saving the official climb failed${payload.error ? `: ${payload.error}` : "."}`;
      } catch {
        message = "Saving the official climb failed.";
      }
      const status = item?.querySelector<HTMLElement>(".climb-status");
      if (status) status.textContent = message;
      else window.alert(message);
    });
  }
};

mountRideDetail();